<template>
  <div class="bigBox apparatus">
    <section v-show='props.isShowTotal' ref="getHeight">
      <AqqcTotal :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" v-model="pageData.listQuery.sblx" :zdlist="sbsslist"
                            :placeholder='"请选择器材类型"'
                            :type='"array"' style="width: 250px;" />
            <el-input class="ml12" placeholder="请输入责任人名称" v-model="pageData.listQuery.responsibilitypersonname"
                      clearable style='width:250px'></el-input>
          </section>
          <section v-if="isOpen" class="mt12">
            <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">
            <span>{{ isOpen ? "收起" : "展开" }}筛选</span>
            <el-icon>
              <DArrowLeft />
            </el-icon>
          </div>
          <el-button @click="gettablist" 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">
        <!--  isAuth-->
        <el-button @click="addUserHander" v-if='props.obj.saveBtnShow'>
          <el-icon>
            <Plus />
          </el-icon>
          新增
        </el-button>
        <el-button @click="handleExport('')" v-loading="exportLoading" :disabled="pageData.tableData.length == 0">
          <el-icon>
            <Download />
          </el-icon>
          导出安全器材
        </el-button>
        <el-button @click="handleExport('200201010000')" v-loading="exportLoading"
                   :disabled="pageData.tableData.length == 0">
          <el-icon>
            <Download />
          </el-icon>
          导出灭火器
        </el-button>
        <el-button @click="handleewm" v-loading="exportLoadings" :disabled="pageData.tableData.length == 0">
          <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" @handleSelecTable="handleSelecTable">
          <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 :options="D_TB_JCYWLX" :value="row.sblx" :tag="false" />
          </template>
          <template #partname="{ row }">
            <span>{{ row.sitename }}-{{ row.buildingname }}-{{ row.floorname }}-{{ 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 }">
            <!-- isAuth && -->
            <span class="operedit" @click="handlexg(row)" v-if='props.obj.saveBtnShow'>
              <el-icon>
                <EditPen />
              </el-icon>编辑</span>
            <!-- isAuth && -->
            <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="aqqcShow" class="dialog-box">
    <Addaqqcindex :formData="formData" @changePage="changePage" :type="props.obj.type" @createPage="createPage" />
  </div>

</template>

<script setup>
import * as MOSTY from "@/components/MyComponents/index"
import Addaqqcindex from "@/components/dialog/Addaqqcindex.vue"
import { reactive, ref, onMounted, getCurrentInstance, watch, computed, nextTick } from "vue"
import { getApi, postApi } from "@/api/tobAcco_api.js"
import { ElMessage, ElLoading } from "element-plus"
import { exportXlsx } from "@/excel/Export2Excel.js"
import { getItem } from "@/utils/storage"
import AqqcTotal from "@/views/yxkzgl/sbss/aqqc/AqqcTotal.vue"
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 props = defineProps({
  obj: {
    default: null,
    type: Object
  },
  type: {
    default: "",
    type: String
  },
  tableHeight: {
    default: "40vh",
    type: String
  },
  isShowTotal: {
    type: Boolean,
    default: false
  }
})
const tableloading = ref(false)
const exportLoadings = ref(false)
const aqqcShow = ref(false)
const keys = ref(1)
const isShowaf = ref(true)
const isAuth = ref(true)
const isOpen = ref(false)
const getHeight = ref(null)
const queryHeight = ref(null)
const aqqcTotal = ref(null)
const formData = ref({
  title: "",
  saveBtnShow: true
})
const sbsslist = ref([])
const exportLoading = ref(false)
let safetyIdentificationMark = ["sblx", "name", "time", "sitename", 'buildingname', "partname", "location",]
let fireExtinguisherLabel = [...safetyIdentificationMark, 'azlx']
const pageData = reactive({
  listQuery: {
    keywords: "",
    type: "1",
    responsibilitypersonname: "",
    sblx: "",
    state: ""
  },
  pageConfiger: {
    pageSize: 10,
    pageCurrent: 1,
    total: 0
  },
  tableColumns: [
    {
      title: "标记",
      prop: "sign",
      sortable: false,
      slot: true
    },
    {
      title: "单位",
      prop: "orgname"
    },
    {
      title: "安全器材名称",
      prop: "name"
    },
    {
      title: "安全器材类型",
      prop: "sblx",
      slot: true
    },
    {
      title: "内部编号",
      prop: "nbbh"
    },

    {
      title: "所属场所部位",
      prop: "partname",
      slot: true
    },
    {
      title: "具体位置",
      prop: "location"
    },
    {
      title: "责任人",
      prop: "responsibilitypersonname",
      slot: true
    }, {
      title: "状态",
      prop: "state",
      slot: true
    },
    {
      title: "操作",
      prop: "actions",
      slot: true
    }
  ],
  tableData: []
})
const fromObj = ref({ type: "1" })
const totalHeight = ref(null)
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 handleSelectStatus = (val) => {
  pageData.listQuery.state = val.value
  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)`
  })
}
onMounted(() => {
  getaqqclb()
  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 == "aqqc") {
    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 getaqqclb = () => {
  getApi({ dm: "2002", zdbh: "D_TB_JCYWLX", level: 2 }, "/mosty-base/sysDict/getJcyelxDictTree").then(res => {
    sbsslist.value = res[0].itemList
  })
}
// 是否可以操作
const isAuthorize = async () => {
  isAuth.value = await getAuth()
}
// 导出
const handleExport = (code) => {
  const loading = ElLoading.service({
    lock: true,
    text: "导出中...",
    background: "rgba(0, 0, 0, 0.7)"
  })
  let _data = {
    ...pageData.listQuery,
    ...pageData.pageConfiger
  }
  if (code == "200201010000") {
    _data.sblx = code
  } else {
    delete _data.sblx
  }
  delete _data.pageCurrent
  delete _data.pageSize
  delete _data.keywords
  delete _data.responsibilitypersonname
  exportLoading.value = true
  let _url = code == "200201010000" ? "sbglAqqc/exportMhqExcel" : "sbglAqqc/exportExcel"
  postApi(_data, `/mosty-jcgl/${_url}`).then(async res => {
    let title = {
      name: "安全器材名称", //B
      nbbh: "内部编号",//C
      sitename: "所属场所部位",//D
      location: "所属位置",//E
      time: "生产日期",//F
      responsibilitydeptname: "责任部门",//G
      responsibilitypersonname: "责任人",//H
      state: "状态"//I
    }
    if (code == "200201010000") {
      title = {
        name: "安全器材名称", //B
        nbbh: "内部编号",//C
        sitename: "所属场所部位",//D
        location: "所属位置",//E
        time: "生产日期",//F
        responsibilitydeptname: "责任部门",//G
        responsibilitypersonname: "责任人",//H
        state: "状态",//I
        mhqName: "灭火器名称及编号",
        mhqType: "灭火器型号",
        mhqSpecification: "规格",
        mhqTime: "灭火器生产日期",
        mhqManufacturer: "灭火器生产厂家",
        mhqState: "灭火器状态"
      }
    }
    let _list = res
    if (_list) {
      for (let i = 0; i < _list.length; i++) {
        _list[i].state = proxy.$getDictVal(_list[i].state, D_BZ_SYZT)
        _list[i].responsibilitypersonname = _list[i].responsibilitypersonname ? _list[i].responsibilitypersonname.replace(/（null）/g, "") : ""
        // if (_list[i].flx == '3') {
        //   let count = await getmhqx(_list[i].ywid)
        //   _list[i].name = `${_list[i].name}(灭火器${count}具)`
        // }
        if (_list[i].floorname) {
          _list[i].sitename = _list[i].sitename + "-" + _list[i].buildingname + "-" + _list[i].floorname + "-" + _list[i].partname
        } else {
          _list[i].sitename = _list[i].sitename + "-" + _list[i].buildingname + "-" + _list[i].partname
        }
        if (_list[i].mhqName) {
          _list[i].mhqName = _list[i].mhqName
        } else if (_list[i].mhqNbbh) {
          _list[i].mhqName = _list[i].mhqNbbh
        } else if (_list[i].mhqName && _list[i].mhqNbbh) {
          _list[i].mhqName = _list[i].mhqName + "-" + _list[i].mhqNbbh
        }
        if (_list[i].mhqSpecification) {
          _list[i].mhqSpecification = (_list[i].mhqSblx == "200201010100" || _list[i].mhqSblx == "200201010200") ? _list[i].mhqSpecification + "KG" : _list[i].mhqSpecification + "L"
        }
        if (_list[i].mhqState) {
          _list[i].mhqState = proxy.$getDictVal(_list[i].mhqState, D_BZ_SYZT)
        }
      }
      let tablename = "安全器材台账.xlsx"
      let _m = []
      if (code) {
        // 处理合并逻辑 start
        let _index = _list.reduce((acc, cur, index, arr) => {
          if (arr.findIndex(v => v.id == cur.id) !== index) {
            acc.push({ index, nbbh: cur.nbbh })
          }
          return acc
        }, [])
        const aa = await res.map(item => item.nbbh)
        const countMap = await aa.reduce((acc, item) => {
          acc[item] = (acc[item] || 0) + 1
          return acc
        }, {})

        if (Array.isArray(_index)) {
          for (let item in countMap) {
            for (let i = 0; i < _index.length; i++) {
              if (item == _index[i].nbbh && countMap[item] > 1) {
                const countIndex = _index[i].index
                _m.push(`B${Number(countIndex + 3)}:B${countIndex + countMap[item] + 2}`)
                _m.push(`C${Number(countIndex + 3)}:C${countIndex + countMap[item] + 2}`)
                _m.push(`D${Number(countIndex + 3)}:D${countIndex + countMap[item] + 2}`)
                _m.push(`E${Number(countIndex + 3)}:E${countIndex + countMap[item] + 2}`)
                _m.push(`F${Number(countIndex + 3)}:F${countIndex + countMap[item] + 2}`)
                _m.push(`G${Number(countIndex + 3)}:G${countIndex + countMap[item] + 2}`)
                _m.push(`H${Number(countIndex + 3)}:H${countIndex + countMap[item] + 2}`)
                _m.push(`I${Number(countIndex + 3)}:I${countIndex + countMap[item] + 2}`)
                break
              }
            }
          }
          // _m = ["B5:B6", "C5:C6"]
          // 处理合并逻辑 end
        } else {
          _m.push(`B3:B${_list.length + 2}`)
          _m.push(`C3:C${_list.length + 2}`)
          _m.push(`D3:D${_list.length + 2}`)
          _m.push(`E3:E${_list.length + 2}`)
          _m.push(`F3:F${_list.length + 2}`)
          _m.push(`G3:G${_list.length + 2}`)
          _m.push(`H3:H${_list.length + 2}`)
          _m.push(`I3:I${_list.length + 2}`)
        }
      }
      exportXlsx(title, _list, props.obj.orgname + "安全器材台账", tablename, "安全器材台账", _m)
    }
    ElMessage.success("导出成功")
  }).finally(() => {
    exportLoading.value = false
    loading.close()
  })
}
// 重置过滤条件
const handleRest = () => {
  pageData.listQuery.keywords = ""
  pageData.listQuery.responsibilitypersonname = ""
  pageData.listQuery.sblx = ""
  pageData.listQuery.state = ""
  pageData.pageConfiger.pageCurrent = 1
  gettablist()
}
// 是否选择多选
const handleSelecTable = row => {
}

//获取安全器材类型
function cahngetype(val) {
  pageData.listQuery.sblx = val.dm
  gettablist()
}

//安全器材分页查询
function gettablist() {
  tableloading.value = true
  postApi({ ...pageData.pageConfiger, ...pageData.listQuery }, "/mosty-jcgl/sbglAqqc/queryTbSbglAqqc").then(async (res) => {
    if (res) {
      keys.value++
      tableloading.value = false
      console.log('服务器返回数据')
      console.log(res.records)
      let table_data = []
      for (let i = 0; i < res.records.length; i++) {
        if (res.records[i].sblx === "200201010000") {
          table_data.push(await singleObjectCheck(res.records[i], fireExtinguisherLabel))
        }else {
          table_data.push(await singleObjectCheck(res.records[i], ["manufacturer", ...safetyIdentificationMark]))
        }
      }
      pageData.tableData = table_data
      console.log("列表数据")
      console.log(pageData.tableData)

      pageData.tableData.forEach(async (item) => {
        if (item.flx == "3") {
          let count = await getmhqx(item.ywid)
          item.name = `${item.name}(灭火器${count}具)`
        }
      })
      pageData.pageConfiger.total = res.total
    }
  })
}

//获取灭火器的个数
const getmhqx = async (id) => {
  return new Promise(ok => {
    getApi({ id }, "/mosty-jcgl/sbglAqqc/countMhq").then((res) => {
      ok(res ? res : 0)
    })
  })
}

//新增
function addUserHander() {
  formData.value = {}
  pageData.listQuery.aqbslb = null
  formData.value.type = props.type
  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
  aqqcShow.value = true
  tableloading.value = false
}

//修改
function handlexg(row) {
  formData.value.type = props.type
  formData.value.qtmc = props.obj.qtmc ? props.obj.qtmc : null
  formData.value.title = "安全器材修改"
  formData.value.saveBtnShow = true
  formData.value.zbid = row.id
  formData.value.id = row.ywid
  formData.value.flx = row.flx//1:消防、2:安防 3:灭火箱
  aqqcShow.value = true
}

//详情
function handleSee(row) {
  formData.value.type = props.type
  formData.value.qtmc = props.obj.qtmc ? props.obj.qtmc : null
  formData.value.title = "安全器材详情"
  formData.value.saveBtnShow = false
  formData.value.zbid = row.id
  formData.value.id = row.ywid
  formData.value.flx = row.flx//1:消防、2:安防 3:灭火箱
  aqqcShow.value = true
}

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

const changePage = async (obj) => {
  // formData.value = {}
  aqqcShow.value = false
  // pageData.listQuery.sblx = null
  emits("searchChange", "aqqc")
  gettablist()
}

const createPage = async () => {
  formData.value = {}
  aqqcShow.value = false
  pageData.listQuery.sblx = null
  pageData.listQuery.keywords = null
  pageData.listQuery.responsibilitypersonname = null
  pageData.pageConfiger.pageCurrent = 1
  emits("searchChange", "aqqc")
  await 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/sbglAqqc/exportQrcodeZip?orgcode=" + pageData.listQuery.orgcode +
    (pageData.listQuery.keywords ? "&keywords" + pageData.listQuery.keywords : "") +
    (pageData.listQuery.responsibilitypersonname ? "&responsibilitypersonname" + pageData.listQuery.responsibilitypersonname : "") +
    (pageData.listQuery.sblx ? "&sblx" + pageData.listQuery.sblx : "") +
    (pageData.listQuery.state ? "&state" + pageData.listQuery.state : "")
  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: 250px;
    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>
