<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 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 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="baOrgName" fixed width="140" />
          <el-table-column label="年配送量(万箱)" prop="actualDeliveryVolume" width="140">
            <template #default="{ row }">
              <span v-if="row.actualDeliveryVolume == null">0</span>
              <span v-else>{{ row.actualDeliveryVolume }}</span>
            </template>
          </el-table-column>
          <el-table-column label="中转站数量(个)" prop="ldcTransferStationQty" width="140" />
          <el-table-column align="center" label="分拣线">
            <el-table-column prop="sortingLineQty" label="数量(条)" />
            <el-table-column prop="ldcSortingCapacity" label="分拣能力(条/小时)" />
          </el-table-column>
          <el-table-column align="center" label="动力保障设备">
            <el-table-column prop="vacuumEquipmentQty" label="真空设备数量(台)" />
            <el-table-column prop="airCompressionEquipmentQty" label="空压设备数量(台)" />
            <el-table-column prop="refrigerationEquipmentQty" label="制冷设备数量(台)" />
            <el-table-column prop="hvdcQty" label="变配电-高压配电数量(台)" />
            <el-table-column prop="transformerQty" label="变配电-变压器数量(台)" />
            <el-table-column prop="alternatorQty" label="变配电-发电机数量(台)" />
          </el-table-column>
          <el-table-column align="center" label="卷烟配送">
            <el-table-column prop="ldcCageCarQty" label="笼车(个)">
              <template #default="{ row }">
                <span v-if="row.ldcCageCarQty == null" style="color: red;">未上报</span>
                <span v-else>{{ row.ldcCageCarQty }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="transportVehiclesQty" label="配送车(辆)" />
            <el-table-column prop="ldcNewEnergyCarQty" 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" 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" @close="dialogClose" :currId="currId" v-if="dialogVisible" />
</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/tab7/dialog";
import SblsTable from '../components/tab7/SblsTable.vue'
import { getItem } from "@/utils/storage";
import { ElMessage, ElLoading } from "element-plus";
import { filterqx } from "@/utils/auth.js";
import { jywlXlsx } from "./tab1tool"
const { proxy } = getCurrentInstance();
const { D_BZ_AQSCBZHDBJB } = proxy.$dict("D_BZ_AQSCBZHDBJB");
const dialogsbyy = ref(false)
const IsCksbjg = ref(false)
const loadingcksbjg = ref(false)
const reportResultInfo = ref({})
const sblsVisible = ref(false)
const currTotal = ref(null)
const currOrgCode = ref(null);
const props = defineProps({ isOpen: Boolean, id: String, title: String });
const popover = reactive({
  title: "",
  content: `
  填表说明：
1. 统计频次：年。
2. 提交周期：每年1月1日至12月25日。
3. 数据统计范围： 填写本年度截止到当前统计周期的累计数据。
4. 设备各单位要据实填写，对没有的设备项填写“0”；
5. 年生产量：指上一年度生产量；
6. 制冷设备：指集中制冷设备。
  `
});
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
});
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 hasEdit = obj => {
  if (obj.sourceId && !isReportResult.value) {
    return true;
  }
  return 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 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;

  if (isAuth.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/ldcInformation/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/ldcInformation/getData").then(res1 => {
          if (res1 && counts.value == 0) {
            getApi({ orgcode: orgcode.value }, "/mosty-jcgl/data/ldcInformation/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 onUpdate = (row, status) => {
  sbloading.value = true
  getApi({ orgCode: row.orgCode, status: status }, '/mosty-jcgl/data/ldcInformation/reportLocalData').then(res => {
    pageData()
  }).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/ldcInformation/upLdcInformation').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/ldcInformation/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 (isProvinces.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/ldcInformation').then(res => {
    jywlXlsx(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);
}
::v-deep .el-link--success {
  margin-right: 8px;
}
</style>
