<template>
  <div class="bigBox">

    <!-- 查询 -->
    <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.name" clearable
              style='width:250px'></el-input>
          </section>
        </section>
        <div class="query-btn">
          <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">
          <el-icon>
            <Plus />
          </el-icon>
          新增
        </el-button>
        <el-button @click="getSheets" :loading="exportInfo.loading">
          <el-icon>
            <File />
          </el-icon>
          导出
        </el-button>
      </section>
      <section style="height:calc(100vh - 370px)">
        <MOSTY.Table :table-columns="pageData.tableColumns" :tableData="pageData.tableData" :tableloading="tableloading"
          :isSelect="true" :isSort="true">
          <template #sitename="{ row }">
            <span>{{ row.sitename ? row.sitename : "" }}{{ row.buildingname ? "-" + row.buildingname : "" }}{{
              row.floorname ? "-" + row.floorname : "" }}{{ row.partname ? "-" + row.partname : "" }}</span>
          </template>
          <template #unit="{ row }">
            <dict-tag v-if="row.unit" :options="D_BZ_WPDW" :value="row.unit" :tag="true" />
            <span v-else>无</span>
          </template>
          <template #actions="{ row }">
            <span class="operedit" @click="onEdit(row)">
              <el-icon>
                <EditPen />
              </el-icon>
              编辑
            </span>
            <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除?"
              @confirm="onDelete(row)">
              <template #reference>
                <span class="operdel" size="small">
                  <el-icon>
                    <Delete />
                  </el-icon>
                  删除</span>
              </template>
            </el-popconfirm>
            <span class="operesee" @click="onSee(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="isShowEdit" class="dialog-box">
    <edit :id="rowId" :row="currRow" @ok="saveSuccess" :tcType="editType" @close="closePage" />
  </div>
</template>
<script setup>
import * as MOSTY from "@/components/MyComponents/index"
import { reactive, ref, onMounted, watch, nextTick, getCurrentInstance, defineProps, defineExpose } from "vue"
import { ElMessage } from "element-plus"
import { getApi, postApi } from "@/api/tobAcco_api.js"
import edit from "./edit.vue"
import { exportXlsx } from "@/excel/Export2Excel.js"
import { getItem } from "@/utils/storage"
import { getValByDic } from "@/utils/tools.js"

const { proxy } = getCurrentInstance()
const { D_TB_JCYWLX, D_BZ_WPDW } = proxy.$dict("D_TB_JCYWLX", "D_BZ_WPDW")
const emits = defineEmits(["handleChange", "searchChange"])
const props = defineProps({
  orgcode: {
    type: String,
    default: ""
  }
})

const tableloading = ref(false)
/** 是否-显示编辑/新增/详情弹框 */
const isShowEdit = ref(false)
/** 类型 add edit see */
const editType = ref("")
const exportLoadings = ref(false)
const keys = ref(0)

const rowId = ref()
const currRow = ref({})
const formData = ref({
  title: ""
})
// const props = defineProps({})

const queryHeight = ref(null)

const sbsslist = ref([])
const isAuth = ref(false)
const exportInfo = reactive({
  name: "实验室设备设施",
  loading: false,
  disabled: true
})
const exportSheets = reactive([])
const pageData = reactive({
  listQuery: {
    name: "",
    orgcode: ""
  },
  pageConfiger: {
    pageSize: 10,
    pageCurrent: 1,
    total: 0
  },
  tableColumns: [
    {
      title: "设备名称",
      prop: "name",
      fixed: "left",
      // slot
    },
    {
      title: "品牌",
      prop: "brand"
    },
    {
      title: "型号",
      prop: "model"
    },
    {
      title: "装置数量",
      prop: "devicename"
    },
    {
      title: "单位",
      prop: "unit",
      slot: true
    },
    {
      title: "投入金额",
      prop: "money"
    },
    {
      title: "所在位置",
      prop: "sitename",
      slot: true,
    },
    {
      title: "安装时间",
      prop: "azsj"
    },
    // {
    //   title: "维保单位",
    //   prop: "maintenanceUnit"
    // },
    // {
    //   title: "维保联系人",
    //   prop: "maintenanceContact"
    // },
    // {
    //   title: "维保人电话",
    //   prop: "maintenancePhone"
    // },
    {
      title: "登记日期",
      prop: "registerDate"
    },
    {
      title: "责任部门",
      prop: "responsibilitydeptname"
    },
    {
      title: "责任人",
      prop: "responsibilitypersonname"
    },
    {
      title: "操作",
      prop: "actions",
      fixed: 'right',
      slot: true
    }
  ],
  tableData: []
})
onMounted(() => {
  // gettablist() // 第一次由外面触发
})
const gettablist = () => {
  exportInfo.disabled = true
  const params = {
    ...pageData.pageConfiger,
    ...pageData.listQuery,
    orgcode: pageData.listQuery.orgcode || getItem("deptId").ssdwid
  }
  tableloading.value = true
  postApi(params, "/mosty-jcgl/syssb/getPageList").then(async (res) => {
    if (res) {
      if (res.records.length) {
        exportInfo.disabled = false
      }
      keys.value++

      pageData.tableData = res?.records

      pageData.pageConfiger.total = res.total
    }
  }).finally(() => {
    tableloading.value = false
  })
}

const handleRest = () => {
  pageData.listQuery.name = ""

  pageData.pageConfiger.pageCurrent = 1
  gettablist()
}

const getSheets = () => {
  console.log('导出');
  exportInfo.loading = true
  const params = {
    // pageSize: 9999999,
    // pageCurrent: 1,
    orgcode: pageData.listQuery.orgcode || getItem("deptId").ssdwid,
  }
  postApi(params, "/mosty-jcgl/syssb/getList").then(res => {

    if (!res) {
      ElMessage.warning("暂无数据")
      exportInfo.loading = false
      return
    }
    let excelArr = Array.isArray(res) ? res : []
    /** 获取需要的单位名称 */
    const getSiteName = (list) => {
      let siteName = ''
      if (list.floorname) {
        siteName = list.sitename + "-" + list.buildingname + "-" + list.floorname + "-" + list.partname
      } else {
        if (list.sitename && list.buildingname && list.partname) {
          siteName = list.sitename + "-" + list.buildingname + "-" + list.partname
        } else {
          siteName = ""
        }
      }
      return siteName
    }
    excelArr.forEach((list, index) => {
      // list.index = index + 1
      list.sitename = getSiteName(list)
      list.state = { '01': '完好', '02': '故障' }[list.state] || ''
      list.unit = getValByDic(list.unit, D_BZ_WPDW.value)
      list.sblx = getValByDic(list.sblx, D_TB_JCYWLX.value)
      list.connectgroundinfo = { 1: '是', 2: '否' }[list.connectgroundinfo] || ''
    })
    let tablename = "实验室设备列表.xlsx"
    /** 标题 */
    const title = {
      // index: "序号",
      name: "设备名称",

      floorname: "所属楼层名称",
      buildingname: "所属建筑物名称",
      sitename: "所属场所名称",

      partname: "所属部位名称",
      brand: "品牌",
      model: "型号",
      power: "功率",

      state: "状态",
      unit: "单位",
      devicename: "装置名称",
      devicenum: "装置数量",
      manufactor: "厂家",
      purchasetime: "购买时间",
      factorytime: "出厂时间",
      factoryno: "出厂编号",
      responsibilitypersonname: "责任人名称",
      responsibilitydeptname: "责任部门",
      sblx: "设备类型",
      money: "投入金额(万元)",
      azsj: "安装时间",
      connectgroundinfo: "接地情况",
    }
    excelArr = JSON.parse(JSON.stringify(excelArr))
    exportXlsx(title, excelArr, "实验室设备列表", tablename, "实验室设备列表")
    exportInfo.loading = false

  }).finally(() => {
    exportInfo.loading = false
  })
}
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()
// }
// 是否可以操作


//新增
function addUserHander() {
  rowId.value = ''
  editType.value = 'add'
  currRow.value = {}

  isShowEdit.value = true
}

//编辑
function onEdit(row) {
  rowId.value = row.id
  editType.value = 'edit'
  currRow.value = row

  isShowEdit.value = true
}

//查看
function onSee(row) {
  rowId.value = row.id
  editType.value = 'see'
  currRow.value = row

  isShowEdit.value = true
}

/**
 * 处理删除设备台账记录操作
 * @param {Object} row - 表格行数据对象，包含待删除记录信息
 * @param {string|number} row.id - 要删除记录的唯一标识符
 */
function onDelete(row) {
  postApi({ id: row.id }, `/mosty-jcgl/syssb/del/${row.id}`).then(res => {
    ElMessage.success("删除成功")
    gettablist()
  })
}

/**
 * 关闭
 * @param val
 * @param obj
 * @returns {Promise<void>}
 */
const saveSuccess = async (val, obj) => {
  isShowEdit.value = false
  gettablist()
}

/**
 * 创建成功后初始化
 * @param obj
 */
const closePage = (obj) => {
  isShowEdit.value = false
  gettablist()
}

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

//页码发生变化
const handleCurrentChange = (val) => {
  pageData.pageConfiger.pageCurrent = val
  gettablist()
}
//查询条数发生变化
const handleSizeChange = (val) => {
  pageData.pageConfiger.pageSize = val
  gettablist()
}
/**左侧 单位改变 */
const orgCodeChange = (orgcode) => {

  pageData.listQuery.name = ""
  pageData.listQuery.orgcode = orgcode
  pageData.pageConfiger.pageCurrent = 1
  gettablist()
}
defineExpose({ orgCodeChange })
</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>