<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.caseTitle" show-action placeholder="请输入案例标题" @search="onRefresh"
                @cancel="handdelectTitle" />

    <!-- 项目列表 -->
    <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: 100px; padding: 0 0 0 0; display: flex; align-items: flex-start;" @click="edits(item)">
                  <template #title>
                    <div class="cell-title">
                      {{ item.caseTitle }}
                    </div>
                  </template>
                  <template #label>
                      <div>案例编号：{{ item.caseNumber }} </div>
                      <div>案例类型：{{ item.caseType }}</div>
                      <div> 浏览量：{{item.viewCount}}</div>

<!--                    <div style="width: 112px" :class="getStatusClass(item.isFinish)">
                      类型：
                      <span v-if="item.isFinish === '待学习'" style="width: 200px">待学习</span>
                      <span v-else-if="item.isFinish === '已学习'" style="width: 200px">已学习</span>
                      <span v-else-if="item.isFinish === '已扣除'" style="width: 200px">已扣除</span>
                    </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  square class="delete-button" text="删除" v-show="item.canDelete"  @click="handleDelete(item)" />
            </template>
          </van-swipe-cell>
        </div>

      </van-list>
    </van-pull-refresh>

    <!-- 删除确认弹窗 -->
    <van-dialog v-model:show="deleteDialogVisible" show-cancel-button @confirm="confirmDelete">
      <template #title>
        <div>删除确认</div>
      </template>
      <div style="padding: 30px;">确定要删除该项目吗？</div>
    </van-dialog>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance, nextTick, toRaw } from 'vue';
import { Dialog, showDialog, showSuccessToast, showToast, Toast } from 'vant';

import tools from '@/tools'

const { proxy } = getCurrentInstance();

const onClickLeft = () => {
  history.back();
};
const headers = ref({
  token: localStorage.getItem('token'),
  userId: localStorage.getItem('userId'),
  dept: JSON.parse(localStorage.getItem('dept'))[0].deptCode
});
const switchIconState = (idx) => {
  openStatus.value[idx] = !openStatus.value[idx]
  openStatus.value = new Array(resultData.value.length).fill(true);
}

// const onClickRight = () =>{
//   searchShow.value = !searchShow.value;
// }

const searchShow = ref(false);
const query = ref({
  caseNumber:'',
  caseTitle:'',
})



const tableData = ref([]);
const selectedRows = ref([]);
const dialogVisibleLook = ref(false);
const deleteDialogVisible = ref(false);
const currentDeleteItem = ref([]);
const dialogVisible = ref(false);
const dialogVisibleFile = ref(false);
const date = ref(null);

const kz = ref(true);
import { useRouter } from 'vue-router';
const router = useRouter();
const handAdd =  () => {

  router.push({ path: "/managerList",
    query: {
      mark:-1
    } });

};
const goaddPeo = (item) => {
  router.push({
    path: '/addPeo',
    query: {
      data: JSON.stringify(item)
    }
  })
}

const edits = (row) => {
  const isOwner = String(row.addId) === currentUserId;
  kz.value = true;
  form.value = { ...row };
  router.push({ path: "/managerList",
    query: {
      mark:1,
      data:JSON.stringify(form.value),
      readOnly: !isOwner ? 'true' : undefined
    } });
  //浏览量
  saveManagerRecord(form.value)
};

const saveManagerRecord = async (formValue) => {
  const payload = formValue;
  payload.viewCount = String((Number(payload.viewCount) || 0) + 1);

  var url = '/sgsafe/Manager/save';
  var param = {
    json: JSON.stringify(payload)
  };
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == '0') {
      getTableData();
    }
  });
};
const form = ref({
  caseNumber:'',
  caseTitle:'',
  caseSource:'',
  accidentLevel:'',
  accidentDept:'',
  accidentLocation:'',
  accidentTime:'',
  accidentType:'',
  accidentTags:'',
  casualtyCount:'',
  accidentSummary:'',
  preventiveMeasures:'',
  fileId:'',
  viewCount:'',
  downloadCount:''
});


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 dept=localStorage.getItem("dept")[0].deptCode;
const currentUserId = String(localStorage.getItem('userId'));
const getTableData = async () => {
  var url = '/sgsafe/Manager/query'
  var 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 ruleIds = ref([]);

const onRefresh = () => {
  basicReset();
  onLoad();
};

//*************************************



//定义字典集合
const dicList = ref([])

const getDicList = () => {
  tools.dic.getDicList([ 'case_type','SEX', 'case_source','accident_level','accident_type','sgsafe_taccidentTags']).then((response => {
    console.log(JSON.stringify(response.data.data))
    dicList.value = response.data.data

  }))
}


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

  getDicList()





  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;
  }
};
/* 通用方法： 重置list数据 */
const basicReset = () => {
  isFinished.value = false;
  isLoading.value = true;
  currentPage.value = 1;
  resultData.value = [];
};

/*onMounted(() => {
  handleSearch();
});

const handleSearch = () => {
/!*  currentPage.value = 1;
  isFinished.value = false;
  tableData.value = [];*!/
  basicReset()
  onLoad()
};*/

const handdelectNumber = () => {
  query.value.caseNumber = '';
  onRefresh()
};

const handdelectTitle = () => {
  query.value.caseTitle = '';
  onRefresh()
};




// 定义生成编号的函数
const generateCode = () => {
  // 获取当前日期并格式化为 YYYYMMDD
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需加1
  const day = String(now.getDate()).padStart(2, '0');
  const formattedDate = `${year}${month}${day}`;
  // 时间部分：HHmmss
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  const formattedTime = `${hours}${minutes}${seconds}`;

  // 模拟生成三位流水号（可以根据需要替换为递增逻辑）
  const sequenceNumber = Math.floor(Math.random() * 1000); // 随机生成 0-999
  const paddedSequence = String(sequenceNumber).padStart(3, '0'); // 补零到三位

  // 拼接编号
  return `SGAL${formattedDate}${formattedTime}${paddedSequence}`;
};

// 使用 ref 存储生成的编号
const generatedCode = ref(generateCode());

// 定义重新生成编号的方法
const regenerateCode = () => {
  generatedCode.value = generateCode();
};

const handleDetailLook = (row) => {
  form.value = { ...row };
  proxy.$router.push({
    name: 'taiZhang_detail',
    query: {
      form: form.value.id
    }
  });
  // dialogVisibleLook.value = true;
};
const deleteData=ref({})

const handleDelete = (item) => {

  deleteData.value=item
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从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.value.cancelTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

    deleteData.value.cancelFlag='1'
  var url = '/sgsafe/Manager/save';
  var param = {
    json: JSON.stringify(deleteData.value)
  };
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == '0') {
      showSuccessToast("删除成功")
      onRefresh();

    } else {
    }

  })
};


const confirmDelete = () => {
  for (let item of currentDeleteItem.value) {
    if (item.addId !== headers.value.userId) {
      showToast({
        type: 'warning',
        message: '只能删除自己添加的数据！'
      });
      return;
    }
  }

  if (currentDeleteItem.value[0].status !== '0' && currentDeleteItem.value[0].hdSelect !== '下发隐患'
    && currentDeleteItem.value[0].hdSelect !== '即查即改') {
    showToast({
      type: 'fail',
      message: '只有尚未提交流程的记录或回到起点的流程经过作废后才可以删除！'
    });
    return;
  }
  if (currentDeleteItem.value[0].status !== '2' && currentDeleteItem.value[0].hdSelect === '下发隐患'
    && currentDeleteItem.value[0].hdSelect !== '即查即改') {
    showToast({
      type: 'fail',
      message: '只有尚未提交流程的记录或回到起点的流程经过作废后才可以删除！'
    });
    return;
  }

  var url = 'sgsafe/Hiddendanger/remove';
  var param = {
    params: JSON.stringify({ ...currentDeleteItem.value.map(x => x.id) })
  };
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == 0) {
      showToast({
        type: 'success',
        message: '删除成功'
      });
      onRefresh();
    } else {
      showToast({
        type: 'fail',
        message: '操作失败！' + response.data.msg
      });
    }
  });
};




const resetForm = () => {
  form.value = {
    projectName: '',
    projectLeader: '',
    phone: '',
    dept: ''
  };
};


//处理人员code
const repairLL = ref('');
const repairOO = ref('');
const acceptLL = ref('');

const jsons = ref({});

const reback = () => {
  // 返回逻辑
};

const deleteRow = (row) => {
  selectedRows.value = [row];
  handleDelete(row);
};

const deleteRowa = (row) => {
  deleteRow(row);
};

/**
 * 按钮实现swipe-cell滑动
 */
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')
  }
  document.addEventListener('click', handleDocumentClick)
}
/**
 * 当点击滑动单元格时，开始监听点击事件
 */
const handleDocumentClick = (event) => {
  openStatus.value = new Array(resultData.value.length).fill(true);
}

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;
}

.status-pending {
  background-color: #fff3cd;
  color: #856404;
  padding: 2px 4px;
  border-radius: 4px;
}

.status-registered {
  background-color: #d1ecf1;
  color: #0c5460;
  padding: 2px 4px;
  border-radius: 4px;
}

.status-analyzing {
  background-color: #fff8e1;
  color: #ff8f00;
  padding: 2px 4px;
  border-radius: 4px;
}

.status-rectifying {
  background-color: #e8f5e9;
  color: #2e7d32;
  padding: 2px 4px;
  border-radius: 4px;
}

.status-accepting {
  background-color: #e3f2fd;
  color: #1565c0;
  padding: 2px 2px;
  border-radius: 2px;
}

.status-closed {
  background-color: #f8bbd0;
  color: #b71c1c;
  padding: 2px 2px;
  border-radius: 2px;
}

.status-finished {
  background-color: #e8eaf6;
  color: #311b92;
  padding: 2px 2px;
  border-radius: 2px;
}

.status-unknown {
  background-color: #efebe9;
  color: #424242;
  padding: 2px 2px;
  border-radius: 2px;
}

.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;
}

.submit-button {
  height: 100%;
  border: none;
  color: #07c160;
  background-image: url('@/assets/img/sub.png');
  background-size: auto 100%;
  background-repeat: no-repeat;
}

.subsuccess {
  height: 100%;
  border: none;
  color: #07c160;
  background-image: url('@/assets/img/sub1.png');
  background-size: auto 100%;
  background-repeat: no-repeat;
}
.single-line-text {
  white-space: nowrap;        /* 强制不换行 */
  overflow: hidden;           /* 超出部分隐藏 */
  text-overflow: ellipsis;    /* 超出显示省略号 ... */
  width: 100%;                /* 或指定宽度 */
  box-sizing: border-box;
}
</style>
