<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 : 236}px)` }">
        <TimeCondition :popover="popover" :ywId="props.id" @change="timeCondition" :title="title + '台账'">
          <template #right>
            <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="若更新数据将重置，是否确认更新?"
              @confirm="manualUpdate">
              <template #reference>
                <el-button type="primary" class="mr5" :loading="permisssion.manualUpdate.loading" v-if="isProvinces"
                  :disabled="permisssion.manualUpdate.disabled">手动更新</el-button>
              </template>
            </el-popconfirm>
            <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="是否确认撤销?"
              @confirm="onRevoke(currentCode)">
              <template #reference>
                <el-button type="primary" class="mr5" :disabled="permisssion.revoke.disabled"
                  v-if="isRevoke">撤销</el-button>
              </template>
            </el-popconfirm>
            <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red"
              :title="`是否确认${permisssion.report.title}?`" @confirm="onReport">
              <template #reference>
                <el-button :title="reportTitleTip" type="primary" class="mr5" :loading="sbloading"
                  :disabled="permisssion.report.disabled">{{
                  permisssion.report.title || '上报' }}</el-button>
              </template>
            </el-popconfirm>
            <el-button type="primary" style="margin-left: 5px !important" @click="onReportResult('view')"
              :loading="loadingcksbjg" v-if="IsCksbjg">查看上报结果</el-button>
            <el-button type="primary" style="margin-left: 5px;" @click="onExport">导出</el-button>
          </template>
        </TimeCondition>
        <el-table :data="tableData" style="width: 99%" border v-loading="tableLoading"
          :header-cell-style="{ background: '#F6F6F6' }" height="calc(100% - 100px)" :cell-style="cellStyle">
          <el-table-column type="selection" width="55" :selectable="onSelectable" />
          <el-table-column :label="item.label" :prop="item.prop" :fixed="item?.fixed"
            v-for="(item, index) in pageData.columnTable" :key="index">
            <template #default="{ row }" v-if="item.prop == 'wsbNum'">
              <span v-if="row.wsbNum == 0">0</span>
              <span v-else-if="row.wsbNum > 0" style="color: red; cursor: pointer" @click="onView(row, '2')">{{
                row.wsbNum }}</span>
            </template>
            <template #default="{ row }" v-if="item.prop == 'sbcs'">
              <span v-if="row.sbcs == 0">0</span>
              <el-link v-else-if="row.sbcs > 0" type="primary" @click="onCount(row)">{{ row.sbcs }}</el-link>
            </template>
            <template #default="{ row }" v-if="item.prop == 'status'">
              <span v-if="row.status == '1'" style="color: green">已上报</span>
              <span v-else-if="row.status == '2'" style="color: red">未上报</span>
              <span v-else-if="row.status == '3'" style="color: #999">无需上报</span>
              <span v-else-if="row.status == '4'" style="color: green">已上报到省公司</span>
              <span v-else-if="row.status == '5'" style="color: orange">正在上报国家局</span>
              <span v-else-if="row.status == '6'" style="color: green">已上报到国家局</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="140" fixed="right">
            <template #default="{ row }">
              <!-- <el-link type="primary" @click="manualUpdate(row.orgCode)">更新</el-link> -->
              <!-- <el-link type="primary" @click="onEdit(row)">编辑</el-link>
              <el-link type="primary" @click="onView(row)">查看</el-link> -->
              <el-link type="primary" @click="onView(row, '')">查看</el-link>
              <el-popconfirm confirm-button-text="是" cancel-button-text="否"
                :disabled="setUpdate(row) || !(row.orgCode === orgid)" icon-color="red" title="若更新数据将重置，是否确认更新?"
                @confirm="rowUpdate(row.orgCode)">
                <template #reference>
                  <RowLink :disabled="setUpdate(row) || !(row.orgCode === orgid)">更新</RowLink>
                </template>
              </el-popconfirm>
              <el-popconfirm confirm-button-text="是" cancel-button-text="否" :disabled="setPeject(row.status)"
                icon-color="red" title="是否确认驳回?" @confirm="onRevoke(row.orgCode)">
                <template #reference>
                  <RowLink type="link" :disabled="setPeject(row.status)" v-if="!isTown">驳回</RowLink>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
  <DialogTable :title="dialogTitle" @close="dialogClose" :isProvinces="isProvinces" :orgCode="currId" :isEdit="isEdit"
    :params="query" v-if="dialogVisible" :reportStatus="reportStatus" :rowItem="rowItem" />

  <ReportHistory ref="reportHistoryRef" :params="historyParams" />

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

<script setup>
import { onMounted, ref, reactive, watch, computed, onBeforeUnmount, getCurrentInstance } 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 DialogTable from "../components/DialogTable.vue"
import ReportHistory from "../components/ReportHistory.vue"
import { getItem } from "@/utils/storage"
import { ElMessage, ElLoading } from "element-plus"
import { filterqx } from "@/utils/auth.js"
import RowLink from "@/views/dataReportWork/components/RowLink.vue"
const { proxy } = getCurrentInstance();
const { D_BZ_XB, D_BZ_AQRYSCLY, D_BZ_ZCAQGCSJB, D_BZ_ZCXFGCSJB, D_BZ_SFWAJWCY, D_BZ_SFWAQGCS, D_BZ_ZZMM } = proxy.$dict(
  "D_BZ_XB", "D_BZ_AQRYSCLY", "D_BZ_ZCAQGCSJB", "D_BZ_ZCXFGCSJB", "D_BZ_SFWAJWCY", "D_BZ_SFWAQGCS", "D_BZ_ZZMM"
);
import { exportXlsx } from "./tab0Tool.js"

const props = defineProps({ isOpen: Boolean, id: String, title: String, orgCode: String })
const pageData = reactive({
  dateTable: [],
  columnTable: [
    { label: "企业名称", prop: "orgName", fixed: "left" },
    { label: "专职安全管理人员数量（人）", prop: "zzaqryzs" },
    { label: "注安师人员数量（人）", prop: "zasrs" },
    { label: "注消师人员数量（人）", prop: "zxsrs" },
    { label: "安技委成员人数（人）", prop: "ajwrs" },
    { label: "评聘为安全工程师人数（人）", prop: "aqgcsrs" },
    { label: "未上报总数", prop: "wsbNum", fixed: "right" },
    { label: "最后一次上报时间", prop: "updateTime", fixed: "right" },
    { label: "当前上报状态", prop: "status", fixed: "right" },
    { label: "累计上报次数", prop: "sbcs", fixed: "right" }
  ],
  listQuery: {
    pageNum: 1,
    pageSize: 2000
  },
  ids: []
})
const popover = reactive({
  title: "",
  content: `
  填表说明：
1. 填报单位：省级单位名称；
2. 企业名称：各省级单位机关或下属单位名称；
3. 统计频次：季度。
4. 提交周期：
● 第一季度：1月1日-4月5日
● 第二季度：4月1日-7月5日
● 第三季度：7月1日-10月10日
● 第四季度：10月1日-12月25日
5. 填写范围：
专职安全管理人员数量包含：配置在安全管理部门和其他部门专职安全员（包含车间、县局级等专职安全员）
统计范围以人事部门设置岗位名称为准。
6. 安全管理队伍人员与上周期没有变化，可使用“复制上周期”功能，将上周期数据同步至本周期。
7. 若没有安全管理队伍人员，可不添加数据；但在周期对应的提交时间范围内仍需处长账号进行“上报确认”操作。
8. 相同统计周期下，“手机号”不可重复。
9. 所在部门（单位）是指：卷烟厂的二级部门、市级公司的二级单位、市级公司机关部门。
10. 注安师资质：高级、中级、初级、无。
11. 注消师资质：一级、二级、高级、无。
12. 擅长领域：按照安技委专家库分类，可多选（最多选2项，无 与其他擅长领域不能同时选择）。
(参照安技委推荐表：体系建设、消防安全、设备安全、危化品安全、交通安全、基建安全、电气安全、仓储安全
、粉尘防爆、应急管理、职业健康、无)
13. 是否为安技委成员：包括以往安技委成员。
  `
})
/** 登录人单位id */
const currentCode = getItem("deptId").ssdwid
const permisssion = reactive({
  manualUpdate: {
    loading: false,
    disabled: false
  },
  report: {
    count: 0,
    title: "上报",
    disabled: true
  },
  revoke: {
    disabled: true
  }
})
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 isRevoke = computed(() => {
  return !isProvinces.value || (query.orgCode.includes(currentCode) && query.orgCode.includes("XN")) ? true : false
})
const query = reactive({
  orgCode: getItem("deptId").ssdwid,
  year: "",
  jd: ""
})
/** 上报提示 */
const reportTitleTip = computed(() => {
  if (!permisssion.report.disabled) return
  if (isTown.value) return "县级：需行状态为【未上报】"
  if (isCity.value) return "市级：需每行状态为【已上报】或【无需上报】（注:本级需为【未上报】）"
  return isProvinces.value ? "省级：需每行状态为【已上报】或【无需上报】或【上报到国家局】（注:本级需为【未上报】）" : "上报确认"
})
const reportStatus = ref("")
const rowItem = ref(null)
const tableLoading = ref(false)
const tableData = ref([])
const dialogVisible = ref(false)
const practitioners = ref([])
const currId = ref(null)
const dialogTitle = ref("")
const isEdit = ref(true)
const reportHistoryRef = ref(null)
const historyParams = ref(null)
// const isSfsb = ref(false)
const reportResultInfo = ref({})
const dialogsbyy = ref(false)
const IsCksbjg = ref(false)
const loadingcksbjg = ref(false)
const isReportResult = ref(false)
const isAutoReport = ref(false)
const sbloading = ref(false)
const timer = ref(null)
// 关闭弹窗
const dialogClose = val => {
  dialogVisible.value = false
  getPageData()
}
const onView = (e, type) => {
  dialogVisible.value = true
  isEdit.value = false
  // isSfsb.value = e.sfsb == "1" ? true : false
  currId.value = e.orgCode
  reportStatus.value = type
  rowItem.value = e
  dialogTitle.value = `安全管理队伍列表（${e.orgName}）`
}

const onCount = e => {
  reportHistoryRef.value.dialogVisible = true
  historyParams.value = {
    orgCode: e.orgCode,
    sbcs: e.sbcs,
    year: query.year,
    jd: query.jd
  }
}
watch(
  () => props.orgCode,
  (n, o) => {
    if (n && query.year) {
      query.orgCode = n
      getPageData()
    }
  }
)
const timeCondition = val => {
  query.year = val.yearValue
  query.jd = val.quarterValue
  query.orgCode = props.orgCode
  if (props.orgCode) getPageData()
}

const manualUpdate = () => {
  permisssion.manualUpdate.loading = true
  setTimeout(() => {
    ElMessage({
      message: "更新成功",
      type: "success"
    })
    permisssion.manualUpdate.loading = false
  }, 1e3)
  return
  getApi({}, `/mosty-jcgl/data/safeManageTeam/upData`)
    .then(res => {
      getPageData()
      ElMessage({
        message: "更新成功",
        type: "success"
      })
      permisssion.manualUpdate.loading = false
    })
    .finally(() => {
      tableLoading.value = false
      permisssion.manualUpdate.loading = false
    })
}
const rowUpdate = code => {
  tableLoading.value = true
  getApi({ orgCode: code }, `/mosty-jcgl/data/safeManageTeam/syncLocal`)
    .then(res => {
      getPageData()
      ElMessage({
        message: "更新成功",
        type: "success"
      })
    })
    .finally(() => {
      tableLoading.value = false
    })
}
const getPageData = (val = true) => {
  tableLoading.value = true
  if (timer.value) {
    window.clearInterval(timer.value)
    timer.value = null
  }
  postApi(query, "/mosty-jcgl/data/safeManageTeamStat/querySafeManageTeamStat").then(res => {
    if (res) {
      tableData.value = res
      tableLoading.value = false
      setPermisssion()
      if (val && res[0]?.status == "5") {
        timer.value = window.setInterval(() => {
          if (!isReportResult.value) {
            window.clearInterval(timer.value)
            timer.value = null
            isAutoReport.value = false
          }
          onReportResult()
        }, 1e4)
      } else {
        window.clearInterval(timer.value)
        timer.value = null
      }
    }
  })
}

const onExport = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '导出中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  getApi(query, '/mosty-jcgl/data/export/safeManageTeam').then(res => {
    if (res) {
      for (let i = 0; i < res.length; i++) {
        res[i].politicalAffiliation = res[i].politicalAffiliation ? res[i].politicalAffiliation : proxy.$getDictVal(res[i].politicalAffiliationCode, D_BZ_YSFYLB);
        res[i].safetyMemberFlag = res[i].safetyMemberFlag == '1' ? '是' : '否'
        res[i].seFlag = res[i].seFlag == '1' ? '是' : '否'
      }
      exportXlsx(res, { D_BZ_XB, D_BZ_AQRYSCLY, D_BZ_ZCAQGCSJB, D_BZ_ZCXFGCSJB, D_BZ_SFWAJWCY, D_BZ_SFWAQGCS, D_BZ_ZZMM }, popover.content)
    }
  }).finally(() => {
    loading.close()
  })

}
// 查看省局上报结果
const onReportResult = val => {
  loadingcksbjg.value = true
  getApi({ year: query.year, id: props.id, jtsj: query.jd }, "/mosty-jcgl/dataCommon/getSbjg")
    .then(res => {
      if (res) {
        reportResultInfo.value = res
        if (val == "view") {
          dialogsbyy.value = true
        }
        if (res.returnCode == "200" && !res.returnHttpCode) {
          isReportResult.value = true
          permisssion.report.disabled = true
        } else {
          if (isAutoReport.value) {
            getPageData()
          }
          if (timer.value) {
            isAutoReport.value = false
          }
          window.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 onSelectable = row => {
  return true
}
const restPermisssion = () => {
  permisssion.manualUpdate.loading = false
  permisssion.manualUpdate.disabled = false
  permisssion.report.count = 0
  permisssion.report.title = "上报"
  permisssion.report.disabled = true
  permisssion.revoke.disabled = true
}
const getRevoke = async () => {
  let res = await postApi(query, `/mosty-jcgl/data/safeManageTeamStat/isRevokedFlag`)
  permisssion.revoke.disabled = res ? false : true
}
const setPermisssion = async () => {
  const currentDate = new Date()
  const currentYear = currentDate.getFullYear()
  const currentQuarter = Math.floor(currentDate.getMonth() / 3) + 1

  restPermisssion()
  if (query.year != currentYear || query.jd != currentQuarter) {
    permisssion.manualUpdate.disabled = true
    return
  }
  // 是否七个工作日 (判断是否上报时间)
  let res = await getApi({ id: props.id }, "/mosty-jcgl/dataCommon/sfQggzr")
  if (!res) {
    permisssion.manualUpdate.disabled = true
    return
  }
  getRevoke()
  let count = 0
  tableData.value.forEach(item => {
    let onTown = () => {
      if (item.status == "2" || item.status == "3") permisssion.report.disabled = false
    }
    if (isTown.value) {
      onTown()
    }
    if (isCity.value) {
      if (query.orgCode.includes(currentCode) && query.orgCode.includes("XN")) {
        //本级
        onTown()
      } else if (query.orgCode === currentCode) {
        //市
        if (["1", "3", "4"].includes(item.status)) count++
        if (count > 0 && count === tableData.value.length) permisssion.report.disabled = false
      } else {
        //其他
      }
    }
    if (isProvinces.value) {
      if (query.orgCode.includes(currentCode) && query.orgCode.includes("XN")) {
        //省级
        permisssion.report.title = "上报"
        onTown()
      } else if (query.orgCode === currentCode) {
        //省
        if (item.sbcs * 1 > 0) {
          permisssion.report.count = item.sbcs * 1
          permisssion.report.title = "修改上报"
        } else {
          permisssion.report.title = "首次上报"
        }
        // status 1: 已上报 4：已上报到省， 6已上报到国家
        if (["1", "4", "6"].includes(item.status)) count++
        if (count > 0 && count === tableData.value.length) permisssion.report.disabled = false
      } else {
        //其他
        permisssion.report.disabled = true
      }
    }
  })
}
const setPeject = status => {
  if (isCity.value) {
    return ["1"].includes(status) ? false : true
  }
  if (isProvinces.value) {
    return ["1", "4", "6"].includes(status) ? false : true
  }
}
const setUpdate = row => {
  if (isTown.value) {
    return row.updateStatus === 1 ? false : true
  }
  if (isCity.value) {
    // if (query.orgCode.includes(currentCode) && query.orgCode.includes("XN")) {
    return row.updateStatus === 1 && ["2", "3"].includes(row.status) ? false : true
    // }
  }

  if (isProvinces.value) {
    if (query.orgCode.includes(currentCode)) {
      return row.updateStatus === 1 ? false : true
    } else return true
  }
}
const onRevoke = async code => {
  // query.orgCode = code
  let res = await postApi({ ...query, orgCode: code }, "/mosty-jcgl/data/safeManageTeamStat/revokeData")
  if (res) {
    ElMessage({
      message: `${code === currentCode ? "撤销" : "驳回"}成功`,
      type: "success"
    })
    getPageData()
  }
}
const onReport = async () => {
  sbloading.value = true
  try {
    let res = await postApi(query, "/mosty-jcgl/data/safeManageTeamStat/reportData")
    if (res) {
      ElMessage({
        message: "上报成功",
        type: "success"
      })
      isAutoReport.value = true
      sbloading.value = false
      getPageData()
      onReportResult()
    } else {
      ElMessage({
        message: "上报失败",
        type: "error"
      })
      getPageData()
      sbloading.value = false
    }
  } catch (error) {
    getPageData()
    sbloading.value = false
  }

}
const cellStyle = ({ row, column, rowIndex, columnIndex }) => {
  if ([2, 3, 4, 5, 6].includes(columnIndex)) {
    return { background: 'rgb(240,249,235) !important' }
  }
  if (columnIndex === 7) {
    return { background: "var(--el-color-primary-light-8)!important" }
  }
}

onMounted(() => {
  if (isAuth.value) {
    orgid.value = orgid.value + 'XN'
  }
  popover.title = props.title.replace("数据", "")
})
onBeforeUnmount(() => {
  if (timer.value) {
    window.clearInterval(timer.value)
    timer.value = null
  }
})


</script>

<style lang="scss" scoped>
::v-deep .el-button--link {
  border: none;
  background: none;
  color: var(--el-color-primary);
  padding: 0;
  margin-left: 10px !important;

  &:hover,
  &:focus {
    background: none;
    border: none;
    opacity: 0.9;
  }
}

::v-deep .el-button--link.is-disabled {
  color: #808596;
  border: none;
  background: none;
}

.content {
  .topper {
    display: flex;

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

  .bottom {
    padding: 0 15px 10px 15px;
  }
}

:v-deep .el-dialog {
  height: 600px !important;
}
</style>
