<template>
  <div class="bottom" :style="{ height: `calc(100vh - ${props.isOpen ? 379 : 245}px)` }">
    <TimeCondition :popover="popover" :ywId="ywId" @change="timeCondition" :title="title" @update="timeUpdate">
      <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" :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:0px 5px !important;" @click="handleExport">导出</el-button>

      </template>
    </TimeCondition>
    <el-table :data="tableData" border style="width: 99%" v-loading="tableLoading"
      :header-cell-style="{ background: '#f5f5f5' }" height="calc(100% - 100px)">
      <el-table-column type="selection" width="55" :selectable="onSelectable" />
      <el-table-column label="序号" type="index" align="center" width="100" />
      <el-table-column label="企业名称" prop="orgName" width="240" />
      <el-table-column label="职业危害场所总数量（个）" prop="placeCount" />
      <el-table-column label="职业危害因素数量（个）" prop="typeCount" />
      <el-table-column prop="failReportCount" label="未上报总数">
        <template #default="{ row }">
          <span v-if="row.failReportCount == 0">0</span>
          <span v-else-if="row.failReportCount > 0" style="color: red; cursor: pointer" @click="onView(row, '2')">{{
            row.failReportCount }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="最后一次上报时间" />
      <el-table-column prop="status" label="当前上报状态">
        <template #default="{ row }">
          <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 prop="sbcs" label="累计上报次数">
        <template #default="{ row }">
          <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>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <el-link type="primary" @click="onView(row, '')">查看</el-link>
          <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="若更新数据将重置，是否确认更新?"
            @confirm="rowUpdate(row.orgCode)">
            <template #reference>
              <el-button type="link" :disabled="setUpdate(row)">更新{{  }}</el-button>
            </template>
          </el-popconfirm>
          <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="是否确认驳回?"
            @confirm="onRevoke(row.orgCode)">
            <template #reference>
              <el-button type="link" :disabled="setPeject(row.status)" v-if="!isTown">驳回</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <DetailDialog ref="detailDialog" :title="dialogTitle" :query="query" :rowItem="rowItem" :dicData="dicData"
    :reportStatus="reportStatus" @close="getPageData" />
  <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, onBeforeUnmount, ref, reactive, computed, getCurrentInstance, defineAsyncComponent, watch, inject } from "vue"
import TimeCondition from "@/views/dataReportWork/components/TimeCondition"
import { getApi, postApi } from "@/api/tobAcco_api.js"
import DetailDialog from "./XfzstzDialog"
import { getItem } from "@/utils/storage"
import { ElMessage, ElLoading } from "element-plus"
import { filterqx } from "@/utils/auth.js"
import ReportHistory from "./ReportHistory.vue"
import * as MOSTY from "@/components/MyComponents/index"
import { zywhcsXlsx } from "../tabs//tabtool";
const { proxy } = getCurrentInstance()
const props = defineProps({ isOpen: Boolean, orgCode: String, dict: Object })
const { D_TB_ZYJK_WHYS, D_TB_JCZQ } = proxy.$dict("D_TB_ZYJK_WHYS", "D_TB_JCZQ")
const ywId = inject("ywId") || ""
const title = ref("职业危害场所")
const popover = reactive({
  title: title.value,
  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. 职业危害场所：相同企业名称、相同统计周期下，“职业危害场所”中场所名称不可重复。
8.  职业危害场所：
（1）职业危害场所名称：烟叶收购站点、烟叶仓储，不计入职业危害场所；
（2）职业危害因素：粉尘、噪声、高温、其他；在职业危害场所中，职业危害因素可选择多个。
（3）检测记录：需根据职业危害场所中所包含的职业危害因素分别进行统计填报，填写本年度截止到当前统计周期的检测信息。
  `
})
const currentCode = getItem("deptId").ssdwid
const permisssion = reactive({
  manualUpdate: {
    loading: false,
    disabled: false
  },
  report: {
    count: 0,
    title: "上报",
    disabled: true
  },
  revoke: {
    disabled: true
  }
})
// 是否是省账号
const isProvinces = computed(() => {
  return filterqx("isaqbm") == "1" && filterqx("isSgs") == "1"
})
// 是否是市账号
const isCity = computed(() => {
  return filterqx("isaqbm") == "1" && filterqx("isgs") == "1"
})
//县级账号
const isTown = computed(() => {
  return filterqx("isaqbm") == "1" && filterqx("isgs") != "1" && filterqx("isSgs") != "1"
})
const isRevoke = computed(() => {
  return !isProvinces.value || (query.orgCode.includes(currentCode) && query.orgCode.includes("XN")) ? true : false
})
/** 上报提示 */
const reportTitleTip = computed(() => {
  if(!permisssion.report.disabled) return
  if(isTown.value) return "县级：需行状态为【未上报】"
  if(isCity.value) return "市级：需每行状态为【已上报】或【无需上报】（注:本级需为【未上报】）"
  return isProvinces.value ? "省级：需每行状态为【已上报】或【无需上报】或【上报到国家局】（注:本级需为【未上报】）" : "上报确认"
})

const query = reactive({
  orgCode: getItem("deptId").ssdwid,
  year: "",
  jd: ""
})
const tableLoading = ref(false)
const tableData = ref([])
const detailDialog = ref(null)
const rowItem = ref(null)
const dialogTitle = ref("")
const dicData = ref(null)
const reportStatus = ref("")
const reportHistoryRef = ref(null)
const historyParams = ref(null)
const reportResultInfo = ref({})
const dialogsbyy = ref(false)
const IsCksbjg = ref(false)
const loadingcksbjg = ref(false)
const isReportResult = ref(false)
const isAutoReport = ref(false)
const timer = ref(null)
/** 是否是第一次触发【手动更新】事件（列表无长度需调用一次） */
const isFirstManual = ref(true);
/** 是否需要刷新（根据传过来的时间，和选择的时间判断） */
const isNeedRefresh = ref(false)
const onView = (e, type) => {
  // e.complianceLevelCode = e.complianceLevelCode + "";
  reportStatus.value = type
  detailDialog.value.dialogVisible = true
  rowItem.value = e
  dialogTitle.value = `${title.value}（${e.baOrgName}）`
  dicData.value = { D_TB_ZYJK_WHYS, D_TB_JCZQ }
}
const onCount = e => {
  reportHistoryRef.value.dialogVisible = true
  historyParams.value = {
    orgCode: e.orgCode,
    sbcs: e.sbcs,
    year: query.year,
    jd: query.jd
  }
}
const timeCondition = val => {
  query.year = val.yearValue
  query.jd = val.quarterValue
  if (props.orgCode) getPageData()
}

const manualUpdate = () => {
  permisssion.manualUpdate.loading = true
  // setTimeout(() => {
  //   ElMessage({
  //     message: "更新成功",
  //     type: "success"
  //   })
  //   permisssion.manualUpdate.loading = false
  // }, 1e3)
  // return
  getApi({ orgCode: query.orgCode }, `/mosty-jcgl/data/hazardPlace/syncLocal`)
    .then(res => {
      getPageData()
      ElMessage({
        message: "更新成功",
        type: "success"
      })
      permisssion.manualUpdate.loading = false
    })
    .finally(() => {
      tableLoading.value = false
      permisssion.manualUpdate.loading = false
    })
}
const timeUpdate = val => {
  isNeedRefresh.value = val
}
/** 触发更新，避免无sourceId */
const handleManualUpdate = () => {
  if (!isFirstManual.value) return
  if (!isNeedRefresh.value) return
  manualUpdate()
  isFirstManual.value = false
}
const rowUpdate = code => {
  tableLoading.value = true
  getApi({ orgCode: code }, `/mosty-jcgl/data/hazardPlace/syncLocal`)
    .then(res => {
      getPageData()
      ElMessage({
        message: "更新成功",
        type: "success"
      })
    })
    .finally(() => {
      tableLoading.value = false
    })
}

const getPageData = (val = true) => {
  tableLoading.value = true
  tableData.value = []
  if (timer.value) {
    window.clearInterval(timer.value)
    timer.value = null
  }
  getApi(query, `/mosty-jcgl/data/hazardPlace/list`)
    .then(res => {
      if (res) {
        // res[0].sbcs = 9
        if (!res?.length) handleManualUpdate() // 无数据时更新一次
        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
        }
      }
    })
    .catch(err => {
      tableLoading.value = false
    })
}
// 查看省局上报结果
const onReportResult = val => {
  loadingcksbjg.value = true
  getApi({ year: query.year, id: ywId.value, 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: ywId.value }, "/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/hazardPlace/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: ywId.value }, "/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 = "首次上报"
        }
        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
  postApi({...query, orgCode: code}, "/mosty-jcgl/data/hazardPlace/withdrawReport").then(res => {
    ElMessage({
      message: `${code === currentCode ? "撤销" : "驳回"}成功`,
      type: "success"
    })
    getPageData()
  })

}
const onReport = async () => {
  postApi(query, "/mosty-jcgl/data/hazardPlace/reportData").then(res => {
    ElMessage({
      message: "上报成功",
      type: "success"
    })
    isAutoReport.value = true
    getPageData()
    onReportResult()
  }).catch(() => {
    // ElMessage({
    //   message: "上报失败",
    //   type: "error"
    // })
  })

}

onBeforeUnmount(() => {
  if (timer.value) {
    window.clearInterval(timer.value)
    timer.value = null
  }
})

watch(
  () => props.orgCode,
  (n, o) => {
    if (n && query.year) {
      query.orgCode = n
      getPageData()
    }
  }
)
const handleExport = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '导出中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  getApi(query, '/mosty-jcgl/data/export/placeStatistics').then(res => {
    zywhcsXlsx(res ? res : [], props.dict, popover.content)

  }).finally(() => {
    loading.close()
  })
}
</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;
}

::v-deep .disable-selection .cell {
  cursor: not-allowed;

  .el-checkbox {
    pointer-events: none;
  }

  .el-checkbox__inner {
    background-color: var(--el-checkbox-disabled-input-fill);
    border-color: var(--el-checkbox-disabled-border-color);
  }
}
</style>
