<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="byTime" :ywId="props.id" :title="title" :popover="popover" @change="onChange">
          <template #right v-if="isProvinces">
            <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 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" @click="handleExport">导出</el-button>
          </template>
        </TimeCondition>
        <el-table :data="tableData" style="width: 99%" border v-loading="loading" @selection-change="selectionChange"
          :span-method="mergeColumns" :header-cell-style="{ background: '#F6F6F6' }" height="calc(100% - 100px)">
          <el-table-column type="selection" width="55" :selectable="handleDisable" />
          <el-table-column label="企业名称" prop="baOrgName" width="200"></el-table-column>
          <el-table-column label="持证人员总数" prop="prop">
            <template #default="{ row }">
              <span>{{ handleTotal(row) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="特种作业人员（按照国家目录）">
            <el-table-column label="高压电工（人）" prop="hpElectricianQty"></el-table-column>
            <el-table-column label="低压电工（人）" prop="lpElectricianQty"></el-table-column>
            <el-table-column label="制冷与空调工（人）" prop="reAcwQty"></el-table-column>
            <el-table-column label="焊接与热切割工（人）" prop="weHcWorkerQty"></el-table-column>
            <el-table-column label="高处作业（人）" prop="highAlWorkerQty"></el-table-column>
          </el-table-column>
          <el-table-column label="特种设备管理及操作人员（按照国家目录）">
            <el-table-column label="特种设备安全管理员（人）" prop="safetyManagementQty"></el-table-column>
            <el-table-column label="工业锅炉司炉（人）" prop="ibFiremanQty"></el-table-column>
            <el-table-column label="锅炉水处理（人）" prop="waterTreatmentQty"></el-table-column>
            <el-table-column label="起重司机（人）" prop="craneDriverQty"></el-table-column>
            <el-table-column label="压力容器操作工（人）" prop="pvOperatorQty"></el-table-column>
            <el-table-column label="叉车司机（人）" prop="forkliftDriverQty"></el-table-column>
            <el-table-column label="观光车司机（人）" prop="sbDriverQty"></el-table-column>
            <el-table-column label="特种设备焊接作业（人）" prop="weldingOperationsQty"></el-table-column>
          </el-table-column>
          <el-table-column label="消防控制室值班和操作持证人员（人）">
            <el-table-column label="五级/初级工人数（人）" prop="juniorWorkerQty"></el-table-column>
            <el-table-column label="四级/中级工人数（人）" prop="intermediateWorkerQty"></el-table-column>
          </el-table-column>
          <el-table-column label="最后一次上报时间" prop="gxTime" fixed="right"></el-table-column>
          <el-table-column label="当前上报状态" prop="status" 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 label="累计上报次数" prop="sbcs" fixed="right">
            <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" />
</template>

<script setup>
import { onMounted, ref, reactive, 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/tab2/Dialog.vue";
import SblsTable from '../components/tab2/SblsTable.vue'
import { getItem } from "@/utils/storage";
import { ElMessage, ElLoading } from "element-plus";
import { filterqx } from "@/utils/auth.js";
import { czrytXlsx } from "./tabsTool/tab0Tool.js";
const currOrgCode = ref(null)
const currTotal = ref(null)
const sblsVisible = ref(false)
const props = defineProps({ isOpen: Boolean, id: String, title: String });
const pageData = reactive({
  dateTable: [],
  listQuery: {
    pageNum: 1,
    pageSize: 2000,
  },
  ids: []
})
const popover = reactive({
  title: "",
  content: `
  填表说明：
1. 填报单位：省级单位名称；
2. 企业名称：各省级单位机关或下属单位名称；
3. 统计频次：半年；
4. 提交周期：上半年1月1日-6月30日、下半年7月1日-12月25日。
5. 数据统计范围： 填写本年度截止到当前统计周期的累计数据。
6. 统计范围为在册在岗员工和劳务派遣人员，不包括业务外包人员。
7. 没有相关持证人员，人数请填写“0”。
8. 技能等级：五级/初级工、四级/中级工两大类。
  `
});
const dialogsbyy = ref(false)
const IsCksbjg = ref(false)
const loadingcksbjg = ref(false)
const reportResultInfo = ref({})
// 选择时间季度
const timer = ref(null);
const uploadNum = ref(0);
const query = reactive({
  orgcode: getItem("deptId").ssdwid,
  year: "",
  bn: ''
});
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 isShowCancelBtn = ref(true)
const isReportResult = ref(false);
const loadingsb = ref(false);
const byTime = ref('')
const manual = reactive({
  loading: false,
  disabled: true,
  isReport: false,
});
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 handleDisable = (row) => {
  if (isProvinces.value && !isReportResult.value && row.status != '99') {
    return hasValue(row)
  } else {
    if (row.status == '99') {
      return false
    } else {
      return true
    }
  }
}
const hasValue = obj => {
  let _data = obj
  for (const prop in _data) {
    if (_data.hasOwnProperty(prop) && (_data[prop] === null || _data[prop] === undefined || _data[prop] === '')) {
      if (prop == 'status' || prop == 'sbcs' || prop == 'gxTime' || prop == 'xtScbz') {
        continue;
      } else {
        return false;
      }

    }
  }
  return true;
}
// 持证人员总数
const handleTotal = (row) => {
  let { hpElectricianQty,
    lpElectricianQty,
    reAcwQty,
    weHcWorkerQty,
    highAlWorkerQty,
    safetyManagementQty,
    ibFiremanQty,
    waterTreatmentQty,
    craneDriverQty,
    pvOperatorQty,
    forkliftDriverQty,
    sbDriverQty,
    weldingOperationsQty,
    juniorWorkerQty,
    intermediateWorkerQty } = row
  let _total = 0
  _total = hpElectricianQty +
    lpElectricianQty +
    reAcwQty +
    weHcWorkerQty +
    highAlWorkerQty +
    safetyManagementQty +
    ibFiremanQty +
    waterTreatmentQty +
    craneDriverQty +
    pvOperatorQty +
    forkliftDriverQty +
    sbDriverQty +
    weldingOperationsQty +
    juniorWorkerQty +
    intermediateWorkerQty
  return _total
}
// 关闭弹窗
const dialogClose = val => {
  dialogVisible.value = false
  if (val) {
    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 {
        isReportResult.value = false;
        if (timer.value) {
          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;
  getApi(query, "/mosty-jcgl/data/certifiedPerson/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/certifiedPerson/getData").then(res1 => {
          if (res1 && counts.value == 0) {
            getApi({ orgcode: orgcode.value }, "/mosty-jcgl/data/certifiedPerson/syncLocal").then((res2) => {
              counts.value++
              getPageData(false)
            })
          } else {
            tableData.value = res;
            loading.value = false;
          }
        });
      } else {
        tableData.value = res;
        loading.value = false;
      }
      if (val && isReportResult.value) {
        timer.value = setInterval(() => {
          if (!isReportResult.value) {
            clearInterval(timer.value);
            timer.value = null;
          }
          reportResult();
        }, 1e4);
      } else {
        clearInterval(timer.value);
        timer.value = null;
      }

    }
  }).catch(err => {
    loading.value = false;
  });
};
const editCheck = (row) => {
  if (row.sourceId) return true
  ElMessage({ message: "数据需要先初始化或更新", type: "warning" });
  return false
}
const onEdit = (e) => {
  if (!editCheck(e)) return
  dialogVisible.value = true;
  isEdit.value = true
  isSfsb.value = e.sfsb == '1' ? true : false
  currId.value = e.sourceId
  dialogTitle.value = `持证人员（${e.baOrgName}）`;
};
const onUpdate = (row, status) => {
  loadingsb.value = true
  getApi({ orgCode: row.orgCode, status: status }, '/mosty-jcgl/data/certifiedPerson/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/certifiedPerson/upCertifiedPerson').then(res => {
      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/certifiedPerson/syncLocal")
    .then((res) => {
      getPageData();
      ElMessage({
        message: "更新成功",
        type: "success"
      });
      manual.loading = false;
    })
    .catch((err) => {
      loading.value = false;
      manual.loading = false;
    });
};

// 表格选择
const selectionChange = (e) => {
  if (isReportResult.value == false && e.length === tableData.value.length) {
    manual.disabled = false
  } else {
    manual.disabled = true
  }
};
onMounted(() => {
  if (isProvinces.value) {
    orgid.value = orgid.value + 'XN'
  }
  popover.title = props.title.replace("数据", "");

});

const handleExport = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '导出中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  getApi(query, '/mosty-jcgl/data/export/certifiedPersonLedger').then(res => {
    czrytXlsx(res ? res : [], {}, popover.content)

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

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