<template>
  <div class="box" style="flex-grow: 0;">
    <section class="box-sjtj" v-if="props.isOpen">
      <section class="hader">
        <MOSTY.Assort title="基本信息" style="padding: 0;" />
        <section style="display: flex;flex-wrap: wrap;">
          <!-- <Sjtj :info="pageData.list" :isShowTip="false" :isShowBottom="false" :width="200" /> -->
        </section>
      </section>
    </section>
  </div>
  <div class="box" style="flex:1">
    <div class="bottom" :style="{ height: `calc(100vh - ${props.isOpen ? 374 : 236}px)` }">
      <TimeCondition title="特种设备-压力管道台账" :byTime="byTime" :popover="popover" :ywId="props.id"
        @change="changeTimeCondition">
        <template #right>
          <template v-if="isShowCancelBtn && showbtn">
            <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" :loading="manual.loading"
                  :disabled='isReportResult'>手动更新</el-button>
              </template>
            </el-popconfirm>
            <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="是否确认上报?"
              @confirm="handleReport('provinces')">
              <template #reference>
                <el-button type="primary" v-if="isShowBtn && uploadNum == 0" :loading="loadingsb"
                  :disabled="isAllSumbit || isReportResult">首次上报</el-button>
                <el-button type="primary" :disabled='isAllSumbit || isReportResult' :loading="loadingsb"
                  v-else-if="isShowBtn && uploadNum > 0">修改上报</el-button>
              </template>
            </el-popconfirm>
            <el-button type="primary" style="margin-left: 5px !important;" @click="reportResult(true)"
              :loading='loadingcksbjg' v-if="IsCksbjg">查看上报结果</el-button>
          </template>
          <el-button type="primary" style="margin:0px 5px !important;" @click="handleExport">导出</el-button>
        </template>
      </TimeCondition>
      <el-table :data="pageData.tableData" style="width: 99%" height="calc(100% - 120px)" v-loading="tableLoading"
        :header-cell-style="{ background: '#F6F6F6' }" @selection-change="selectionChange" border>
        <el-table-column v-if="isShowCancelBtn && showbtn" type="selection" width="55" :selectable="handleDisable" />
        <el-table-column prop="orgname" label="企业名称" fixed width="250"> </el-table-column>
        <el-table-column prop="count" label="压力管道总数" fixed> </el-table-column>
        <el-table-column prop="count1" label="GC1级压力管道数量" fixed> </el-table-column>
        <el-table-column prop="count2" label="GC2级压力管道数量" fixed> </el-table-column>
        <el-table-column prop="count3" label="GC3级压力管道数量" fixed> </el-table-column>
        <el-table-column prop="sbsj" label="最后一次上报时间" fixed width="200"> </el-table-column>
        <el-table-column prop="status" label="当前上报状态" fixed>
          <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="sbgjjcs" label="累计上报次数" fixed>
          <template #default="{ row }">
            <el-link type="primary" @click="handleHistory(row)">{{ row.sbgjjcs }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="170" fixed="right">
          <template #default='{ row }'>
            <el-link type="primary" @click='seetable(row)'
              :data-v-updatebtn="`${!isReportResult} -${row.status == '0'} - ${isShowCancelBtn}`">详情 </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-popconfirm v-if="!isReportResult && row.status == '0' && isShowCancelBtn" confirm-button-text="是"
              cancel-button-text="否" icon-color="red" title="若更新数据将重置，是否确认更新?" @confirm="manualUpdate(row.orgcode)">
              <template #reference>
                <span class="operesee" size="small">更新</span>
              </template>
            </el-popconfirm>
            <!-- <el-link type="primary">上报历史</el-link> -->
          </template>
        </el-table-column>
      </el-table>
    </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>上报结果：失败</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>
  </el-dialog>
  <SblsTable :title="dialogTitle" @close="dialoglsjl = false" :orgObj="orgObj" :params="query" v-if="dialoglsjl" />
  <DialogTableylgd :title="dialogTitle" @close="dialogClose" :isProvinces="isProvinces" :isSfsb="isSfsb"
    :orgObj="orgObj" :params="query" v-if="dialogVisible" />
</template>

<script setup>
import { onMounted, ref, reactive, onUnmounted, inject, computed } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import TimeCondition from "@/views/dataReportWork/components/TimeCondition";
import * as MOSTY from "@/components/MyComponents/index"
import Sjtj from "@/views/dataReportWork/aqjypx/components/sjtj.vue"
import DialogTableylgd from "../components/DialogTableylgd.vue";
import SblsTable from "../components/tab2/SblsTable.vue";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import { getItem } from "@/utils/storage";
import { ElMessage, ElLoading } from "element-plus";
import { filterqx } from "@/utils/auth.js";
import { ylgdXlsx } from "./tabtool";
const props = defineProps({ isOpen: Boolean, id: String, dict: Object });
const ywId = inject('ywId') || '';
const isShowCancelBtn = ref(true);
const dialogVisible = ref(false);
const tableLoading = ref(false);
const dialogTitle = ref("");
const orgObj = ref({});
const isShowBtn = ref(false)
const loading = ref(false);
const isSfsb = ref(false)

const loadingcksbjg = ref(false)
const reportResultInfo = ref({})
const IsCksbjg = ref(false)
const dialogsbyy = ref(false)
const isAutoReport = ref(false)

const query = reactive({
  orgcode: getItem("deptId").ssdwid,
  year: "",
  half: ''
});
const checklength = ref(0)
const dialoglsjl = ref(false)
const popover = ref({
  title: "压力管道台账",
  content: `
填表说明：
1. 填报单位：省级单位名称；
2. 企业名称：各省级单位机关或下属单位名称；
3. 统计频次：半年；
4. 提交周期：上半年：1月1日-6月30日；下半年：7月1日-12月25日。
5. 若没有特种设备信息，可不添加数据；但在周期对应的提交时间范围内仍需处长账号进行“上报确认”操作。
6. 压力管道级别：GC1级、GC2级、GC3级。
  `
})
const manual = reactive({
  loading: false,
  disabled: true,
  isReport: false,
});
const uploadNum = ref(0);
const showbtn = ref(true);
const timer = ref(null);
const isReportResult = ref(false);
const byTime = ref("");
const loadingsb = ref(false);
const pageData = reactive({
  list: [
    { title: 'GC1级', num: 0 },
    { title: 'GC2级', num: 0 },
    { title: 'GC3级', num: 0 },
  ],
  tableData: [],
})
onMounted(() => {
  if (isProvinces.value) {
    orgid.value = orgid.value + 'XN'
  }
  getYearQ()
})
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 reportResult = (val) => {
  getApi({ year: query.year, id: props.id, jtsj: query.half }, "/mosty-jcgl/dataCommon/getSbjg").then((res) => {
    res = 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;
      }
    }
    // 只针对是否展示查看上报结果
    if (res?.returnCode || res?.returnHttpCode) {
      IsCksbjg.value = true
    } else {
      IsCksbjg.value = false
    }
  }).finally(() => {
    loadingcksbjg.value = false
  });
};
const handleHistory = (row) => {
  orgObj.value.orgcode = row.orgcode
  orgObj.value.orgname = row.orgname
  dialogTitle.value = `特种设备-压力管道（${row.orgname}）上报历史`;
  dialoglsjl.value = true;
}
const getShowBtn = async () => {
  isShowBtn.value = await getApi({ id: props.id }, "/mosty-jcgl/dataCommon/sfQggzr")
  uploadNum.value = await getApi({ year: query.year, id: props.id, jtsj: query.half }, "/mosty-jcgl/dataCommon/getSccs");
};
//手动更新
const manualUpdate = (code, isItem = false) => {
  tableLoading.value = true;
  if (isItem) manual.loading = true;
  getApi({ orgcode: code }, "/mosty-jcgl/data/prepipe/syncLocal")
    .then((res) => {
      getPageData();
      ElMessage({
        message: "更新成功",
        type: "success"
      });
      manual.loading = false;
    }).catch((err) => {
      tableLoading.value = false;
      manual.loading = false;
    });
};
//上报
const handleReport = () => {
  if (isProvinces.value) {
    tableLoading.value = true;
    loadingsb.value = true
    postApi({ 'orgCode': query.orgcode }, '/mosty-jcgl/data/prepipe/upPrepipe').then(res => {
      isAutoReport.value = true
      reportResult()
      getPageData()
      manual.disabled = true

    }).finally(() => {
      loadingsb.value = false
      tableLoading.value = false
    })
  }
};
//是否全选状态
const selectionChange = (e) => {
  checklength.value = e.length
  // 1.1、(return0perationCode为null||'')&&returnbode=='200'=>不能手动更新、不能上传)
  if (isReportResult.value == false && e.length === pageData.tableData.length) {
    manual.disabled = false
  } else {
    manual.disabled = true
  }
};
const handleDisable = (row) => {
  if (isReportResult.value) {
    return false
  } else {
    if (row.status == '99') {
      return false
    } else {
      return true
    }
  }
}
const isAllSumbit = ref(true)
//获取表格数据
function getPageData() {
  tableLoading.value = true;
  getApi(query, "/mosty-jcgl/data/prepipe/getList").then((res) => {
    if (res) {
      pageData.tableData = res;
      tableLoading.value = false;
      byTime.value = res[0]?.sbsj ? res[0].sbsj : "";
      if (isProvinces.value) {
        reportResult();
        if (isReportResult.value) {
          timer.value = setInterval(() => {
            if (!isReportResult.value) {
              clearInterval(timer.value);
              timer.value = null;
              isAutoReport.value = false
            }
            reportResult();
          }, 1e4);
        }
      }
      let count = 0
      res.forEach((item) => {
        if (item.status === '1' || item.status === '99') count++
      })
      if (count === res.length) isAllSumbit.value = false
    }
  }).catch(err => {
    tableLoading.value = false;
  });;
}

const getYearQ = () => {
  let now = new Date();
  let year = now.getFullYear(); // 获取当前年份
  let quarter = Math.floor(now.getMonth() / 6) + 1; // 获取当前季度
  query.year = year
  query.half = quarter
  if (query.year == now.getFullYear() && query.half == Math.floor(now.getMonth() / 6) + 1) {
    isShowCancelBtn.value = true
  } else {
    isShowCancelBtn.value = false
  }
}
//选择
const changeTimeCondition = val => {
  const { yearValue, halfValue } = val
  let now = new Date();
  query.year = yearValue.toString()
  query.half = halfValue
  if (query.year == now.getFullYear() && query.half == Math.floor(now.getMonth() / 6) + 1) {
    isShowCancelBtn.value = true
  } else {
    isShowCancelBtn.value = false
  }
  //判断是否是安全部门
  if (filterqx('isaqbm') == '1') {
    if (filterqx("isSgs") == "1") {
      // 省公司-安全员
      getShowBtn()
      getPageData()
    } else if (filterqx("isgs") == "1") {
      //市公司-安全员 不展示手动更新、上报 、多选
      getShowBtn()
      showbtn.value = false
      getPageData()
    } else {
      showbtn.value = false
      getPageData()
    }

  } else {
    // 所有单位下非安全管理部门的人员，进入此功能，均只展示列表表头，不展示数据“暂无数据”，手动更新和首次上报按钮均显示或不可操作
    pageData.tableData = []
    showbtn.value = false
  }
}
const onUpdate = (row, status) => {
  loadingsb.value = true
  getApi({ orgCode: row.orgcode, status: status }, '/mosty-jcgl/data/prepipe/reportLocalData').then(res => {
    getPageData()
  }).finally(() => {
    loadingsb.value = false
  })
};
//详情
function seetable(row) {
  isSfsb.value = row.sfsb == '1' ? true : false
  orgObj.value.orgcode = row.orgcode
  orgObj.value.orgname = row.orgname
  dialogTitle.value = `特种设备-压力管道列表（${row.orgname}）`;
  dialogVisible.value = true;
}
// 关闭弹窗
const dialogClose = val => {
  dialogVisible.value = false
  getPageData();
}
onUnmounted(() => {
  if (timer.value) {
    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/epsemPrepipe').then(res => {
    ylgdXlsx(res ? res : [], props.dict, popover.value.content)

  }).finally(() => {
    loading.close()
  })

}
</script>

<style lang="scss" scoped>
.box-sjtj {
  background-color: #fff;
  width: 100%;
  padding: 0 16px 7px 16px;
  box-sizing: border-box;
}
</style>
