<template>
  <div class="bigBox">
    <section v-show='props.isShowTotal' ref="getHeight">
      <TzsbTotal :obj="fromObj" ref="aqqcTotal" :key="keys" />
    </section>
    <!-- 查询 -->
    <el-divider />
    <div class='tabox'>
      <section class="query-flex" ref="queryHeight">
        <section class="query-section">
          <section class="flex">
            <el-input placeholder="请输入特种设备名称或内部编号" v-model="pageData.listQuery.keywords" clearable
                      style='width:250px'></el-input>
            <MOSTY.DictTree class="ml12 mr12" v-model="pageData.listQuery.sblx" :zdlist="sbsslist"
                            :placeholder='"请选择设备类型"' :type='"array"' style="width: 250px;"
                            @onChange='cahngesblx' />
            <MOSTY.DictRidioAndSelect style='width:250px' :dictData="D_BZ_SYZT" v-model="pageData.listQuery.state"
                                      selectType="select" @getselect="handleSelectStatus" />
          </section>
        </section>
        <div class="query-btn">
          <div class="toggle" :class="{ active: isOpen }" @click="handleClickOpen" v-if="false">
            <span>{{ isOpen ? "收起" : "展开" }}筛选</span>
            <el-icon>
              <DArrowLeft />
            </el-icon>
          </div>
          <el-button @click="Searchdata" class="ml6">
            <el-icon>
              <Search />
            </el-icon>
            查询
          </el-button>
          <el-button @click="handleRest">
            <el-icon>
              <Refresh />
            </el-icon>
            重置
          </el-button>
        </div>
      </section>
      <el-divider />
      <section class="button">
        <el-button @click="addUserHander" v-if='isAuth && 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">
          <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 #flx="{ row }">
            <span v-if="row.flx == '1'">电梯</span>
            <span v-else-if="row.flx == '2'">锅炉</span>
            <span v-else-if="row.flx == '3'">压力容器</span>
            <span v-else-if="row.flx == '4'">压力管道</span>
            <span v-else-if="row.flx == '5'">场内机动车</span>
            <span v-else-if="row.flx == '6'">起重机械</span>
            <span v-else-if="row.flx == '7'">工业气瓶</span>
          </template>
          <template #time="{ row }">
            {{ row.time ? row.time + "月" : "" }}
          </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"
                      :color="row.state == '01' ? 'green' : 'red'" />
            <span v-else>无</span>
          </template>
          <template #actions="{ row }">
            <span class="operedit" @click="setFn(row)" v-if='isAuth && props.obj.saveBtnShow'>
              <el-icon>
                <EditPen />
              </el-icon>
              编辑
            </span>
            <el-popconfirm v-if='isAuth && 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="showdialogtzsb" class="dialog-box">
    <tzsbDialog :formData="formData" @saveSuccess="saveSuccess" @createPage="createPage"  :type="props.obj.type" />
  </div>
</template>
<script setup>
import * as MOSTY from "@/components/MyComponents/index"
import tzsbDialog from "@/components/dialog/tzsbDialog.vue"
import { reactive, ref, onMounted, watch, nextTick, getCurrentInstance } from "vue"
import { ElMessage } from "element-plus"
import { getApi, postApi } from "@/api/tobAcco_api.js"
import TzsbTotal from "@/views/yxkzgl/sbss/tzsb/TzsbTotal.vue"
import EquipmentSheets from "./EquipmentSheets.js"
import { getAuth, downloadewm, singleObjectCheck } from "@/utils/tools.js"

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 showdialogtzsb = ref(false)
const exportLoadings = ref(false)
const total = ref(0)
const keys = ref(0)
// 电梯
let listOfSpecialEquipmentElevators = ["sitename", "buildingname", "sblx", "name", "sccj",
   "ccrq", "azsj", "trsysj", "certificateNumber", "registrationOrgan", "location", "userorgname",
  "responsibilitydeptname", "responsibilitypersonname"]
// 过滤
let boiler = ["sitename", "buildingname", "sblx", "name", "evaporation", "sccj", "ccbh",
  "ccrq", "azsj", "trsysj", "certificateNumber", "registrationOrgan", "location", "userorgname",
  "responsibilitydeptname", "responsibilitypersonname"]
// 压力容器
let pressureVessel = ["sitename", "buildingname", "floorname", "partname", "sblx", "mediumName",
  "saveBtnShow", "sccj", "ccrq", "designPressure", "testPressure", "mawp", "vesselShellDesignTemperature",
  "vesselVolume", "mainMaterial", "certificateNumber", "registrationOrgan", "location", "userorgname",
  "responsibilitydeptname", "responsibilitypersonname"]
// 压力管道
let pressurePiping = ["sitename", "buildingname", "floorname", "partname", "name", "jsdw", "workingmedium",
  "gdcd", "sblx", "diameter", "sjyl", "sggzyl", "sjwd", "wallThickness", "azsj", "certificateNumber", "registrationOrgan",
  "location", "userorgname", "responsibilitydeptname", "responsibilitypersonname"]
// 机动车
let motorVehicles = ["sitename", "buildingname", "floorname", "partname", "sblx", "name", "clbh", "clyxsd",
  "cledhz", "cldlfs", "zzrq", "ccrq", "certificateNumber", "registrationOrgan", "location", "userorgname", "responsibilitydeptname", "responsibilitypersonname"]
// 起重机械
let hoistingMachinery = ["sitename", "buildingname", "floorname", "partname", "sblx", "liftingCapacity", "zzny",
  "zzdw", "azsj", "certificateNumber", "registrationOrgan", "location", "userorgname",
  "responsibilitydeptname", "responsibilitypersonname"]
// 工业气瓶
let industrialGasCylinder = ["sitename", "buildingname", "floorname", "partname", "name", "sblx", "color",
  "certificateNumber", "registrationOrgan", "location", "userorgname",
  "responsibilitydeptname", "responsibilitypersonname"]
const fromObj = ref({
  type: "1"
})
const formData = ref({
  title: ""
})
const props = defineProps({
  obj: {
    default: null,
    type: Object
  },
  type: {
    default: "",
    type: String
  },
  tableHeight: {
    default: "40vh",
    type: String
  },
  isShowTotal: {
    type: Boolean,
    default: false
  }
})

// 重构后的变量方法 start
const getHeight = ref(null)
const queryHeight = ref(null)
const totalHeight = ref(null)
const aqqcTotal = ref(null)
const isOpen = ref(false)
const sbsslist = ref([])
const isAuth = ref(false)
const exportInfo = reactive({
  name: "特种设备设施",
  loading: false,
  disabled: true
})
const exportSheets = reactive(EquipmentSheets)
const pageData = reactive({
  listQuery: {
    type: "1",
    keywords: "",
    state: "",
    sblx: ""
  },
  pageConfiger: {
    pageSize: 10,
    pageCurrent: 1,
    total: 0
  },
  tableColumns: [
    // {
    //   title: "标记",
    //   prop: "sign",
    //   sortable: false,
    //   slot: true
    // },
    {
      title: "特种设备名称",
      prop: "name"
    },
    {
      title: "特种设备类型",
      prop: "flx",
      slot: true
    },
    {
      title: "内部编号",
      prop: "nbbh"
    },
    {
      title: "上一次检测日期",
      prop: "sycjcrq"
    },
    {
      title: "下一次检测日期",
      prop: "xycjcrq"
    },
    {
      title: "所属场所部位",
      prop: "sitename",
      slot: true
    },
    {
      title: "具体位置",
      prop: "location"
    },
    {
      title: "责任部门",
      prop: "responsibilitydeptname"
    },
    {
      title: "责任人",
      prop: "responsibilitypersonname",
      slot: true
    },
    {
      title: "状态",
      prop: "state",
      slot: true
    },
    {
      title: "操作",
      prop: "actions",
      slot: true
    }
  ],
  tableData: []
})
onMounted(() => {
  getsblb()
  isAuthorize()
  nextTick(() => {
    totalHeight.value = `calc(100vh - ${338 + getHeight.value.offsetHeight + queryHeight.value.offsetHeight}px)`
  })
  //判断是重点部位还是非重点部位
  if (props.type == "cs") {
    pageData.listQuery.siteid = props.obj.id
    fromObj.value.siteid = props.obj.id
    gettablist()
  } else if (props.type == "jzw") {
    pageData.listQuery.buildingid = props.obj.id
    fromObj.value.buildingid = props.obj.id
    gettablist()
  } else if (props.type == "lc") {
    pageData.listQuery.floorid = props.obj.id
    fromObj.value.floorid = props.obj.id
    gettablist()
  } else if (props.type == "bw") {
    pageData.listQuery.partid = props.obj.id
    fromObj.value.partid = props.obj.id
    gettablist()
  } else if (props.type == "tzsb") {
    pageData.pageConfiger.pageSize = 20
    watch(
      () => props.obj.orgid,
      (newValue) => {
        if (newValue) {
          pageData.listQuery.orgcode = newValue
          fromObj.value.orgcode = newValue
          fromObj.value.type = "0"
          pageData.listQuery.type = "0"
          gettablist()
        }

      },
      { deep: true, immediate: true }
    )
  }
})
const gettablist = () => {
  tableloading.value = true
  exportInfo.disabled = true
  postApi({ ...pageData.pageConfiger, ...pageData.listQuery }, "/mosty-jcgl/sbglTzsb/queryTbSbglTzsb").then(async (res) => {
    if (res) {
      if (res.records.length) {
        exportInfo.disabled = false
      }
      keys.value++
      let table_data = []
      let type_map = new Map(
        [
          ["1", listOfSpecialEquipmentElevators],
          ["2", boiler],
          ["3", pressureVessel],
          ["4", pressurePiping],
          ["5", motorVehicles],
          ["6", hoistingMachinery],
          ["7", industrialGasCylinder]
        ]
      )
      for (let i = 0; i < res.records.length; i++) {
        table_data.push(await singleObjectCheck(res.records[i], type_map.get(res.records[i].flx)))
      }
      pageData.tableData = table_data
      console.log("页面数据")
      console.log(pageData.tableData)
      pageData.pageConfiger.total = res.total
    }
  }).finally(() => {
    tableloading.value = false
  })
}
watch(() => props.isShowTotal, (val) => {
  nextTick(() => {
    if (val) {
      totalHeight.value = `calc(100vh - ${338 + queryHeight.value.offsetHeight + getHeight.value.offsetHeight}px)`
      return
    }
    totalHeight.value = `calc(100vh - 370px)`
  })
}, {
  deep: true,
  immediate: true
})
const handleRest = () => {
  pageData.listQuery.keywords = ""
  pageData.listQuery.state = ""
  pageData.listQuery.sblx = ""
  pageData.pageConfiger.pageCurrent = 1
  gettablist()
}
const handleClickOpen = () => {
  isOpen.value = !isOpen.value
  nextTick(() => {
    if (isOpen.value) {
      totalHeight.value = `calc(100vh - ${338 + getHeight.value.offsetHeight + queryHeight.value.offsetHeight}px)`
      return
    }
    totalHeight.value = `calc(100vh - 370px)`
  })
}
const getSheets = go => {
  pageData.listQuery.pageSize = 1e5 //取1W
  exportInfo.loading = true
  postApi({ ...pageData.pageConfiger, ...pageData.listQuery }, "/mosty-jcgl/sbglTzsb/exportTbSbglTzsb").then(res => {
    if (!res) {
      exportInfo.loading = false
      return
    }
    let _arrList = []
    res.forEach(list => {
      for (let i in list) {
        _arrList.push(...list[i])
      }

    })
    _arrList.forEach(list => {
      if (list.floorname) {
        list.sitename = list.sitename + "-" + list.buildingname + "-" + list.floorname + "-" + list.partname
      } else {
        if (list.sitename && list.buildingname && list.partname) {
          list.sitename = list.sitename + "-" + list.buildingname + "-" + list.partname
        } else {
          list.sitename = ""
        }
      }
      if (getTreeItem(sbsslist.value, list.sblx)?.dm) {
        exportSheets.forEach(item => {
          if (item.code == getTreeItem(sbsslist.value, list.sblx)?.dm) item.data.push(list)
        })
      }
    })
    setTimeout(() => {
      exportInfo.loading = false
      go()
    }, 3e2)
  })
}
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 cahngesblx = (val) => {
  pageData.listQuery.sblx = val ? val.dm : ""
  gettablist()
}
// 选择状态
const handleSelectStatus = (val) => {
  pageData.listQuery.state = val.value
  gettablist()
}
// 是否可以操作
const isAuthorize = async () => {
  isAuth.value = await getAuth()
}
// 重构后的变量方法 end
//获取设备设施类型
const getsblb = () => {
  getApi({ zdbh: "D_TB_JCYWLX", dm: "2005", level: 5 }, "/mosty-base/sysDict/getJcyelxDictTree").then(res => {
    sbsslist.value = res[0].itemList
  })
}
// 2005


//新增
function addUserHander() {
  formData.value.type = props.type
  formData.value = {}
  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
  showdialogtzsb.value = true
}

//编辑
function setFn(row) {
  formData.value.type = props.type
  formData.value.partid = props.obj.id
  formData.value.id = row.ywid
  formData.value.flx = row.flx
  formData.value.qtmc = props.obj.qtmc ? props.obj.qtmc : null
  formData.value.xgfMc = row.xgfMc
  formData.value.xgfId = row.xgfId
  formData.value.xgfRyMc = row.xgfRyMc
  formData.value.xgfRyId = row.xgfRyId
  formData.value.title = "特种设备修改"
  formData.value.saveBtnShow = true
  showdialogtzsb.value = true
}

//查看
function handleSee(row) {
  formData.value.partid = props.obj.id
  formData.value.id = row.ywid
  formData.value.flx = row.flx
  formData.value.qtmc = props.obj.qtmc ? props.obj.qtmc : null
  formData.value.title = "特种设备详情"
  formData.value.saveBtnShow = false
  showdialogtzsb.value = true
}

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

/**
 * 关闭
 * @param val
 * @param obj
 * @returns {Promise<void>}
 */
const saveSuccess = async (val, obj) => {
  // formData.value = {}
  showdialogtzsb.value = false
  emits("searchChange", "tzsb")
  gettablist()
}

/**
 * 创建成功后初始化
 * @param obj
 */
const createPage = (obj) => {
  formData.value = {}
  showdialogtzsb.value = false
  pageData.listQuery.keywords = null
  pageData.listQuery.sbsslist = null
  pageData.listQuery.state = null
  pageData.listQuery.pageCurrent = 1
  emits("searchChange", "aqbs")
  gettablist()
}

//查询
function Searchdata() {
  gettablist()
}

//页码发生变化
const handleCurrentChange = (val) => {
  pageData.pageConfiger.pageCurrent = val
  gettablist()
}
//查询条数发生变化
const handleSizeChange = (val) => {
  pageData.pageConfiger.pageSize = val
  gettablist()
}

//批量导出二维码
function handleewm() {
  let url = "/mosty-api/mosty-jcgl/sbglTzsb/exportQrcodeZip?orgcode=" + pageData.listQuery.orgcode +
    (pageData.listQuery.keywords ? "&keywords" + pageData.listQuery.keywords : "") +
    (pageData.listQuery.state ? "&state" + pageData.listQuery.state : "") +
    (pageData.listQuery.sblx ? "&sblx" + pageData.listQuery.sblx : "")
  downloadewm(url, "特种设备设施二维码")

}
</script>

<style lang="scss" scoped>
::v-deep .el-divider--horizontal {
  margin: 12px 0;
}

.query-flex {
  display: flex;
  justify-content: space-between;

  .query-section {
    width: 68%;
  }

  .query-btn {
    width: 240px;
    display: flex;
    justify-content: flex-end;

    .toggle {
      height: 32px;
      cursor: pointer;
      display: flex;
      align-items: center;
      color: #0f3916;

      .el-icon {
        transform: rotate(90deg);
        transition: all 0.25s ease;
      }

      &.active {
        .el-icon {
          transform: rotate(-90deg);
        }
      }
    }
  }
}

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