<template>
  <div class="bigBoxs pr10">
    <section v-show='isShowTotal' ref="getHeight">
      <section class="box-sjtj">
        <MOSTY.Assort :title="'变配电和防雷设备设施分类'" style="padding: 0;" />
        <section class="flex">
          <section class="left-tj">
            <Sjtj :info="pageData.countlist" :isShowTip="false" :isShowBottom="false" :width="265" mb="6px" />
          </section>
        </section>
      </section>
    </section>
    <!-- 查询 -->
    <el-divider />
    <MOSTY.Search :searchArr="searchArr" ref="resetFormRef" @submit="onSearch" />
    <el-divider />
    <div class='tabox'>
      <section class="button">
        <el-button @click="addUserHander" v-if='props.obj.saveBtnShow'>
          <el-icon>
            <Plus />
          </el-icon>
          新增
        </el-button>
        <MOSTY.ExportExcel :exportSheets="exportSheets" :exportInfo="exportInfo" @getSheets="getSheets"
          :ditData="{ D_BZ_SYZT, D_TB_JCYWLX }" />
        <el-button @click="handleewm" v-loading="exportLoadings" :disabled="pageData.tableData.length == 0"
          class="ml10">
          <el-icon>
            <Download />
          </el-icon>
          批量导出二维码
        </el-button>
      </section>
      <section :style="{ 'height': totalHeight }">
        <MOSTY.Table :table-columns="pageData.tableColumns" :tableData="pageData.tableData" :tableloading="tableloading"
          :isSelect="true" :isSort="true" :tableHeight="'100%'" @SortChange="SortChange" :actionsW="'280'">
          <template #sign="{ row }">
            <p style=" width: 12px; height: 12px;border-radius: 50%;margin: 0 auto"
              :style="{ 'background-color': row?.sign ? '#33CC00' : '#FC5F76' }"></p>
          </template>
          <template #sblx="{ row }">
            <dict-tag v-if="row.sblx" :options="D_TB_JCYWLX" :value="row.sblx" :tag="false" />
            <span v-else>无</span>
          </template>
          <template #sitename="{ row }">
            <span>{{ row.sitename ? row.sitename : "" }}{{ row.buildingname ? "-" + row.buildingname : "" }}{{
              row.floorname ? "-" + row.floorname : "" }}{{ row.partname ? "-" + row.partname : "" }}</span>
          </template>
          <template #responsibilitypersonname="{ row }">
            <span>{{ row.responsibilitypersonname ? row.responsibilitypersonname.replace(/（null）/g, "") : "" }}</span>
          </template>
          <template #state="{ row }">
            <dict-tag v-if="row.state" :options="D_BZ_SYZT" :value="row.state" :tag="false" />
            <span v-else>无</span>
          </template>
          <template #actions="{ row }">
            <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="复制该条数据并进行数据编辑?"
              @confirm="handlcopy(row)" v-if='props.obj.saveBtnShow'>
              <template #reference>
                <span class="operecopy" size="small">
                  <el-icon>
                    <CopyDocument />
                  </el-icon>
                  复制</span>
              </template>
            </el-popconfirm>
            <span class="operedit" @click="handlexg(row)" v-if='props.obj.saveBtnShow'>
              <el-icon>
                <EditPen />
              </el-icon>编辑</span>
            <el-popconfirm v-if='props.obj.saveBtnShow' confirm-button-text="是" cancel-button-text="否" icon-color="red"
              title="确定要删除?" @confirm="handledelete(row)">
              <template #reference>
                <span class="operdel" size="small">
                  <el-icon>
                    <Delete />
                  </el-icon>
                  删除</span>
              </template>
            </el-popconfirm>
            <span class="operesee" @click="handleSee(row)">
              <el-icon>
                <View />
              </el-icon>查看</span>
          </template>
        </MOSTY.Table>
      </section>
      <div class="fenye">
        <MOSTY.Pages :pageConfiger="pageData.pageConfiger" @changeNo="handleCurrentChange"
          @changeSize="handleSizeChange" />
      </div>
    </div>
  </div>
  <!--变配电和防雷设备设施-->
  <div v-if="addbpdShow" class="dialog-box">
    <Addbpdindex :formData="formData" @changePage="changePage" :type="props.obj.type" @createPage="createPage" />
  </div>
</template>
<script setup>
import * as MOSTY from "@/components/MyComponents/index"
import Addbpdindex from "@/components/dialog/Addbpdindex.vue"
import Sjtj from "@/views/dataReportWork/aqjypx/components/sjtj.vue"
import { reactive, ref, onMounted, getCurrentInstance, watch, nextTick } from "vue"
import { getApi, postApi } from "@/api/tobAcco_api.js"
import { ElMessage } from "element-plus"
import { downloadewm, singleObjectCheck } from "@/utils/tools.js"
import DistributingSheets from "./DistributingSheets.js"
import { useStore } from "vuex"

const { proxy } = getCurrentInstance()
const { D_BZ_SYZT, D_TB_JCYWLX } = proxy.$dict("D_BZ_SYZT", "D_TB_JCYWLX")
const emits = defineEmits(["handleChange", "searchChange"])
const tableloading = ref(false)
const exportLoadings = ref(false)
let resetFormRef = ref()
const sblxlist = ref([])
const addbpdShow = ref(false)
const isShowTotal = ref(false)
const store = useStore()
// 电压配电柜
let tageDistributionCabinet = ['sblx', "name", "trsysj", "sitename", "buildingname", "partname", "installlocation", "voltage", "electricCurrent", "responsibilitydeptname", "responsibilitypersonname"]
// 变压器
let transformer = ['sblx', "name", "type", "capacity", "trsysj", "sitename", "buildingname", "partname", "installlocation", "responsibilitydeptname", "responsibilitypersonname"]
// 发电机
let dynamo = ['sblx', "name", "power", "trsysj", "sitename", "buildingname", "partname", "installlocation", "responsibilitydeptname", "responsibilitypersonname"]
// 配电柜
let distributionBox = ['sblx', "name", "trsysj", "sitename", "buildingname", "partname", "installlocation", "protectionLevel", "responsibilitydeptname", "responsibilitypersonname"]
// 电源
let powerSupply = ['sblx', "name", "apparentPower", "activePower", "trsysj", "sitename", "buildingname", "partname", "installlocation", "responsibilitydeptname", "responsibilitypersonname"]
// 开关锁
let switchLock = ['sblx', "name", "trsysj", "sitename", "buildingname", "partname", "installlocation", "switchCount", "responsibilitydeptname", "responsibilitypersonname"]
// 防雷
let lightningProtection = ['sblx', "name", "trsysj", "sitename", "buildingname", "partname", "installlocation", "responsibilitydeptname", "responsibilitypersonname"]
// 新能源充电装置
let newPowerProtection = ['sblx', "name", "trsysj", "sitename", "buildingname", "partname", "installlocation", "responsibilitydeptname", "responsibilitypersonname"]

const exportInfo = reactive({
  name: "变配电和防雷设备设施",
  loading: false,
  disabled: false
})
const props = defineProps({
  obj: {
    default: null,
    type: Object
  },
  type: {
    default: "",
    type: String
  },
  tableHeight: {
    default: "52vh",
    type: String
  },
  isShowTotal: {
    type: Boolean,
    default: false
  }
})
const total = ref(0)
const formData = ref({
  title: "",
  saveBtnShow: true
})
const totalHeight = ref(null)
const pageData = reactive({
  countlist: [
    { title: "高压配电柜", num: 0, dm: "200601000000", icon: "ccss/icon_01.png" },
    { title: "低压配电柜", num: 0, dm: "200602000000", icon: "ccss/icon_02.png" },
    { title: "变压器", num: 0, dm: "200603000000", icon: "ccss/icon_03.png" },
    { title: "发电机", num: 0, dm: "200604000000", icon: "ccss/icon_04.png" },
    { title: "其他", num: 0, dm: "20060", icon: "ccss/icon_05.png" }
  ],
  listQuery: {
    pageCurrent: 1,
    pageSize: 20,
    type: "1"
  },
  pageConfiger: {
    pageSize: 20,
    pageCurrent: 1,
    total: 0
  },
  tableColumns: [
    {
      title: "标记",
      prop: "sign",
      sortable: false,
      fixed: "left",
      slot: true
    },
    {
      title: "单位",
      prop: "orgname",
      fixed: "left",
      width: "200",
      sortable: true
    },
    {
      title: "变配电和防雷设备设施名称",
      prop: "name",
      width: "200",
      sortable: true
    },
    {
      title: "变配电和防雷设备设施类型",
      prop: "sblx",
      slot: true,
      width: "200",
      sortable: true
    },
    {
      title: "内部编号",
      prop: "nbbh",
      width: "120",
      sortable: true
    },
    {
      title: "所属现场部位",
      prop: "sitename",
      width: "200",
      slot: true,
      sortable: true
    },
    {
      title: "具体位置",
      prop: "installlocation",
      width: "120",
      sortable: true
    },
    {
      title: "品牌型号",
      prop: "brandModel",
      width: "120",
      sortable: true
    },
    {
      title: "投入使用日期",
      prop: "trsysj",
      width: "200",
      sortable: true
    },
    {
      title: "责任部门",
      prop: "responsibilitydeptname",
      sortable: true
    },
    {
      title: "责任人",
      prop: "responsibilitypersonname",
      slot: true,
      sortable: true
    },
    {
      title: "状态",//正常、异常，平铺
      prop: "state",
      slot: true,
      sortable: true
    },
    {
      title: "操作",
      prop: "actions",
      fixed: "right",
      slot: true
    }
  ],
  tableData: []
})
const getHeight = ref(null)
const exportSheets = reactive(DistributingSheets)
const fromObj = ref({ type: "1" })
const searchArr = reactive([
  {
    showType: "input",
    prop: "keywords",
    width: "350px",
    placeholder: "变配电和防雷设备设施名称或内部编号搜索"
  }, {
    showType: "zdlistTree",
    prop: "sblx",
    width: "250px",
    placeholder: "请选择设备设施类型",
    options: sblxlist
  }, {
    showType: "input",
    prop: "siteName",
    width: "250px",
    placeholder: "请输入所属场所部位"
  }
])
watch(() => props.isShowTotal, (val) => {
  isShowTotal.value = props.isShowTotal
  nextTick(() => {
    if (val) {
      totalHeight.value = `calc(100vh - ${379 + getHeight.value.offsetHeight}px)`
    } else {
      totalHeight.value = `calc(100vh - 379px)`
    }

  })
}, {
  deep: true,
  immediate: true
})

function onSearch(obj) {
  pageData.listQuery.keywords = obj.keywords
  pageData.listQuery.sblx = obj.sblx
  pageData.listQuery.siteName = obj.siteName
  pageData.pageConfiger.pageCurrent = 1
  gettablist()
}

onMounted(() => {
  getsblb()
  nextTick(() => {
    if (props.type == "bpdsb") {
      isShowTotal.value = props.isShowTotal
      totalHeight.value = `calc(100vh - ${379 + getHeight.value.offsetHeight}px)`
    } else {
      isShowTotal.value = true
      totalHeight.value = `calc(100vh - 442px)`
    }

  })
  if (props.type == "cs") {
    pageData.listQuery.siteid = props.obj.id
    fromObj.value.siteid = props.obj.id
    getbgsbsscount()
    gettablist()
  } else if (props.type == "jzw") {
    pageData.listQuery.buildingid = props.obj.id
    fromObj.value.buildingid = props.obj.id
    getbgsbsscount()
    gettablist()
  } else if (props.type == "lc") {
    pageData.listQuery.floorid = props.obj.id
    fromObj.value.floorid = props.obj.id
    getbgsbsscount()
    gettablist()
  } else if (props.type == "bw") {
    pageData.listQuery.partid = props.obj.id
    fromObj.value.partid = props.obj.id
    getbgsbsscount()
    gettablist()
  } else if (props.type == "bpdsb") {
    watch(
      () => props.obj.orgid,
      (newValue) => {
        if (newValue) {
          pageData.listQuery.orgcode = newValue
          fromObj.value.orgcode = newValue
          fromObj.value.type = "0"
          pageData.listQuery.type = "0"
          getbgsbsscount()
          gettablist()
        }

      },
      { deep: true, immediate: true }
    )
  }


})

//获取设备设施类型
function getsblb() {
  getApi({ zdbh: "D_TB_JCYWLX", dm: "2006", level: 2 }, "/mosty-base/sysDict/getJcyelxDictTree").then(res => {
    sblxlist.value = res[0].itemList
  })
}

function handleRest() {
  pageData.listQuery.sblx = ""
  pageData.listQuery.keywords = ""
  pageData.listQuery.siteName = ""
  pageData.listQuery.pageCurrent = 1
  pageData.pageConfiger.pageCurrent = 1
  gettablist()
}

//统计各类（场、建、楼、部）或单位下，变配电和防雷设备设施
function getbgsbsscount() {
  postApi(fromObj.value, "/mosty-jcgl/sbglBpdsb/countTbSbglBpdsb").then(res => {
    if (res.length > 0) {
      for (let i = 0; i < pageData.countlist.length; i++) {
        const el = pageData.countlist[i]
        el.num = 0
        for (let j = 0; j < res.length; j++) {
          const li = res[j]
          if (li.dm == el.dm) {
            el.num = li.count
          }
        }
      }
    }
  })
}

//排序
function SortChange(prop, order) {
  if (prop == "orgname") {
    pageData.listQuery.sortField = "orgcode"
  } else {
    pageData.listQuery.sortField = prop
  }

  pageData.listQuery.sortOrder = order
  gettablist()
}

//变配电分页查询功能
function gettablist() {
  tableloading.value = true
  let type_map = new Map([
    ["200601000000", tageDistributionCabinet],
    ["200602000000", tageDistributionCabinet],
    ["200603000000", transformer],
    ["200604000000", dynamo],
    ["200605000000", distributionBox],
    ["200606000000", powerSupply],
    ["200607000000", switchLock],
    ["200608000000", lightningProtection],
    ["200609000000", lightningProtection],
    [null, newPowerProtection]
  ])
  let table_data = []
  postApi(pageData.listQuery, "/mosty-jcgl/sbglBpdsb/queryTbSbglBpdsb").then(async (res) => {
    if (res) {
      tableloading.value = false
      for (let i = 0; i < res.records.length; i++) {
        table_data.push(await singleObjectCheck(res.records[i], type_map.get(res.records[i].sblx)))
      }
      pageData.tableData = table_data
      pageData.pageConfiger.total = res.total
    }
  })
}

//新增
function addUserHander() {
  formData.value.type = props.type
  formData.value = {}
  pageData.listQuery.sblx = null
  if (props.type == "cs") {
    formData.value.siteid = props.obj.id
    formData.value.sitename = props.obj.placename
  } else if (props.type == "jzw") {
    if (props.obj.type == "cq") {
      formData.value.publicarea = "1"
    }
    formData.value.siteid = props.obj.siteid
    formData.value.sitename = props.obj.sitename
    formData.value.buildingid = props.obj.id
    formData.value.buildingname = props.obj.buildingname
    formData.value.publicarea = props.obj.publicarea
  } else if (props.type == "lc") {
    formData.value.siteid = props.obj.siteid
    formData.value.sitename = props.obj.sitename
    formData.value.buildingid = props.obj.buildingid
    formData.value.buildingname = props.obj.buildingname
    formData.value.floorid = props.obj.id
    formData.value.floorname = props.obj.floorname
  } else if (props.type == "bw") {
    if (props.obj.type == "cq") {
      formData.value.sfcq = "1"
      formData.value.publicarea = "1"
    } else {
      if (props.obj.sfcq && props.obj.sfcq == "1") {
        formData.value.sfcq = "1"
        formData.value.publicarea = "1"
      } else {
        formData.value.sfcq = "2"
        formData.value.publicarea = "2"
      }
    }
    formData.value.siteid = props.obj.siteid
    formData.value.sitename = props.obj.sitename
    formData.value.buildingid = props.obj.buildingid
    formData.value.buildingname = props.obj.buildingname
    formData.value.floorid = props.obj.floorid
    formData.value.floorname = props.obj.floorname
    formData.value.partid = props.obj.id
    formData.value.partname = props.obj.partname
    formData.value.qtmc = props.obj.qtmc ? props.obj.qtmc : null


  }
  formData.value.title = "变配电和防雷设备设施新增"
  formData.value.saveBtnShow = true
  addbpdShow.value = true
  tableloading.value = false
}
//复制
function handlcopy(row) {
  formData.value.type = props.type
  formData.value.id = row.id
  formData.value.qtmc = props.obj.qtmc ? props.obj.qtmc : null
  formData.value.title = "变配电和防雷设备设施复制"
  formData.value.xgfMc = row.xgfMc
  formData.value.xgfId = row.xgfId
  formData.value.xgfRyMc = row.xgfRyMc
  formData.value.xgfRyId = row.xgfRyId
  formData.value.saveBtnShow = true
  addbpdShow.value = true
}
//修改
function handlexg(row) {
  formData.value.type = props.type
  formData.value.id = row.id
  formData.value.qtmc = props.obj.qtmc ? props.obj.qtmc : null
  formData.value.title = "变配电和防雷设备设施修改"
  formData.value.xgfMc = row.xgfMc
  formData.value.xgfId = row.xgfId
  formData.value.xgfRyMc = row.xgfRyMc
  formData.value.xgfRyId = row.xgfRyId
  formData.value.saveBtnShow = true
  addbpdShow.value = true
}

//详情
function handleSee(row) {
  formData.value.type = props.type
  formData.value.id = row.id
  formData.value.qtmc = props.obj.qtmc ? props.obj.qtmc : null
  formData.value.title = "变配电和防雷设备设施详情"
  formData.value.saveBtnShow = false
  addbpdShow.value = true
}

//注销
function handledelete(row) {
  getApi({ id: row.id }, `/mosty-jcgl/sbglBpdsb/deleteTbSbglBpdsbOne`).then(res => {
    ElMessage.success("删除成功")
    emits("searchChange", "bpdsb")
    getbgsbsscount()
    gettablist()
  })
}

//关闭
const changePage = async (obj) => {
  // formData.value = {}
  addbpdShow.value = false
  // pageData.listQuery.sblx = null
  getbgsbsscount()
  emits("searchChange", "bpdsb")
  gettablist()
}

const createPage = (obj) => {
  formData.value = {}
  addbpdShow.value = false
  pageData.listQuery.sblx = null
  pageData.listQuery.keywords = null
  pageData.listQuery.siteName = null
  resetFormRef.value.reset_form()
  pageData.listQuery.pageCurrent = 1
  emits("searchChange", 'scsb');
  gettablist()
}

//页码发生变化
const handleCurrentChange = (val) => {
  pageData.listQuery.pageCurrent = val
  pageData.pageConfiger.pageCurrent = val
  gettablist()
}
//查询条数发生变化
const handleSizeChange = (val) => {
  pageData.listQuery.pageSize = val
  pageData.pageConfiger.pageSize = val
  gettablist()
}
const getTreeItem = (treeData, id) => {
  for (let i in treeData) {
    if (treeData[i].dm === id) {
      return treeData[i]
    }
    if (treeData[i].itemList && treeData[i].itemList.length) {
      var res = getTreeItem(treeData[i].itemList, id)
      if (res) return res
    }
  }
}
// 导出
const getSheets = go => {
  let obj = { ...pageData.listQuery }
  obj.pageSize = 1e5 //取1W
  exportInfo.loading = true
  if (pageData.listQuery.sblx) exportInfo.name += "-" + getTreeItem(sblxlist.value, pageData.listQuery.sblx).zdmc
  exportSheets.forEach(item => {
    if (!item.title.includes(store.state.user.currentDeptName)) item.title = store.state.user.currentDeptName + item.title
    item.data = []
  })

  getApi({ ...obj }, "/mosty-jcgl/sbglBpdsb/exportData").then(res => {
    if (!res) {
      exportInfo.loading = false
      return
    } else {
      res.forEach(list => {
        list.sitename = `${list.sitename ? list.sitename : ""}${list.buildingname ? "-" + list.buildingname : ""}${list.floorname ? "-" + list.floorname : ""}${list.partname ? "-" + list.partname : ""}`
        if (!getTreeItem(sblxlist.value, list.sblx)) return
        let name = getTreeItem(sblxlist.value, list.sblx).zdmc
        exportSheets.forEach(item => {
          if (item.name === name) item.data.push(list)
        })
      })

      setTimeout(() => {
        exportInfo.loading = false
        go()
      }, 3e2)
    }
  })
}

//批量导出二维码
function handleewm() {
  let url = "/mosty-api/mosty-jcgl/sbglBpdsb/exportQrcodeZip?orgcode=" + pageData.listQuery.orgcode +
    (pageData.listQuery.keywords ? "&keywords" + pageData.listQuery.keywords : "") +
    (pageData.listQuery.siteName ? "&siteName" + pageData.listQuery.siteName : "") +
    (pageData.listQuery.sblx ? "&sblx" + pageData.listQuery.sblx : "")
  downloadewm(url, "变配电和防雷设备设施二维码")
}
</script>

<style lang="scss" scoped>
.button {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 12px;
}
</style>
