<template>
  <div class="h5-container">
    <van-nav-bar title="项目案例" @click-left="onClickLeft" @click-right="handAdd">
      <template #right>
        <van-icon name="add" size="25" color="#000" />
      </template>
    </van-nav-bar>
    
    <van-search 
      v-model="query.projectName" 
      show-action 
      placeholder="请输入项目名称" 
      @search="onRefresh"
      @cancel="handleClearSearch" 
    />

    <!-- 项目列表 -->
    <van-pull-refresh v-model="isRefreshing" success-text="刷新成功" @refresh="onRefresh">
      <van-list 
        v-model:loading="isLoading" 
        :finished="isFinished" 
        finished-text="没有更多了" 
        offset="200" 
        @load="onLoad"
      >
        <div v-for="(item, idx) in resultData" :key="item.id">
          <van-swipe-cell 
            title-style="color: #007aff" 
            style="height: 80px;" 
            :ref="el => getSwipeCellRef(el, idx)"
          >
            <template #default>
              <div class="swipe-cell-default">
                <van-cell 
                  style="min-height: 120px; padding: 0 0 0 0; display: flex; align-items: flex-start;" 
                  @click="edits(item)"
                >
                  <template #title>
                    <div class="cell-title">
                      {{ item.projectName }}
                    </div>
                  </template>
                  <template #label>
                    <div>案例编号：{{ item.caseNumber }}</div>
                    <div>案例类型：{{ item.caseType }}</div>
                    <div>浏览量：{{ item.viewCount }}</div>
                  </template>
                </van-cell>
                <div class="swipe-cell-default-icon">
                  <van-icon 
                    v-if="openStatus[idx]" 
                    name="arrow-double-left" 
                    @click.stop="openSwipe(idx)" 
                  />
                  <van-icon 
                    v-else 
                    name="arrow-double-right" 
                    @click.stop="closeSwipe(idx)" 
                  />
                </div>
              </div>
            </template>

            <template #right>
              <van-button 
                v-if="item.canDelete" 
                square 
                class="delete-button" 
                text="删除" 
                @click="handleDelete(item)" 
              />
            </template>
          </van-swipe-cell>
        </div>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance } from 'vue';
import { useRouter } from 'vue-router';
import { showDialog, showSuccessToast, showToast } from 'vant';

const { proxy } = getCurrentInstance();
const router = useRouter();

const onClickLeft = () => {
  history.back();
};

const query = ref({
  caseNumber: '',
  projectName: ''
});

const isRefreshing = ref(false);
const isLoading = ref(false);
const isFinished = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const totalRows = ref(0);
const resultData = ref([]);
const tableData = ref([]);

const currentUserId = String(localStorage.getItem('userId'));

// 获取列表数据
const getTableData = async () => {
  const url = '/sgsafe/Manager/queryProject';
  const param = {
    page: currentPage.value,
    rows: pageSize.value,
    params: JSON.stringify(query.value)
  };
  
  const response = await proxy.$axios.get(url, param);
  if (response.data.code == 0) {
    tableData.value = response.data.data.records.map(item => ({
      ...item,
      canDelete: String(item.addId) === currentUserId
    }));
    console.log('列表数据', tableData.value);
    totalRows.value = response.data.data.total;
  } else {
    showToast({
      type: 'error',
      message: '操作失败！' + response.data.msg
    });
  }
};

// 刷新
const onRefresh = () => {
  basicReset();
  onLoad();
};

// 加载数据
const onLoad = async () => {
  if (isRefreshing.value) {
    resultData.value = [];
    currentPage.value = 1;
    isRefreshing.value = false;
  }

  try {
    await getTableData();

    if (pageSize.value * currentPage.value < totalRows.value) {
      resultData.value = [...resultData.value, ...tableData.value];
      openStatus.value = new Array(resultData.value.length).fill(true);
      currentPage.value++;
    } else {
      resultData.value = [...resultData.value, ...tableData.value];
      openStatus.value = new Array(resultData.value.length).fill(true);
      isFinished.value = true;
    }

    console.log('resultData', resultData.value);
  } catch (error) {
    console.log(error);
    isFinished.value = true;
  } finally {
    isLoading.value = false;
  }
};

// 重置列表
const basicReset = () => {
  isFinished.value = false;
  isLoading.value = true;
  currentPage.value = 1;
  resultData.value = [];
};

// 清空搜索
const handleClearSearch = () => {
  query.value.projectName = '';
  onRefresh();
};

// 新增
const handAdd = () => {
  router.push({ 
    path: "/projectList",
    query: { mark: -1 } 
  });
};

// 编辑/查看
const edits = async (row) => {
  const currentUserId = localStorage.getItem('userId');
  const addId = row.addId;
  const isOwner = String(addId).trim().toLowerCase() === String(currentUserId).trim().toLowerCase();

  // 更新浏览量
  await updateViewCount(row);

  router.push({ 
    path: "/projectList",
    query: {
      mark: 1,
      data: JSON.stringify(row),
      readOnly: !isOwner ? 'true' : undefined
    } 
  });
};

// 更新浏览量
const updateViewCount = async (item) => {
  try {
    const payload = { ...item };
    payload.viewCount = String((Number(payload.viewCount) || 0) + 1);

    const url = '/sgsafe/Manager/saveProject';
    const param = {
      json: JSON.stringify(payload)
    };

    const response = await proxy.$axios.post(url, param);
    if (response.data.code === '0' || response.data.code === 0) {
      const index = resultData.value.findIndex(data => data.id === item.id);
      if (index !== -1) {
        resultData.value[index].viewCount = payload.viewCount;
      }
    }
  } catch (error) {
    console.error('更新浏览量失败:', error);
  }
};

// 删除
const handleDelete = (item) => {
  const currentUserId = localStorage.getItem('userId');
  const addId = item.addId;
  
  if (!currentUserId || !addId || String(addId).trim() !== String(currentUserId).trim()) {
    showToast({
      type: 'warning',
      message: '无权限删除！只能删除自己添加的案例。'
    });
    return;
  }
  
  showDialog({
    title: '删除确认',
    message: `确定要删除项目"${item.projectName}"吗？删除后将无法恢复。`,
    showCancelButton: true,
    confirmButtonText: '确定删除',
    cancelButtonText: '取消',
  }).then(() => {
    executeDelete(item);
  }).catch(() => {
    console.log('取消删除');
  });
};

// 执行删除
const executeDelete = (item) => {
  const deleteData = { ...item };
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  deleteData.cancelTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  deleteData.cancelFlag = '1';
  
  const url = '/sgsafe/Manager/saveProject';
  const param = {
    json: JSON.stringify(deleteData)
  };
  
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == '0' || response.data.code === 0) {
      showSuccessToast("删除成功");
      onRefresh();
    } else {
      showToast({
        type: 'fail',
        message: '删除失败：' + (response.data.msg || '未知错误')
      });
    }
  }).catch(error => {
    showToast({
      type: 'fail',
      message: '删除失败：网络错误'
    });
    console.error('删除失败:', error);
  });
};

// 滑动单元格控制
const openStatus = ref([]);
const swipeCellRefs = ref([]);

const getSwipeCellRef = (el, index) => {
  if (el) {
    swipeCellRefs.value[index] = el;
  }
};

const openSwipe = (idx) => {
  openStatus.value = new Array(resultData.value.length).fill(true);
  if (idx >= 0 && idx < swipeCellRefs.value.length) {
    openStatus.value[idx] = false;
    swipeCellRefs.value[idx].open('right');
  }
};

const closeSwipe = (idx) => {
  if (idx >= 0 && idx < swipeCellRefs.value.length) {
    openStatus.value[idx] = true;
    swipeCellRefs.value[idx].close();
  }
};
</script>

<style scoped>
.h5-container {
  width: 100%;
  padding: 5px;
  box-sizing: border-box;
}

.cell-title {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.5;
  max-height: calc(1.5em * 2);
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.swipe-cell-default {
  display: flex;
  background-color: #ffffff;
  justify-content: center;
  align-items: center;
}

.swipe-cell-default-icon {
  width: 60px;
  display: flex;
  justify-content: center;
}

.delete-button {
  height: 100%;
  border: none;
  color: #ff0000;
  background-image: url('@/assets/img/del.png');
  background-size: auto 100%;
  background-repeat: no-repeat;
}
</style>