<template>
  <div class="content scroll">
    <div class="box" v-if="props.isOpen">
      <div class="topper">
        <div class="sub-le">
          <div class="title">重点人员安全培训</div>
          <BaseTag :items="practitioners" :num="3" />
        </div>
      </div>
    </div>
    <div class="box">
      <div class="bottom" :style="{ height: `calc(100vh - ${props.isOpen ? 461 : 250}px)` }">
        <!-- <TimeCondition byTime="2024-05-25" :ywId="props.id" @change="onChange" :title="title + '台账'" :popover="popover"></TimeCondition> -->
        <TimeCondition :byTime="byTime" :ywId="props.id" :title="title + '台账'" :popover="popover" @change="onChange">
          <template #right>
            <div v-if="isProvinces">
              <!-- <el-popconfirm v-if="isShowCancelBtn" confirm-button-text="是" cancel-button-text="否" icon-color="red"
                title="若更新数据将重置，是否确认更新?" @confirm="manualUpdate(query.orgcode, true)">
                <template #reference>
                  <el-button type="primary" class="mr5" :disabled="isReportResult"
                    :loading="manual.loading">手动更新</el-button>
                </template>
</el-popconfirm> -->

              <el-popconfirm v-if="isShowCancelBtn" confirm-button-text="是" cancel-button-text="否" icon-color="red"
                title="是否确认上报?" @confirm="handleReport('provinces')">
                <template #reference>
                  <el-button :title="manual.disabled ? '需勾选所有行' : ''" type="primary" v-if="isShowBtn && uploadNum == 0"
                    :loading="loadingsb" :disabled="manual.disabled || isReportResult">首次上报</el-button>
                  <el-button type="primary" v-else-if="isShowBtn && uploadNum > 0" :loading="loadingsb"
                    :disabled="manual.disabled || isReportResult">修改上报</el-button>
                </template>
              </el-popconfirm>
              <el-button type="primary" style="margin-left: 5px !important;" @click="reportResult(true)"
                :loading='loadingcksbjg' v-if="IsCksbjg">查看上报结果</el-button>
            </div>
            <el-button type="primary" class="ml5 mr5" @click="onAdd">新增</el-button>
            <el-button type="primary" @click="handleExport">导出</el-button>
          </template>
        </TimeCondition>
        <el-table id="mergeTable" :data="tableData" style="width: 99%" border v-loading="loading"
          @selection-change="selectionChange" :header-cell-style="{ background: '#F6F6F6' }"
          height="calc(100% - 100px)">
          <el-table-column type="selection" width="55" :selectable="handleDisable" v-if="isShowCancelBtn" />
          <el-table-column label="企业名称" prop="baOrgName" fixed="left" width="250" />
          <el-table-column prop="traineeName" label="岗位类别" width="250" />
          <el-table-column prop="remark" label="姓名" />
          <el-table-column prop="neAnnualTotalHour" label="年度培训总学时" />
          <el-table-column prop="mainHeadTeachingQty" label="授课次数">
            <template #default="{ row }">
              <span v-if="row.traineeName == '主要负责人'">{{ row.mainHeadTeachingQty }}</span>
              <div v-else style="background: #afafaf !important;"></div>
            </template>
          </el-table-column>
          <el-table-column prop="gxTime" label="最后一次上报时间" />
          <el-table-column prop="status" label="当前上报状态" fixed="right">
            <template #default="{ row }">
              <span v-if="row.status == '0' && !isReportResult" style="color: red;">未上报</span>
              <span v-if="row.status == '1' && !isReportResult" style="color: green;">已上报</span>
              <span v-if="isReportResult" style="color: orange;">正在上报国家局</span>
              <span v-if="row.status == '99' && !isReportResult" style="color: green;">已上报</span>
            </template>
          </el-table-column>
          <el-table-column prop="sbcs" label="累计上报次数">
            <template #default="{ row }">
              <el-link type="primary" @click="handleHistory(row)">{{ row.sbcs }}</el-link>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="140" fixed="right">
            <template #default="{ row }">
              <el-popconfirm v-if="isShowCancelBtn && !isReportResult && row.status == '0'" confirm-button-text="是"
                cancel-button-text="否" icon-color="red" title="若更新数据将重置，是否确认更新?" @confirm="manualUpdate(row.orgCode)">
                <template #reference>
                  <el-link type="primary">更新</el-link>
                </template>
              </el-popconfirm>
              <el-popconfirm
                v-if="row.status == '0' && (isTown || isCity || isProvinces) && (row.orgCode === orgid) && isShowBtn"
                confirm-button-text="是" cancel-button-text="否" icon-color="red" title="是否确认上报?"
                @confirm="onUpdate(row, '1')">
                <template #reference>
                  <el-link type="primary">上报</el-link>
                </template>
              </el-popconfirm>
              <el-popconfirm
                v-if="row.status == '1' && (isTown || isCity || isProvinces) && (row.orgCode === orgid) && isShowBtn"
                confirm-button-text="是" cancel-button-text="否" icon-color="red" title="是否撤销上报?"
                @confirm="onUpdate(row, '0')">
                <template #reference>
                  <el-link>撤销</el-link>
                </template>
              </el-popconfirm>
              <el-link type="primary" v-if="row.status == '0' && !isReportResult" @click="onEdit(row)">编辑</el-link>
              <el-link type="primary" @click="onView(row)">查看</el-link>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
  <el-dialog v-model="dialogsbyy" :title="reportResultInfo?.dataname + '上报结果'" width="800px">
    <section v-if="reportResultInfo?.returnCode == '200' && !reportResultInfo.returnHttpCode">
      <section>上报人：{{ reportResultInfo.username }}</section>
      <section>上报时间：{{ reportResultInfo.sbsj }}</section>
      <section>上报结果：未出上报结果，请等待上报结果</section>
    </section>
    <section v-else-if="reportResultInfo?.returnCode !== '200' && !reportResultInfo.returnHttpCode">
      <section>上报人：{{ reportResultInfo.username }}</section>
      <section>上报时间：{{ reportResultInfo.sbsj }}</section>
      <section>上报结果：{{ reportResultInfo.returnMsg }}</section>
    </section>
    <section v-else-if="reportResultInfo?.returnCode == '200' && reportResultInfo?.returnHttpCode == '200'">
      <section>上报人：{{ reportResultInfo.username }}</section>
      <section>上报时间：{{ reportResultInfo.sbsj }}</section>
      <section>上报结果：上报成功</section>
    </section>
    <section v-else-if="reportResultInfo?.returnCode == '200' && reportResultInfo?.returnHttpCode != '200'">
      <section>上报人：{{ reportResultInfo.username }}</section>
      <section>上报时间：{{ reportResultInfo.sbsj }}</section>
      <section>上报结果：{{ reportResultInfo?.returnOperationResult }}</section>
    </section>
  </el-dialog>
  <SblsTable v-if="sblsVisible" :currCode="currOrgCode" :currTotal="currTotal" @close="sblsVisible = false"
    :params="query" />
  <Dialog :title="dialogTitle" @close="dialogClose" :detailId="currId" :isEdit="isEdit" v-if="dialogVisible"
    :orgObj="orgObj" />
</template>

<script setup>
import { onMounted, ref, reactive, nextTick, watch, computed } from "vue";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import BaseTag from "@/views/dataReportWork/org/components/baseTag";
import TimeCondition from "@/views/dataReportWork/components/TimeCondition";
import Dialog from "../components/tab0/Dialog.vue";
import SblsTable from '../components/tab0/SblsTable.vue'
import { getItem } from "@/utils/storage";
import { ElMessage, ElLoading } from "element-plus";
import { filterqx } from "@/utils/auth.js";
import { exportXlsx } from "./tabsTool/tab0Tool.js";
const currOrgCode = ref(null)
const currTotal = ref(null)
const orgObj = ref({})
const sblsVisible = ref(false)
const props = defineProps({ isOpen: Boolean, id: String, title: String });
const pageData = reactive({
  dateTable: [],
  columnTable: [
    { label: '企业名称', prop: 'baOrgName', fixed: 'left' },
    { label: '岗位类别', prop: 'traineeName' },
    { label: '姓名', prop: 'remark' },
    { label: '年度培训总学时', prop: 'neAnnualTotalHour' },
    { label: '授课次数', prop: 'mainHeadTeachingQty' },
    { label: '最后一次上报时间', prop: 'gxTime', fixed: 'right' },
    { label: '当前上报状态', prop: 'status', fixed: 'right' },
    { label: '累计上报次数', prop: 'sbcs', fixed: 'right' },
  ],
  listQuery: {
    pageNum: 1,
    pageSize: 2000,
  },
  ids: []
})
const timer = ref(null);
const popover = reactive({
  title: "",
  content: `
  填表说明：
1. 填报单位：省级单位名称；
2. 企业名称：各省级单位机关或下属单位名称；
3. 统计频次：半年；
4. 提交周期：上半年1月1日-6月30日、下半年7月1日-12月25日。
5. 数据统计范围： 填写本年度截止到当前统计周期的累计数据。
6. 企业主要负责人按照新《安全生产法》释义进行界定。
7. 填写各单位的主要负责人、安全分管领导的人员安全教育培训明细。
8. 主要负责人、安全分管领导的年度培训总学时：指年内参与各级组织的线上、线下安全培训的总学时。
  `
});

const uploadNum = ref(0);
const query = reactive({
  orgcode: getItem("deptId").ssdwid,
  year: "",
  bn: ''
});
const isReportResult = ref(false);
const loadingsb = ref(false);
const loading = ref(false);
const tableData = ref([]);
const dialogVisible = ref(false)
const practitioners = ref([]);
const currId = ref(null)
const dialogTitle = ref("");
const isEdit = ref(true)
const isSfsb = ref(false)
const isShowBtn = ref(false)
const isAutoReport = ref(false)
const isShowCancelBtn = ref(true)
const byTime = ref('')
const manual = reactive({
  loading: false,
  disabled: true,
  isReport: false,
});
const dialogsbyy = ref(false)
const IsCksbjg = ref(false)
const loadingcksbjg = ref(false)
const reportResultInfo = ref({})
let orgid = ref(getItem("deptId").ssdwid)
// 是否是省账号
const isProvinces = computed(() => {
  return filterqx('isaqbm') == '1' && filterqx("isSgs") == "1";
});
// 是否是省或者市账号
const isAuth = computed(() => {
  return filterqx("isaqbm") == "1" && (filterqx("isSgs") == "1" || filterqx("isgs") == "1") ? true : false;
});
// 是否是市账号
const isCity = computed(() => {
  return filterqx("isaqbm") == "1" && filterqx("isgs") == "1"
})
//县级账号
const isTown = computed(() => {
  return filterqx("isaqbm") == "1" && filterqx("isgs") != "1" && filterqx("isSgs") != "1"
})
// 是否是复烤厂账号
const isPlant = computed(() => {
  let code = getItem("deptId").ssdwid;
  return code.startsWith("5299");
});

const handleExport = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '导出中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  getApi(query, '/mosty-jcgl/data/export/manageTrainInfo').then(res => {
    if (res.length > 0) {
      for (let i = 0; i < res.length; i++) {
        res[i].neAnnualTotalHour = res[i].neAnnualTotalHour ? res[i].neAnnualTotalHour : 0;

      }

    }
    exportXlsx(res ? res : [], {}, popover.content)

  }).finally(() => {
    loading.close()
  })

}
// 是否可以选择多选
const handleDisable = (row, index) => {
  if (tableData.value.length) {
    if (index % 2 == 0) {
      const _nextRow = tableData.value[index + 1];
      if (isProvinces.value && !isReportResult.value) {
        if ((!row.remark || !_nextRow.remark)) {
          return true
        }
        if ((row.remark && row.neAnnualTotalHour != null && row.neAnnualTotalHour >= 0 && row.mainHeadTeachingQty != null && row.mainHeadTeachingQty >= 0) && (_nextRow.remark && _nextRow.neAnnualTotalHour != null && _nextRow.neAnnualTotalHour >= 0)) {
          return true;
        }
        return false
      }
    }
  } else {
    if (row.status == '99' || _nextRow.status == '99') {
      return false
    } else {
      return true
    }
  }
}

// 关闭弹窗
const dialogClose = val => {
  dialogVisible.value = false
  getPageData();
}
// 获取时间组件
const onChange = val => {
  const { yearValue, halfValue } = val
  let now = new Date();
  query.year = yearValue
  query.bn = halfValue
  if (query.year == now.getFullYear() && query.bn == Math.floor(now.getMonth() / 6) + 1) {
    isShowCancelBtn.value = true
  } else {
    isShowCancelBtn.value = false
  }
  if (isAuth.value || isPlant.value) {
    getPageData()
    getShowBtn()
  }

}

const getShowBtn = async () => {
  isShowBtn.value = await getApi({ id: props.id }, "/mosty-jcgl/dataCommon/sfQggzr")
  uploadNum.value = await getApi({ year: query.year, id: props.id, jtsj: query.bn }, "/mosty-jcgl/dataCommon/getSccs");
};
// 查看省局上报结果
const reportResult = (val) => {
  loadingcksbjg.value = true
  getApi({ year: query.year, id: props.id, jtsj: query.bn }, "/mosty-jcgl/dataCommon/getSbjg").then((res) => {
    if (res) {
      reportResultInfo.value = res
      if (val) {
        dialogsbyy.value = true
      }
      if (res.returnCode == "200" && !res.returnHttpCode) {
        isReportResult.value = true;
        manual.disabled = true
      } else {
        if (isAutoReport.value) {
          getPageData()
        }
        isReportResult.value = false;
        if (timer.value) {
          isAutoReport.value = false
          clearInterval(timer.value);
          timer.value = null;
        }
      }
      if (res.returnCode == "200" && res.returnHttpCode == '500') {
        let res = getApi({ dataId: props.id }, "/mosty-jcgl/dataCommon/goBackData")
        if (res) {
          getPageData(false)
        }
      }
      // 只针对是否展示查看上报结果
      if (res.returnCode || res.returnHttpCode) {
        IsCksbjg.value = true

      } else {
        IsCksbjg.value = false
      }
    }


  }).finally(() => {
    loadingcksbjg.value = false
  });
};
const orgcode = ref('')
const counts = ref(0)
const getPageData = (val = true) => {
  loading.value = true;
  tableData.value = [];
  getApi(query, "/mosty-jcgl/data/manageTrainInfo/getList").then((res) => {
    if (res) {
      byTime.value = res[0]?.gxTime ? res[0].gxTime : ''
      if (query.year == new Date().getFullYear()) {
        if (isProvinces.value) {
          orgcode.value = query.orgcode
        } else {
          orgcode.value = res[0].orgCode
        }
        getApi({ year: query.year, orgcode: orgcode.value, bn: query.bn }, "/mosty-jcgl/data/manageTrainInfo/getData").then(res1 => {
          if (res1 && counts.value == 0) {
            getApi({ orgcode: orgcode.value }, "/mosty-jcgl/data/manageTrainInfo/syncLocal").then((res2) => {
              counts.value++
              getPageData()
            })
          } else {
            tableData.value = res;
            loading.value = false;
            onMergeTable()
          }
        });
      } else {
        tableData.value = res;
        loading.value = false;
        onMergeTable()
      }

      if (val && isReportResult.value) {
        timer.value = setInterval(() => {
          if (!isReportResult.value) {
            clearInterval(timer.value);
            timer.value = null;
            isAutoReport.value = false
          }
          reportResult();
        }, 1e4);
      } else {
        clearInterval(timer.value);
        timer.value = null;
      }

    }
  }).catch(err => {
    loading.value = false;
  });
};
const onEdit = (e) => {
  dialogVisible.value = true
  isEdit.value = true
  isSfsb.value = e.sfsb == "1" ? true : false
  currId.value = e.sourceId
  orgObj.value = e
  dialogTitle.value = `编辑重点人员安全培训（管理层）（${e.baOrgName}）`
};
const onAdd = () => {
  dialogVisible.value = true
  isEdit.value = true
  orgObj.value = {}
  isSfsb.value = false
  currId.value = ""
  dialogTitle.value = `新增重点人员安全培训（管理层）`
}
const onUpdate = (row, status) => {
  loadingsb.value = true
  getApi({ orgCode: row.orgCode, traineeCode: row.traineeCode, status: status }, '/mosty-jcgl/data/manageTrainInfo/reportLocalData').then(res => {
    getPageData()
  }).finally(() => {
    loadingsb.value = false
  })
};
const onView = (e) => {
  dialogVisible.value = true
  isEdit.value = false
  isSfsb.value = e.sfsb == "1" ? true : false
  currId.value = e.sourceId
  dialogTitle.value = `查看重点人员安全培训（管理层）（${e.baOrgName}）`
};
// 点击上报历史
const handleHistory = (row) => {
  currOrgCode.value = row ? row.orgCode : pageData?.params.orgcode
  currTotal.value = row.sbcs
  if (currOrgCode.value) {
    sblsVisible.value = true
  }
}
const handleReport = () => {
  if (isProvinces.value) {
    loadingsb.value = true
    getApi({ 'orgCode': query.orgcode }, '/mosty-jcgl/data/manageTrainInfo/upManageTrainInfo').then(res => {
      isAutoReport.value = true
      reportResult()
      getPageData()

    }).finally(() => {
      loadingsb.value = false
    })

  }
};
const manualUpdate = (code, isItem = false) => {
  loading.value = true;
  if (isItem) manual.loading = true;
  getApi({ orgcode: code }, "/mosty-jcgl/data/manageTrainInfo/syncLocal")
    .then((res) => {
      getPageData();
      manual.loading = false;
      ElMessage({
        message: "更新成功",
        type: "success"
      });
    })
    .catch((err) => {
      loading.value = false;
      manual.loading = false;
    });
};

// 表格选择
const selectionChange = (e) => {
  // 没有上报成功  且（&&）  选择了全部（两个合并为一行，所以除以2），才可以点击上报
  if (isReportResult.value == false && e.length === tableData.value.length / 2) {
    manual.disabled = false
  } else {
    manual.disabled = true
  }
};
onMounted(() => {
  if (isProvinces.value) {
    orgid.value = orgid.value + 'XN'
  }
  popover.title = props.title.replace("数据", "");

});
const onMergeTable = () => {
  nextTick(() => {
    let colnumIndex = 2,
      tableFirstTd = "",
      tableCurrentTd = "",
      tableSpanNum = 0,
      tableTdArr = document.querySelectorAll("#mergeTable .el-table__body tr td:nth-child(" + colnumIndex + ")")

    for (let i = 0; i < tableTdArr.length; i++) {
      if (i === 0) {
        tableFirstTd = tableTdArr[0]
        tableSpanNum = 1
      } else {
        tableCurrentTd = tableTdArr[i]

        if (tableFirstTd.innerText === tableCurrentTd.innerText) {
          tableSpanNum++
          tableCurrentTd.style.display = "none"
          tableFirstTd.setAttribute("rowSpan", tableSpanNum)
          tableCurrentTd.previousSibling.style.display = "none"
          tableFirstTd.previousSibling.setAttribute("rowSpan", tableSpanNum)

        } else {
          tableFirstTd = tableTdArr[i]
          tableSpanNum = 1
        }
      }
    }

    let count = 0
    let tableFirstTdArr = document.querySelectorAll("#mergeTable .el-table__body tr td:nth-child(" + 1 + ")")
    tableFirstTdArr.forEach(item => {
      if (item.style.display !== "none") {
        count++
        // item.innerHTML = `<div>${count}</div>`
      }
    })
  })
}
</script>

<style lang="scss" scoped>
.content {
  .topper {
    display: flex;

    .sub-le {
      flex: 1;
      padding: 15px 15px 5px 15px;
      border-right: 1px solid #ebeef5;
    }
  }

  .bottom {
    padding: 0 15px 10px 15px;
  }
}
</style>
