<!-- 设备规格型号管理列表 -->
<script lang="ts" setup name="DeviceModelList">
import { reactive, ref, watch } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import { deleteModel, exportModelList, getDeviceNameList, getModelAllList, getModelByname, getModelList } from '@/api/eqpt/device/model'
import { exportFile } from '@/utils/exportUtils'
import { getDictByCode } from '@/api/system/dict'
const { proxy } = getCurrentInstance() as any
const listQuery = reactive({
  category: '',
  equipmentName: '',
  helpInstruction: '',
  model: '',
  offset: 1,
  limit: 20,
})
const columns = ref([
  {
    text: '规格型号编号',
    value: 'modelNo',
    align: 'center',
  },
  {
    text: '设备名称',
    value: 'equipmentName',
    align: 'center',
  },
  {
    text: '规格型号',
    value: 'model',
    align: 'center',
  },
  {
    text: '辅助字段',
    value: 'helpInstruction',
    align: 'center',
  },
  {
    text: '设备分类',
    value: 'categoryName',
    align: 'center',
  },
  {
    text: '检定周期',
    value: 'checkCycle',
    align: 'center',
  },
  {
    text: '使用说明书',
    value: 'instructionsFile',
    align: 'center',
  },
  {
    text: '备注',
    value: 'remark',
    align: 'center',
  },
])
const list = ref([])
const total = ref(0)
const listLoading = ref(true)

// 获取数据
const fetchData = (isNowPage = true) => {
  listLoading.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.offset = 1
  }
  getModelList(listQuery).then((response) => {
    list.value = response.data.rows.map((item: any) => ({ ...item, helpInstruction: item.helpInstruction ? item.helpInstruction : '/' }))
    total.value = parseInt(response.data.total)
    listLoading.value = false
  })
}
fetchData()
// 查询数据
const search = () => {
  fetchData(false)
}

// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
const changePage = (val: { size: number; page: number }) => {
  if (val && val.size) {
    listQuery.limit = val.size
  }
  if (val && val.page) {
    listQuery.offset = val.page
  }
  fetchData()
}
const $router = useRouter()
// 新建编辑操作
const handler = (row: any, type: string) => {
  $router.push({
    path: `/dmodel/${type}`,
    query: {
      row: JSON.stringify(row),
      id: row.id,
    },
  })
}
// 删除
const delHandler = (row: any) => {
  ElMessageBox.confirm(
    '确认删除操作？注意删除不可逆。',
    '确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    // 判断设备是否被绑定
    // 此设备型号与已存在设备绑定，请先删除设备
    deleteModel({ id: row.id }).then((res) => {
      ElMessage.success('操作成功')
      search()
    })
  })
}
// 表格被选中的行
const selectList = ref<any[]>([])
// 表格多选
const multiSelect = (row: any[]) => {
  selectList.value = row
}
// 导出列表
const exportList = () => {
  if (list.value.length) {
    const loading = ElLoading.service({
      lock: true,
      text: 'Loading',
      background: 'rgba(255, 255, 255, 0.8)',
    })
    const data = {
      ...listQuery,
      offset: undefined,
      limit: undefined,
      ids: selectList.value.map(item => item.id),
    }
    exportModelList(data).then((res) => {
      exportFile(res.data, '设备规格型号')
      loading.close()
    })
      .catch((_) => {
        loading.close()
      })
  }
  else {
    ElMessage.warning('无可导出内容')
  }
}
// 获取下拉列表相关
// 设备名称
const deviceNameList = ref<string[]>([])
// 设备分类
const deviceTypeList = ref<{ id: string; value: string; name: string }[]>([])
// 规格型号
const modelList = ref<any[]>([])
// 辅助字段
const helpList = ref<any[]>([])
const allList = ref<any[]>([])
const fetchSelect = () => {
  // 设备分类
  getDictByCode('eqptDeviceType').then((res) => {
    deviceTypeList.value = res.data
  })
  // 设备名称
  getDeviceNameList().then((res) => {
    deviceNameList.value = res.data
  })
  // 规格型号及辅助字段
  getModelAllList({}).then((res) => {
    allList.value = res.data
    modelList.value = Array.from(new Set(res.data.filter((item: any) => item.model).map((item: any) => item.model)))
    helpList.value = Array.from(new Set(res.data.filter((item: any) => item.helpInstruction).map((item: any) => item.helpInstruction)))
  })
}
fetchSelect()
// 监听设备名称下拉框，修改规格型号和辅助字段
watch(() => listQuery.equipmentName, (newVal) => {
  listQuery.helpInstruction = ''
  listQuery.model = ''
  if (newVal) {
    // 修改规格型号和辅助字段列表
    const data = allList.value.filter(item => item.equipmentName === newVal)
    modelList.value = Array.from(new Set(data.filter(item => item.model).map(item => item.model)))
    helpList.value = Array.from(new Set(data.filter(item => item.helpInstruction).map(item => item.helpInstruction)))
  }
  else {
    modelList.value = Array.from(new Set(allList.value.filter(item => item.model).map(item => item.model)))
    helpList.value = Array.from(new Set(allList.value.filter(item => item.helpInstruction).map(item => item.helpInstruction)))
  }
})
// 监听规格型号下拉框，修改辅助字段
watch(() => listQuery.model, (newVal) => {
  listQuery.helpInstruction = ''
  if (newVal && listQuery.equipmentName) {
    // 修改规格型号和辅助字段列表
    helpList.value = Array.from(new Set(allList.value.filter(item => item.helpInstruction).filter(item => item.equipmentName === listQuery.equipmentName && item.model === newVal).map(item => item.helpInstruction)))
  }
  else if (newVal) {
    helpList.value = Array.from(new Set(allList.value.filter(item => item.helpInstruction).filter(item => item.model === newVal).map(item => item.helpInstruction)))
  }
  else {
    helpList.value = Array.from(new Set(allList.value.filter(item => item.helpInstruction).map(item => item.helpInstruction)))
  }
})
// 重置
const reset = () => {
  listQuery.category = ''
  listQuery.equipmentName = ''
  listQuery.helpInstruction = ''
  listQuery.model = ''
  modelList.value = Array.from(new Set(allList.value.filter(item => item.model).map(item => item.model)))
  helpList.value = Array.from(new Set(allList.value.filter(item => item.helpInstruction).map(item => item.helpInstruction)))
  listQuery.offset = 1
  listQuery.limit = 20
  search()
}
</script>

<template>
  <app-container>
    <!-- 筛选条件 -->
    <search-area :need-clear="true" @search="search" @clear="reset">
      <search-item>
        <el-select v-model.trim="listQuery.equipmentName" filterable placeholder="设备名称" clearable>
          <el-option v-for="item in deviceNameList" :key="item" :label="item" :value="item" />
        </el-select>
      </search-item>
      <search-item>
        <el-select v-model.trim="listQuery.model" filterable placeholder="规格型号" clearable>
          <el-option v-for="item in modelList" :key="item" :label="item" :value="item" />
        </el-select>
      </search-item>
      <search-item>
        <el-select v-model.trim="listQuery.helpInstruction" placeholder="辅助字段" clearable>
          <el-option v-for="item in helpList" :key="item" :label="item" :value="item" />
        </el-select>
      </search-item>
      <search-item>
        <el-select v-model.trim="listQuery.category" placeholder="设备分类" clearable>
          <el-option v-for="item in deviceTypeList" :key="item.id" :label="item.name" :value="item.value" />
        </el-select>
      </search-item>
    </search-area>
    <table-container>
      <template #btns-right>
        <!--  -->
        <!-- /device/model/delete -->
        <!-- /device/model/update -->
        <icon-button v-if="proxy.hasPerm('/device/model/add')" icon="icon-add" title="新增" @click="handler({}, 'create')" />
        <icon-button icon="icon-export" title="导出" @click="exportList" />
      </template>
      <!-- 普通表格 -->
      <normal-table
        :data="list" :total="total" :columns="columns" :query="listQuery" :list-loading="listLoading"
        :is-showmulti-select="true" :is-multi="true" @change="changePage" @multi-select="multiSelect"
      >
        <template #columns>
          <el-table-column label="操作" width="140" align="center">
            <template #default="scope">
              <el-button link type="primary" size="small" @click="handler(scope.row, 'detail')">
                查看
              </el-button>
              <el-button v-if="proxy.hasPerm('/device/model/update')" link type="primary" size="small" @click="handler(scope.row, 'update')">
                编辑
              </el-button>
              <el-button v-if="proxy.hasPerm('/device/model/delete')" link type="danger" size="small" @click="delHandler(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
  </app-container>
</template>

