<template>
  <MOSTY.PageTable :table-columns="tableColumns" :tableData="tableData" heightnum="55vh" :tableloading="tableloading"
    :showselection="true" page-title="隐患清单" :search-type="'01'" @getDeptId="getDeptId"
    @selection-change="handleSelectionChange" :selectable="customSelectable" :displayMode="props.displayMode">
    <template #header>
      <ul class="top_box">
        <li v-for="item in topList" :key="item" :class="liBgClassName == item.value ? 'active_bg' : ''"
          @click="clickLiFn(item)">
          <div :class="getClassName(item.value)" class="count_num">
            {{ item.count }}
          </div>
          <div class="count_text">{{ item.text }}</div>
        </li>
      </ul>
    </template>
    <template #card>
      <div class="card" v-for="(item, index) in cardData" :key="index">
        <div class="card1">{{ item?.shortid || '-' }}</div>
        <div class="card2">
          <div class="card2-0">{{ item?.pitfallDescribe || '-' }}</div>
          <div class="card2-1">
            <div class="card2-1-1">发现人:{{ item?.founderName || '-' }}</div>
            <div class="card2-1-1">隐患等级: <span :class="`level-${item.pitfallLevel}`">
                {{ getPitfallLevelLabel(item.pitfallLevel) }}
              </span></div>
          </div>
          <div class="card2-2">
            <div class="card2-2-2">发现时间:{{ item?.founderTime || '-' }}</div>
            <div class="card2-2-2">所属单位:{{ item?.founderOrgname || '-' }}</div>
            <div class="card2-2-2">所属部门:{{ item?.founderDeptname || '-' }}</div>
          </div>
        </div>
        <div class="card3">
          <div class="card3-left" :class="item.finishFlag == '3' ? 'resolved' : 'pending'">
            <div>{{ item.finishFlag == '3' ? '已整改' : item.nextstaename }}</div>
          </div>
          <div class="card3-right">
            <div class="card3-right-1">
              <!-- <div @click="handlecl(item)" v-if="item.finishFlag == '2'">处理</div> -->
            </div>
            <div class="card3-right-2">
              <div @click="configuration(item)">查看</div>
            </div>
            <!-- 删除按钮 -->
            <div class="card3-right-2"></div>
            <el-popconfirm v-if="getItem('USERID') == '000000'" confirm-button-text="是" cancel-button-text="否"
              icon-color="red" title="注意：将删除所有对应日志，任务，整改方案，落实验证情况，确定删除?" @confirm="handsystemleDel(item)">
              <template #reference>
                <div class="card3-right-2 card-delete">
                  <div>删除</div>
                </div>
              </template>
            </el-popconfirm>
          </div>
        </div>
      </div>
    </template>
    <template #serach>
      <el-date-picker v-model="monthTime" type="monthrange" range-separator="至" format="YYYY-MM" date-format="YYYY-MM"
        value-format="YYYY-MM" style="width: 250px;margin-right: 5px;" />
      <el-input v-model="listQuery.keywordss" placeholder="请输入检查对象/检查人/隐患描述/进行查询"
        style="width: 280px;margin-right: 5px;" />
      <el-select v-model="listQuery.finishFlag" clearable placeholder="请选择整改状态进行查询" style='width: 250px;' class="mr20">
        <el-option v-for="obj in D_BZ_YHZGZT" :key="obj.value" :label="obj.label" :value="obj.value" />
      </el-select>
      <el-button style="margin-left: 2px" type="primary" @click="batchRectify">
        <el-icon>
          <EditPen />
        </el-icon>
        <span>批量整改{{ selectedRows?.length || '' }}</span>
      </el-button>
      <el-button style="margin-left: 10px" type="primary" @click="addUserHander">
        <el-icon>
          <Search />
        </el-icon>
        <span>查询</span>
      </el-button>
      <el-button style="margin-left: 10px" type="primary" @click="onloadExcel" v-loading="loadingShow">
        <el-icon>
          <House />
        </el-icon>
        <span>导出</span>
      </el-button>
      <el-button @click="onAdd">
        <el-icon>
          <Plus />
        </el-icon>
        <span>新增</span>
      </el-button>
    </template>

    <template #sourcetype="{ row }">
      <dict-tag :options="D_BZ_YHLX" :value="row.sourcetype" :tag="false"></dict-tag>
    </template>
    <template #pitfallLevel="{ row }">
      <dict-tag :options="D_DBZ_YHDJ" :value="row.pitfallLevel" :tag="false" />
    </template>
    <template #statename="{ row }">
      <span v-if="row.finishFlag == '3'">已整改</span>
      <span v-else>{{ row.nextstaename }}</span>
    </template>
    <template #actions="{ row }">
      <span class="operesee" @click="configuration(row)"
        :v-data-aa="`${row.belongCityid}-${row.belongCityid == '522610522601'}-${isQdNAqbm}`">
        <el-icon>
          <Compass />
        </el-icon>
        查看
      </span>
      <span class="operesee" @click="handlecl(row)" v-if="row.finishFlag == '2'">
        <el-icon>
          <EditPen />
        </el-icon>
        整改
      </span>
      <!-- 黔东南信息 只能黔东南安全科改,且非县公司（省公司安全科也可以改，目前除了省安全科可以看全部，都是自己看自己数据，） -->
      <el-popconfirm
        v-if="row.becheckedOrgid && row.becheckedOrgid.indexOf('5226105226') == '0' ? isAqbm && !isxgs : isAqbm"
        confirm-button-text="是" cancel-button-text="否" icon-color="red" title="注意：将删除所有对应日志，任务，整改方案，落实验证情况，确定删除?"
        @confirm="handleDel(row)">
        <template #reference>
          <span class="operdel" size="small">
            <el-icon>
              <Delete />
            </el-icon>
            删除</span>
        </template>
      </el-popconfirm>
    </template>
    <template #fenye>
      <div class="fenye" :style="{ top: tableHeight + 'px' }">
        <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="listQuery.pageCurrent" :page-sizes="[2, 5, 10, 20]" :page-size="listQuery.pageSize"
          layout="total, prev, pager, next, sizes, jumper" :total="total"></el-pagination>
      </div>
    </template>
  </MOSTY.PageTable>

  <!-- 【详情】 ，【审核】 -->
  <div v-if="comprehensiveShow" class="dialog-box">
    <Ckyhjd @changePage="changePage" :editObj="editObj.editObj" />
  </div>
  <div v-if="isShowAdd" class="dialog-box">
    <addPage @ok="addOk" @close="addClose" />
  </div>
  <!-- 整改 -->
  <div v-if="showclzdfa" class="dialog-box">
    <Clzgfa @changePage="closeclzgfa" :Rowobj="Rowobj" :type="type" />
  </div>

</template>

<script setup>
// 引入
import { reactive, onMounted, watch, ref, getCurrentInstance, defineProps, computed } from "vue";
import { getApi, deleteApi, putApi, postApi } from "@/api/tobAcco_api.js";
import { dateFormat } from "../../../utils/tools";
import Ckyhjd from "./components/ckyhjd.vue";
import addPage from "./components/addPage.vue";
import Clzgfa from "./components/clzgfa.vue";
import { getItem } from "@/utils/storage";
import { exportXlsx } from "@/excel/Export2Excel.js";
import * as XLSX from "xlsx";
import * as MOSTY from "@/components/MyComponents/index";
import { ElMessage } from "element-plus"
import { useRoute, useRouter } from "vue-router";
import { filterqx } from "@/utils/auth.js";// isSgs,isgs,isxgs,isaqbm,isldbz
import { getMultiDictVal } from "../../../utils/dict.js"
import { string } from "html-docx-js/dist/html-docx";
const props = defineProps({
  displayMode: {
    type: string,
    default: ''
  }
})
// 数据
//查询条件
const { proxy } = getCurrentInstance();
const route = useRoute();
const router = useRouter();

const { D_DBZ_YHDJ, D_BZ_YHLX, D_BZ_YHZGZT } = proxy.$dict("D_DBZ_YHDJ", "D_BZ_YHLX", "D_BZ_YHZGZT");
const emits = defineEmits("close");
const loadingShow = ref(false);
const isShowAdd = ref(false)
const deptId = ref(getItem("deptId"));
/** 是否是安全部门 */
const isAqbm = ref(filterqx('isaqbm') === '1')
/** 是否是 【黔东南】安全科或者【省公司】安全科 (黔东南的数据只能被黔东南安全科，或者省公司安全科可以删)*/
const isQdNAqbm = ref(filterqx('isaqbm') === '1' && (deptId.value.ssdwdm === '522610522601' || filterqx('isSgs') == '1'))
const isxgs = ref(filterqx('isxgs') === '1')
const monthTime = ref([
  dateFormat({ type: "one", time: new Date() }),
  dateFormat({ type: "month", time: new Date() })
]);
const editObj = reactive({
  editObj: null
})
const tableHeight = ref();
const bigHeight = ref(); //整个高度
const total = ref(0);
const comprehensiveShow = ref(false);
const liBgClassName = ref("");
const tableColumns = ref([
  {
    title: "隐患编号",
    prop: "shortid"
  },
  {
    title: "检查类型",
    prop: "sourcetype",
    slot: true
  },
  {
    title: "发现时间",
    prop: "founderTime"
  },
  {
    title: "隐患描述",
    prop: "pitfallDescribe"
  },
  {
    title: "检查对象",
    prop: "objname"
  },
  {
    title: "检查人",
    prop: "founderName"
  },
  {
    title: "责任人",
    prop: "dutyUsername"
  },

  {
    title: "隐患等级",
    prop: "pitfallLevel",
    slot: true
  },
  {
    title: "整改落实情况",
    prop: "statename",
    slot: true

  },
  {
    title: "操作",
    prop: "actions",
    slot: true,
    width: "250px"
  }
]);
const topList = ref([
  {
    text: "重大隐患",
    count: "0",
    value: "1"
  },
  {
    text: "较大",
    count: "0",
    value: "2"
  },
  {
    text: "一般",
    count: "0",
    value: "3"
  },
  {
    text: "轻微",
    count: "0",
    value: "4"
  },
  {
    text: "已整改",
    count: "10",
    value: "5"
  },
  {
    text: "未整改",
    count: "0",
    value: "6"
  }
]);
const tableData = ref([]);
const tableloading = ref(false);
const listQuery = ref({
  keywordss: "",
  finishFlag: "",
  pageCurrent: 1,
  pageSize: 10,
  startTime: monthTime.value[0],
  endTime: monthTime.value[1],
  ssbmid: null
});

onMounted(() => {
  tabHeightFn();
  bigHeightFn();
  getcount()
  getDataList();
  // 如果是卡片模式，同时获取卡片数据
  // if (props.displayMode === 'card') {
  //   getCardDataList();
  // }
  // 去审核
  if (route.query.id) goToAudit(route.query)
});
const bigHeightFn = () => {
  bigHeight.value = window.innerHeight - 147 + "px";
};
const clickLiFn = (val) => {
  liBgClassName.value = val.value;
  if (['1', '2', '3', '4'].includes(val.value)) {
    listQuery.value.pitfallLevel = val.value
    listQuery.value.finishFlag = ''
  }
  if (val.value == '5') {
    listQuery.value.finishFlag = '3'
    listQuery.value.pitfallLevel = ''
  }
  if (val.value == '6') {
    listQuery.value.finishFlag = '2'
    listQuery.value.pitfallLevel = ''
  }
  if (props.displayMode === 'card') {
    getCardDataList();
  } else {
    getDataList();
  }


};
function changePage (e, obj = {}) {
  comprehensiveShow.value = false
  if (route.query.id) router.replace({ path: '/fxgk/jcss', query: { tabtype: '69' } })//地址还原
  if (obj?.refresh) {
    getDataList()
  }
}
const onAdd = (row) => {
  isShowAdd.value = true
}
const addClose = () => {
  isShowAdd.value = false
}
const addOk = () => {
  isShowAdd.value = false
  // 刷新
  listQuery.pageCurrent = 1;
  getcount()
  getDataList()
}
// 配置
const configuration = (row) => {
  editObj.editObj = row
  comprehensiveShow.value = true;
};
const handleDel = (row) => {
  postApi({}, `/mosty-jcgl/yhb/delYh/${row.id}`).then(res => {
    ElMessage.success("删除成功");
    // 刷新列表
    listQuery.pageCurrent = 1;
    getcount()
    getCardDataList()
    getDataList()
  })
}
// 系统管理员删除
const handsystemleDel = (row) => {
  postApi({}, `/mosty-jcgl/yhb/delYh/${row.id}`).then(res => {
    ElMessage.success("删除成功");
    // 刷新列表
    listQuery.pageCurrent = 1;
    getcount()
    getCardDataList()
    getDataList()
  })
}
function addUserHander () {
  listQuery.value.pageCurrent = 1;
  getcount();
  getDataList(); // 列表模式数据
}
function getcount () {
  let obj = {
    startTime: monthTime.value[0],
    endTime: monthTime.value[1],
    ssbmid: listQuery.value.ssbmid
  }
  getApi(obj, '/mosty-jcgl/yhb/yhtz/statistics').then(res => {
    topList.value[0].count = res.count1;
    topList.value[1].count = res.count2;
    topList.value[2].count = res.count3;
    topList.value[3].count = res.count4;
    topList.value[4].count = res.countY;
    topList.value[5].count = res.countW;

  })
}
//获取列表数据
function getDataList () {
  tableloading.value = true;
  listQuery.value.startTime = monthTime.value[0];
  listQuery.value.endTime = monthTime.value[1];
  getApi(listQuery.value, "/mosty-jcgl/yhb/yhtz/getPage")
    .then((res) => {
      if (res.records) {
        tableloading.value = false;
        tableData.value = res.records;
        total.value = res.total;
      }
    })
    .catch((err) => {
      tableData.value = [];
      tableloading.value = false;
    });
}
// 表格高度计算
const tabHeightFn = () => {
  tableHeight.value = window.innerHeight - 310;
};
function getDeptId (val) {
  listQuery.value.ssbmid = val;
  getDataList();
  getcount()
  if (props.displayMode === 'card') {
    getCardDataList();
  }
};


const getClassName = (val) => {
  switch (val) {
    case "1":
      return "red";
      break;
    case "2":
      return "orange";
      break;
    case "3":
      return "yellow";
      break;
    case "4":
      return "blue";
      break;
    case "5":
      return "green";
      break;
    case "6":
      return "pink";
      break;
  }
};

//分页
const handleSizeChange = (currentSize) => {
  listQuery.value.pageSize = currentSize;
  getDataList();
};
const handleCurrentChange = (currentPage) => {
  listQuery.value.pageCurrent = currentPage;
  getDataList();
};
function onloadExcel () {
  loadingShow.value = true;
  let title = {
    shortid: "隐患编号",
    objname: "检查对象",
    founderName: "检查人",
    pitfallDescribe: "隐患描述",
    _sourcetype: "检查类型",
    pitfallLevels: "隐患等级",
    founderTime: "发现日期",
    founderOrgname: "发现单位或部门",
    reformMeasure: "整改措施",
    becheckedOrgname: "隐患所属单位或部门",
    dutyUsername: "整改责任人",
    planOvertime: "限期整改时间",
    execution: "整改完成情况",
    signUsername: "整改验证人",
    budgetAmount: "整改投资金",
    bz: "备注",
  };
  let obj = { ...listQuery.value }
  obj.pageSize = 100000
  getApi(obj, "/mosty-jcgl/yhb/yhtz/exportData").then((res) => {
    if (res) {
      let data = res;
      if (data) {
        for (let i = 0; i < data.length; i++) {
          data[i].pitfallLevels = getMultiDictVal(data[i].pitfallLevel, D_DBZ_YHDJ.value)
          data[i]._sourcetype = getMultiDictVal(data[i].sourcetype, D_BZ_YHLX.value)

        }
        const timeStr = `${monthTime.value?.[0] || ' '} - ${monthTime.value?.[1] || ''}`
        let tablename = "隐患排查治理登记台账.xlsx";
        exportXlsx(title, data, `隐患排查治理登记台账 (时间段： ${timeStr})`, tablename);
      }
    }
  }).finally(() => {
    loadingShow.value = false
  })
}

const goToAudit = (query) => {
  editObj.editObj = { id: query.id, isAudit: true, rwlx: query.rwlx }
  comprehensiveShow.value = true;
};


// 添加选择条件方法
const customSelectable = (row, index) => {
  // 只有未整改的才能选择
  return row.finishFlag === '2';
};
const showclzdfa = ref(false)
const Rowobj = ref(null)
const type = ref(null)
// 整改
const handlecl = (row) => {
  Rowobj.value = row;
  type.value = '01';
  showclzdfa.value = true;
}
const closeclzgfa = (val) => {
  showclzdfa.value = false;
  Rowobj.value = null;
  getDataList();
  if (route.query.tab == 'yhtz') { router.go(-1) }
  // router.replace({ path: '/fxgk/jcss/yhtz' })//地址还原
}
const selectedRows = ref([]); // 存储选中的行数据
// 选中行数据
const handleSelectionChange = (val) => {
  selectedRows.value = val;

}
//批量整改按钮的点击事件
const batchRectify = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要整改的隐患');
    return;
  }

  // 验证选中的隐患是否都是未整改状态
  const hasInvalid = selectedRows.value.some(row => row.finishFlag !== '2');
  if (hasInvalid) {
    ElMessage.warning('只能选择未整改的隐患进行批量操作');
    return;
  }


  // 如果需要打开整改弹窗，可以这样：
  Rowobj.value = {
    batchData: selectedRows.value,
    isBatch: true
  };
  type.value = '01';
  showclzdfa.value = true;
}

const getPitfallLevelLabel = (value) => {
  const option = D_DBZ_YHDJ.value.find(item => item.value === value);
  return option ? option.label : value;
};
// 在script setup中添加
const cardData = ref([]); // 专门用于卡片模式的数据
const cardLoading = ref(false);

// 专门为卡片模式获取所有数据的方法
function getCardDataList () {
  cardLoading.value = true;
  const queryParams = {
    ...listQuery.value,
    pageSize: 10000, // 获取所有数据
    pageCurrent: 1,
    startTime: monthTime.value[0],
    endTime: monthTime.value[1],

  };
  getApi(queryParams, "/mosty-jcgl/yhb/yhtz/getPage")
    .then((res) => {
      if (res.records) {
        cardLoading.value = false;
        cardData.value = res.records;
      }
    })
    .catch((err) => {
      cardData.value = [];
      cardLoading.value = false;
    });
}
</script>

<style lang="scss" scoped>
.el-table__body-wrapper is-scrolling-left {
  border: none;
}

.el-table__row {
  line-height: 21px;
}

.el-table th,
.el-table td {
  padding: 4px 8px;
}

.el-table__body-wrapper is-scrolling-left .cell {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.el-dialog__headerbtn {
  margin-top: -6px !important;
}

.el-dialog__headerbtn .el-dialog__close {
  font-size: 27px !important;
}

.bigBox {
  display: flex;
  background-color: #f0f3f4;

  .title {
    height: 45px;
    line-height: 45px;
    font-size: 18px;
    color: #0f3916;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .zzjgxx {
      font-size: 18px;
      font-weight: 400;
      color: #0f3916;
      line-height: 24px;
    }

    .el-icon {
      cursor: pointer;
    }
  }

  .cent {
    width: 100%;
    text-align: center;

    .el-form {
      margin-left: 27%;
    }
  }

  .left {
    width: 300px;
    // height: 1030px;
    background: #ffffff;
    box-shadow: 0px 2px 10px 0px rgba(107, 107, 107, 0.1);
    border-radius: 0px 0px 0px 0px;
    opacity: 1;

    .treeBox {
      overflow: auto;
    }
  }

  .right {
    // width: calc(100% - 300px);
    padding: 0 10px;
    margin: 0px 14px;
    background: #fff;

    .headBox {
      height: 60px;
      display: flex;
      justify-content: space-between;
      position: relative;
      z-index: 2;

      .el-select {
        width: 150px;
      }

      .btnBox {
        display: flex;
        width: 500px;
        justify-content: space-between;
        align-items: center;
      }
    }
  }
}

.top_box {
  display: flex;
  justify-content: space-between;
  text-align: center;

  li {
    width: 15%;
    background: #eee;
    padding: 0 0 10px 0;
    margin-right: 14px;

    .count_num {
      height: 40px;
      line-height: 40px;
      font-size: 24px;
      font-weight: 600;
    }

    .count_text {
      color: #000;
      margin-top: 10px;
    }
  }
}

.red {
  background: red;
}

.orange {
  background: orange;
}

.yellow {
  background: #e7e71c;
}

.green {
  background: green;
}

.pink {
  background: rgb(0, 157, 255);
}

.blue {
  background: blue;
}

.tabBox {
  height: calc(100% - 70px);
  border-left: 0 !important;

  .el-table {
    height: 91%;
  }

  .fenye {
    top: 95%;
  }
}

.btn {
  padding: 10px;
  float: right;
}

.active_bg {
  border: 1px solid skyblue;
}

.card {
  box-sizing: border-box;
  max-height: 240px;
  display: flex;
  flex-direction: column;
  border: 1px solid #ccc;
  padding: 10px;
  margin: 5px;
  width: calc(25% - 10px);


  .card1 {
    height: 30px;
    margin-bottom: 5px;
    line-height: 30px;
    border-bottom: 1px solid #ccc;
  }

  .card2 {
    max-height: 150px;
    flex: 1;
    margin-bottom: 5px;
    border-bottom: 1px solid #ccc;

    .card2-0 {
      margin-bottom: 5px;
    }

    .card2-1 {
      display: flex;
      margin-bottom: 5px;
      justify-content: space-between;
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
    }

    .card2-2 {
      display: flex;
      flex-direction: column;
      gap: 5px;
      margin-bottom: 5px;
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
    }
  }

  .card3 {
    height: 30px;
    line-height: 30px;
    display: flex;

    .card3-left {
      margin-left: 10px;
      position: relative;
      width: 60%;

      div {
        overflow: hidden; // 必须：隐藏溢出内容
        text-overflow: ellipsis; // 必须：显示省略号
        white-space: nowrap; // 必须：禁止换行

      }

      &::after {
        content: '';
        position: absolute;
        top: 50%;
        left: -13px;
        transform: translateY(-50%);
        width: 10px; // 稍微大一点更明显
        height: 10px;

        border-radius: 50%;
      }

      &.pending {
        color: red;

        &::after {
          background-color: red;
        }
      }

      &.resolved {
        color: #1890ff; // 蓝色字体

        &::after {
          background-color: #1890ff; // 蓝色圆点
        }
      }
    }

    .card3-right {
      cursor: pointer;
      flex: 1;
      display: flex;
      gap: 10px;
      justify-content: end;

      .card3-right-1 {
        color: #007457;
      }

      .card3-right-2 {
        color: #1890ff; // 蓝色字体
      }

      .card-delete {
        color: #e71111;
        cursor: pointer;
      }

      .card-delete:hover {
        color: #f78989;
      }
    }
  }
}

.level-1 {
  color: #ff4d4f; // 重大隐患 - 红色
  font-weight: bold;
}

.level-2 {
  color: #fa8c16; // 较大隐患 - 橙色
  font-weight: bold;
}

.level-3 {
  color: #faad14; // 一般隐患 - 黄色
}

.level-4 {
  color: #52c41a; // 轻微隐患 - 绿色
}

// 如果没有匹配的等级，使用默认颜色
.level-default {
  color: #666;
}
</style>
