<template>
  <div class="bottom" :style="{ height: `calc(100vh - ${isOpen ? 465 : 240}px)` }">
    <TimeCondition :ywId="ywId" :byTime="byTime" :title="title" :popover="popover" @change="onChange">
      <template #right>
        <div v-if="isProvinces">
          <el-popconfirm v-if="!tableData.length" 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 || !isProvinces"
                :loading="manual.loading">手动更新</el-button>
            </template>
          </el-popconfirm>
          <el-button type="primary" @click="handleReport" v-if="isShowBtn && uploadNum == 0"
            :disabled="isAllSumbit || !isShowCurrent || !isProvinces">首次上报</el-button>
          <el-button type="primary" @click="handleReport" v-else-if="isShowBtn && uploadNum > 0"
            :disabled="!isProvinces || !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"
      :header-cell-style="{ background: '#f5f5f5' }" height="calc(100% - 100px)">
      <el-table-column type="selection" width="55" :selectable="handleDisable" />
      <el-table-column label="企业名称" prop="baOrgName" fixed width="240" />
      <el-table-column label="消防池（座）" prop="firePoolQty" width="110" />
      <el-table-column label="应急广播（套）" prop="emgcBroadcastQty" width="130" />
      <el-table-column align="center" label="消防拴系统（套）">
        <el-table-column prop="idrFrHdrtSysQty" label="室内消火栓（套）" width="140" />
        <el-table-column prop="odrFrHdrtSysQty" label="室外消火栓（套）" width="140" />
      </el-table-column>
      <el-table-column align="center" label="火灾自动报警系统（套）">
        <!-- <el-table-column label="是否独立设置" width="110">
          <template #default="scope">
            {{ scope.row.independentSettingsFlag && scope.row.independentSettingsFlag === 1 ? "是" : "否" }}
          </template>
        </el-table-column> -->
        <el-table-column prop="fasSmkTmpSsrQty" label="烟感、温感（套）" width="140" />
        <el-table-column prop="fasAirSampleQty" label="空气采样（套）" width="130" />
        <el-table-column prop="fasIfrdRdatQty" label="红外对射（套）" width="130" />
        <el-table-column prop="fasCmbsGsDtctQty" label="可燃气体探测（套）" width="155" />
        <el-table-column prop="fasElecFrCtrlQty" label="电气火灾监控（套）" width="155" />
        <el-table-column prop="fasOtherFasQty" label="其他（套）" width="110" />
      </el-table-column>
      <el-table-column align="center" label="自动灭火系统">
        <el-table-column prop="affsWtsprSysQty" label="水喷淋（套）" width="110" />
        <el-table-column prop="affsSdpSysQty" label="超音速干粉（套）" width="140" />
        <el-table-column prop="affsHpwmSysQty" label="高压细水（套）" width="130" />
        <el-table-column prop="affsCbdxSysQty" label="二氧化碳（套）" width="130" />
        <el-table-column prop="affsHfcSysQty" label="七氟丙烷（套）" width="130" />
        <el-table-column prop="affsArslSysQty" label="气溶胶（套）" width="110" />
        <el-table-column prop="affsAfffSysQty" label="水炮（套）" width="100" />
        <el-table-column prop="affsOtherAffsQty" label="其他（套）" width="100" />
      </el-table-column>
      <el-table-column prop="smkCtrlSysQty" label="防排烟系统（套）" width="140" />
      <el-table-column prop="emgcEvcuatSysQty" label="应急疏散指示系统（套）" width="140" />
      <el-table-column prop="frConRoomQty" label="消防控制室（个）" width="140" />
      <el-table-column align="center" label="消控室值班人员（人）">
        <el-table-column prop="juniorWorkerQty" label="五级/初级工（人）" width="130" />
        <el-table-column prop="intermediateWorkerQty" label="四级/中级工（人）" width="130" />
      </el-table-column>
      <el-table-column align="center" label="消防救援">
        <el-table-column prop="prvtFrBrigadeQty" label="专职消防队（个）" width="140" />
        <el-table-column prop="prvtFrmanQty" label="专职消防员（个）" width="140" />
        <el-table-column prop="frFightTruckQty" label="消防车（台）" width="120" />
        <el-table-column prop="miniFrStatQty" label="微型消防站（个）" width="140" />
        <el-table-column prop="miniFrStatFrmanQty" label="微型消防站队员数（人）" width="150" />
      </el-table-column>
      <el-table-column prop="updateTime" label="最后一次上报时间" width="150" fixed="right" />
      <el-table-column prop="status" label="当前上报状态" width="110" fixed="right">
        <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="累计上报次数" width="110" fixed="right">
        <template #default="{ row }">
          <el-link type="primary" @click="onHistory(row)">{{ row.sbcs }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="140" fixed="right">
        <template #default="{ row }">
          <el-link type="primary" @click="manualUpdate(row.orgCode)" :disabled="!isShowCurrent">更新</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="onEdit(row)" :disabled="!isShowCurrent">编辑</el-link>
          <el-link type="primary" @click="onView(row)">查看</el-link>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <DetailDialog ref="detailDialog" :title="dialogTitle" :type="dialogType" :rowItem="rowItem" @onSave="onSave" />
  <HistoryDialog ref="historyDialog" :title="dialogTitle" :baOrgCode="baOrgCode" :query="query" />

  <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, 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 HistoryDialog from "./XfzstzHistory"
import { getItem } from "@/utils/storage"
import { ElMessage, ElLoading } from "element-plus"
import { filterqx } from "@/utils/auth.js"
import { xfssXlsx } from "./tabtool";
const props = defineProps({
  dict: Object
});
const apiPath = `/mosty-jcgl/data/firEquipment`
const ywId = inject("ywId") || ""
const title = inject("title") || ""
const isOpen = inject("isOpen") || ""
const popover = reactive({
  title: title.value,
  content: `
填表说明：
1. 填写单位：省级单位名称；
2. 企业名称：各省级单位机关或下属单位名称；
3. 统计频次：半年；
4. 提交周期：每年1月1日-6月30日、7月1日-12月25日。
5. 若周期内无符合要求的消防安全信息数据，可不添加数据；但在周期对应的提交时间范围内仍需处长账号进行“上报确认”操作。
6. 消防设施：
（1）相同统计周期下，“消防设施”中的企业名称信息不可重复；​
（2）应急疏散指示系统：是指集中供电型应急疏散指示系统；
（3）消防室值班人员：分为消控室值班人员五级/初级工、消控室值班人员四级/中级工及以上。
  `
})
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: "",
  bn: ""
})
const baOrgCode = ref("")
const tableLoading = ref(false)
const tableData = ref([])
const dialogType = 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 emit = defineEmits(["onQuery"])
// 是否可以选择多选
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.bn }, "/mosty-jcgl/dataCommon/getSccs")
}
const onChange = val => {
  query.year = val.yearValue
  query.bn = val.halfValue

  const currentDate = new Date()
  const currentYear = currentDate.getFullYear()
  const currentMonth = currentDate.getMonth()
  if (query.year == currentYear && query.bn == Math.floor(currentMonth / 6) + 1) {
    isShowCurrent.value = true
  } else {
    isShowCurrent.value = false
  }
  // if (val.yearValue != currentYear) {
  //   isShowCurrent.value = false;
  // } else {
  //   isShowCurrent.value = true;
  // }
  emit("onQuery", query)

  if (isAuth.value || isPlant.value) {
    pageData()
    getShowBtn()
  }
}
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
      tableLoading.value = false
      byTime.value = res[0]?.updateTime ? res[0].updateTime : ""
      if (isAuth.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
    }
  })
}

// 查看省局上报结果
const onReportResult = val => {
  loadingcksbjg.value = true
  getApi({ year: query.year, id: ywId.value, jtsj: query.bn }, "/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 {
          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) {
            pageData(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/firEquipment/reportLocalData').then(res => {
    pageData()
  }).finally(() => {
    loadingcksbjg.value = false
  })
};
const onEdit = e => {
  dialogType.value = "edit"
  detailDialog.value.dialogVisible = true
  rowItem.value = e
  dialogTitle.value = `编辑${title.value.replace("台账", "")}（${e.baOrgName}）`
}
const onView = e => {
  dialogType.value = "view"
  detailDialog.value.dialogVisible = true
  rowItem.value = e
  dialogTitle.value = `查看${title.value.replace("台账", "")}（${e.baOrgName}）`
}
const onHistory = e => {
  baOrgCode.value = e.baOrgCode
  historyDialog.value.dialogVisible = true
  rowItem.value = e
  dialogTitle.value = `${title.value.replace("台账", "")}（${e.baOrgName}）历史`
}
const onSave = e => {
  pageData()
}
const handleReport = () => {
  // if (isProvinces.value) {
  //   postApi({ orgCode: query.orgcode }, `${apiPath}/upFir`).then(res => {
  //     if (res) {
  //       ElMessage({
  //         message: "上报成功",
  //         type: "success"
  //       })
  //       provincesBtn.value = res
  //     }
  //   })
  //   setTimeout(() => {
  //     ElMessage({
  //       message: "上报成功",
  //       type: "success"
  //     })
  //     // provincesBtn.value = true;
  //   }, 1000)
  // } else {
  postApi({ orgCode: query.orgcode }, `${apiPath}/upFir`).then(res => {
    if (res) {
      ElMessage({
        message: "上报成功",
        type: "success"
      })
      isAutoReport.value = true
      pageData()
      onReportResult()
    } else {
      ElMessage({
        message: "上报失败",
        type: "error"
      })
    }
  })
  // }
}
const manualUpdate = (code, isItem = false) => {
  // let code = getItem("deptId").ssdwid;
  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
  }
})
const handleExport = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '导出中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  getApi(query, '/mosty-jcgl/data/export/epfsmFirEquipment').then(res => {
    xfssXlsx(res ? res : [], props.dict, popover.content)

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

<style lang="scss" scoped>
::v-deep .el-table {
  .cell {
    padding: 0 5px;
  }
}

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