<template>
  <div class="bottom">
    <TimeCondition :popover="popover" :ywId="props.id" @change="timeCondition" :title="title">
      <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(query.orgCode)">
          <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 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 border :data="tableData" :height="`calc(100vh - ${props.isOpen ? 655 : 350}px)`" v-loading="tableLoading"
      :header-cell-style="{ background: '#F6F6F6' }" :cell-style="cellStyle" style="width: 99%;">
      <el-table-column type="selection" width="55" :selectable="onSelectable" />
      <el-table-column prop="orgName" label="企业名称" width="260"> </el-table-column>
      <el-table-column label="仓库总数量(个)">
        <template #default="{ row }">
          {{ row.danCCkNum * 1 + row.duoCCkNum * 1 + row.luTHcNum * 1 + row.liTCkNum * 1 + row.dongKNum * 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="danCCkNum" label="单层仓库(个)" />
      <el-table-column prop="duoCCkNum" label="多层仓库(个)" />
      <el-table-column prop="luTHcNum" label="露天货场(个)" />
      <el-table-column prop="liTCkNum" label="立体仓库数量(个)" />
      <el-table-column prop="dongKNum" label="洞库(个)" />
      <el-table-column prop="wsbNum" label="未上报总数">
        <template #default="{ row }">
          <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>
      </el-table-column>
      <el-table-column prop="updateTime" label="最后一次上报时间" width="160" />
      <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="170" 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="否" :disabled="setPeject(row.status)"
            icon-color="red" title="是否确认驳回?" @confirm="onRevoke(row.orgCode)">
            <template #reference>
              <RowLink type="link" :disabled="setPeject(row.status)" v-if="!isTown">驳回</RowLink>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <DialogTablecc :title="dialogTitle" @close="dialogClose" :isSfsb="isSfsb" :orgCode="currId" :params="query"
    :reportStatus="reportStatus" :rowItem="rowItem" v-if="dialogVisible" />
  <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, ref, reactive, computed, watch, onUnmounted, inject, getCurrentInstance, onBeforeUnmount } from "vue"
import TimeCondition from "@/views/dataReportWork/components/TimeCondition"
import { getApi, postApi } from "@/api/tobAcco_api.js"
import { getItem } from "@/utils/storage"
import { filterqx } from "@/utils/auth.js"
import DialogTablecc from "./DialogTablecc.vue"
import ReportHistory from "./ReportHistory.vue"
import { ElMessage, ElLoading } from "element-plus"
import { xfssXlsx } from "./tabtool";
import RowLink from "@/views/dataReportWork/components/RowLink.vue"


const { proxy } = getCurrentInstance();
const { D_BZ_CKLX, D_BZ_JZJGLX, D_BZ_JZWHZWXXLB, D_BZ_JYCCXS, D_BZ_JYCKXZ, D_BZ_SF } = proxy.$dict(
  "D_BZ_CKLX", "D_BZ_JZJGLX", "D_BZ_JZWHZWXXLB", "D_BZ_JYCCXS", "D_BZ_JYCKXZ", "D_BZ_SF");

const props = defineProps({ isOpen: Boolean, id: String, orgCode: String })
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 query = reactive({
  orgCode: currentCode,
  year: "",
  bn: ""
})
const reportStatus = ref("")
const rowItem = ref(null)
const tableLoading = ref(false)
const tableData = ref([])
const dialogTitle = ref("")
const title = ref("仓储设施台账")
const popover = reactive({
  title: title.value,
  content: `
填表说明：
1. 填写单位：省级单位名称；
2. 企业名称：各省级单位机关或下属单位名称；
3. 填报范围：包括属于联合工房内转周库的填写联合工房中间库；
4. 仓储安全管理模块统计频次：半年；
5. 仓储安全管理模块提交周期：提交时间范围分别为：每年1月1日-6月30日、7月1日-12月25日。
6. 仓储信息与上周期没有变化，可使用“复制上周期”功能，将上周期数据同步至本周期。
7. 相同企业名称、相同统计周期下，同一个物流节点名称下的仓库名称不可重复。
8. 若没有仓库信息，可不添加数据；但在周期对应的提交时间范围内仍需处长账号进行“上报确认”操作。
9. 物流节点名称：仓库所在场所名称，如：某某库区或某某厂区。
10. 仓储物资类别：原烟、片烟、烟丝、卷烟、滤棒、其他烟用材料、香精香料。
11. 仓库类型：单层仓库、多层仓库、立体仓库、露天货场、洞库。
注意：烟丝、香精香料、卷烟、滤棒、其他烟用材料，仓库类型不支持选择“露天货场”和“洞库”。
12. 仓储形式 ：单层托盘地面堆放存储、多层托盘货架存储、托盘立体库存储、密集式仓储、其他。
13. 仓储性质：自有仓库、租赁行业外仓库。
注意：仓储物资类别为：烟丝、滤棒、其他烟用材料时，仓储性质不可选择“租赁行业外仓库”。
14. 火灾危险性分类：按照《建筑设计防火规范》分为：甲、乙、丙、丁、戊。
15. 库容量填报说明：库容量的单位，与“仓储物资类别”关联 ；对应关系如下：
（1）原烟，库容量计量单位 ： 担 ；
（2）片烟，库容量计量单位：  箱 ；
（3）烟丝，库容量计量单位： 吨  ；
（4）卷烟，库容量计量单位：万支；
（5）滤棒，库容量计量单位：万支；
（6）其他烟用材料，库容量计量单位：吨；
（7）香精香料，库容量计量单位：吨；
注意：库容量按设计的最大存储量填写。
  `
})
const currId = ref(null)
const isSfsb = ref(false)
const dialogVisible = ref(false)
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)

//详情
function onView(row, type) {
  dialogVisible.value = true
  isSfsb.value = row.sfsb == "1" ? true : false
  reportStatus.value = type
  rowItem.value = row
  currId.value = row.orgCode
  dialogTitle.value = `仓储实施列表（${row.orgName}）`
}
const onCount = e => {
  reportHistoryRef.value.dialogVisible = true
  historyParams.value = {
    orgCode: e.orgCode,
    sbcs: e.sbcs,
    year: query.year,
    bn: query.bn
  }
}
const dialogClose = val => {
  dialogVisible.value = false
  if (val) {
    getPageData()
  }
}
const timeCondition = val => {
  query.year = val.yearValue
  query.bn = val.halfValue
  if (props.orgCode) getPageData()
}
const manualUpdate = () => {
  permisssion.manualUpdate.loading = true
  setTimeout(() => {
    ElMessage({
      message: "更新成功",
      type: "success"
    })
    permisssion.manualUpdate.loading = false
  }, 1e3)
  return
  getApi({}, `/mosty-jcgl/data/StorageEscalation/manualUpdate`)
    .then(res => {
      getPageData()
      ElMessage({
        message: "更新成功",
        type: "success"
      })
      permisssion.manualUpdate.loading = false
    })
    .finally(() => {
      tableLoading.value = false
      permisssion.manualUpdate.loading = false
    })
}
const rowUpdate = code => {
  getApi({ orgCode: code }, `/mosty-jcgl/data/StorageEscalation/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
  }
  postApi(query, "/mosty-jcgl/data/StorageEscalationStat/queryStorageEscalationStat")
    .then(res => {
      if (res) {
        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: props.id, 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
          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: props.id }, "/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

  //按钮权限
  // 详情 全部可用
  // 手动更新 本级、县 status !='4'
  // 更新 (row.updateStatus === 1)  权重小于 row.status ['4','5']
  // 撤销 接口？
  // 县 只有1条数据
  // 上报 status ='2'
  // 更新？
  // 驳回 不显示

  // 市 本级 同 县
  // 市 非本级 驳回 status ='1'
  // 市
  // 上报 status ='1'
  // 驳回 status ='1'

  // 省 本级 同 县
  // 省 非本级 驳回 status ='1'||'4'
  // 省
  // 上报 status ='1'
  // 驳回 status ='1'||'4'

  //  省安全部门账号
  // 省   首次上报 修改上报  sbcs>0
  // 本级 上报
  // 其他  禁用

  // <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: green">上报到国家局</span>
  // <span v-else-if="row.status == '6'" style="color: green">上报到国家局成功</span>
}
const getRevoke = async () => {
  let res = await postApi(query, `/mosty-jcgl/data/StorageEscalationStat/isRevokedFlag`)
  permisssion.revoke.disabled = res ? false : true
}
const setPermisssion = async () => {
  const currentDate = new Date()
  const currentYear = currentDate.getFullYear()
  const currentMonth = currentDate.getMonth()

  restPermisssion()
  if (query.year != currentYear || query.bn != Math.floor(currentMonth / 6) + 1) {
    permisssion.manualUpdate.disabled = true
    return
  }
  let res = await getApi({ id: props.id }, "/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 (row.orgCode.includes(currentCode)) {
      return row.updateStatus === 1 ? false : true
    } else return true
  }
}
const onRevoke = async (code) => {
  // query.orgCode = code
  // let params = JSON.parse(JSON.stringify(query))
  // params.orgCode = code
  let res = await postApi({ ...query, orgCode: code }, "/mosty-jcgl/data/StorageEscalationStat/revokeData")
  if (res) {
    ElMessage({
      message: `${code === currentCode ? "撤销" : "驳回"}成功`,
      type: "success"
    })
    getPageData()
  }
}
const onReport = async () => {
  let res = await postApi(query, "/mosty-jcgl/data/StorageEscalationStat/reportData")
  if (res) {
    ElMessage({
      message: "上报成功",
      type: "success"
    })
    isAutoReport.value = true
    getPageData()
    onReportResult()
  } else {
    ElMessage({
      message: "上报失败",
      type: "error"
    })
  }
}
const cellStyle = ({ row, column, rowIndex, columnIndex }) => {
  if ([2, 3, 4, 5, 6, 7].includes(columnIndex)) {
    return { background: ' rgb(240,249,235) !important' }
  }
  if (columnIndex === 8) {
    return { background: "var(--el-color-primary-light-8)!important" }
  }
}
onBeforeUnmount(() => {
  if (timer.value) {
    window.clearInterval(timer.value)
    timer.value = null
  }
})

watch(
  () => props.orgCode,
  (n, o) => {
    if (n) {
      query.orgCode = n
      getPageData()
    }
  }
  // { deep: 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/storageEscalation').then(res => {

    if (res.length > 0) {
      for (let i = 0; i < res.length; i++) {
        res[i].conHydrantSysFlag = res[i].conHydrantSysFlag == '1' ? '是' : '否';
        res[i].conAlarmSysFlag = res[i].conAlarmSysFlag == '1' ? '是' : '否';
        res[i].conOutfireSysFlag = res[i].conOutfireSysFlag == '1' ? '是' : '否';
      }
    }
    xfssXlsx(res ? res : [], { D_BZ_CKLX, D_BZ_JZJGLX, D_BZ_JZWHZWXXLB, D_BZ_JYCCXS, D_BZ_JYCKXZ, D_BZ_SF }, 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;
    margin-bottom: 10px;

    .sub-le {
      // flex: 4;
      width: 710px;
      padding: 15px 15px 5px 15px;
      // border-right: 1px solid #ebeef5;
    }

    // .sub-ri {
    //   flex: 4;
    //   padding: 15px 15px 5px 15px;
    // }
  }

  .bottom {
    padding: 15px 15px 5px 15px;
  }

  .leceri {
    display: flex;

    .le,
    .ri {
      flex: 1;
    }

    .ce {
      padding: 6px 0;

      .ince {
        width: 36px;
        padding-left: 10px;
        background: #eef6f6;
        height: 100%;
        margin: 0 3px;
      }
    }
  }

  .subs {
    display: flex;
    padding-top: 6px;

    .sub-le {
      flex: 1;
    }

    .sub-ri {
      width: 450px;

      ::v-deep .item {
        padding: 0 3px;

        .inner {
          height: 103px;
          padding-top: 26px;
        }
      }
    }
  }
}
</style>
