<template>
  <MOSTY.PageTree :pageTitle="pageTitle" :searchType="'03'" @getDeptId="getdeptId">
    <template #serach>
      <el-divider />
      <MOSTY.Search :searchArr="searchArr" @submit="onSearch" @reset="reset">
        <template #searbox>
          <el-date-picker v-model="listQuery.starttime" type="date" value-format="YYYY-MM-DD" placeholder="请选择开始日期"
            style="width: 250px;height: 32px;" />
          <el-date-picker class="ml10" v-model="listQuery.endtime" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择结束日期" style="width: 250px;height: 32px;" />
        </template>
      </MOSTY.Search>
      <div class="flex just-end mb10">
        <el-button type="primary" @click="export2Excel" v-loading="exportLoading">
          <el-icon>
            <Download />
          </el-icon>
          <span>导出</span>
        </el-button>
      </div>
    </template>
    <template #table>
      <section ref="tableSectionRef" :style="{ height: `calc(100vh - ${tableTopHeight}px)` }">
        <MOSTY.Table :table-columns="data.tableColumn" :tableData="data.tableData" :tableloading="tableloading"
          :isSelect="false" :isSort="true" actionsW="300px" style="width: 100%;">
          <template #disposetype="{ row }">
            <dict-tag v-if="row.disposetype" :options="D_TB_SLLX" :value="row.disposetype" :tag="false" />
          </template>
          <template #actions="{ row }">
            <span class="operedit" @click="sl(row, '受理', 'sl')" v-if="row.state == '2' && isaqbm">
              <el-icon>
                <Brush />
              </el-icon>受理</span>
            <span class="operesee" @click="sl(row, '整改进度', 'zgjd')"
              v-if="['1', '3'].includes(row.disposetype) && row.state != '2'">
              <el-icon>
                <Compass />
              </el-icon>整改进度</span>
            <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="您确认要将该条记录取消光荣榜?"
              @confirm="setHonorRoll(row, '2')" v-if="row.ishonor == '1' && disposeType == '1'">
              <template #reference>
                <span class="operedit" size="small">
                  <el-icon>
                    <EditPen />
                  </el-icon>取消光荣榜</span>
              </template>
            </el-popconfirm>
            <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="您确认要将该条记录设置为光荣榜?"
              @confirm="setHonorRoll(row, '1')" v-if="row.ishonor != '1' && disposeType == '1'">
              <template #reference>
                <span class="operedit" size="small">
                  <el-icon>
                    <EditPen />
                  </el-icon>设置光荣榜</span>
              </template>
            </el-popconfirm>
            <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除?"
              @confirm="handledelete(row)" v-if="row.state == '2'">
              <template #reference>
                <span class="operdel" size="small">
                  <el-icon>
                    <Delete />
                  </el-icon>删除</span>
              </template>
            </el-popconfirm>
            <span class="operesee" @click="sl(row, '查看详情', 'ck')">
              <el-icon>
                <View />
              </el-icon>查看</span>
          </template>
        </MOSTY.Table>
      </section>
      <div class="fenye">
        <MOSTY.Pages :pageConfiger="data.pageConfiger" @changeNo="changeNo" @changeSize="changeSize" />

      </div>
    </template>
  </MOSTY.PageTree>

</template>

<script setup>
import * as MOSTY from "@/components/MyComponents/index";
import { getApi, deleteApi, putApi, postApi } from "@/api/tobAcco_api.js";
import { ElMessage } from "element-plus";
import { reactive, onMounted, ref, getCurrentInstance } from "vue";
import { useRoute, useRouter } from "vue-router";
// import { exportXlsx, exportXlsxByArr } from "@/excel/Export2Excel.js"
import { getValByDic } from "@/utils/tools.js"
import { ExpXlsx } from "@/excel/Export3Excel.js"

import { filterqx } from "@/utils/auth.js";// isSgs,isgs,isxgs,isaqbm,isldbz
const router = useRouter();
const { proxy } = getCurrentInstance();
const { D_TB_SLLX, D_TB_SBYHLB, D_DBZ_YHDJ } = proxy.$dict("D_TB_SLLX", "D_TB_SBYHLB", "D_DBZ_YHDJ");

/** 是否安全部门 */
const isaqbm = filterqx('isaqbm') == '1'
const zdlist = reactive({ D_TB_SLLX })
const emit = defineEmits("changePage");
const pageTitle = ref('随手拍列表')
const disposeType = ref('1')
const tableSectionRef = ref()
/** 导出 */
const exportLoading = ref(false)
/** table 顶部的高度 */
const tableTopHeight = ref('500')
const searchArr = reactive([
  {
    showType: "input",
    prop: "username",
    width: '250px',
    placeholder: "请输入记录人名称"
  },
  {
    showType: "select",
    prop: "state",
    width: '250px',
    // 已受理和未受理
    options: [
      {
        value: null,
        label: '全部'
      },
      {
        value: '1',
        label: '已受理'
      },
      {
        value: '2',
        label: '未受理'
      }
    ],
    placeholder: "请选择受理状态"
  }
]);
const listQuery = reactive({
  pageCurrent: 1,
  pageSize: 20,
  disposeType: ['01', '02']
});

const data = reactive({
  searchObj: {},
  tableData: [],
  tableColumn: [
    {
      title: "记录人部门",
      prop: "deptname",
    },
    {
      title: "记录人",
      prop: "username",
    },
    {
      title: "记录位置",
      prop: "sitename",
    },
    {
      title: "责任部门",
      prop: "sitedeptname",
    },
    {
      title: "记录时间",
      prop: "observetime",
    },
    {
      title: "处理人",
      prop: "disposepeoplename",
    },
    {
      title: "处理方式",
      prop: "disposetype",
      slot: true
    },
    {
      title: "操作",
      prop: "actions",
      slot: true
    }
  ],

  pageConfiger: {
    pageSize: 20,
    pageCurrent: 1,
    total: 0
  },
  grbParams: null //光荣榜参数
});
const searchDisposeType = ref(['1', '2'])

const getTableHeight = () => {
  let TableRef = tableSectionRef.value
  if (!TableRef) return 500
  let top = TableRef.getBoundingClientRect()?.top || 400
  return top + 65
}
onMounted(() => {
  tableTopHeight.value = getTableHeight()
  if (router.currentRoute.value.path == '/fxgk/yhbg') {
    pageTitle.value = '隐患报告列表'
    disposeType.value = '3'
    listQuery.disposeType = ['3']
  } else {
    pageTitle.value = '随手拍列表'
    disposeType.value = '1'
    listQuery.disposeType = ['1', '2']
    // 增加 受理类型搜索
    let serchObj = {
      showType: "select",
      prop: "disposeType",
      width: '250px',
      placeholder: "处理方式",
      options: [ // 1-隐患 2-靓点
        {
          value: '1',
          label: '隐患'
        },
        {
          value: '2',
          label: '靓点'
        }
      ],
    }
    searchArr.push(serchObj)
  }
  // getTableData();

});
//导出表格
const export2Excel = () => {
  let title = {
    indexNum: "序号", //
    siteorgname: "所属单位", //
    username: "记录人",
    deptname: "记录人部门",
    observedescribe: "描述",
    pitfallTypeText: "隐患类别",// pitfallType
    pitfallLevelText: "隐患级别", // D_DBZ_YHDJ
    observetime: "记录时间",
    sitedeptname: "隐患所属部门", // 隐患所属部门
    // sitename: "记录位置",
    // sitedeptname: "责任部门", // 隐患所属部门
    disposepeoplename: "受理人",
    disposetypeText: "受理方式",
    disposedescribe: "受理意见",
    stateText: "整改落实情况",
  }

  exportLoading.value = true;
  const params = {
    ...listQuery,
    pageCurrent: 1,
    pageSize: 10000,
    starttime: listQuery.starttime || '',
    endtime: listQuery.endtime || '',
  }
  /** 是否随手拍 */
  const isSsp = router.currentRoute.value.path != '/fxgk/yhbg'
  if (isSsp) {
    params.disposeType = searchDisposeType.value ? searchDisposeType.value : ['1', '2'];
  }
  postApi(params, `/mosty-jcgl/safetyobserve/getPageList`).then((res) => {
    if (res.records?.length) {// 随手拍或隐患报告统计表（样式）
      let tablename = isSsp ? "随手拍报告统计表" : "隐患报告统计表"
      let sheetName = isSsp ? "随手拍报告统计表" : "隐患报告统计表"

      let data = [...res.records]
      data = data.map((item, index) => {
        item.disposetypeText = item.disposetype == '2' ? '靓点' : '隐患' // 1 隐患 2靓点 3隐患
        item.pitfallTypeText = getValByDic(item.pitfallType, D_TB_SBYHLB.value) // 隐患类别
        item.pitfallLevelText = getValByDic(item.pitfallLevel, D_DBZ_YHDJ.value) // 隐患级别
        item.stateText = { 1: '已处理', 2: '未处理' }[item.state]
        item.indexNum = index + 1
        return item
      })
      // exportXlsx(title, data, sheetName, tablename, sheetName)
      const time = `${listQuery.starttime || ''} - ${listQuery.endtime || ''}`
      const secondcontent = ['', '', '', '', '', '', '', '', '', '', `统计时间段：${time} `, '', '']
      /** 数组转sheet之前执行 */
      const beforeToSheet = (sheet) => {
        const sheetArr = [sheet[0], secondcontent, ...sheet.slice(1)]
        return sheetArr
      }
      /** 在加入sheet之前执行修改样式 */
      const beforeAppendSheet = (ws, XLSXST) => {
        // 设置第二行时间样式
        for (let col = 0; col < secondcontent.length; col++) {
          const cell = XLSXST.utils.encode_cell({ r: 1, c: col });

          if (cell && ws[cell]) {
            ws[cell].s = {
              font: { name: "微软雅黑", sz: 12 },
              alignment: { vertical: "center", horizontal: "center" },
              border: {
                top: { style: "thin", color: { rgb: "D7D7D7" } },
                bottom: { style: "thin", color: { rgb: "000000" } },
                left: { style: "thin", color: { rgb: "D7D7D7" } },
                right: { style: "thin", color: { rgb: "D7D7D7" } }
              }
            }
          }
        }
        return ws
      }
      const merges = [
        { s: { r: 0, c: 0 }, e: { r: 0, c: 12 } },
        { s: { r: 1, c: 10 }, e: { r: 1, c: 12 } } // 合并时间统计列
      ]
      const titleWidth = {
        siteorgname: 200,
        observedescribe: 200,
        observetime: 180,
        sitedeptname: 200,
      }
      const rowsH = [30, 22, 25]
      ExpXlsx(title, data, tablename, { beforeToSheet, beforeAppendSheet, merges, titleWidth,rowsH })
    } else {
      ElMessage.warning("暂无数据")
      dcloading.value = false
    }
  }).finally(() => {
    exportLoading.value = false;
  });


}
function getdeptId(val) {
  listQuery.orgid = val.id
  getTableData()
}
const reset = () => {
  listQuery.starttime = null
  listQuery.endtime = null
}
const onSearch = (obj) => {
  listQuery.username = obj.username;
  listQuery.state = obj.state;
  searchDisposeType.value = obj.disposeType ? [obj.disposeType] : ['1', '2']
  listQuery.pageCurrent = 1;
  data.pageConfiger.pageCurrent = 1;
  getTableData();
}
//分页
const changeNo = (val) => {
  listQuery.pageCurrent = val;
  data.pageConfiger.pageCurrent = val;
  getTableData();
};
const changeSize = (val) => {
  listQuery.pageSize = val;
  data.pageConfiger.pageSize = val;
  getTableData();
};
const tableloading = ref(false);
// 查询数据
function getTableData() {
  tableloading.value = true;
  const params = {
    ...listQuery,
  }
  /** 是否随手拍 */
  const isSsp = router.currentRoute.value.path != '/fxgk/yhbg'
  if (isSsp) {
    params.disposeType = searchDisposeType.value ? searchDisposeType.value : ['1', '2'];
  }
  postApi(params, `/mosty-jcgl/safetyobserve/getPageList`).then((res) => {
    if (res.records) {
      data.tableData = res.records;
      tableloading.value = false;
      data.pageConfiger.total = res.total;
    } else {
      data.tableData = [];
      tableloading.value = false;
    }
  }).finally(() => {
    tableloading.value = false;
  });
}

//打开设置光荣榜弹窗
const setHonorRoll = (row, ishonor) => {
  const { id } = row;
  data.grbParams = { id, ishonor };
  onConfirmGrb()
};
//设置光荣榜
const onConfirmGrb = () => {
  if (!data.grbParams) return;
  postApi(data.grbParams, "/mosty-jcgl/safetyobserve/editHonor")
    .then((res) => {
      if (data.grbParams.ishonor === "2") {
        ElMessage.success("取消成功");
      } else {
        ElMessage.success("设置成功");
      }
      getTableData();
    })
};
// 受理 || 查看 || 整改进度
const sl = (row, title, type) => {
  if (type == 'ck') {
    let arr = {
      saveBtnShow: false,
      disposeType: disposeType.value,
      title,
      type,
      zdlist: zdlist,
      id: row?.id
    }
    emit("changePage", "AddOrEdite", arr);
  } else {
    let arr = {
      saveBtnShow: true,
      disposeType: disposeType.value,
      title,
      type,
      zdlist: zdlist,
      id: row?.id
    };
    emit("changePage", "AddOrEdite", arr);
  }

};
//删除
const handledelete = (row) => {
  postApi({}, `/mosty-jcgl/safetyobserve/del/${row.id}`).then((res) => {
    ElMessage.success("删除成功");
    getTableData();
  });
};

</script>

<style lang="scss" scoped>
.eltab4 {
  height: calc(100vh - 320px);
}

.btnBox {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 12px;
}
</style>
