<template>
  <div class="bigBox">
    <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="236" mb="6px" />
          </section>
        </section>
      </section>
    </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.logoname" clearable
                      style='width:250px'></el-input>
            <MOSTY.DictTree class="ml12" v-model="pageData.listQuery.aqbslb" :zdlist="aqbslist"
                            :placeholder='"安全标识类型"'
                            :type='"array"' style="width: 250px;" />
            <MOSTY.DictRidioAndSelect class="ml12" style="width: 250px;" :dictData="D_TB_AQBS_LX"
                                      v-model="pageData.listQuery.logotypecode" selectType="select"
                                      :placeholder='"业务分类"' :disabled="false" />
          </section>
          <template v-if="isOpensearch">
            <MOSTY.DictRidioAndSelect class="mt10" style="width: 250px;" :dictData="D_BZ_SYZT"
                                      v-model="pageData.listQuery.state" selectType="select" :placeholder='"状态"'
                                      :disabled="false" />
          </template>
        </section>
        <div class="query-btn">
          <div class="toggle" :class="{ active: isOpensearch }" @click="handleClickOpen">
            <span>{{ isOpensearch ? "收起" : "展开" }}筛选</span>
            <el-icon>
              <DArrowLeft />
            </el-icon>
          </div>
          <el-button @click="seachchange" class="ml6">
            <el-icon>
              <Search />
            </el-icon>
            <span>查询</span></el-button>
          <el-button @click="handleRest">
            <el-icon>
              <Refresh />
            </el-icon>
            <span>重置</span></el-button>
        </div>
      </section>
      <el-divider />
      <section class="button">
        <el-button type="primary" v-if="isAuth && props.obj.saveBtnShow" @click="addUserHander">
          <el-icon>
            <CirclePlus />
          </el-icon>
          <span>新增</span>
        </el-button>
        <el-button type="primary" @click="export2Excel" v-loading="dcloading"
                   :disabled="pageData.tableData.length == 0">
          <el-icon>
            <Download />
          </el-icon>
          <span>导出</span>
        </el-button>
      </section>
      <section :style="{ 'height': totalHeights }">
        <MOSTY.Table :table-columns="pageData.tableColumns" :isSelect="true" :isSort="true"
                     :tableData="pageData.tableData" :tableloading="tableloading" @handleSelecTable="handleSelecTable"
                     element-loading-text="数据加载中...">
          <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 #aqbslb="{ row }">
            <dict-tag v-if="row.aqbslb" :options="D_TB_JCYWLX" :value="row.aqbslb" :tag="false" />
            <span v-else>无</span>
          </template>
          <template #logotypecode="{ row }">
            <dict-tag v-if="row.logotypecode" :options="D_TB_AQBS_LX" :value="row.logotypecode" :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 #responsibleusername="{ row }">
            <span>{{ row.responsibleusername ? row.responsibleusername.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 }">
            <span class="operedit" v-if="isAuth && props.obj.saveBtnShow" @click="handlexg(row)">
              <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="showaqbsdia" class="dialog-box">
    <Addaqbsindex :formData="formData" @changePage="changePage" @createPage="createPage" :type="props.obj.type" />
  </div>
</template>
<script setup>
import * as MOSTY from "@/components/MyComponents/index"
import Addaqbsindex from "@/components/dialog/Addaqbsindex.vue"
import { reactive, ref, onMounted, getCurrentInstance, watch, nextTick } from "vue"
import { getApi, postApi } from "@/api/tobAcco_api.js"
import { ElMessage } from "element-plus"
import { exportXlsx } from "@/excel/Export2Excel.js"
import Sjtj from "@/views/dataReportWork/aqjypx/components/sjtj.vue"
import { getAuth } from "@/utils/tools.js"

const { proxy } = getCurrentInstance()
const {
  D_TB_AQBS_LX,
  D_BZ_SYZT,
  D_TB_JCYWLX
} = proxy.$dict("D_TB_AQBS_LX", "D_BZ_SYZT", "D_TB_JCYWLX")
const emits = defineEmits(["handleChange", "searchChange"])
const tableloading = ref(false)
const showaqbsdia = ref(false)
const isShowTotal = ref(false)
const dcloading = ref(false)
const isOpensearch = ref(false)
const isAuth = ref(true)
const total = ref(0)
import { arrayFiltering } from "@/utils/tools"

const formData = ref({
  title: ""
})
const props = defineProps({
  obj: {
    default: null,
    type: Object
  },
  type: {
    default: "",
    type: String
  },
  tableHeight: {
    default: "52vh",
    type: String
  },
  isShowTotal: {
    type: Boolean,
    default: true
  }
})
const aqbslist = ref([])
const sign = ["logoname", "aqbslb", "logotypecode", "installationdate", "sitename", "buildingname",
  "partname", "location"]
const pageData = reactive({
  countlist: [
    {
      title: "总数",
      num: 0,
      dm: "",
      icon: "ccss/icon_01.png"
    },
    {
      title: "警告类标识",
      num: 0,
      dm: "200301000000",
      icon: "ccss/icon_02.png"
    },
    {
      title: "禁止类标识",
      num: 0,
      dm: "200302000000",
      icon: "ccss/icon_03.png"
    },
    {
      title: "指令类标识",
      num: 0,
      dm: "200303000000",
      icon: "ccss/icon_04.png"
    },
    {
      title: "提示类标识",
      num: 0,
      dm: "200304000000",
      icon: "ccss/icon_05.png"
    }
  ],
  listQuery: {
    type: "1",
    pageCurrent: 1,
    pageSize: 20,
    logotypecode: "",
    logoname: "",
    aqbslb: ""

  },
  tableColumns: [
    {
      title: "标记",
      prop: "sign",
      sortable: false,
      slot: true
    },
    {
      title: "单位",
      prop: "orgname"
    },
    {
      title: "安全标识名称",
      prop: "logoname"
    },
    {
      title: "安全标识类型",
      prop: "aqbslb",
      slot: true
    },
    {
      title: "业务分类",
      prop: "logotypecode",
      slot: true
    },
    {
      title: "所属现场部位",
      prop: "sitename",
      slot: true
    },
    {
      title: "悬挂位置",
      prop: "location"
    },
    {
      title: "责任部门",
      prop: "deptname"
    },
    {
      title: "责任人",
      prop: "responsibleusername",
      slot: true
    },
    {
      title: "状态",//正常、异常，平铺
      prop: "state",
      slot: true
    },
    {
      title: "操作",
      prop: "actions",
      slot: true
    }
  ],
  tableData: [],
  pageConfiger: {
    pageSize: 10,
    pageCurrent: 1,
    total: 0
  }
})
const getHeight = ref(null)
const queryHeight = ref(null)
const fromObj = ref({ type: "1" })
const totalHeights = ref(null)
watch(() => props.isShowTotal, (val) => {
  isShowTotal.value = props.isShowTotal
  nextTick(() => {
    if (val) {
      totalHeights.value = `calc(100vh - ${337 + queryHeight.value.offsetHeight + getHeight.value.offsetHeight}px)`
    } else {
      totalHeights.value = `calc(100vh - 373px)`
    }

  })
}, {
  deep: true,
  immediate: true
})
const handleClickOpen = () => {
  isOpensearch.value = !isOpensearch.value
  nextTick(() => {
    if (props.type == "aqbs") {
      if (isOpensearch.value) {
        totalHeights.value = `calc(100vh - ${337 + getHeight.value.offsetHeight + queryHeight.value.offsetHeight}px)`
      } else {
        totalHeights.value = `calc(100vh - 373px)`
      }
    } else {
      if (isOpensearch.value) {
        totalHeights.value = `calc(100vh - ${280 + getHeight.value.offsetHeight + queryHeight.value.offsetHeight}px)`
      } else {
        totalHeights.value = `calc(100vh - 443px)`
      }
    }

  })
}
onMounted(() => {
  nextTick(() => {
    if (props.type == "aqbs") {
      totalHeights.value = `calc(100vh - ${337 + getHeight.value.offsetHeight + queryHeight.value.offsetHeight}px)`
    } else {
      totalHeights.value = `calc(100vh - 443px)`
    }

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

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

})
// 是否可以操作
const isAuthorize = async () => {
  isAuth.value = await getAuth()
}

const handleSelecTable = () => {

}

// （新）统计各类（场、建、楼、部）下或单位,安全标识
function getaqbscount() {
  postApi(fromObj.value, "/mosty-jcgl/sitelogo/countSitelogo").then((res) => {
    // getApi(pageData.listQuery, '/mosty-jcgl/sitelogo/getStatistics').then((res) => {
    if (res.length > 0) {
      for (let i = 0; i < res.length; i++) {
        const el = res[i]
        for (let j = 0; j < pageData.countlist.length; j++) {
          const li = pageData.countlist[j]
          // if (li.dm == el.aqbslb) {
          if (li.dm == el.dm) {
            li.num = el.count
          }
        }
        pageData.countlist[0].num = pageData.countlist[1].num + pageData.countlist[2].num + pageData.countlist[3].num
          + pageData.countlist[4].num
      }
    }
  })
}

//安全标识分页查询
function gettablist() {
  tableloading.value = true
  postApi(pageData.listQuery, "/mosty-jcgl/sitelogo/queryTbSitelogo").then(async (res) => {
    if (res) {
      tableloading.value = false
      pageData.tableData = arrayFiltering(res?.records, sign)
      console.log('表格数据')
      console.log(pageData.tableData)
      pageData.pageConfiger.total = res.total
    }
  })
}

//获取安全标识类型
function getaqbslb() {
  getApi({
    zdbh: "D_TB_JCYWLX",
    dm: "2003",
    level: 2
  }, "/mosty-base/sysDict/getJcyelxDictTree").then(res => {
    aqbslist.value = res[0].itemList
  })
}

function seachchange() {
  getaqbscount()
  gettablist()
}

//注销
function handledelete(row) {
  postApi({}, `/mosty-jcgl/sitelogo/deleteTbSitelogoOne/${row.id}`).then(res => {
    ElMessage.success("删除成功")
    emits("searchChange", "aqbs")
    getaqbscount()
    gettablist()
  })
}

//新增
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
  showaqbsdia.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.id = row.id

  formData.value.xgfMc = row.xgfMc
  formData.value.xgfId = row.xgfId
  formData.value.xgfRyMc = row.xgfRyMc
  formData.value.xgfRyId = row.xgfRyId
  showaqbsdia.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.id = row.id
  showaqbsdia.value = true
}

//关闭
const changePage = async (obj) => {
  // formData.value = {}
  showaqbsdia.value = false
  // pageData.listQuery.aqbslb = null
  gettablist()
  getaqbscount()
  emits("searchChange", "aqbs")
  // if (obj) {
  //
  //   //新增成功不刷新表格直接追加
  //   pageData.tableData.unshift(obj)
  //   total.value + 1
  // } else {
  //   //修改不追加，直接刷新
  //   gettablist()
  // }
}
//新增
const createPage = (obj) => {
  formData.value = {}
  showaqbsdia.value = false
  pageData.listQuery.aqbslb = null
  emits("searchChange", "aqbs")
  getaqbscount()
  if (obj) {

    //新增成功不刷新表格直接追加
    pageData.tableData.unshift(obj)
    total.value + 1
  } else {
    //修改不追加，直接刷新
    gettablist()
  }
}
//查询
const handleRest = () => {
  pageData.listQuery.aqbslb = ""
  pageData.listQuery.logoname = ""
  pageData.listQuery.logotypecode = ""
  pageData.listQuery.state = ""
  pageData.listQuery.pageCurrent = 1
  pageData.pageConfiger.pageCurrent = 1
  gettablist()
  getaqbscount()
}
//页码发生变化
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 export2Excel = () => {
  let title = {
    index: "序号",
    orgname: "单位",
    aqbslb: "安全标识类型",
    logoname: "安全标识名称",
    logotypecode: "业务分类",
    sitename: "所属现场部位",
    location: "悬挂位置",
    installationdate: "安装日期",
    deptname: "责任部门",
    responsibleusername: "责任人",
    state: "状态"
  }
  const param = {
    pageCurrent: 1,
    pageSize: 10000,
    type: "0",
    orgid: fromObj.value.orgcode
  }
  dcloading.value = true
  postApi(param, "/mosty-jcgl/sitelogo/exportTbSitelogo").then(async (res) => {
    if (res) {
      let data = res
      if (data.length > 0) {
        for (let i = 0; i < data.length; i++) {
          data[i].index = i + 1
          data[i].logotypecode = data[i].logotypecode ? proxy.$getDictVal(data[i].logotypecode, D_TB_AQBS_LX) : "无"
          data[i].responsibleusername = data[i].responsibleusername ? data[i].responsibleusername.replace(/（null）/g, "") : ""
          data[i].state = data[i].state ? proxy.$getDictVal(data[i].state, D_BZ_SYZT) : "无"
          data[i].aqbslb = data[i].aqbslb ? proxy.$getDictVal(data[i].aqbslb, D_TB_JCYWLX) : "无"
          data[i].sitename = `${data[i].sitename ? data[i].sitename : ""}${data[i].buildingname ? "-" + data[i].buildingname : ""}${data[i].floorname ? "-" + data[i].floorname : ""}${data[i].partname ? "-" + data[i].partname : ""}`
        }
        let tablename = "安全标识.xlsx"
        exportXlsx(title, data, "安全标识", tablename, "安全标识")
        dcloading.value = false
      } else {
        ElMessage.warning("暂无数据")
        dcloading.value = false
      }
    }
  }).catch(err => {
    dcloading.value = false
  })
}
</script>

<style lang="scss" scoped>
.headBox {
  display: flex;
  justify-content: end;
  width: 100%;
  margin-bottom: 10px;
}

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

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

  .query-section {

    width: 68%;
  }

  .query-btn {
    width: 360px;
    display: flex;
    justify-content: 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);
        }
      }
    }
  }
}
</style>
