<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 v-if="isProvinces" confirm-button-text="是" cancel-button-text="否" icon-color="red"
              title="若更新数据将重置，是否确认更新?" @confirm="manualUpdate">
              <template #reference>
                <el-button type="primary" class="mr5" :loading="permisssion.manualUpdate.loading"
                  :disabled="permisssion.manualUpdate.disabled">手动更新</el-button>
              </template>
            </el-popconfirm>
            <el-popconfirm v-if="!isProvinces || isProvincesXN" 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">撤销</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 type="primary" :loading="loadingscsb" class="mr5" :disabled="permisssion.report.disabled">{{
                  permisssion.report.title }}</el-button>
              </template>
            </el-popconfirm>
            <el-button type="primary" class="mr5" @click="excelTab">导出</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="onView(row, '')">查看</el-link>
              <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="若更新数据将重置，是否确认更新?"
                @confirm="rowUpdate(row.orgCode)">
                <template #reference>
                  <el-link type="primary" class="mr5" :disabled="setUpdate(row)">更新</el-link>
                </template>
              </el-popconfirm>
              <el-popconfirm v-if="!isTown && !setPeject(row.status)" confirm-button-text="是" cancel-button-text="否"
                icon-color="red" title="是否确认驳回?" @confirm="onRevoke(row.orgCode)">
                <template #reference>
                  <el-link type="primary">驳回</el-link>
                </template>
              </el-popconfirm>
              <el-link v-if="isTown && setPeject(row.status)" disabled>驳回</el-link>
            </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" />
</template>

<script setup>
import { onMounted, ref, reactive, watch, computed, onUnmounted, 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 { sgsjXlsx } from "./tabtool";
import { filterqx } from "@/utils/auth.js"
const { proxy } = getCurrentInstance();
const { D_BZ_SGZRLX, D_BZ_SGSJLB } = proxy.$dict(
  "D_BZ_SGZRLX", "D_BZ_SGSJLB");

const loadingcksbjg = ref(false)
const props = defineProps({ isOpen: Boolean, id: String, title: String, orgCode: String })
const pageData = reactive({
  dateTable: [],
  columnTable: [
    { label: "企业名称", prop: "orgName", fixed: "left" },
    { label: "事故总数", prop: "count" },
    { label: "自然灾害数量", prop: "naturalCount" },
    { label: "安全生产事故数量", prop: "safetyCount" },
    { 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 query = reactive({
  orgCode: getItem("deptId").ssdwid,
  year: "",
  jd: ""
})
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. 填写本年度内截止到本周期的事故，事故范围：
（1）一次造成员工重伤、死亡或轻伤的事故；
（2）有产生直接经济损失的事故；
（3）相关方在工作场所内作业，或在工作场所外作业导致我方经济损失及人员死亡的事故。
6. 若周期内未发生事故，可不添加“事故”数据；但在周期对应的提交时间范围内仍需处长账号进行“上报确认”
操作。
7. 相同单位名称、相同统计周期下，事故名称不可重复。
8. 事故类型为“生产安全”事故时，事故责任为必填，事故类型为“自然灾害”时，事故责任无需填写。
9. 事故损失（包含死亡、重伤、轻伤和直接经济损失）：当没有事故损失时，请填写“0”。
10. 事故类型为物体打击、机械伤害、起重伤害、触电、淹溺、灼烫、高处坠落、中毒和窒息、食物中毒时，
无需填写直接经济损失。
  `
})

const loadingscsb = ref(false)
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 isProvincesXN = computed(() => {
  return filterqx("isaqbm") == "1" && filterqx("isSgs") == "1" && props.orgCode.includes('XN')
})
// 是否是市账号
const isCity = computed(() => {
  return filterqx("isaqbm") == "1" && filterqx("isgs") == "1"
})
//县级账号
const isTown = computed(() => {
  return filterqx("isaqbm") == "1" && filterqx("isgs") != "1" && filterqx("isSgs") != "1"
})


const timer = ref(null)
const reportStatus = ref("")
const rowItem = ref(null)
const tableLoading = ref(false)
const tableData = ref([])
const dialogVisible = ref(false)
const isReportResult = 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 dialogClose = val => {
  dialogVisible.value = false
  getPageData()
}
const onView = (e, type) => {
  dialogVisible.value = true
  isEdit.value = 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
  }
}
const timeCondition = val => {
  query.year = val.yearValue
  query.jd = val.quarterValue
  if (props.orgCode) getPageData()
}
const manualUpdate = () => {
  permisssion.manualUpdate.loading = true
  tableLoading.value = true
  setTimeout(() => {
    ElMessage({
      message: "更新成功",
      type: "success"
    })
    permisssion.manualUpdate.loading = false
    tableLoading.value = false
  }, 1e3)
  return
  getApi({}, `/mosty-jcgl/data/accidentEvents/manualUpdate`)
    .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/accidentEvents/syncLocal`)
    .then(res => {
      getPageData()
      ElMessage({
        message: "更新成功",
        type: "success"
      })
    })
    .finally(() => {
      tableLoading.value = false
    })
}
const getPageData = (val = true) => {
  tableLoading.value = true
  postApi(query, "/mosty-jcgl/data/accidentEventsStat/queryAccidentEventsStat").then(res => {
    if (res) {
      tableData.value = res
      tableLoading.value = false
      setPermisssion()
      if (isProvinces.value) {
        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;
        }
      }
    }
  }).finally(() => {
    tableLoading.value = false
  })
}
// 查看省局上报结果
const reportResult = (val) => {
  let _data = {
    id: props.id,
    ...query
  }
  if (_data.jd) {
    _data.jtsj = _data.jd
    delete _data.jd
  }
  getApi(_data, "/mosty-jcgl/dataCommon/getSbjg").then(res => {
    if (res) {
      pageData.reportResultInfo = res
      if (res.returnCode == '200' && !res.returnHttpCode) {
        isReportResult.value = true
      } else {
        isReportResult.value = false
        if (timer.value) {
          isReportResult.value = false;
          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)
        }
      }
    }
  }).finally(err => {
  })
}
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/accidentEventsStat/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 = false //这里暂时打开手动更新按钮
    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) {
    return row.updateStatus === 1 && ["2", "3"].includes(row.status) ? false : true
  }

  if (isProvinces.value) {
    if (query.orgCode.includes(currentCode) && query.orgCode.includes("XN") || row.orgCode == currentCode + 'XN') {
      return row.updateStatus === 1 ? false : true
    } else return true
  }
}
const onRevoke = async code => {
  let obj = {
    orgCode: code,
    jd: query.jd,
    year: query.year,

  }

  let res = await postApi(obj, "/mosty-jcgl/data/accidentEventsStat/revokeData")
  if (res) {
    ElMessage({
      message: `${code === currentCode ? "撤销" : "驳回"}成功`,
      type: "success"
    })
    getPageData()
  }
}
const onReport = async () => {
  loadingscsb.value = true
  try {
    let res = await postApi(query, "/mosty-jcgl/data/accidentEventsStat/reportData").then(res => { })
    ElMessage({
      message: "上报成功",
      type: "success"
    })
    reportResult()
    getPageData()
    loadingscsb.value = false
    // ElMessage({
    //   message: "上报失败",
    //   type: "warning"
    // })
    // getPageData()
    // loadingscsb.value = false
  } catch (error) {
    getPageData()
    loadingscsb.value = false
  }


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

onMounted(() => {
  popover.title = props.title.replace("数据", "")
})

watch(
  () => props.orgCode,
  (n, o) => {
    if (n) {
      query.orgCode = n
      getPageData()
    }
  }
  // { deep: true }
  // { immediate: true, deep: true }
)
onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = null;
  }
})
//导出

const excelTab = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '导出中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  getApi(query, '/mosty-jcgl/data/export/accident').then(res => {
    sgsjXlsx(res ? res : [], { D_BZ_SGZRLX, D_BZ_SGSJLB }, 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;
}

.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>
