<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 : 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> -->
              <el-popconfirm v-if="isShowSbBtn && isShowBtn" confirm-button-text="是" cancel-button-text="否"
                icon-color="red" title="是否确认上报?" @confirm="handleReport()">
                <template #reference>
                  <el-button type="primary" :loading="sbloading" :disabled="manual.disabled || 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> -->
            </div>
            <el-button type="primary" style="margin-left: 5px;" @click="onExport">导出</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" v-if="isShowSbBtn" />
          <el-table-column label="企业名称" prop="baOrgName" fixed width="280" />
          <el-table-column align="center" label="从业人员人数">
            <el-table-column prop="jobDutyPeopleQty" label="在册在岗人数" width="110" />
            <el-table-column prop="dispatchDutyPeopleQty" label="劳务派遣人数" width="110" />
          </el-table-column>
          <el-table-column align="center" label="安全管理机构">
            <el-table-column label="是否独立设置" width="110">
              <template #default="{ row }">
                <span v-if="row.independentSettingsFlag === 0">否</span>
                <span v-else-if="row.independentSettingsFlag === 1">是</span>
              </template>
            </el-table-column>
            <el-table-column prop="organizationPeopleQty" label="编制人数" width="90" />
            <el-table-column prop="allocationPeopleQty" label="配置人数" width="90" />
            <el-table-column label="是否设置安全工程师岗位" width="110">
              <template #default="{ row }">
                <span v-if="row.sePositionFlag === 0">否</span>
                <span v-else-if="row.sePositionFlag === 1">是</span>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column align="center" label="专业持证人数">
            <el-table-column prop="safetyPeopleQty" label="注安人数" width="90" />
            <el-table-column prop="cancellationPeopleQty" label="注消人数" width="90" />
          </el-table-column>
          <el-table-column align="center" label="安全生产标准化">
            <el-table-column label="达标级别" width="90">
              <template #default="scope">
                {{ scope.row.complianceLevelName }}
              </template>
            </el-table-column>
            <el-table-column prop="complianceScore" label="达标得分" width="90" />
            <el-table-column prop="expireDate" label="有效截止日期" width="110" />
            <el-table-column prop="yearSelfEvaluationScore" label="年度自评得分" width="110" />
          </el-table-column>
          <el-table-column align="center" label="职业健康管理体系">
            <el-table-column label="是否认证" width="90">
              <template #default="{ row }">
                <span v-if="row.attestationFlag === 0">否</span>
                <span v-else-if="row.attestationFlag === 1">是</span>
              </template>
            </el-table-column>
            <el-table-column prop="effectiveUntilDate" label="有效截止日期" width="110" />
          </el-table-column>
          <el-table-column prop="gxTime" label="最后一次上报时间" width="150" fixed="right">
            <template #default="scope">
              {{ scope.row.gxTime || '--' }}
            </template>
          </el-table-column>
          <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="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="110" fixed="right">
            <template #default="{ row }">
              <el-link type="primary" @click="handleHistory(row)">{{ row.sbcs || 0 }}</el-link>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="140" fixed="right">
            <template #default="{ row }">
              <!-- <el-popconfirm v-if="isShowSbBtn && !isReportResult" 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> -->
              <template v-if="hasEdit(row)">
                <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" :year="query.year"
    @close="sblsVisible = false" :params="pageData.params" />
  <Dialog ref="tabDialog" :title="dialogTitle" :rowItem="rowItem" @onSave="onSave" />
</template>

<script setup>
import { getImgUrl } from "@/utils/tools.js"
import { onMounted, ref, reactive, computed, getCurrentInstance } 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/tab1/dialog";
import SblsTable from '../components/tab1/SblsTable.vue'
import { getItem } from "@/utils/storage";
import { ElMessage, ElLoading } from "element-plus";
import { filterqx } from "@/utils/auth.js";
import { exportXlsx, ryqkXlsx } from "./tab1tool"
const { proxy } = getCurrentInstance();
const { D_BZ_AQSCBZHDBJB } = proxy.$dict("D_BZ_AQSCBZHDBJB");

const props = defineProps({ isOpen: Boolean, id: String, title: String });
const popover = reactive({
  title: "",
  content: `
  填表说明：
1. 填写范围：统计的企业基本信息应包含各省级单位本部及其下属单位的基本信息，不包括多元化企业；
2. 统计频次：年。
3. 提交周期：每年1月1日至12月25日。
4. 数据统计范围： 填写本年度截止到当前统计周期的累计数据。
5. 企业基本信息：需完整填写各省级单位机关及下属各单位对应信息，提交周期内每家单位有且仅有一条数据。
6. 安全管理机构：指省级单位及其下属单位是否设置独立的安全管理部门，不包含县级局（分公司）情况。
7. 安全管理信息系统：是指由省级单位统一建设部署的安全管理信息系统。
8. 安全生产标准化达标等级：一级、二级、三级和未评级；未评级可不填写安全生产标准化其他信息。
9. 年度自评得分：省级本级单位非必填。
10. 职业健康安全管理体系：是/否，认证为“否”时可不填写职业健康安全管理体系其他信息。
  `
});
const sbloading = ref(false)
const dialogsbyy = ref(false)
const IsCksbjg = ref(false)
const loadingcksbjg = ref(false)
const reportResultInfo = ref({})
// 是否是省账号
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 isPlant = computed(() => {
  let code = getItem("deptId").ssdwid;
  return code.startsWith("5299");
});
const isShowBtn = ref(false);
const uploadNum = ref(0);
const sblsVisible = ref(false)
const currOrgCode = ref(null)
const currTotal = ref(null)
const query = reactive({
  orgcode: getItem("deptId").ssdwid,
  year: ""
});
const tableLoading = ref(false);
const tableData = ref([]);
const practitioners = reactive([
  {
    name: "从业人员在册在岗人数",
    icon: getImgUrl('dataReportWork/tab1/在册在岗人.png'),
    count: 1123
  },
  {
    name: "从业人员劳务派遣人数",
    icon: getImgUrl('dataReportWork/tab1/派遣.png'),
    count: 1123
  },
  {
    name: "安全管理人员编制人数",
    icon: getImgUrl('dataReportWork/tab1/注安人数.png'),
    count: 1123
  },
  {
    name: "安全管理人员配置人数",
    icon: getImgUrl('dataReportWork/tab1/注销人员.png'),
    count: 1123
  },
  {
    name: "注安专业持证人数",
    icon: getImgUrl('dataReportWork/tab1/编制.png'),
    count: 1123
  },
  {
    name: "注消专业持证人数",
    icon: getImgUrl('dataReportWork/tab1/配置人数.png'),
    count: 1123
  }
]);
const tabDialog = ref(null);
const rowItem = ref(null);
const dialogTitle = ref("");
const byTime = ref("");
const isReportResult = ref(false);
const timer = ref(null);
const isShowSbBtn = ref(true);
const manual = reactive({
  loading: false,
  disabled: true
});
onMounted(() => {
  popover.title = props.title.replace("数据", "");
});

// 是否显示编辑按钮
const hasEdit = obj => {
  if (obj.sourceId && !isReportResult.value) {
    return true;
  }
  return false;
}
// 是否可以选择多选
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') {
        continue;
      } else {
        return false;
      }

    }
  }
  return true;
}
// 点击上报历史
const handleHistory = (row) => {
  currOrgCode.value = row ? row.orgCode : pageData?.params.orgcode
  currTotal.value = row.sbcs
  if (currOrgCode.value) {
    sblsVisible.value = true
  }
}
// 是否可以选择多选
const handleDisable = (row) => {
  if (isProvinces.value && row.status != '99') {
    return hasValue(row)
  } else {
    if (row.status == '99') {
      return false
    } else {
      return 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: 0 }, "/mosty-jcgl/dataCommon/getSccs");
};
// 查看省局上报结果
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 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;
  if (isAuth.value || isPlant.value) {
    countAll();
    pageData();
    getShowBtn();
  }
};
//查看当期是否有数据
const orgcode = ref('')
const counts = ref(0)
const pageData = (val = true) => {
  tableLoading.value = true;
  tableData.value = [];
  getApi(query, "/mosty-jcgl/enterpriseInfo/getList").then((res) => {
    if (res) {
      byTime.value = res[0]?.updateTime ? res[0].updateTime : "";

      if (query.year == new Date().getFullYear()) {
        if (isProvinces.value) {
          orgcode.value = query.orgcode
        } else {
          orgcode.value = res[0].orgCode
        }
        getApi({ year: query.year, orgcode: orgcode.value }, "/mosty-jcgl/enterpriseInfo/getData").then(res1 => {
          if (res1 && counts == 0) {
            getApi({ orgcode: orgcode.value }, "/mosty-jcgl/enterpriseInfo/syncLocal").then((res2) => {
              counts.value++
              pageData()
            })
          } else {
            tableData.value = res;
            tableLoading.value = false;
          }
        });
      } else {
        tableData.value = res;
        tableLoading.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;
      }

    }
  }).catch(err => {
    tableLoading.value = false;
  });
};
const onEdit = (e) => {
  // e.complianceLevelCode = e.complianceLevelCode + "";
  tabDialog.value.dialogVisible = true;
  rowItem.value = e;
  dialogTitle.value = `编辑单位信息（${e.baOrgName}）`;
};
const onView = (e) => {
  // e.complianceLevelCode = e.complianceLevelCode + "";
  tabDialog.value.dialogVisible = true;
  rowItem.value = e;
  dialogTitle.value = `查看单位信息（${e.baOrgName}）`;
};
const onSave = (e) => {
  pageData();
};
const handleReport = () => {
  sbloading.value = true
  if (isProvinces.value) {
    getApi({ 'orgCode': query.orgcode }, '/mosty-jcgl/enterpriseInfo/upEnterpriseInfo').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) => {
  tableLoading.value = true;
  if (isItem) manual.loading = true;
  getApi({ orgcode: code }, "/mosty-jcgl/enterpriseInfo/syncLocal")
    .then((res) => {
      pageData();
      ElMessage({
        message: "更新成功",
        type: "success"
      });
      manual.loading = false;
    }).catch(err => {
      tableLoading.value = false;
      manual.loading = false;
    })

};
const countAll = () => {
  getApi(query, "/mosty-jcgl/enterpriseInfo/countAll").then((res) => {
    if (res) {
      practitioners[0].count = res.zczgrs;
      practitioners[1].count = res.nwpqrs;
      practitioners[2].count = res.bzrs;
      practitioners[3].count = res.pzrs;
      practitioners[4].count = res.zazyczrs;
      practitioners[5].count = res.zxzyczrs;
    }
  });
};
const selectionChange = (e) => {
  manual.disabled = e.length === tableData.value.length ? false : true;
};



// watch(
//   () => props.isOpen,
//   (n, o) => {
//     onMock(n);
//   },
//   { immediate: true }
//   // { immediate: true, deep: true }
// );
//导出
const onExport = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '导出中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  getApi(query, '/mosty-jcgl/data/export/enterprise').then(res => {
    if (res) {
      let data = res
      if (data) {
        for (let i = 0; i < data.length; i++) {
          data[i].independentSettingsFlag = data[i].independentSettingsFlag == 0 ? '否' : '是';
          data[i].sePositionFlag = data[i].sePositionFlag == 0 ? '否' : '是';
          data[i].attestationFlag = data[i].attestationFlag == 0 ? '否' : '是';
          data[i].complianceLevelName = data[i].complianceLevelName ? data[i].complianceLevelName : '未评级';
          data[i].complianceScore = data[i].complianceScore ? data[i].complianceScore : 0;
          data[i].expireDate = data[i].expireDate ? data[i].expireDate : '';
          data[i].yearSelfEvaluationScore = data[i].yearSelfEvaluationScore ? data[i].yearSelfEvaluationScore : '';
          data[i].effectiveUntilDate = data[i].effectiveUntilDate ? data[i].effectiveUntilDate : '';
          data[i].wu = '';
        }
      }
      exportXlsx(data, popover.content, { D_BZ_AQSCBZHDBJB })
    } else {
      exportXlsx([], popover.content, { D_BZ_AQSCBZHDBJB })
    }
  }).finally(() => {
    loading.close()
  })
  getApi({ year: query.year }, '/mosty-jcgl/data/export/honor').then(res => {
    if (res) {
      let datas = res
      if (datas) {
        for (let i = 0; i < datas.length; i++) {
          datas[i].name = datas[i].name ? datas[i].name : '';
          datas[i].time = datas[i].time ? datas[i].time : '';
          datas[i].bz = datas[i].bz ? datas[i].bz : '';
        }
      }
      ryqkXlsx(datas, {})
    }
  }).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>
