<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 - 236px)` }">
        <TimeCondition :byTime="byTime" :ywId="ywId" @change="onChange" :title="title + '台账'" :popover="popover">
          <template #right>
            <span v-if="isProvinces">
              <el-popconfirm v-if="isShowSbBtn" 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" :loading="manual.loading"
                    style="display:none">手动更新</el-button>
                </template>
              </el-popconfirm>

              <el-popconfirm v-if="isShowSbBtn" confirm-button-text="是" cancel-button-text="否" icon-color="red"
                title="是否确认上报?" @confirm="handleReport()">
                <template #reference>
                  <el-button type="primary" class="mr5" v-if="uploadNum == 0" :loading="sbloading"
                    :disabled="(manual.disabled || isReportResult || isAllSumbit)">首次上报</el-button>
                  <el-button type="primary" class="mr5" v-else-if="uploadNum > 0" :loading="sbloading"
                    :disabled="(manual.disabled || isReportResult || isAllSumbit)">修改上报</el-button>
                </template>
              </el-popconfirm>
              <el-button type="primary" style="margin-left: 5px !important" @click="reportResult(true)"
                :loading="loadingcksbjg" v-if="IsCksbjg">查看上报结果</el-button>
            </span>
            <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red"
              :title="`复制上周期数据前将清空本周期数据，请确认是否继续？`" @confirm="onCopyData">
              <template #reference>
                <el-button type="primary">复制上周期数据</el-button>
              </template>
            </el-popconfirm>
            <el-button type="primary" style="margin:0px 5px !important;" @click="handleExport">导出</el-button>

          </template>
        </TimeCondition>
        <el-table :data="tableData" border @selection-change="selectionChange" style="width: 100%"
          v-loading="tableLoading" :header-cell-style="{ background: '#f5f5f5' }" height="calc(100% - 100px)">
          <el-table-column type="selection" width="55" :selectable="handleDisable" />
          <el-table-column label="企业名称" prop="baOrgName" />
          <!-- <el-table-column label="总数" prop="total">
            <template #default="{ row }">
              {{ row.level1 * 1 + row.level2 * 1 }}
            </template>
          </el-table-column> -->
          <!-- <el-table-column label="重大隐患数量" prop="zdCount" /> -->
          <el-table-column label="一般隐患（A类）数量" prop="ybACount" />
          <el-table-column label="一般隐患（B类）数量" prop="ybBCount" />

          <el-table-column prop="gxTime" label="最后一次上报时间">
            <template #default="scope">
              {{ scope.row.gxTime }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="当前上报状态">
            <template #default="{ row }">
              <span v-if="row.status == '0' && !isReportResult" style="color: red">未上报</span>
              <span v-if="row.status == '1' && !isReportResult" style="color: green;">已上报</span>
              <span v-if="isReportResult" style="color: orange">正在上报国家局</span>
              <span v-if="row.status == '99' && !isReportResult" style="color: green">已上报国家局</span>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="sbcs" label="累计上报次数">
            <template #default="{ row }">
              <el-link type="primary" @click="handleHistory(row)">{{ row.sbcs }}</el-link>
            </template>
          </el-table-column> -->
          <el-table-column label="操作" width="140" fixed="right">
            <template #default="{ row }">
              <el-popconfirm v-if="isShowSbBtn && !isReportResult" confirm-button-text="是" cancel-button-text="否"
                icon-color="red" title="若更新数据将重置，是否确认更新?" @confirm="manualUpdate(row.orgCode)">
                <template #reference>
                  <el-link type="primary">更新</el-link>
                </template>
              </el-popconfirm>
              <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" v-if="!isReportResult" @click="handleDiglog(row, 'edit')">编辑</el-link>
              <el-link type="primary" @click="handleDiglog(row, 'view')">查看</el-link>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
  <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>
  <SblsTable v-if="sblsVisible" :item="item" @close="sblsVisible = false" />
  <DialogTable v-if="dialogVisible" @close="closeDialog" :title="dialogTitle" :item="item" :isDetail="true"
    :isEdit="isEdit" :rowItem="rowItem" :query="query" />
</template>

<script setup>
import { onMounted, getCurrentInstance, ref, reactive, computed, inject } from "vue"
import { getApi } from "@/api/tobAcco_api.js"
import BaseTag from "@/views/dataReportWork/org/components/baseTag"
import TimeCondition from "@/views/dataReportWork/components/TimeCondition"
import SblsTable from "../components/tab0/ReportHistory.vue"
import DialogTable from "../components/tab0/DialogTable"
import { getItem } from "@/utils/storage"
import { filterqx } from "@/utils/auth.js"
import * as MOSTY from "@/components/MyComponents/index"
import { ElMessage, ElLoading } from "element-plus";
import { yhpcXlsx } from "./tabtool";
const { proxy } = getCurrentInstance();
const { D_BZ_SF, D_BZ_YHPCFS, D_BZ_YHZGZT } = proxy.$dict("D_BZ_SF", "D_BZ_YHPCFS", "D_BZ_YHZGZT");
const ywId = inject("ywId") || ""
const props = defineProps({ isOpen: Boolean, orgCode: String, title: String })
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. 危险作业：
（1）危险作业类别：分为吊装作业、拆除作业、动火作业、高处作业、有限空间作业、
熏蒸杀虫作业、临时用电等；“临时用电”为新《安全生产法》明确规定的危险作业，按低压用电和高压用电分别管控。
（2）危险作业级别：中度风险、高度风险。
注意：高度风险高处作业至少应包括：无固定平台且高处作业高度15m及以上的作业；
使用吊篮、吊板进行的外墙清洗等作业。
  `
})
const sbloading = ref(false)
const dialogsbyy = ref(false)
const IsCksbjg = ref(false)
const loadingcksbjg = ref(false)
const reportResultInfo = ref({})
const dialogVisible = ref(false)
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 isEdit = ref(false)
const sblsVisible = ref(false)
const item = ref({})
const query = reactive({
  orgcode: getItem("deptId").ssdwid,
  year: ""
})
const tableLoading = ref(false)
const rowItem = ref({})
const tableData = ref([])
const tabDialog = ref(null)
const currId = ref("")
const dialogTitle = ref("")
const byTime = ref("")
const isReportResult = ref(false)
const timer = ref(null)
const isShowSbBtn = ref(true)
const IsData = ref(true)
const manual = reactive({
  loading: false,
  disabled: true
})
const practitioners = []
const tempOptions = {
  url: "/data/hazardInvestigation/getAllList",
  params: query,
  columns: [
    "baOrgName",
    "investigationStartDate",
    "investigationEndDate",
    "riskEnterpriseHeadFlag",
    "investigationMethodName",
    "hdExistOrgName",
    "describe",
    "categoryName",
    "levelName",
    "rectificationDeadline",
    "rectificationStatusName",
    "completionDate"
  ],
  name: "隐患排查治理"
}
onMounted(() => {
  if (isProvinces.value) {
    orgid.value = orgid.value + 'XN'
  }
  // pageData()
  popover.title = props.title.replace("数据", "")

})
const onCopyData = () => {
  getApi({ orgCode: getItem("deptId").ssdwid, year: query.year, jd: query.jtsj }, `/mosty-jcgl/data/hazardInvestigation/copyData`).then(res => {
    if (!res) return
    ElMessage({
      message: "拷贝成功", //res.message === "OK" ? "拷贝成功" : res.message",
      type: "success"
    })
    pageData()
  })
}
// 点击上报历史
const handleHistory = row => {
  item.value.cs = row.sbcs || 0
  item.value.orgcode = row.orgCode
  item.value.jtsj = query.jtsj
  item.value.year = query.year
  sblsVisible.value = true
}
// 是否可以选择多选
const handleDisable = row => {
  if (isReportResult.value) {
    return false
  }
  if (isProvinces.value) {
    if (row.status != "99") {
      return true
    } else {
      return false
    }
  } else {
    return 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.jtsj }, "/mosty-jcgl/dataCommon/getSccs")
}
// 查看省局上报结果
const reportResult = val => {
  loadingcksbjg.value = true
  getApi({ year: query.year, id: ywId.value, jtsj: query.jtsj }, "/mosty-jcgl/dataCommon/getSbjg")
    .then(res => {
      if (res) {
        reportResultInfo.value = res
        if (val) {
          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
            clearInterval(timer.value)
            timer.value = null
          }
          // pageData()
        }
        if (res.returnCode == "200" && res.returnHttpCode == "500") {
          let res = getApi({ dataId: ywId.value }, "/mosty-jcgl/dataCommon/goBackData")
          if (res) {
            pageData(false)
          }
        }
        // 只针对是否展示查看上报结果
        if (res.returnCode || res.returnHttpCode) {
          IsCksbjg.value = true
        } else {
          IsCksbjg.value = false
        }
      }
    })
    .finally(() => {
      loadingcksbjg.value = false
    })
}
/** 时间选择器 change事件
 * @param {*} val
 * @param {*} isReportDate 是否是上报时间
 */
const onChange = (val, isReportDate) => {

  const currentDate = new Date()
  const currentYear = currentDate.getFullYear() // 返回当前年份
  isShowSbBtn.value = isReportDate;
  query.year = val.yearValue
  query.jtsj = val.quarterValue
  if (isAuth.value || isPlant.value) {
    getShowBtn()
    currData()
  }

}
// 查看当期是否有数据
const counts = ref(0)
const currData = () => {
  if (isShowSbBtn.value) {
    pageData()
    // getApi(query, "/mosty-jcgl/data/ops/getData").then(res => {
    //   if (res && counts.value == 0) {
    //     counts.valun++
    //     manualUpdate(query.orgcode)
    //   } else {
    //     pageData()
    //   }
    // })
  } else {
    pageData()
  }
}
const isAllSumbit = ref(true)
//获取表格数据
const pageData = (val = true) => {
  tableLoading.value = true
  tableData.value = []
  getApi(query, "/mosty-jcgl/data/hazardInvestigation/getStatList")
    .then(res => {
      if (res) {
        // console.log(678,res)
        // return
        byTime.value = res[0]?.updateTime ? res[0].updateTime : ""
        tableData.value = res
        if (val && isReportResult.value) {
          timer.value = setInterval(() => {
            if (!isReportResult.value) {
              clearInterval(timer.value)
              timer.value = null
            }
            reportResult()
          }, 1e4)
        } else {
          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 closeDialog = val => {
  dialogVisible.value = false
  if (val) {
    pageData()
  }
}
const onUpdate = (row, status) => {
  loadingcksbjg.value = true
  getApi({ orgCode: row.orgCode, status: status }, '/mosty-jcgl/data/hazardInvestigation/reportLocalData').then(res => {
    pageData()
  }).finally(() => {
    loadingcksbjg.value = false
  })
};
const handleDiglog = (val, type) => {
  dialogTitle.value = `${type == "view" ? "查看" : "编辑"}（${val.baOrgName}）`
  isEdit.value = type == "edit" ? true : false
  item.value.jtsj = query.jtsj
  item.value.year = query.year
  item.value.orgcode = val.orgCode
  rowItem.value = val
  dialogVisible.value = true
}
// const onEdit = (e) => {
//   dialogVisible.value = true
//   currId.value = e.sourceId
//   dialogTitle.value = `编辑单位信息（${e.baOrgName}）`;
// };
// const onView = (e) => {
//   dialogVisible.value = true
//   currId.value = e.sourceId
//   dialogTitle.value = `查看单位信息（${e.baOrgName}）`;
// };
const onSave = e => {
  pageData()
}
const handleReport = () => {
  sbloading.value = true
  if (isProvinces.value) {
    getApi({ orgCode: query.orgcode }, "/mosty-jcgl/data/ops/upOps")
      .then(res => {
        if (res) {
          reportResult()
          pageData()
        }
      })
      .finally(() => {
        sbloading.value = false
      })
  }
}
const manualUpdate = (code, isItem = false) => {
  tableLoading.value = true
  if (isItem) manual.loading = true
  getApi({ orgcode: code }, "/mosty-jcgl/data/hazardInvestigation/syncLocal")
    .then(res => {
      pageData()
      ElMessage({
        message: "更新成功",
        type: "success"
      })
      manual.loading = false
    })
    .catch(err => {
      tableLoading.value = false
      manual.loading = false
    })
}
const selectionChange = e => {
  manual.disabled = e.length === tableData.value.length ? false : true
}
const handleExport = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '导出中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  getApi(query, '/mosty-jcgl/data/export/hazardInvestigation').then(res => {
    if (res.length > 0) {
      for (let i = 0; i < res.length; i++) {
        res[i].riskEnterpriseHeadFlag = res[i].riskEnterpriseHeadFlag == '1' ? '是' : '否';

      }
    }
    yhpcXlsx(res ? res : [], { D_BZ_SF, D_BZ_YHPCFS, D_BZ_YHZGZT }, popover.content)

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

<style lang="scss" scoped>
.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-button.is-disabled:hover {
  background-color: #808596;
  border-color: var(--el-button-disabled-border-color);
}
</style>
