<template>
  <div class="content scroll">
    <div class="box">
      <div class="bottom" :style="{ height: `calc(100vh - 250px)` }">
        <TimeCondition :byTime="byTime" :ywId="props.id" @change="onChange" :title="title + '台账'" :popover="popover">
          <template #right>
            <div v-if="isProvinces">
              <!-- <el-popconfirm v-if="isShowSbBtn && isShowBtn" 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-button type="primary" class="mr5" :disabled="isReportResult" @click="manualUpdate(query.orgcode, true)" :loading="manual.loading">手动更新</el-button> -->
              <template v-if="isShowSbBtn">
                <el-popconfirm v-if="isShowBtn" confirm-button-text="是" cancel-button-text="否" icon-color="red"
                  title="是否确认上报?" @confirm="handleReport">
                  <template #reference>
                    <el-button type="primary" :loading="sbloading" :disabled="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>
            <el-button :data-v-auth="`sbBtn=${isShowSbBtn}--btn-api-sfQggzr=${isShowBtn}`" type="primary"
              style="margin-left: 5px;" @click="onExport">导出</el-button>
          </template>
        </TimeCondition>
        <el-table :data="tableData" @selection-change="selectionChange" style="width: 99%" border
          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 prop="reportingYear" label="计划年度" min-width="120" />
          <el-table-column prop="annualPlanName" label="计划名称" min-width="120" />
          <el-table-column label="计划附件" min-width="120">
            <template #default="scope">
              <el-link type="primary" v-if="scope.row.attachments" @click="handledlon(scope.row.attachments)">
                <el-icon style="margin-left: 5px">
                  <Download />
                </el-icon>下载
              </el-link>
            </template>
          </el-table-column>
          <el-table-column prop="gxTime" label="最后一次上报时间" width="150" fixed="right">
            <template #default="{ row }">
              <span>{{ row.gxTime || '--' }}</span>
            </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="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="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="170" 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>
              <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)">
                <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 ref="tabDialog" :title="dialogTitle" :rowItem="rowItem" @onSave="onSave" />
</template>

<script setup>
import { onMounted, onBeforeUnmount, ref, reactive, getCurrentInstance, watch, computed } from "vue";
import TimeCondition from "@/views/dataReportWork/components/TimeCondition";
import { getItem } from "@/utils/storage";
import { ElMessage, ElLoading } from "element-plus";
import { filterqx } from "@/utils/auth.js";
import { getApi } from "@/api/tobAcco_api.js";
import Dialog from "../components/tab2/dialog";
import SblsTable from '../components/tab2/SblsTable.vue'
import { createAndClickLink } from "@/utils/tools.js";
import { ndjhXlsx } 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日至次年3月31日。
4. 数据统计范围： 填写本年度截止到当前统计周期的累计数据。
5. 导入成功后，请在年度计划中补充年度附件信息。
  `
});
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 isPlant = computed(() => {
  let code = getItem("deptId").ssdwid;
  return code.startsWith("5299");
});
const isShowBtn = ref(false);
const uploadNum = ref(0);
const tableLoading = ref(false);
const tableData = ref([]);
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 dialogsbyy = ref(false)
const IsCksbjg = ref(false)
const loadingcksbjg = ref(false)
const reportResultInfo = ref({})
const sblsVisible = ref(false)
const currOrgCode = ref(null);
const currTotal = ref(null)
// end
const query = reactive({
  orgcode: getItem("deptId").ssdwid,
  year: ""
});
const manual = reactive({
  loading: false,
  disabled: true
});
// 是否显示编辑按钮
const hasEdit = obj => {
  if (obj.sourceId && !isReportResult.value) {
    return true;
  }
  return false;
}
// 是否可以选择多选
const handleDisable = (row) => {
  if (isNaN(row.annualPlanName) && isNaN(row.attachments) && isProvinces.value && row.status != '99') {
    return true
  } else {
    if (row.status == '99') {
      return false
    } else {
      return true
    }
  }

};
// 点击上报历史
const handleHistory = (row) => {
  currOrgCode.value = row.orgCode
  currTotal.value = row.sbcs
  if (currOrgCode.value) {
    sblsVisible.value = true
  }
}
// 查看省局上报结果
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 getShowBtn = async () => {
  if (isAuth.value) {
    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 orgcode = ref('')

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) {
    pageData();
    getShowBtn();
  }
};
const isAllSumbit = ref(true)
const counts = ref(0)
const pageData = (val = true) => {
  tableLoading.value = true;
  tableData.value = [];
  getApi(query, "/mosty-jcgl/data/annualPlan/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/annualPlan/getData").then(res1 => {
          if (res1 && counts.value == 0) {
            getApi({ orgcode: orgcode.value }, "/mosty-jcgl/data/annualPlan/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;
      }
      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 onUpdate = (row, status) => {
  sbloading.value = true
  getApi({ orgCode: row.orgCode, status: status }, '/mosty-jcgl/data/annualPlan/reportLocalData').then(res => {
    pageData()
  }).finally(() => {
    sbloading.value = false
  })
};
const onEdit = (e) => {
  tabDialog.value.dialogVisible = true;
  rowItem.value = e;
  dialogTitle.value = `编辑年度计划（${e.baOrgName}）`;
};
const onView = (e) => {
  tabDialog.value.dialogVisible = true;
  rowItem.value = e;
  dialogTitle.value = `查看年度计划（${e.baOrgName}）`;
};
const onSave = (e) => {
  pageData();
};
const sbloading = ref(false)
const handleReport = () => {
  sbloading.value = true
  if (isProvinces.value) {
    getApi({ orgCode: query.orgcode }, '/mosty-jcgl/data/annualPlan/upAnnualPlan').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/data/annualPlan/syncLocal")
    .then((res) => {
      pageData();
      ElMessage({
        message: "更新成功",
        type: "success"
      });
      manual.loading = false;
    }).catch((err) => {
      tableLoading.value = false;
      manual.loading = false;
    });
};
const selectionChange = (e) => {
  manual.disabled = e.length === tableData.value.length ? false : true;
};
const handledlon = (id) => {
  if (id) {
    getApi({}, `/mosty-base/minio/file/download/${id}`).then((res) => {
      if (res) {
        createAndClickLink(res.url, res.originalName);
      }
    });
  }
};

onMounted(() => {
  if (isProvinces.value) {
    orgid.value = orgid.value + 'XN'
  }
  popover.title = props.title.replace("数据", "");
});
onBeforeUnmount(() => {

});
// 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/annualPlan').then(res => {
    if (res) {
      let data = res
      if (data) {
        for (let i = 0; i < data.length; i++) {
          data[i].annualPlanName = data[i].annualPlanName ? data[i].annualPlanName : '';
          data[i].file = data[i].file ? data[i].file : '';
        }
      }
      ndjhXlsx(data, popover.content, { D_BZ_AQSCBZHDBJB })
    } else {
      ndjhXlsx([], popover.content, { D_BZ_AQSCBZHDBJB })
    }
  }).finally(() => {
    loading.close()
  })
}
</script>

<style lang="scss" scoped>
.content {
  .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>
