<template>
  <section class="stage-wrapper">
    <section class="right">
      <div class="header">
        <div class="topper">
          <span class="base">
            <el-icon>
              <WarningFilled />
            </el-icon>危险物品管理</span>
        </div>
        <div class="bottom">
          <el-tabs v-model="activeTab" type="card">
            <el-tab-pane :label="item.label" :name="item.value" v-for="(item, i) in tabs" :key="i" />
          </el-tabs>
        </div>
      </div>
      <div class="bottom" :style="{ height: `calc(100vh - 230px)` }">
        <TimeCondition :ywId="ywId" :byTime="byTime" :title="title" :popover="popover" @change="onChange"
          @update="timeUpdate">
          <template #right>
            <div v-if="isProvinces">
              <el-popconfirm 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 || !isShowCurrent"
                    :loading="manual.loading">手动更新</el-button>
                </template>
              </el-popconfirm>
              <el-button type="primary" @click="handleReport" v-if="isShowBtn && uploadNum == 0"
                :disabled="isAllSumbit || !isShowCurrent">首次上报</el-button>
              <el-button type="primary" @click="handleReport" v-else-if="isShowBtn && uploadNum > 0"
                :disabled="!isShowCurrent || isAllSumbit">修改上报</el-button>
              <el-button type="primary" style="margin-left: 5px !important" @click="onReportResult('view')"
                :loading="loadingcksbjg" v-if="IsCksbjg">查看上报结果</el-button>
            </div>
            <el-button type="primary" style="margin:0px 5px !important;" @click="handleExport">导出</el-button>

          </template>
        </TimeCondition>
        <el-table :data="tableData" @selection-change="selectionChange" style="width: 99%" v-loading="tableLoading"
          border :header-cell-style="{ background: '#f5f5f5' }" height="calc(100% - 100px)">
          <el-table-column type="selection" width="55" :selectable="handleDisable" />
          <el-table-column label="序号" type="index" align="center" width="100" />
          <el-table-column label="企业名称" prop="baOrgName" width="240" />
          <el-table-column label="危险物品种类数量（类）" prop="typeCount" />
          <!-- <el-table-column label="是否独立设置" width="110">
          <template #default="scope">
            {{ scope.row.independentSettingsFlag && scope.row.independentSettingsFlag === 1 ? "是" : "否" }}
          </template>
        </el-table-column> -->
          <el-table-column prop="updateTime" label="最后一次上报时间" />
          <el-table-column prop="status" label="当前上报状态">
            <template #default="scope">
              <span style="color: red" v-if="scope.row.status == '0'">未上报</span>
              <span style="color: green" v-if="scope.row.status == '1'">已上报</span>
              <span style="color: green;" v-if="scope.row.status == '99'">已上报国家局</span>
            </template>
          </el-table-column>
          <el-table-column label="累计上报次数">
            <template #default="{ row }">
              {{ row.sbcs }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160" fixed="right">
            <template #default="{ row }">
              <el-link type="primary" @click="manualUpdate(row.orgCode)" :disabled="!isShowCurrent"
                style="margin-right: 10px">更新</el-link>
              <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" @click="onView(row)">查看</el-link>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <DetailDialog ref="detailDialog" :title="dialogTitle" :query="query" :rowItem="rowItem" @close="closeChange" />
      <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>
    </section>
  </section>
</template>

<script setup>
import { onMounted, onBeforeUnmount, ref, reactive, computed, getCurrentInstance, watch, inject } from "vue"
import TimeCondition from "@/views/dataReportWork/components/TimeCondition"
import { getApi } from "@/api/tobAcco_api.js"
import DetailDialog from "./XfzstzDialog"
import { getItem } from "@/utils/storage"
import { filterqx } from "@/utils/auth.js"
import { ElMessage, ElLoading } from "element-plus";
import { wxhxpXlsx } from "./tabtool";
const { proxy } = getCurrentInstance();
const { D_BZ_SF } = proxy.$dict("D_BZ_SF");

const activeTab = ref("32")
const tabs = [
  {
    label: "危险物品管理",
    value: "32"
  }
]
const apiPath = `/mosty-jcgl/data/hazardChemicalInfo`
const ywId = ref("32")
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. 危险化学品名称：按照《危险化学品目录》中规范名称进行填报；系统支持按危险化学品编码、危险化学品名称、
及危险化学品别名等3个信息的模糊检索匹配。
7. 最大储存量、年使用量单位：L/kg，保留四位小数。
8. 是否属于剧毒品：依据国家颁布的《剧毒化学品目录》确定。
9. 是否属于易制毒品：依据国家颁布的《易制毒化学品分类和目录》确定。
10. 是否属于易制爆品：依据国家颁布的《易制爆危险化学品名录》确定。
  `
})
const byTime = ref("")
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 isShowBtn = ref(false)
const uploadNum = ref(0)
const query = reactive({
  orgcode: getItem("deptId").ssdwid,
  year: "",
  jd: ""
})
const tableLoading = ref(false)
const tableData = ref([])
const detailDialog = ref(null)
const historyDialog = ref(null)
const rowItem = ref(null)
const dialogTitle = ref("")
const isShowCurrent = ref(true)
const manual = reactive({
  loading: false,
  disabled: true
})
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 emit = defineEmits(["onQuery"])

const timeUpdate = val => {
  isNeedRefresh.value = val
}
// 是否可以选择多选
const handleDisable = row => {
  return true
  // if (
  //   row.effectiveUntilDate
  // ) {
  //   return true;
  // } else {
  //   false;
  // }
}
const getShowBtn = async () => {
  isShowBtn.value = await getApi({ id: ywId.value }, "/mosty-jcgl/dataCommon/sfQggzr")
  uploadNum.value = await getApi({ year: query.year, id: ywId.value, jtsj: query.jd }, "/mosty-jcgl/dataCommon/getSccs")
}
/** 时间选择器 change事件
 * @param {*} val
 * @param {*} isReportDate 是否是上报时间
 */
const onChange = (val, isReportDate) => {
  query.year = val.yearValue
  query.jd = val.quarterValue
  const currentDate = new Date()
  const currentYear = currentDate.getFullYear()
  const currentQuarter = Math.floor(currentDate.getMonth() / 3) + 1

  // if (query.year == currentYear && query.jd == currentQuarter) {
  //   isShowCurrent.value = true
  // } else {
  // }
  isShowCurrent.value = isReportDate
  emit("onQuery", query)

  if (isAuth.value || isPlant.value) {
    pageData()
    getShowBtn()
  }
}
/** 触发更新，避免无sourceId */
const handleManualUpdate = () => {
  if (!isFirstManual.value) return
  if (!isNeedRefresh.value) return
  manualUpdate(query.orgcode)
  isFirstManual.value = false
}
function closeChange() {
  pageData()
}
const isAllSumbit = ref(true)
const pageData = (val = true) => {
  tableLoading.value = true
  tableData.value = []
  if (timer.value) {
    window.clearInterval(timer.value)
    timer.value = null
  }
  getApi(query, `${apiPath}/list`).then(res => {
    if (res) {
      tableData.value = res
      //  如果没有表格内容 手动更新一次
      if (!res?.length) handleManualUpdate()
      tableLoading.value = false
      byTime.value = res[0]?.updateTime ? res[0].updateTime : ""
      if (isProvinces.value) {
        // 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
        // }
      }
      let count = 0
      res.forEach((item) => {
        if (item.status === '1' || item.status === '99') count++
      })
      if (count === res.length) isAllSumbit.value = false
    }
  }).finally(() => {
    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
          manual.disabled = true
        } else {
          isReportResult.value = false
          if (timer.value) {
            isReportResult.value = false;
            window.clearInterval(timer.value);
            timer.value = null;
          }
          // if (isAutoReport.value) {
          //   pageData()
          // }
          // 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 onUpdate = (row, status) => {
  loadingcksbjg.value = true
  getApi({ orgCode: row.orgCode, status: status }, '/mosty-jcgl/data/hazardChemicalInfo/reportLocalData').then(res => {
    pageData()
  }).finally(() => {
    loadingcksbjg.value = false
  })
};
const onView = e => {
  // e.complianceLevelCode = e.complianceLevelCode + "";
  detailDialog.value.dialogVisible = true
  rowItem.value = e
  dialogTitle.value = `${e.baOrgName}`
}
const handleReport = () => {
  getApi({ orgCode: query.orgcode }, `${apiPath}/upChemical`).then(res => {
    if (res) {
      ElMessage({
        message: "上报成功",
        type: "success"
      })
      isAutoReport.value = true
      pageData()
      onReportResult()
    } else {
      ElMessage({
        message: "上报失败",
        type: "error"
      })
    }
  })
}
const manualUpdate = (code, isItem = false) => {
  code = getItem("deptId").ssdwid;
  // let code = query.orgcode;
  if (isItem) manual.loading = true
  // setTimeout(() => {
  //   ElMessage({
  //     message: "更新成功",
  //     type: "success"
  //   })
  //   manual.loading = false
  // }, 1e3)
  // return
  getApi({ orgcode: code }, `${apiPath}/syncLocal`)
    .then(res => {
      pageData()
      ElMessage({
        message: "更新成功",
        type: "success"
      })
      manual.loading = false
    })
    .finally(() => {
      tableLoading.value = false
      manual.loading = false
    })
}
const selectionChange = e => {
  manual.disabled = e.length === tableData.value.length ? false : true
}

onMounted(() => {
  if (isProvinces.value) {
    orgid.value = orgid.value + 'XN'
  }
})
onBeforeUnmount(() => {
  if (timer.value) {
    window.clearInterval(timer.value)
    timer.value = null
  }
})
// watch(
//   () => isOpen.value,
//   (n, o) => {
//     if (n) {
//       emit("onQuery", query);
//     }
//   },
//   { immediate: true }
//   // { immediate: true, deep: true }
// );
const handleExport = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '导出中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  getApi(query, '/mosty-jcgl/data/export/hazardChemicalInfo').then(res => {
    if (res.length > 0) {
      for (let i = 0; i < res.length; i++) {
        res[i].cmHighlyToxicFlag = res[i].cmHighlyToxicFlag == '1' ? '是' : '否';
        res[i].cmEasyMakeToxicFlag = res[i].cmEasyMakeToxicFlag == '1' ? '是' : '否';
        res[i].cmEasyMakeExplosiveFlag = res[i].cmEasyMakeExplosiveFlag == '1' ? '是' : '否';
        res[i].cmMajorHazardFlag = res[i].cmMajorHazardFlag == '1' ? '是' : '否';
        res[i].cmHazchemListFlag = res[i].cmHazchemListFlag == '1' ? '是' : '否';
        res[i].cmHazardProcessFlag = res[i].cmHazardProcessFlag == '1' ? '是' : '否';

      }
    }
    wxhxpXlsx(res ? res : [], { D_BZ_SF }, popover.content)

  }).finally(() => {
    loading.close()
  })
}
</script>

<style lang="scss" scoped>
.el-link.el-link--primary.is-disabled {
  color: rgba(15, 142, 135, 0.7);
  cursor: not-allowed;
}

.bottom {
  background: #fff;
}
</style>
