<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 ? 450 : 250}px)` }">
        <TimeCondition :byTime="byTime" :ywId="props.id" @change="onChange" :title="title + '台账'" :popover="popover">
          <template #right>
            <div 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">手动更新</el-button>
                </template>
              </el-popconfirm>
              <template v-if="isShowSbBtn">
                <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="是否确认上报?"
                  @confirm="handleReport">
                  <template #reference>
                    <el-button type="primary" :loading="sbloading"
                      :disabled="!isShowBtn || isAllSumbit || isReportResult">{{
                        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>
            </div>
            <div v-if="isCity">
              <template v-if="isShowSbBtn">
                <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="是否确认上报?"
                  @confirm="onUpdate({ orgCode: getItem('deptId').ssdwid }, '1', '2')">
                  <template #reference>
                    <el-button type="primary" :disabled="isAllSumbit">上报</el-button>
                  </template>
                </el-popconfirm>
                <!-- <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="是否撤销上报?"
                  @confirm="onUpdate({ orgCode: getItem('deptId').ssdwid }, '0', '1')">
                  <template #reference>
                    <el-button type="primary">撤销</el-button>
                  </template>
                </el-popconfirm> -->
              </template>
            </div>
            <el-button type="primary" style="margin-left: 5px;" @click="onExport">导出</el-button>
          </template>
        </TimeCondition>
        <el-table :data="tableData" style="width: 99%" border v-loading="loading" @selection-change="selectionChange"
          :header-cell-style="{ background: '#F6F6F6' }" height="calc(100% - 100px)">
          <el-table-column type="selection" width="55" v-if="isShowSbBtn" :selectable="handleDisable" />
          <el-table-column label="企业名称" prop="orgName" fixed width="140" />
          <el-table-column align="center" label="安全设施费用(万元)">
            <el-table-column prop="safetyFacilitieYearBudget" label="年度预算" />
            <el-table-column prop="safetyFacilitieInputCost" label="已执行投入" />
          </el-table-column>
          <el-table-column align="center" label="应急救援费用(万元)">
            <el-table-column prop="emergencyRescueYearBudget" label="年度预算" />
            <el-table-column prop="emergencyRescueInputCost" label="已执行投入" />
          </el-table-column>
          <el-table-column align="center" label="安全防护用品费用(万元)">
            <el-table-column prop="safetyProtectionYearBudget" label="年度预算" />
            <el-table-column prop="safetyProtectionInputCost" label="已执行投入" />
          </el-table-column>
          <el-table-column align="center" label="安全信息化费用(万元)">
            <el-table-column prop="safetyInformationizeYearBudget" label="年度预算" />
            <el-table-column prop="safetyInformationizeInputCost" label="已执行投入" />
          </el-table-column>
          <el-table-column align="center" label="安全生产宣传教育培训支出费用(万元)">
            <el-table-column prop="safeProductEduTrainExpenditureYearBudget" label="年度预算" />
            <el-table-column prop="safeProductEduTrainExpenditureCost" label="已执行投入" />
          </el-table-column>
          <el-table-column align="center" label="隐患奖励费用(万元)">
            <el-table-column prop="hdRewardYearBudget" label="年度预算" />
            <el-table-column prop="hdRewardInputCost" label="已执行投入" />
          </el-table-column>
          <el-table-column align="center" label="安全保险费用(万元)">
            <el-table-column prop="safetyInsuranceYearBudget" label="年度预算" />
            <el-table-column prop="safetyInsuranceInputCost" label="已执行投入" />
          </el-table-column>
          <el-table-column align="center" label="安全咨询服务器费用(万元)">
            <el-table-column prop="safetyConsultingServiceYearBudget" label="年度预算" />
            <el-table-column prop="safetyConsultingServiceInputCost" label="已执行投入" />
          </el-table-column>
          <el-table-column align="center" label="其他费用(万元)">
            <el-table-column prop="otherYearBudget" label="年度预算" />
            <el-table-column prop="otherInputCost" label="已执行投入" />
          </el-table-column>
          <el-table-column align="center" label="合计总费用数(万元)">
            <el-table-column prop="budget" label="年度预算" />
            <el-table-column prop="cost" label="已执行投入" />
          </el-table-column>
          <el-table-column prop="gxTime" label="最后一次上报时间" width="100" fixed="right" />
          <el-table-column prop="status" label="当前上报状态" width="110" fixed="right">
            <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="累计上报次数" width="100" fixed="right">
            <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 && (row.orgCode === orgid)" 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-link v-else type="primary" disabled>更新</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>
              <template v-if="hasEdit(row) && row.orgCode === orgid">
                <el-link type="primary" @click="onEdit(row)">编辑</el-link>
              </template>
              <el-link type="primary" @click="onView(row)">查看</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" :currCode="currOrgCode" :currTotal="currTotal" :orgId="props.orgCode" :year="query.year"
    @close="sblsVisible = false" :params="pageData.params" />
  <Dialog v-if="dialogVisible" :title="dialogTitle" @close="dialogClose" :currId="currId" />
</template>

<script setup>
import { onMounted, getCurrentInstance, ref, reactive, defineAsyncComponent, watch, computed } 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 Dialog from "../components/tab5/dialog";
import SblsTable from '../components/tab5/SblsTable.vue'
import { getItem } from "@/utils/storage";
import { ElMessage, ElLoading } from "element-plus";
import { filterqx } from "@/utils/auth.js";
import { aqtrXlsx } from "./tab1tool"
const { proxy } = getCurrentInstance();
const { D_BZ_AQSCBZHDBJB } = proxy.$dict("D_BZ_AQSCBZHDBJB");
// 上报历史
const sblsVisible = ref(false)
const currTotal = ref(null)
const currOrgCode = ref(null);
const props = defineProps({ isOpen: Boolean, id: String, orgCode: String, title: String });
const popover = reactive({
  title: "",
  content: `
  填表说明：
1. 填写范围：统计的企业基本信息应包含各省级单位本部及其下属单位的基本信息，不包括多元化企业；
2. 统计频次：年。
3. 提交周期：每年1月1日至次年3月31日。
4. 数据统计范围： 填写本年度截止到当前统计周期的累计数据。
5. 安全投入：需完整填写各省级单位机关及下属各单位对应信息，提交周期内每家单位有且仅有一条数据。
6. 安全投入统计范围包括：（参照：《企业安全生产费用提取和使用管理办法》财资〔2022〕136号）
（1）安全设施：购置购建、更新改造、检测检验、检定校准、运行维护安全防护和紧急避险设施设施
设备支出[不含按照“建设项目安全设施必须与主体工程同时设计、同时施工、
同时投入生产和使用”（以下简称“三同时”）规定投入的安全设施、设备]；
（2）应急救援：配备、更新、维护、保养应急救援器材、设备支出；企业应急救援队伍建设
（含建设应急救援队伍所需应急救援物资储备、人员培训等方面）；应急预案制修订、应急演练支出；
（3）安全防护用品：配备、更新、维护、保养安全防护用品；
（4）安全信息化：购置、开发、推广应用、更新升级、运行维护安全生产信息系统、软件、网络安全、技术支出；
（5）安全生产宣传教育培训支出；
（6）隐患奖励：从业人员发现报告事故隐患的奖励支出；
（7）安全保险：安全生产责任保险、承运人责任险等与安全生产直接相关的法定保险支出；
（8）安全咨询服务：安全生产检查检测、评估评价（不含新建、改建、扩建项目安全评价）、评审、咨询、标准化建设；
（9）其他：与安全生产直接相关的其他支出。
  `
});
const uploadNum = ref(0);
const query = reactive({
  orgcode: getItem("deptId").ssdwid,
  year: ""
});
const loading = ref(false);
const tableData = ref([]);
const dialogVisible = ref(false)
const practitioners = ref([]);
const tabDialog = ref(null);
const currId = ref(null)
const dialogTitle = ref("");
/** 是否七个工作日 不是不能上报 (接口查询)*/
const isShowBtn = ref(false);
const isShowSbBtn = ref(true);
const byTime = ref("");
const isReportResult = ref(false);
const timer = ref(null);
const manual = reactive({
  loading: false,
  disabled: true
});
const dialogsbyy = ref(false)
const IsCksbjg = ref(false)
const loadingcksbjg = ref(false)
const reportResultInfo = 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" ? true : false;
});
//县级账号
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 hasEdit = obj => {
  if (obj.sourceId && !isReportResult.value) {
    return true;
  }
  return false;
}
// 查看省局上报结果
const reportResult = (val) => {
  loadingcksbjg.value = true
  getApi({ year: query.year, id: props.id, jtsj: 0 }, "/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) {
          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) {
          pageData(false);
        }
      }
      // 只针对是否展示查看上报结果
      if (res.returnCode || res.returnHttpCode) {
        IsCksbjg.value = true

      } else {
        IsCksbjg.value = false
      }
    }


  }).finally(() => {
    loadingcksbjg.value = false
  });
};
// 关闭弹窗
const dialogClose = val => {
  dialogVisible.value = false
  if (val) {
    pageData();
  }
}
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: 0 }, "/mosty-jcgl/dataCommon/getSccs");
};
const onChange = (val) => {
  const currentDate = new Date();
  const currentYear = currentDate.getFullYear(); // 返回当前年份
  if (val.yearValue != currentYear) {
    isShowSbBtn.value = false;
  } else {
    isShowSbBtn.value = true;
  }
  query.year = val.yearValue;
  query.jd = val.quarterValue;

  if (isAuth.value || isPlant.value || isTown.value) {
    pageData();
    getShowBtn();
  }
};
//查看当期是否有数据
const orgcode = ref('')
const counts = ref(0)
const isAllSumbit = ref(true)
const pageData = (val = true) => {
  loading.value = true;
  getApi(query, "/mosty-jcgl/data/Siledger/getList").then((res) => {

    if (res) {
      byTime.value = res[0]?.updateTime ? res[0].updateTime : "";
      if (isProvinces.value) {
        orgcode.value = query.orgcode
      } else {
        orgcode.value = res[0].orgCode
      }
      if (query.year == new Date().getFullYear()) {
        getApi({ year: query.year, orgcode: orgcode.value }, "/mosty-jcgl/data/Siledger/getData").then(res1 => {
          if (res1 && counts.value == 0) {
            getApi({ orgcode: orgcode.value }, "/mosty-jcgl/data/Siledger/syncLocal").then((res2) => {
              counts.value++
              pageData();
            })
          } else {
            tableData.value = res;
            loading.value = false;
          }
        });
      } else {
        tableData.value = res;
        loading.value = false;
      }
      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
    }
  }).catch(err => {
    loading.value = false;
  });
};
// 是否可以选择多选
const handleDisable = (row) => {
  if (isProvinces.value && row.status != '99') {
    return hasValue(row)
  } else {
    if (row.status == '99') {
      return false
    } else {
      return true
    }
  }
};
// 是否可以选择多选
const hasValue = obj => {
  let _data = obj
  for (const prop in _data) {
    if (_data.hasOwnProperty(prop) && (_data[prop] === null || _data[prop] === undefined || _data[prop] === '')) {
      if (prop == 'status' || prop == 'sbcs' || prop == 'gxTime' || prop == 'lyid' || prop == 'baOrgCode') {
        continue;
      } else {
        return false;
      }

    }
  }
  return true;
}
const onUpdate = (row, status, state) => {
  sbloading.value = true
  getApi({ orgCode: row.orgCode, status: status }, '/mosty-jcgl/data/Siledger/reportLocalData').then(res => {
    pageData()
    if (state === '2') {
      ElMessage({
        message: "上报省局成功",
        type: "success"
      });
    } else if (state === '1') {
      ElMessage({
        message: "撤销成功",
        type: "success"
      });
    }
  }).finally(() => {
  sbloading.value = false
})
};
const onEdit = (e) => {
  e.complianceLevelCode = e.complianceLevelCode + "";
  dialogVisible.value = true;
  currId.value = e.sourceId
  dialogTitle.value = `编辑单位信息（${e.baOrgName}）`;
};
const onView = (e) => {
  e.complianceLevelCode = e.complianceLevelCode + "";
  dialogVisible.value = true;
  currId.value = e.sourceId
  dialogTitle.value = `单位信息（${e.baOrgName}）详情`;
};
// 点击上报历史
const handleHistory = (row) => {
  currOrgCode.value = row.orgCode
  currTotal.value = row.sbcs
  if (currOrgCode.value) {
    sblsVisible.value = true
  }
}
const sbloading = ref(false)
const handleReport = () => {
  sbloading.value = true
  getApi({ 'orgCode': query.orgcode }, '/mosty-jcgl/data/Siledger/upSiLedger').then(res => {
    if (res) {
      ElMessage({
        message: "上报成功",
        type: "success"
      });
      reportResult()
      pageData()

    } else {
      ElMessage({
        message: "上报失败",
        type: "error"
      });
      pageData()
    }
  }).finally(() => {
    sbloading.value = false
  })

};
const manualUpdate = (code, isItem = false) => {
  if (isItem) manual.loading = true;
  loading.value = true;
  getApi({ orgcode: code }, "/mosty-jcgl/data/Siledger/syncLocal")
    .then((res) => {
      pageData();
      ElMessage({
        message: "更新成功",
        type: "success"
      });
      manual.loading = false;
    })
    .catch((err) => {
      loading.value = false;
      manual.loading = false;
    });
};

const selectionChange = (e) => {
  manual.disabled = e.length === tableData.value.length ? false : true;
};
onMounted(() => {
  if (isAuth.value) {
    orgid.value = orgid.value + 'XN'
  }
  popover.title = props.title.replace("数据", "");
});

const onExport = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '导出中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  getApi(query, '/mosty-jcgl/data/export/siLedger').then(res => {
    aqtrXlsx(res ? res : [], popover.content, { D_BZ_AQSCBZHDBJB })
  }).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>
