<template>
  <div>
    <div class="bigBox" @click="containerClick">
      <!-- 组织机构信息 -->
      <div class="zzjg-left" :style="{ width: lfBoxWid }">
        <div class="title">
          <div style="display: flex; align-items: center;">
            <div class="pt5 mr5">
              <el-icon style="color: var(--el-color-primary) !important">
                <List />
              </el-icon>
            </div>
            <span class="zzjgxx" v-if="iconChange">组织机构信息</span>
          </div>
          <el-icon @click="handleCollapse" v-show="iconChange">
            <DArrowLeft />
          </el-icon>
          <el-icon @click="handleCollapse" v-show="!iconChange">
            <DArrowRight />
          </el-icon>
        </div>
        <div class="treeBox">
          <!-- 非安全员登录 -->
          <MOSTY.DepartmentTree width="100%" placeholder="管理部门ID" clearable filterable :searchType="'03'"
            @getdeptData="getdeptData" />
        </div>
      </div>
      <!-- 统计页面 -->
      <div v-if="showTotal" class="rightTotal ml10" :style="{ width: rgBoxWid }">
        <AqgljghrypzTotal v-model="showTotal" :orgCode="orgid"
          :dict="{ D_BZ_PYYYLX, D_BZ_RCLX, D_BZ_AQRYWHCD, D_BZ_XB, D_BZ_AQRYZZMM, D_BZ_AQRYSCLY }"
          :queryOrgCode="listQuery.orgCode" :orgName="listQuery.orgName" @exportFile="getSheets" />
      </div>
      <!-- 配置页面 -->
      <div class="right" v-else>
        <!-- 部门人数 -->
        <div class="perNum">
          <div class="head">
            <!-- 部门人数详情 -->
            <div class="from_box">
              <el-form ref="elform" :model="fromObj" :inline="true" :rules="rules" :disabled='!showBut'>
                <el-form-item label="单位：" prop="orgname">
                  <el-input placeholder="请输入单位" v-model="fromObj.orgname" style="width: 230px" clearable
                    disabled></el-input>
                </el-form-item>
                <el-form-item label="主要领导:" prop="executivename">
                  <el-input v-model="fromObj.executivename" style="width: 110px" disabled></el-input>
                </el-form-item>
                <el-form-item label="安全分/协管领导:" prop="leadershipname">
                  <el-input v-model="fromObj.leadershipname" style="width: 110px" disabled></el-input>
                </el-form-item>
                <el-form-item :label="bzrsTitle + '安全部门编制人数:'" prop="bzrs" v-if="bzrsShow">
                  <el-input v-model.number="fromObj.bzrs" :max="500" type='number' style="width: 110px"
                    @blur="savefrom" />
                </el-form-item>
              </el-form>
            </div>
            <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 = !exportVisible">导出安全管理人员</el-button>
              </template>
            </el-popover>

          </div>
          <div class="detail">

            <div class="detail-item">
              <div>评聘安全工程师</div>
              <div class="flex just-between ">
                <span class="detail-number">已聘：{{ aqgcsCount }}</span>
              </div>
            </div>
            <div class="detail-item">
              <div>编制数</div>
              <div class="flex just-between ">
                <span class="detail-number">总数：{{ fromObj.bzrs }}</span>
              </div>
            </div>
            <div class="detail-item " title="导出所有安全员">
              <div>安全员总数</div>
              <div class="flex just-between ">
                <span class="detail-number pointer" @click="SecurityGuardClick('all')">总数：{{ fromObj.centerCount
                  }}</span>
                <span class="detail-number pointer" @click="SecurityGuardClick('0')">专职：{{ fromObj.centerZzCount
                  }}</span>
                <span class="detail-number pointer" @click="SecurityGuardClick('1')">兼职：{{ fromObj.centerJzCount
                  }}</span>
              </div>
            </div>

          </div>
          <el-form ref="elform" :model="fromObj" :inline="true" :rules="rules" style="display: block">
            <el-form-item label="评聘安全工程师:" style="width: 100%;margin-bottom: 5px;">
              <div class="flex ww100 just-between">
                <el-input placeholder="请配置评聘安全工程师" v-model="aqgcsNames"
                  :style="{ width: showConfigBut ? '95%' : '100%' }" readonly />
                <!-- <el-button type="primary" @click="onClickConfig('03')" v-if="showConfigBut">配置</el-button> -->
              </div>
            </el-form-item>

          </el-form>
        </div>
        <!-- 表格 -->
        <MOSTY.Assort title="部门管理" />
        <section class="eltabs4">
          <MOSTY.Table ref="deptTableRef" :table-columns="tabColumns" :tableloading="deptListLoading"
            :tableData="tableData" :showSummary="false" :getSummaries="getSummary" :tableHeight="'100%'"
            :sortWidth="'116'" :isSelect="false" style="width: 100%;" :isSort="true" @headerDragend="setTableWidth">
            <template #mtcsoltype="{ row }">
              <span v-if="row.orgBizType != '02'">
                <span v-if="row.mtcsoltype == '0'">专职</span>
                <span v-if="row.mtcsoltype == '1'">兼职</span>
                <span v-if="row.mtcsoltype == '2'">否</span>
              </span>
              <span v-else>-</span>
            </template>
            <template #actions="{ row }">
              <span class="operedit" @click="registration(row)"><el-icon>
                  <EditPen />
                </el-icon>登记</span>
            </template>
          </MOSTY.Table>

          <!-- <table class="bottom-total-table">
            <tr>
              <td style="width: 116px;">小计: </td>
              <td style="width: calc(50% - 58px);">专职编制数: {{ zzAqyTotal }}</td>
              <td style="width: calc(50% - 58px);">兼职编制数: {{ jzAqyTotal}}</td>
            </tr>
          </table> -->
        </section>

      </div>
    </div>
    <!-- 登记 -->
    <div class="dialog-box" v-if="comprehensiveShow" @click="containerClick">
      <Registration @close="changeRegi" :rowId="rowid" :orgId="orgId" :type="orgBizType" :deptId="deptId"
        :mtcsoltype="mtcsoltype" :clickSsdwid="clickSsdwid" :leaderId="leaderId" :orgCode="listQuery.orgCode"
        :orgName="listQuery.orgName" :tableData="tableData" />
    </div>
    <!-- 已聘用人才列表 -->
    <PyList v-if="pyShow" @close="closePy" :dict="{ D_BZ_PYYYLX, D_BZ_RCLX }" :zslx="zslx" :orgid="orgid"
      :title="pyTitle" />

    <!-- 安全员列表弹框 start -->
    <aqyTable v-if="isShowAqyTable" :type="aqrylxType" :exportLoading="exportLoading" :orgcode="listQuery.orgCode"
      :dict="{ D_BZ_PYYYLX, D_BZ_RCLX, D_BZ_AQRYWHCD, D_BZ_XB, D_BZ_AQRYZZMM, D_BZ_AQRYSCLY }"
      @close="isShowAqyTable = false" @export="downLoadExcel" />
    <!-- 安全员列表弹框 end -->
    <!-- 导出安全员组件 start -->
    <NewExcel ref="excelRef" :exportSheets="exportSheets" isHideBtn :exportInfo="exportInfo">
    </NewExcel>

    <NewExcel ref="excelZzRef" :exportSheets="exportZzSheets" isHideBtn :exportInfo="exportInfo">
    </NewExcel>
    <NewExcel ref="excelJzRef" :exportSheets="exportJzSheets" isHideBtn :exportInfo="exportInfo">
    </NewExcel>
    <!-- 导出安全员组件 end -->
  </div>
</template>

<script setup>
// 引入 
import { getItem } from "@/utils/storage";
import * as MOSTY from "@/components/MyComponents/index";
import AqgljghrypzTotal from "@/views/dutyBook/jgryandzz/commponents/AqgljghrypzTotal.vue"
import { onMounted, ref, reactive, getCurrentInstance, computed, nextTick } from "vue";
import { filterqx } from "@/utils/auth.js"
import Registration from "./commponents/registration.vue";
import PyList from "./commponents/pyList.vue";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import { exportXlsx } from "@/excel/Export2Excel.js";
import NewExcel from '@/components/MyComponents/NewExcel/index.vue'
import aqyTable from "./commponents/aqyTable.vue";
import { ElMessage } from "element-plus";
import * as rule from "@/utils/rules.js";
import { anQuanYuanSheet } from "@/views/dutyBook/jgryandzz/commponents/comjs/gljgTool.js"
import * as XLSX from 'xlsx'
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 showTotal = ref(false);//是否显示统计模块
const elform = ref()
const comprehensiveShow = ref(false);
/** 安全员类型 all 0,1 */
const aqrylxType = ref('all')
/** 展示安全员列表 */
const isShowAqyTable = ref(false)
/** excel组件 */
const excelRef = ref()
/** excel专职组件 */
const excelZzRef = ref()
/** excel兼职组件 */
const excelJzRef = ref()
/** 评聘安全工程师txt */
const aqgcsNames = ref('')
/** 评聘安全工程师个数 */
const aqgcsCount = ref('0')
/** 编制数 */
const compileCount = ref('0')

const showConfigBut = ref(false);//是否显示配置按钮
const rules = reactive({
  orgname: [{ required: true, message: "单位不能为空", trigger: "blur" }],
  executivename: [{ required: true, message: "主管领导不能为空", trigger: "blur" }],
  leadershipname: [{ required: true, message: "分管领导不能为空", trigger: "blur" }],
  ...rule.numberzzsRule({ validator: true, require: true, num: 500 }, "bzrs"),
})
const deptId = ref('');
/** 领导班子的id,选领导组件时用 */
const leaderId = ref();
const orgId = ref('');
const orgBizType = ref('');
/** 部门table 组件ref */
const deptTableRef = ref()
const fromObj = ref({
  aqbmCount: 0,
  aqyCount: 0,
  jzCount: 0,
  centerCount: 0,
  centerZzCount: 0,
  centerJzCount: 0,
  zzCount: 0,
  bzrs: 0,
  executivename: '',
  leadershipname: '',
  orgname: '',
});
/** 表格数据 */
const tableData = ref([]);
const listQuery = reactive({
  aqryTotal: {},//安全人员统计数据
})
const rowid = ref('')
// 树的展开与折叠
const iconChange = ref(true);
const lfBoxWid = ref("300px");
const rgBoxWid = ref("calc(100% - 300px)");
const showBut = ref(false);
const clickSsdwid = ref(null)
// 聘用人员弹窗类型
const zslx = ref('')
const pyShow = ref(false)
const pyTitle = ref('')
const mtcsoltype = ref('')
const deptListLoading = ref(false)
// 聘用只查看市级的数据
const orgid = ref(null)
const bzrsShow = ref(false)
const bzrsTitle = 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 isAqbm = computed(() => {
  return filterqx("isaqbm") == "1"
})
// 是否是县账号
const isCity = computed(() => {
  return filterqx("isaqbm") == "1" && filterqx("isgs") == "1"
})
const InfoFilled = ref();
/** 编制【专职】 数*/
const zzAqyTotal = computed(() => {
  let zzAqyCount = 0
  let tableList = Array.isArray(tableData.value) ? tableData.value : []
  tableList.forEach(item => {
    zzAqyCount = zzAqyCount + (item.zzAqyCount || 0)
  })
  return zzAqyCount
})
/** 编制【兼职】数*/
const jzAqyTotal = computed(() => {
  let jzAqyCount = 0
  let tableList = Array.isArray(tableData.value) ? tableData.value : []
  tableList.forEach(item => {
    jzAqyCount = jzAqyCount + (item.jzAqyCount || 0)
  })
  return jzAqyCount
})
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
}
/** 安全员点击
 * @type {String} type 安全员类型 'all'|'0'|'1'
 */
const SecurityGuardClick = (type) => {
  isShowAqyTable.value = true
  aqrylxType.value = type
}

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

  let aqrylxBtn = aqrylx

  // exportVisible.value = false

  // loadingShow.value = true
  exportLoading.value = true
  let aqrylxType = aqrylx == 'all' ? '' : aqrylx
  getApi({ orgcode: listQuery.orgCode, aqrylx: aqrylxType }, '/mosty-jcgl/aqy/exportExcel').then((res) => {
    exportLoading.value = false
    if (res) {
      let resArr = Array.isArray(res) ? res : []
      if (!res.length) return ElMessage.console.warn("无数据");
      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 = listQuery.orgName + type + '安全管理人员台账.xlsx'

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

        currRef.value.onExport(sheet, excelName)
      }

    }
  }).catch(err => {

    // loadingShow.value = false
    exportLoading.value = false
  })
}

/** 获取总计 */
const getSummary = (param) => {
  const { columns, data } = param

  const sums = []
  let zzAqyCount = 0
  let jzAqyCount = 0
  let tableList = Array.isArray(tableData.value) ? tableData.value : []
  tableList.forEach(item => {
    zzAqyCount = zzAqyCount + (item.zzAqyCount || 0)
    jzAqyCount = jzAqyCount + (item.jzAqyCount || 0)
  })

  sums[0] = '合计'
  sums[1] = zzAqyCount // 编制 专职
  sums[2] = jzAqyCount // 编制兼职数

  return sums
}
const tabColumns = reactive([
  // {
  //   title: "编制数",
  //   suntab: [
  //     {
  //       title: "专职",
  //       prop: "zzAqyCount",
  //       width: '130',
  //     },
  //     {
  //       title: "兼职",
  //       prop: "jzAqyCount",
  //       width: '130',
  //     }
  //   ]
  // },
  {
    title: "部门",
    prop: "deptname"
  },
  {
    title: "是否安全部门",
    prop: "mtcsoltype",
    slot: true
  },
  {
    title: "部门负责人",
    prop: "principalheadname"
  },
  {
    title: "部门分管领导",
    // title: "分管领导",
    prop: "fgldname"
  },
  {
    title: "安全人员",
    suntab: [
      {
        title: "专职",
        prop: "zzAqy",
        width: '130',
      },
      {
        title: "兼职",
        prop: "jzAqy",
        width: '130',
      }
    ]
  },
])


const setDeptTableWidth = (from) => {
  nextTick(() => {
    let table = deptTableRef.value

    if (!table) return
    if (typeof table.getTableRef !== 'function') return
    let elTalbe = table.getTableRef()

    if (!elTalbe) return
    setTableWidth(elTalbe, from)
  })
}

const setTableWidth = (table, from) => {

  nextTick(() => {
    if (!table) return
    const tableRefs = table.$refs
    if (!tableRefs) return
    let { footerWrapper, tableBody } = tableRefs || {}
    if (!footerWrapper) return
    if (!tableBody) return
    let columnsEl = tableBody.children[0]?.children
    let footCol = footerWrapper.children?.[0]?.childNodes?.[1]?.children?.[0]?.children
    if (columnsEl.length) {
      for (let i = 0; i < columnsEl.length; i++) {
        const col = columnsEl[i];
        const width = col.clientWidth || col.width || 0

        if (footCol[i]) footCol[i].style.width = width + 'px'
        if (footCol[i]) footCol[i].style.overFlow = 'hidden'
        if (footCol[i]) footCol[i].width = width + 'px'
      }
    }
  })

}
function hiddentab(params) {
  if (showBut.value && showConfigBut.value) {
    if (tabColumns.at(-1).prop != 'actions') {
      tabColumns.push({
        title: "操作",
        prop: "actions",
        slot: true
      })
    }
  } else {
    if (tabColumns.at(-1).prop == 'actions') {
      tabColumns.pop()
    }
  }
}
// 初始化
onMounted(() => {
  const dept = getItem("deptId")
  showTotal.value = setShowTotal(dept.orgLevel).show
  orgid.value = dept.sssgsid || dept.ssdwid
  getAqryTotal()
});

//设置是否有保存和等级按钮
const setShowSaveBut = (val) => {
  const dept = getItem("deptId")
  let code = JSON.parse(JSON.stringify(listQuery.orgCode))
  if (code.indexOf("XN") != -1) code = code.replace("XN", "")
  //如果是本单位 或者是 子单位 都显示保存
  if ((dept.ssdwid === code || dept.ssdwid === val.parentid) && (dept.orgBizType == '04' || dept.orgBizType == '52')) {
    return true
  } else {
    return false
  }
}
//设置是否显示统计
const setShowTotal = (code) => {
  const level = code.substring(0, 1)
  let show = false
  switch (level) {
    case "1":
    case "2":
      show = true
      break
    default:
      show = false
  }
  return { show, level }
}
// 工程师配置页面跳转
const onClickConfig = (val) => {
  let name = proxy.$getDictVal(val, D_BZ_PYYYLX);
  pyShow.value = true
  zslx.value = val
  pyTitle.value = name + '聘用列表'
}
//选择右侧部门
function getdeptData(val) {
  clickSsdwid.value = val.id.replace('XN', '')
  // 编制人数权限判断
  let ssdwid = val.id
  let ssdwmc = val.orgname
  let orglevel = val.orglevel.substring(0, 1)
  if (orglevel == '2' && ssdwid.indexOf("XN") != -1) {
    bzrsShow.value = true
    bzrsTitle.value = '省本级'
  } else if (orglevel == '3' && ssdwid.indexOf("XN") != -1) {
    bzrsShow.value = true
    if (ssdwmc.indexOf('复烤') != -1) {
      bzrsTitle.value = '复烤公司本级'
    } else if (ssdwmc.indexOf('黔南') != -1 || ssdwmc.indexOf('黔西南') != -1 || ssdwmc.indexOf('黔东南') != -1) {
      bzrsTitle.value = '全州'
    } else if (ssdwmc.indexOf('市') != -1) {
      bzrsTitle.value = '全市'
    } else {
      bzrsTitle.value = '本级'
    }
  } else if (orglevel == '3' && ssdwid.indexOf('5299') != -1) {
    bzrsShow.value = true
    bzrsTitle.value = '厂本级'
  } else {
    bzrsShow.value = false
  }
  showTotal.value = setShowTotal(val.orglevel).show
  listQuery.orgCode = val.id;
  listQuery.orgName = val.orgname;
  showBut.value = setShowSaveBut(val);
  orgid.value = val.id;

  //如果是本级显示列表
  if (isCity.value) {
    showConfigBut.value = true;
  }
  if (val.id.indexOf("XN") != -1) showTotal.value = false
  // 安全部门都能修改（能看到就能修改，因为能看到是自己的，修改也是自己的 val.id.indexOf("XN") != -1 &&）
  if (isAqbm.value) {
    showConfigBut.value = true;//如果是虚拟账号 显示配置按钮
  }
  getTotaldata();
  getdeptlist()
  hiddentab();
  getPingPAnQy();
}
//获取安全人员统计数据
const getAqryTotal = () => {
  getApi({ orgcode: listQuery.orgCode }, "/mosty-jcgl/aqy/selectInfo").then(res => {
    if (res) listQuery.aqryTotal = res
  })
}
/** 获取评聘安全员数据 */
const getPingPAnQy = () => {
  getApi({ orgId: listQuery.orgCode }, "/mosty-jcgl/assessEmployStaff/selectStaffByOrgId").then(res => {
    if (!res) return
    aqgcsNames.value = res.map(item => item.userName).toString();
    aqgcsCount.value = res.length;
  })
}

// 查询详情信息--右侧的统计和表单
function getTotaldata() {
  getApi({ orgcode: listQuery.orgCode }, '/mosty-jcgl/aqy/selectInfo').then((res) => {
    fromObj.value = res
    fromObj.value.executivename = res.staff.executivename
    fromObj.value.executiveid = res.staff.executiveid
    fromObj.value.leadershipname = res.staff.leadershipname
    fromObj.value.leadershipid = res.staff.leadershipid
    fromObj.value.bzrs = res.staff.bzrs ? res.staff.bzrs : 0;
  })
}
//	查询部门管理列表
function getdeptlist() {
  deptListLoading.value = true
  getApi({ orgcode: listQuery.orgCode }, '/mosty-jcgl/aqy/getBmList').then((res) => {
    if (res) {
      tableData.value = res
      deptListLoading.value = false
      setDeptTableWidth('api')
    }
  }).finally(() => {
    deptListLoading.value = false
  })
}
const getLeaderId = () => {
  const arr = Array.isArray(tableData.value) ? tableData.value : [];
  if (!arr.length) return
  const find = arr.find(item => item.orgBizType == '02')
  return find ? find.deptid : undefined;
}
//登记
const registration = (row) => {
  rowid.value = row.id
  // deptId.value = row.orgBizType == '02' ? row.orid : row.deptid
  deptId.value = row.deptid
  orgId.value = row.orid
  orgBizType.value = row.orgBizType
  mtcsoltype.value = row.mtcsoltype
  comprehensiveShow.value = true;
  // leaderId.value = getLeaderId()
};
// 退出聘用页面
function closePy() {
  pyShow.value = false
  getTotaldata();
  getdeptlist()
}
// 退出登记-刷新
function changeRegi() {
  comprehensiveShow.value = false
  getTotaldata();
  getdeptlist()
}
const loadingShow = ref(false)
/** 是否展示导出弹框 */
const exportVisible = ref(false)
/** 导出 加载状态 */
const exportLoading = ref(false)

/**根据字典获取值
 * @param {Array} dicArr 字典数组
 * @param {String} val 值
 */
function getValByDic(val, dicArr) {

  val = typeof val === 'string' ? val : ''
  /** 是否多个数值 */
  const isMult = val.indexOf(",") > -1
  if (val === undefined) return ''
  dicArr = Array.isArray(dicArr) ? dicArr : []
  /** 字典对象 */
  let dicObj = {}
  for (let i = 0; i < dicArr.length; i++) {
    const item = dicArr[i];
    dicObj[item.value] = item.label
  }
  if (isMult) {
    let valArr = val.split(',')
    return valArr.map(dm => dicObj[dm]).join(',')
  } else {
    return dicObj[val] || val || ''
  }

}
//导出
function onloadExecl(aqrylx) {
  exportVisible.value = false
  let type = ''
  if (aqrylx) {
    type = aqrylx == '0' ? '专职' : '兼职'
  } else {
    type = '全部'
  }
  let title = {
    index: '序号',
    username: '安全员姓名',
    orgname: '所属单位',
    deptname: '所在部门',
    politicalStatus: '政治面貌',
    xb: '性别',
    csrq: '出生年月',
    telephone: '联系方式',
    jobTitle: '岗位名称',
    highestTechnical: '最高技术资格名称',
    dutyName: '职务',
    highestFullTimeEducation: '文化程度',
    expertise: '擅长领域',
    fullTimeYearly: '累计从事专职安全管理工作年限',
    zasLevel: '注册安全工程师级别',
    zxsLevel: '注册消防工程师级别',
  }
  //D_BZ_AQRYWHCD
  loadingShow.value = true
  getApi({ orgcode: listQuery.orgCode, aqrylx: aqrylx }, '/mosty-jcgl/aqy/exportExcel').then((res) => {
    if (res) {
      let resArr = Array.isArray(res) ? res : []
      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 tablename = listQuery.orgName + type + '安全管理人员台账.xlsx'

      exportXlsx(title, resArr, XLSX, tablename);
      loadingShow.value = false
    }
  }).catch(err => {
    loadingShow.value = false
  })
}
//保存安全人员信息
const savefrom = async () => {
  let data = {
    orid: fromObj.value.orgcode,
    bzrs: fromObj.value.bzrs,
  }
  postApi(data, '/mosty-jcgl/staff/saveBzrs').then(() => {
    ElMessage.success("编制人数保存成功");
  })
}

const handleCollapse = () => {
  iconChange.value = !iconChange.value;
  if (iconChange.value) {
    lfBoxWid.value = "300px";
    rgBoxWid.value = "calc(100% - 300px)";
  } else {
    lfBoxWid.value = "40px";
    rgBoxWid.value = "calc(100% - 40px)";
  }
};
</script>

<style lang="scss" scoped>
.eltabs4 {
  height: calc(100vh - 440px);
  // height: calc(100vh - 490px);

  .bottom-total {
    width: 100%;
    height: 40px;
    border: 1px solid #ececec;
  }

  .bottom-total-table {
    width: 100%;
    border-collapse: collapse;
    color: #000;
    height: 40px;
    text-align: center;

    tr td {
      border: 1px solid #ececec;
      border-top: none;
    }
  }
}

.bottom-total {
  color: #000;
  width: 100%;
  height: 40px;
  border: 1px solid #ececec;
}

.bigBox {
  display: flex;
  overflow: hidden;

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

    .el-icon {
      cursor: pointer;
    }
  }

  .left {
    width: 300px;
    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;
    }
  }

  .rightTotal {
    width: calc(100% - 320px);
  }

  .right {
    width: 100%;
    padding: 0 10px;
    margin: 0px 0 10px 10px;
    background: #fff;
    box-sizing: border-box;
    overflow: hidden;

    .perNum {
      // height: 271px;
      height: 230px;
    }

    .head {
      display: flex;
      width: 100%;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px dashed var(--el-color-primary);
      height: 60px;
      color: #000;

      .el-select {
        width: 180px;
      }
    }

    .from_box {
      margin-top: 18px;

      .el-form {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;

        .el-form-item {
          display: flex;
          align-items: center;
        }

        .sec {
          display: flex;
          justify-content: space-between;

          div {
            width: 45%;
            display: flex;
            justify-content: space-between;
            align-items: center;

            .el-form-item {
              width: 100%;

              .el-input {
                width: 90%;
              }
            }
          }
        }
      }
    }

    .detail {
      border-top: 1px dashed var(--el-color-primary);
      padding: 10px 10px;
      display: flex;
      justify-content: space-between;

      .detail-item {}

      &>div {
        width: 30%;
        // width: 46%;
        text-align: center;
        background-color: var(--el-color-primary);
        padding: 25px 0;
        font-size: 18px;
        border-radius: 10px;

        span {
          font-size: 18px;
          display: block;
          width: 100%;
          height: 37px;
          line-height: 37px;
          padding: 0;
          margin: 0;
        }
      }

      // .detail-number {
      //   // font-size: 37px
      // }
    }

    .title {
      border-top: 1px dashed var(--el-color-primary);
    }
  }
}

.tabBox {
  .el-table {
    border-bottom: 1px solid var(--el-color-primary);
    overflow: auto;
  }
}

.ld_box {
  display: flex;

  >div {
    display: flex;
    margin-right: 30px;

    .el-form-item {
      margin-right: 10px;
    }
  }
}

::v-deep .el-form--label-top .el-form-item .el-form-item__label {
  margin-bottom: 0px;
}

.pointer {
  cursor: pointer;
}
</style>