<template>
  <div class="box">
    <TimeCondition :byTime="byTime" :ywId="props.ywId" @change="changeTimeCondition" title="建筑物台账"
      :popover="pageData.popover" @handleHistory="handleHistory" v-if="isAqbm">
      <template #right>
        <!-- <el-popconfirm v-if="isProvinces" confirm-button-text="是" cancel-button-text="否" icon-color="red"
          title="若更新数据将重置，是否确认更新?" @confirm="manualUpdate">
          <template #reference>
            <el-button type="primary" class="mr5" :loading="permisssion.manualUpdate.loading"
              :disabled="permisssion.manualUpdate.disabled">手动更新</el-button>
          </template>
</el-popconfirm> -->
        <el-popconfirm v-if="!isProvinces || isProvincesXN" confirm-button-text="是" cancel-button-text="否"
          icon-color="red" title="是否确认撤销?" @confirm="onRevoke()">
          <template #reference>
            <el-button type="primary" class="mr5" :disabled="permisssion.revoke.disabled"
              :loading="loadingbh">撤销</el-button>
          </template>
        </el-popconfirm>
        <el-button type="primary" class="mr5" @click="reportResult(true)" :loading='loadingcksbjg'
          v-if="IsCksbjg">查看上报结果</el-button>
        <el-popconfirm v-if="isProvincesXN" confirm-button-text="是" cancel-button-text="否" icon-color="red"
          :title="`是否确认上报?`" @confirm="onReport">
          <template #reference>
            <el-button type="primary" class="mr5" :loading="loadingscsb"
              :disabled="permisssion.report.disabled">首次上报</el-button>
          </template>
        </el-popconfirm>
        <el-popconfirm v-else confirm-button-text="是" cancel-button-text="否" icon-color="red"
          :title="`是否确认${isProvinces && permisssion.report.count > 0 ? '修改' : ''}上报?`" @confirm="onReport">
          <template #reference>
            <el-button type="primary" class="mr5" :loading="loadingscsb" :disabled="permisssion.report.disabled">{{
              isProvinces &&
    permisssion.report.count > 0 ? "修改" : "首次" }}上报</el-button>
          </template>
        </el-popconfirm>
        <el-button type="primary" @click="handleExport">导出</el-button>
      </template>
    </TimeCondition>
    <el-table :data="pageData.tableData" border style="width: 99%" height="calc(100% - 100px)" v-loading="loading"
      :header-cell-style="{ background: '#F6F6F6' }" :cell-style="cellStyle" element-loading-text="数据加载中..."
      @selection-change="onTableChange">
      <el-table-column align="center" type="selection" width="55" :selectable="handleDisable" />
      <el-table-column v-for="(item, index) in pageData.tableColumn" :key="index" :prop="item.prop" :label="item.label"
        :width="item.width">
        <template #default="{ row }" v-if="item.prop == 'total'">
          <span>{{ Number(row.gcmyjzNum || 0) + Number(row.lhgfNum || 0) + Number(row.xzNum || 0) + Number(row.czNum
            || 0)
          }}</span>
        </template>
        <template #default="{ row }" v-if="item.prop == 'wsbNum'">
          <span v-if='row.wsbNum > 0' style="color: red;">{{ row.wsbNum }}</span>
          <span v-else>{{ row.wsbNum }}</span>
        </template>

        <template #default="{ row }" v-if="item.prop == 'status'">
          <span v-if="row.status == '1'" style="color: green">已上报</span>
          <span v-else-if="row.status == '2'" style="color: red">未上报</span>
          <span v-else-if="row.status == '3'" style="color: #999">未查到数据</span>
          <span v-else-if="row.status == '4'" style="color: green">已上报到省公司</span>
          <span v-else-if="row.status == '5'" style="color: orange">正在上报国家局</span>
          <span v-else-if="row.status == '6'" style="color: green">已上报到国家局</span>
        </template>
        <template #default="{ row }" v-if="item.prop == 'sbcs'">
          <el-link type="primary" @click="handleHistory(row)">{{ row.sbcs }}</el-link>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="170" fixed="right">
        <template #default="{ row }">
          <el-link type="primary" @click="onView(row)">查看</el-link>
          <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="若更新数据将重置，是否确认更新?"
            @confirm="rowUpdate(row.orgCode)">
            <template #reference>
              <el-link type="primary" class="mr5" :disabled="setUpdate(row)">更新</el-link>
            </template>
          </el-popconfirm>
          <el-popconfirm v-if="!isTown && !setPeject(row.status)" confirm-button-text="是" cancel-button-text="否"
            icon-color="red" title="是否确认驳回?" @confirm="onRevoke(row.orgCode)">
            <template #reference>
              <el-link type="primary">驳回</el-link>
            </template>
          </el-popconfirm>
          <el-link v-if="isTown && setPeject(row.status)" disabled>驳回</el-link>
        </template>
      </el-table-column>
    </el-table>
    <!-- 二级table 内容 start -->
    <ChooseUser v-if="chooseUserVisible" :title="'详情'" :currCode="currOrgCode" :orgId="props.orgCode" :isAuth="isAuth"
      :rowItem="rowItem" :ywId="props.ywId" @close="handleClose" :params="query" :isReport="isReport" :isShowDec="true">
    </ChooseUser>
    <!-- 二级table 内容 end -->
    <el-dialog v-model="dialogVisible" :title="pageData.reportResultInfo?.dataname + '上报结果'" width="800px">
      <section v-if="pageData.reportResultInfo?.returnCode == '200' && !pageData.reportResultInfo.returnHttpCode">
        <section>上报人：{{ pageData.reportResultInfo.username }}</section>
        <section>上报时间：{{ pageData.reportResultInfo.sbsj }}</section>
        <section>上报结果：未出上报结果，请等待上报结果</section>
      </section>
      <section v-else-if="pageData.reportResultInfo?.returnCode !== '200' && !pageData.reportResultInfo.returnHttpCode">
        <section>上报人：{{ pageData.reportResultInfo.username }}</section>
        <section>上报时间：{{ pageData.reportResultInfo.sbsj }}</section>
        <section>上报结果：{{ pageData.reportResultInfo.returnMsg }}</section>
      </section>
      <section
        v-else-if="pageData.reportResultInfo?.returnCode == '200' && pageData.reportResultInfo?.returnHttpCode == '200'">
        <section>上报人：{{ pageData.reportResultInfo.username }}</section>
        <section>上报时间：{{ pageData.reportResultInfo.sbsj }}</section>
        <section>上报结果：上报成功</section>
      </section>
      <section
        v-else-if="pageData.reportResultInfo?.returnCode == '200' && pageData.reportResultInfo?.returnHttpCode != '200'">
        <section>上报人：{{ pageData.reportResultInfo.username }}</section>
        <section>上报时间：{{ pageData.reportResultInfo.sbsj }}</section>
        <section>上报结果：{{ pageData.reportResultInfo?.returnOperationResult }}</section>
      </section>
    </el-dialog>
    <SblsTable v-if="sblsVisible" :currCode="currOrgCode" :currTotal="currTotal" :orgId="props.orgCode" :isAuth="isAuth"
      :rootId="getItem('deptId').ssdwid" :ywId="props.ywId" @close="handleHistoryClose" :params="query"
      :isReport="isReport" />
  </div>
</template>
<script setup>
import ChooseUser from './ChooseTable'
import SblsTable from './SblsTable.vue'
import TimeCondition from "@/views/dataReportWork/components/TimeCondition"
import { computed, ref, getCurrentInstance, reactive, watch, onUnmounted, onBeforeUnmount } from "vue";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import { filterqx } from "@/utils/auth.js";
import { getItem } from "@/utils/storage";
import { ElMessage, ElLoading } from "element-plus";
import { jzwXlsx } from "./tabtool";
const { proxy } = getCurrentInstance();
const { D_BZ_JZWHZWXXLB, D_TB_NHDJ, D_BZ_JZWWQBWCLXN, D_BZ_SF, D_BZ_JZWCZYT } = proxy.$dict(
  "D_BZ_JZWHZWXXLB", "D_TB_NHDJ", "D_BZ_JZWWQBWCLXN", "D_BZ_SF", "D_BZ_JZWCZYT");
const emits = defineEmits(["changeSelect"]);
const props = defineProps({
  orgCode: String,
  orglevel: String,
  ywId: String
});
const currentCode = getItem("deptId").ssdwid
const permisssion = reactive({
  manualUpdate: {
    //手动更新
    loading: false,
    disabled: false
  },
  report: {
    //上报
    count: 0,
    disabled: true
  },
  revoke: {
    //撤销
    disabled: true
  }
})
const rowItem = ref({})
const loading = ref(false)
const chooseUserVisible = ref(false)
const sblsVisible = ref(false)
const isShowAll = ref(0)
const currOrgCode = ref(false)
const isReport = ref(true)
const dialogVisible = ref(false)
const isReportResult = ref(false)
const timer = ref(null)
const loadingcksbjg = ref(false)
const IsCksbjg = ref(false)
const currTotal = ref(0)
const pageData = reactive({
  popover: {
    title: "建筑物基本情况",
    content: `
  填表说明：
1. 填报单位：省级单位名称；
2. 企业名称：各省级单位机关或下属单位名称；
3. 统计频次：半年；
4. 提交周期：上半年：1月1日-6月30日；下半年：7月1日-12月25日。
5. 填写范围：省级公司本部及下属单位自有产权的建筑；
6. 若没有符合要求的建筑，可不添加建筑数据；但在周期对应的提交时间范围内仍需处长账号进行“上报确认”
操作。
7. 相同企业名称、相同统计周期下，“建筑物基本信息”中建筑物名称不可重复。
8. 建筑物类别：高层民用建筑、联合工坊、出租场所、闲置场所。
9. 高层民用建筑类别：一类高层建筑、二类高层建筑。
10. 建筑用途：高层民用建筑分为办公楼、科研楼、其他；联合工房分为卷烟生产、物流分拣、打叶复烤、其他。
注：出租建筑、闲置建筑无需填写。
11. 出租用途：餐饮、宾馆、教育培训、综合体、工厂、仓储、其他。
注：仅出租建筑填写，其他类型建筑无需填写。
12. 建造时间：建造竣工时间，以产权证为准，需精确到具体日期。
13. 建筑结构：砖木结构（类型为：高层民用建筑和联合工房无此选项）、砖混结构、钢筋混凝土结构、钢结构、其他。
14. 火灾危险性分类：按照《建筑设计防火规范》分为：甲、乙、丙、丁、戊。
注：高层民用建筑无需填写；联合工坊必须填写；出租建筑、闲置建筑选择填写。
15. 耐火等级：
（1）一级耐火等级：建筑是钢筋混凝土结构或砖墙与钢混凝土结构组成的混合结构；
（2）二级耐火等级：建筑是钢结构屋架、钢筋混凝土柱或砖墙组成的混合结构；
（3）三级耐火等级：建筑物是木屋顶和砖墙组成的砖木结构；
（4）四级耐火等级：建筑物是木屋顶、难燃烧体墙壁组成的可燃结构。
16. 外墙保温材料性能：不燃、难燃、可燃、易燃、无。
  `
  },
  tableData: [],
  tableColumn: [
    { label: '企业名称', prop: 'orgName' },
    { label: '建筑总数', prop: 'total', width: '100' },
    { label: '高层民用建筑总数', prop: 'gcmyjzNum', width: '100' },
    { label: '联合工坊总数', prop: 'lhgfNum', width: '100' },
    { label: '闲置场所总数', prop: 'xzNum', width: '100' },
    { label: '出租场所总数', prop: 'czNum', width: '100' },
    { label: '未上报总数', prop: 'wsbNum', width: '100' },
    { label: '最后一次上报时间', prop: 'updateTime' },
    { label: '当前上报状态', prop: 'status', width: '100' },
    { label: '累计上报次数', prop: 'sbcs', width: '100' },
  ],
  params: {},
  orgCode: [],
  ids: [],
  listQuery: {
    pageNum: 1,
    pageSize: 200,
  },
  reportResultInfo: null,
})

const query = reactive({
  orgCode: currentCode,
  year: "",
  bn: ""
})
const loadingscsb = ref(false)
const loadingbh = ref(false)
const IsSbtn = ref(false)
// 是否是省账号
const isProvinces = computed(() => {
  return filterqx("isaqbm") == "1" && filterqx("isSgs") == "1"
})
// 是否是省账号 并且时省本级
const isProvincesXN = computed(() => {
  return filterqx("isaqbm") == "1" && filterqx("isSgs") == "1" && props.orgCode.includes('XN')
})
// 是否是市账号
const isCity = computed(() => {
  return filterqx("isaqbm") == "1" && filterqx("isgs") == "1"
})
//县级账号
const isTown = computed(() => {
  return filterqx("isaqbm") == "1" && filterqx("isgs") != "1" && filterqx("isSgs") != "1"
})
// 是否是安全部门
const isAqbm = computed(() => {
  return filterqx('isaqbm') == '1'
})
//更新禁用
const setUpdate = row => {
  if (isTown.value) {
    return row.updateStatus === 1 ? false : true
  }
  if (isCity.value) {
    return row.updateStatus === 1 && ["2", "3"].includes(row.status) ? false : true

  }

  if (isProvinces.value) {
    if ((query.orgCode.includes(currentCode) && query.orgCode.includes("XN")) || row.orgCode == currentCode + 'XN') {
      return ["2", "3"].includes(row.status) ? false : true
    } else return true
  }
}
//驳回禁用
const setPeject = status => {
  if (isCity.value) {
    return ["1"].includes(status) ? false : true
  }
  if (isProvinces.value) {
    return ["1", "4", "6"].includes(status) ? false : true
  }
}

const byTime = ref("")
onBeforeUnmount(() => {
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = null;
  }
})

//驳回、撤销
const onRevoke = async (code) => {
  loadingbh.value = true
  let params = JSON.parse(JSON.stringify(query))
  params.orgCode = code ? code : currentCode
  let res = await postApi(params, "/mosty-jcgl/data/BuildSafeStat/revokeData")
  if (res) {
    ElMessage({
      message: `${code === currentCode ? "撤销" : "驳回"}成功`,
      type: "success"
    })
    loadingbh.value = false
    getListData()
  } else {
    getListData()
    loadingbh.value = false
  }
}

// 关闭详情弹窗
const handleClose = () => {
  chooseUserVisible.value = false
  // changeTimeCondition()
  getListData()

}
// 关闭上报历史弹窗
const handleHistoryClose = () => {
  sblsVisible.value = false
}
// 查看省局上报结果
const reportResult = (val) => {
  loadingcksbjg.value = true
  let _data = {
    id: props.ywId,
    ...query
  }
  if (_data.bn) {
    _data.jtsj = _data.bn
    delete _data.bn
  }
  getApi(_data, "/mosty-jcgl/dataCommon/getSbjg").then(res => {
    if (res) {
      pageData.reportResultInfo = res
      if (res.returnCode == '200' && !res.returnHttpCode) {
        isReportResult.value = true
      } else {
        isReportResult.value = false
        if (timer.value) {
          isReportResult.value = false;
          clearInterval(timer.value);
          timer.value = null;
        }
      }
      if (pageData.reportResultInfo && val) {
        dialogVisible.value = true
      }
      if (res.returnCode == "200" && res.returnHttpCode == '500') {
        let res = getApi({ dataId: props.ywId }, "/mosty-jcgl/dataCommon/goBackData")
        if (res) {
          getListData(false)
        }
      }
      // 只针对是否展示查看上报结果
      if (res.returnCode || res.returnHttpCode) {
        IsCksbjg.value = true

      } else {
        IsCksbjg.value = false
      }
    }
    loadingcksbjg.value = false
  }).finally(err => {
    loadingcksbjg.value = false
  })
}
//	建筑物统计数据--判断是否能够进行撤销操作
const getRevoke = async () => {
  let res = await postApi(query, `/mosty-jcgl/data/BuildSafeStat/isRevokedFlag`)
  permisssion.revoke.disabled = res ? false : true
}
// 是否显示上报按钮 是否首次上报
const setPermisssion = async () => {
  const currentDate = new Date()
  const currentYear = currentDate.getFullYear()
  const currentMonth = currentDate.getMonth()
  restPermisssion()
  if (query.year != currentYear || query.bn != Math.floor(currentMonth / 6) + 1) return
  let res = await getApi({ id: props.ywId }, "/mosty-jcgl/dataCommon/sfQggzr")
  if (!res) {
    permisssion.manualUpdate.disabled = true
    return
  }
  getRevoke()
  let count = 0
  pageData.tableData.forEach(item => {
    if (item.sbcs * 1 > 0) permisssion.report.count = item.sbcs * 1
    let onTown = () => {
      if (item.status == "2" || item.status == "3") permisssion.report.disabled = false
    }
    if (isTown.value) {
      onTown()
    }
    if (isCity.value) {
      if (query.orgCode.includes(currentCode) && query.orgCode.includes("XN")) {
        //本级
        onTown()
      } else if (query.orgCode === currentCode) {
        //市
        if (["1", "3", "4"].includes(item.status)) count++
        if (count > 0 && count === pageData.tableData.length) permisssion.report.disabled = false
      } else {
        //其他
      }
    }
    if (isProvinces.value) {
      if (query.orgCode.includes(currentCode) && query.orgCode.includes("XN")) {
        //省级
        onTown()
      } else if (query.orgCode === currentCode) {
        //省
        if (["1", "4", "6"].includes(item.status)) count++
        if (count > 0 && count === pageData.tableData.length) permisssion.report.disabled = false
      } else {
        //其他
      }
    }
  })
}

// 是否可以选择多选
const handleDisable = (row) => {
  return true
}
// 点击详情
const onView = (row) => {
  rowItem.value = row
  currOrgCode.value = row.orgCode
  isReport.value = row.status == "1" ? true : false
  chooseUserVisible.value = true
}
// 点击总的上报历史
const handleHistory = (row) => {
  currOrgCode.value = row ? row.orgCode : pageData?.params.orgcode
  currTotal.value = row.sbcs
  if (currOrgCode.value) {
    sblsVisible.value = true
  }
}

//选择
const changeTimeCondition = val => {
  query.year = val.yearValue
  query.bn = val.halfValue
  if (props.orgCode) getListData()
}

//表格选择
const onTableChange = (val) => {
  isShowAll.value = val.length
  return true
}
const restPermisssion = () => {
  permisssion.manualUpdate.disabled = false
  permisssion.report.disabled = true
  permisssion.revoke.disabled = true
}
// 上报
const onReport = async () => {
  loadingscsb.value = true
  try {
    let res = await postApi(query, "/mosty-jcgl/data/BuildSafeStat/reportData")
    if (res) {
      ElMessage({
        message: "上报成功",
        type: "success"
      })
      reportResult()
      getListData()
      loadingscsb.value = false
    } else {
      ElMessage({
        message: "上报失败",
        type: "warning"
      })
      getListData()
      loadingscsb.value = false
    }
  } catch (error) {
    getListData()
    loadingscsb.value = false
  }

}

//手动更新
const manualUpdate = () => {
  permisssion.manualUpdate.loading = true
  setTimeout(() => {
    ElMessage({
      message: "更新成功",
      type: "success"
    })
    permisssion.manualUpdate.loading = false
  }, 1e3)
  return
  getApi({ orgCode: query.orgCode }, `/mosty-jcgl/data/buildSafe/syncLocal`)
    .then(res => {
      getListData()
      ElMessage({
        message: "更新成功",
        type: "success"
      })
      permisssion.manualUpdate.loading = false
    })
    .finally(() => {
      loading.value = false
      permisssion.manualUpdate.loading = false
    })
}
//列表更新
const rowUpdate = code => {
  loading.value = true
  getApi({ orgCode: code }, `/mosty-jcgl/data/buildSafe/syncLocal`).then(res => {
    getListData()
    ElMessage({
      message: "更新成功！请对建筑物基本信息进行核对，已有内容请确认，无数据的项请按上报要求补充。",
      type: "success"
    })
  }).catch((err) => {
    loading.value = false
  })
}
//列表
const getListData = (val = true) => {
  loading.value = true
  pageData.tableData = []
  postApi(query, '/mosty-jcgl/data/BuildSafeStat/queryBuildSafeStat').then(res => {
    if (res) {
      if (res.length == 1 && res[0].status == '2') {
        permisssion.report.disabled = true
      }
      pageData.tableData = res
      loading.value = false
      setPermisssion()
      if (isProvinces.value) {
        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;
        }
      }
    }

  }).finally(() => {
    loading.value = false
  })
}
const cellStyle = ({ row, column, rowIndex, columnIndex }) => {
  if ([2, 3, 4, 5, 6].includes(columnIndex)) {
    return { background: ' rgb(240,249,235) !important' }
  }
  if (columnIndex === 7) {
    return { background: "var(--el-color-primary-light-8)!important" }
  }
}
watch(
  () => props.orgCode,
  (newVal, oldVal) => {
    if (newVal) {
      query.orgCode = newVal
    }
  },
  { deep: true }
);
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/buildSafe').then(res => {
    if (res) {
      let data = res
      if (data) {
        for (let i = 0; i < data.length; i++) {
          data[i].conHydrantSysFlag = data[i].conHydrantSysFlag == '1' ? '是' : '否';
          data[i].conAlarmSysFlag = data[i].conAlarmSysFlag == '1' ? '是' : '否';
          data[i].conOutfireSysFlag = data[i].conOutfireSysFlag == '1' ? '是' : '否';
        }
      }
      jzwXlsx(data, { D_BZ_JZWHZWXXLB, D_TB_NHDJ, D_BZ_JZWWQBWCLXN, D_BZ_SF, D_BZ_JZWCZYT }, pageData.popover.content)
    } else {
      jzwXlsx([], { D_BZ_JZWHZWXXLB, D_TB_NHDJ, D_BZ_JZWWQBWCLXN, D_BZ_SF, D_BZ_JZWCZYT }, pageData.popover.content)
    }


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

}
defineExpose({ getListData })
</script>

<style lang="scss" scoped>
::v-deep .el-button--link {
  border: none;
  background: none;
  color: var(--el-color-primary);
  padding: 0;
  margin-left: 10px !important;

  &:hover,
  &:focus {
    background: none;
    border: none;
    opacity: 0.9;
  }
}

::v-deep .el-button--link.is-disabled {
  color: #808596;
  border: none;
  background: none;
}

.box {
  width: 100%;
  height: 100%;
}

.pagination {
  padding: 0 !important;
}

.fenye {
  margin: 5px;
}
</style>
