<template>
  <div>
    <div class="model_box  ww100" @click="containerClick">
      <div class="flex just-between">
        <MOSTY.Assort title="省/市州公司安全人员统计"></MOSTY.Assort>
        <!-- <el-button  class="export-excel" type="primary" v-loading="loadingShow" @click="onloadExecl">
          <span>导出Excel</span>
        </el-button> -->
        <div style="margin-right: 10px;margin-top: 13px;">
          <el-popover :visible="exportVisible" placement="top" :width="260">
            <p style="text-align: center;">请选择需要导出的安全人员类型?</p>
            <div style="display: flex; text-align: center; margin: 0">
              <NewExcel ref="excelRef" :exportSheets="exportSheets" isHideBtn :exportInfo="exportInfo">
                <el-button style="margin-right: 10px;" size="small" type="primary"
                  @click.stop="downLoadExcel('all')">全部</el-button>
              </NewExcel>

              <NewExcel ref="excelZzRef" :exportSheets="exportZzSheets" isHideBtn :exportInfo="exportInfo">
                <el-button style="margin-right: 10px;" size="small" type="primary"
                  @click.stop="downLoadExcel('0')">专职安全员</el-button>
              </NewExcel>
              <NewExcel ref="excelJzRef" :exportSheets="exportJzSheets" isHideBtn :exportInfo="exportInfo">
                <el-button style="margin-right: 10px;" size="small" type="primary"
                  @click.stop="downLoadExcel('1')">兼职安全员</el-button>
              </NewExcel>
            </div>
            <template #reference>
              <el-button @click.stop="exportVisible = true">导出安全管理人员</el-button>
            </template>
          </el-popover>
        </div>
      </div>
      <div class="flex align-start just-between" style="width: 100%;overflow-x: scroll;">
        <RyTotal v-for="item in pageData.totalList" :key="item" :item="item" @query-info="handleQueryInfo" />
      </div>
    </div>
    <div class="mt10 flex" @click="containerClick">
      <div class="ww50">
        <ModelItem title="安全机构统计" height="200px" :tabs="[{ value: '20', label: '市级' }, { value: '30', label: '区县级' }]"
          @change="onChangeLeft($event, 'pie')">
          <AnnularPie :data="pageData.aqjgtjList" :keys="aqjgtjIndex" style='width:700px;' />
        </ModelItem>
      </div>
      <div style="width: calc(50% - 10px)" class="ml10">
        <ModelItem title="安全管理人员统计" height="200px" :tabs="[{ value: '1', label: '文化程度' }, { value: '2', label: '年龄' }]"
          @change="onChangeRight($event, 'pie')">
          <AnnularPie :data="pageData.aqglrytjList" :keys="aqglryIndex" style='width:700px;' />
        </ModelItem>
      </div>
    </div>
    <div class="mt10 flex">
      <div class="ww50">
        <ModelItem title="安全管理人员" height="calc(100vh - 667px )"
          :tabs="[{ value: '0', label: '专职' }, { value: '1', label: '兼职' }]" @change="onChangeLeft($event, 'list')">
          <!-- <template #left>
            <span>总数：{{ pageData.totalList[1].total[0].value }} 专职：{{ pageData.totalList[1].total[2].value }} 兼职：{{ pageData.totalList[1].total[1].value }}</span>
          </template> -->
          <section class="eltabs4 mt5">
            <MOSTY.Table :table-columns="pageData.tableColumn" :tableloading="tableloading"
              :tableData="pageData.tableData" :tableHeight="'100%'" :isSelect="false" style="width: 100%;"
              :isSort="true">
              <template #aqrylx="{ row }">
                <span> {{ row.aqrylx == '0' ? '专职' : '兼职' }}</span>
              </template>
            </MOSTY.Table>
            <div class="flex">
              <MOSTY.Pages :pageConfiger="pageData.pageConfigerLeft" @changeNo="changeNo" @changeSize="changeSize" />
            </div>
          </section>
        </ModelItem>
      </div>
      <div style="width: calc(50% - 10px)" class="ml10">
        <ModelItem title="安全管理人才" height="calc(100vh - 667px )"
          :tabs="[{ value: '1', label: '已聘' }, { value: '2', label: '未聘' }]" @change="onChangeRight($event, 'list')">
          <section class="eltabs4 mt5">
            <MOSTY.Table :table-columns="pageData.tableColumnRight" :tableloading="tableloading"
              :tableData="pageData.tableData1" :tableHeight="'100%'" :isSelect="false" style="width: 100%;"
              :isSort="true">
              <template #type="{ row }">
                <dict-tag :options="props.dict.D_BZ_RCLX" v-for="item in row.type" :key="item" :value="item" />
              </template>
            </MOSTY.Table>
            <div class="flex">
              <MOSTY.Pages :pageConfiger="pageData.pageConfigerRight" @changeNo="changeNoRight"
                @changeSize="changeSizeRight" />

            </div>
          </section>
        </ModelItem>
      </div>
    </div>
    <!--机构列表-->

    <div>
      <div>
        <el-dialog v-model="showSecurityManagementAgencyList" title="安全管理机构列表" width="60%">
          <SecurityManagementAgencyList v-if="showSecurityManagementAgencyList" :orgCode="orgCode" :title="listTitle"
            :label="listLabel" :type="listType" />
        </el-dialog>
      </div>
      <div>
        <el-dialog v-model="showSecurityPersonnelList" title="安全人员列表" width="60%">
          <SecurityPersonnelList v-if="showSecurityPersonnelList" :orgCode="orgCode" :title="listTitle"
            :label="listLabel" :type="listType" />
        </el-dialog>
      </div>
      <div>
        <el-dialog v-model="showLicensedPersonnelList" title="持证安全人员列表" width="60%">
          <LicensedPersonnelList v-if="showLicensedPersonnelList" :orgCode="orgCode" :title="listTitle"
            :label="listLabel" :type="listType" />
        </el-dialog>
      </div>
      <div>
        <el-dialog v-model="showHiredPersonnelList" title="聘用人员列表" width="60%">
          <HiredPersonnelList v-if="showHiredPersonnelList" :orgCode="orgCode" :title="listTitle" :label="listLabel"
            :type="listType" />
        </el-dialog>
      </div>
      <div>
        <el-dialog v-model="showTalentList" title="注安/注消师列表" width="60%">
          <TalentList v-if="showTalentList" :orgCode="orgCode" :title="listTitle" :label="listLabel" :type="listType" />
        </el-dialog>
      </div>
      <div>
        <el-dialog v-model="showSecurityProfessionalsList" title="安全人才列表" width="60%">
          <SecurityProfessionalsList v-if="showSecurityProfessionalsList" :orgCode="orgCode" :title="listTitle"
            :label="listLabel" :type="listType" />
        </el-dialog>
      </div>
    </div>
  </div>
</template>
<script setup>

import ModelItem from "@/views/dutyBook/jgryandzz/commponents/total/ModelItem.vue"
import * as MOSTY from "@/components/MyComponents/index";
import RyTotal from "@/views/dutyBook/jgryandzz/commponents/total/RyTotal.vue"
import AnnularPie from "@/views/dutyBook/jgryandzz/commponents/total/AnnularPie.vue"
import { ref, reactive, defineProps, defineEmits, watch, getCurrentInstance } from "vue"
import { getApi } from "@/api/tobAcco_api.js";
import { exportXlsx } from "@/excel/Export2Excel.js";
import NewExcel from '@/components/MyComponents/NewExcel/index.vue'
import { anQuanYuanSheet } from "@/views/dutyBook/jgryandzz/commponents/comjs/gljgTool.js"
import { ElMessage } from "element-plus";
import { getValByDic } from "@/utils/tools.js"
import SecurityManagementAgencyList from "@/views/dutyBook/jgryandzz/commponents/list/securityManagementAgencyList.vue"
import SecurityPersonnelList from "@/views/dutyBook/jgryandzz/commponents/list/securityPersonnelList.vue"
import LicensedPersonnelList from "@/views/dutyBook/jgryandzz/commponents/list/licensedPersonnelList.vue"
import HiredPersonnelList from "@/views/dutyBook/jgryandzz/commponents/list/hiredPersonnelList.vue"
import TalentList from "@/views/dutyBook/jgryandzz/commponents/list/talentList.vue"
import SecurityProfessionalsList from "@/views/dutyBook/jgryandzz/commponents/list/securityProfessionalsList.vue"
import * as XLSX from 'xlsx'
const props = defineProps({
  modelValue: Boolean,
  orgCode: String,//部门ID
  dict: {
    type: Object,
    default: {
      D_BZ_PYYYLX: [],
      D_BZ_RCLX: [],
      D_BZ_AQRYWHCD: [],
      D_BZ_XB: [],
      D_BZ_AQRYZZMM: [],
      D_BZ_AQRYSCLY: [],
    }
  },
  queryOrgCode: {
    type: String,
    default: '',
  },
  orgName: {
    type: String,
    default: '',
  },
})
const emits = defineEmits(["update:modelValue", "exportFile"])
const { proxy } = getCurrentInstance()

const { D_BZ_PYYYLX, D_BZ_RCLX, D_BZ_AQRYWHCD, D_BZ_XB, D_BZ_AQRYZZMM, D_BZ_AQRYSCLY } = proxy.$dict("D_BZ_PYYYLX", "D_BZ_RCLX", "D_BZ_AQRYWHCD", "D_BZ_XB", "D_BZ_AQRYZZMM", "D_BZ_AQRYSCLY")
const tableloading = ref(false)
const aqjgtjIndex = ref(1);
const aqglryIndex = ref(1)
const leftSelectType = ref("0");//左侧列表筛选
const rightSelectType = ref("1");//右侧侧列表筛选

/** excel组件 */
const excelRef = ref()
/** excel专职组件 */
const excelZzRef = ref()
/** excel兼职组件 */
const excelJzRef = ref()
/**导出的全部sheet */
const exportSheets = reactive(anQuanYuanSheet)
/**导出的专职sheet */
const exportZzSheets = reactive(anQuanYuanSheet.slice(0, 1))
/**导出的专职sheet */
const exportJzSheets = reactive(anQuanYuanSheet.slice(1, 2))
/**导出相关配置信息 */
const exportInfo = reactive({
  name: "",
  loading: false,
  disabled: false
})
const InfoFilled = ref()
/**导出弹框是否显示 */
const exportVisible = ref(false)
const pageData = reactive({
  tableData: [],
  tableData1: [],
  pageConfigerLeft: {
    pageSize: 20,
    pageCurrent: 1,
    total: 0
  },
  pageConfigerRight: {
    pageSize: 20,
    pageCurrent: 1,
    total: 0
  },
  tableConfiger: {
    showIndex: false,
    loading: false,
    haveControls: false,
    height: '100%'
  },
  tableColumn: [
    { title: "所属单位", prop: "orgname", width: 250 },
    { title: "所属部门", prop: "deptname", },
    { title: "姓名", prop: "username", },
    { title: "类型", prop: "aqrylx", slot: true },
  ],
  tableColumnRight: [
    { title: "所属单位", prop: "orgName", width: 250 },
    { title: "所属部门", prop: "deptName", },
    { title: "人员姓名", prop: "userName", },
    { title: "人才类型", prop: "type", slot: true },],
  // 统计数据
  totalList: [
    {
      title: "安全管理机构",
      total: [
        { label: "总数", value: 0, type: "00" },
        { label: "兼职", value: 0, type: "01" },
        { label: "专职", value: 0, type: "02" }
      ]
    },
    {
      title: "安全人员",
      total: [
        { label: "总数", value: 0, type: "00" },
        { label: "兼职", value: 0, type: "01" },
        { label: "专职", value: 0, type: "02" },
        { label: "持证率(专)", value: 0, type: "03" },
      ]
    },
    {
      title: "注安/注消师",
      total: [
        { label: "总数", value: 0, type: "00" },
        { label: "注安师", value: 0, type: "01" },
        { label: "注消师", value: 0, type: "02" },
        { label: "聘用", value: 0, type: "03" }
      ]
    },
    {
      title: "安全人才",
      total: [
        { label: "总数", value: 0, type: "00" },
        { label: "安技委", value: 0, type: "01" },
        { label: "标准化评审", value: 0, type: "02" },
        { label: "其它", value: 0, type: "03" }
      ]
    }
  ],
  aqjgtjList: [
    { value: 0, name: '专职', color: "#006E4A" },
    { value: 0, name: '兼职', color: "#FFD023" },
  ],
  aqglrytjList: [
    { value: 0, name: '研究生及以上', color: "#006E4A" },
    { value: 0, name: '本科', color: "#4FCCFF" },
    { value: 0, name: '专科及以下', color: "#4C7AF3" },
    { value: 0, name: '其他', color: "#FFD023" }
  ],
  headerTotal: {}
})
//安全人员分页
const changeNo = (val) => {
  pageData.pageConfigerLeft.pageCurrent = val
  getAqyList()
}
const changeSize = (val) => {
  pageData.pageConfigerLeft.pageSize = val
  getAqyList()
}
//安全人才分页
const changeNoRight = (val) => {
  pageData.pageConfigerRight.pageCurrent = val
  getTalents()
}
const changeSizeRight = (val) => {
  pageData.pageConfigerRight.pageSize = val
  getTalents()
}
//安全管理人才列表
const getTalents = () => {
  pageData.pageConfigerRight = { ...pageData.pageConfigerRight, orgCode: props.orgCode, type: rightSelectType.value }
  getApi(pageData.pageConfigerRight, "/mosty-jcgl/aqy/getTalents").then(res => {
    if (res?.records) {
      for (let i = 0; i < res.records.length; i++) {
        res.records[i].type = res.records[i].type.split(",")
      }
      pageData.pageConfigerRight.total = res.total
      pageData.tableData1 = res.records
    }
  })
}
//安全人力机构列表
const getAqyList = () => {
  pageData.pageConfigerLeft = { ...pageData.pageConfigerLeft, orgCode: props.orgCode, type: leftSelectType.value }
  getApi(pageData.pageConfigerLeft, "/mosty-jcgl/aqy/getAqyList").then(res => {
    if (res?.records) {
      pageData.pageConfigerLeft.total = res.total
      pageData.tableData = res.records
    }
  })
}
//安全管理机构筛选
const onChangeLeft = (val, type) => {
  if (type === "pie") {
    getOrgStatistic(val)
  } else {
    leftSelectType.value = val
    pageData.pageConfigerLeft.pageCurrent = 1
    getAqyList()
  }
}
//安全管理人员筛选
const onChangeRight = (val, type) => {
  if (type === "pie") {
    getAqyStatistic(val)
  } else {
    rightSelectType.value = val
    pageData.pageConfigerRight.pageCurrent = 1
    getTalents()
  }
}
//安全人员统计
const getAqyStatistic = (type = "1") => {
  getApi({ orgCode: props.orgCode, type }, "/mosty-jcgl/aqy/getAqyStatistic").then(res => {
    if (res) {
      if (type == 1) {
        pageData.aqglrytjList = [
          { value: res.otherCount, name: '研究生及以上', color: "#006E4A" },
          { value: res.bksCount, name: '本科', color: "#4FCCFF" },
          { value: res.zksCount, name: '专科及以下', color: "#4C7AF3" },
          { value: res.otherCount, name: '其他', color: "#FFD023" }
        ]
      } else {
        pageData.aqglrytjList = [
          { value: res.underThirtyCount, name: '30及30以下', color: "#006E4A" },
          { value: res.thirtyCount, name: '30以上', color: "#4FCCFF" },
          { value: res.fortyCount, name: '40以上', color: "#4C7AF3" },
          { value: res.overFiftyCount, name: '50以上', color: "#FFD023" }
        ]
      }
      aqglryIndex.value++
    }
  })
}
//头部统计
const getHeaderTotal = () => {
  getApi({ orgCode: props.orgCode }, "/mosty-jcgl/aqy/getStatisticInfo").then(res => {
    if (res) {
      pageData.totalList[3].total[3].value = res.otherCount
      pageData.totalList[3].total[2].value = res.standardizationReviewerCount
      pageData.totalList[3].total[1].value = res.safetyTechnologyCommitteeCount
      pageData.totalList[3].total[0].value = res.securityProfessionalsOverallCount
      pageData.totalList[2].total[3].value = res.employeeCount
      pageData.totalList[2].total[2].value = res.registeredFireEngineerCount
      pageData.totalList[2].total[1].value = res.registeredSafetyEngineerCount
      pageData.totalList[2].total[0].value = res.registeredEngineerCount
      pageData.totalList[1].total[3].value = res.rate + "%"
      pageData.totalList[1].total[2].value = res.zzCount
      pageData.totalList[1].total[1].value = res.jzCount
      pageData.totalList[1].total[0].value = res.aqyCount
      pageData.totalList[0].total[2].value = res.zzaqbmCount
      pageData.totalList[0].total[1].value = res.jzaqbmCount
      pageData.totalList[0].total[0].value = res.aqbmCount
    }
  })
}
//安全管理机构统计
const getOrgStatistic = (orgLevel = "20") => {
  getApi({ orgCode: props.orgCode, orgLevel }, "/mosty-jcgl/aqy/getOrgStatistic").then(res => {
    if (res) {
      pageData.aqjgtjList = [
        { value: res.zzaqbmCount, name: '专职', color: "#FFD023" },
        { value: res.jzaqbmCount, name: '兼职', color: "#006E4A" }
      ]
      aqjgtjIndex.value++
    }
  })
}
/**导出loading状态 */
const loadingShow = ref(false)


const getSheets = (obj) => {
  /**安全人员类型 */
  let aqrylx = obj.aqrylx
  /**安全人员类型 中文名 */
  let type = obj.type
  /** 当前下载组件 */
  let currRef = obj.currRef
  /** sheet内容 */
  let sheet = obj.sheet

  let aqrylxBtn = aqrylx
  let aqrylxType = aqrylx == 'all' ? '' : aqrylx
  getApi({ orgcode: props.queryOrgCode, aqrylx: aqrylxType }, '/mosty-jcgl/aqy/exportExcel').then((res) => {
    if (res) {
      let resArr = Array.isArray(res) ? res : []
      // if (!res.length) return ElMessage.
      for (let index = 0; index < resArr.length; index++) {
        const item = resArr[index];
        item.index = index + 1
        item["highestFullTimeEducation"] = getValByDic(item["highestFullTimeEducation"], D_BZ_AQRYWHCD.value)
        item["xb"] = getValByDic(item["xb"], D_BZ_XB.value)
        item["politicalStatus"] = getValByDic(item["politicalStatus"], D_BZ_AQRYZZMM.value)
        item["expertise"] = getValByDic(item["expertise"], D_BZ_AQRYSCLY.value)
      }
      /** */
      let excelName = props.orgName + type + '安全管理人员台账.xlsx'

      exportInfo.name = excelName
      if (aqrylxBtn == '0' || aqrylxBtn == '1') {
        sheet[0].data = resArr
        sheet[0].title = `${props.orgName}${type}安全管理人员台账`
        currRef.value.onExport(sheet, excelName)
      } else if (aqrylxBtn == 'all') {
        sheet[0].data = resArr.filter(item => item.aqrylx == "0")
        sheet[0].title = `${props.orgName}专职安全管理人员台账`
        sheet[1].data = resArr.filter(item => item.aqrylx == "1")
        sheet[1].title = `${props.orgName}兼职安全管理人员台账`

        currRef.value.onExport(sheet, excelName)
      }

    }
  }).catch(err => {
    // loadingShow.value = false
  })
}

const containerClick = () => {
  if (exportVisible.value) exportVisible.value = false
}

/**下载Excel */
const downLoadExcel = (aqrylx) => {
  let allObj = {
    all: {
      type: '全部',
      currRef: excelRef,
      sheet: exportSheets
    },
    0: {
      type: '专职',
      currRef: excelZzRef,
      sheet: exportZzSheets
    },
    1: {
      type: '兼职',
      currRef: excelJzRef,
      sheet: exportJzSheets
    },
  }
  let { type, currRef, sheet } = allObj[aqrylx] || {}
  getSheets({ aqrylx, type, currRef, sheet })
  exportVisible.value = false
  // emits("exportFile",{ aqrylx, type, currRef, sheet })
}

const showSecurityManagementAgencyList = ref(false) // 控制 SecurityManagementAgencyList 显示
const showSecurityPersonnelList = ref(false) // 控制 SecurityPersonnelList 显示
const showLicensedPersonnelList = ref(false) // 控制 LicensedPersonnelList 显示
const showHiredPersonnelList = ref(false) // 控制 HiredPersonnelList 显示
const showTalentList = ref(false) // 控制 TalentList 显示
const showSecurityProfessionalsList = ref(false) // 控制 showSecurityProfessionalsList 显示
const listTitle = ref('')
const listLabel = ref('')
const listType = ref('')

const handleQueryInfo = ({ title, label, type }) => {
  if (title === "安全管理机构") {
    showSecurityManagementAgencyList.value = true    // 打开安全管理机构列表
  }
  else if (title === "安全人员" && label !== "持证率(专)") {
    showSecurityPersonnelList.value = true  //打开安全人员列表
  }
  else if (title === "安全人员" && label === "持证率(专)") {
    showLicensedPersonnelList.value = true  //打开持证人员列表
  }
  else if (title === "注安/注消师" && label === "聘用") {
    showHiredPersonnelList.value = true  //打开聘用人员列表
  }
  else if (title === "注安/注消师" && label !== "聘用") {
    showTalentList.value = true
  }
  else {
    showSecurityProfessionalsList.value = true  //打开人才人员列表
  }

  listTitle.value = title
  listLabel.value = label
  listType.value = type
}

watch(() => props.orgCode, val => {
  if (val) {
    getHeaderTotal()
    getOrgStatistic()
    getAqyStatistic()
    getAqyList()
    getTalents()
  }
}, { deep: true, immediate: true })
</script>
<style lang="scss" scoped>
::v-deep .el-pagination {
  --el-pagination-font-size: 13px !important;
  --el-pagination-button-width: 25px !important;
  padding: 1px 0px !important;
}

::v-deep .el-pagination__sizes {
  margin: 0px !important;
}

.eltabs4 {
  height: calc(100% - 35px);
}

.export-excel {
  margin-top: 10px;
}
</style>
