<!-- 选择设备对话框 -->
<script lang="ts" setup name="ReceiveDialog">
import { ref } from 'vue'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'
import type { IdeviceList } from './status-interface'
import useUserStore from '@/store/modules/user'
import { listPageApi } from '@/api/device/standingBook'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { getDictByCode } from '@/api/system/dict'
import type { selectType } from '@/views/device/standingBook/standingBook-interface'
import { getStatusList } from '@/api/device/stateManage'
import { SCHEDULE } from '@/utils/scheduleDict'
const props = defineProps({
  dialogSelectDiviceVisible: {
    type: Boolean,
    default: false,
  },
  isMulti: Boolean, // 是否多选
  statusTypeName: { // 状态管理类型
    type: String,
    default: '',
  },
})
// 提醒文字
const emits = defineEmits(['closeDialog', 'updateDeviceConfirm'])
const defineMessageTest = ref('') // 提醒文字
const loadingTable = ref<boolean>(false)
const userStore = useUserStore()
// 查询条件
const listQuery = ref({
  equipmentName: '', // 设备名称
  equipmentNo: '', // 设备编号
  managerState: '', // 管理状态
  offset: 1,
  limit: 20,
})
const total = ref(20)
// 多选选中的内容
const checkoutList = ref([]) as any
const isSelectDisabled = ref(false) // 状态管理筛选框是否禁用
const list = ref([])// 表格数据
const columns = ref<TableColumn[]>([
  { text: '设备名称', value: 'equipmentName', align: 'center', fixed: true },
  { text: '设备编号', value: 'equipmentNo', align: 'center', fixed: true, width: '160' },
  { text: '型号', value: 'modelNo', align: 'center' },
  { text: '出厂编号', value: 'manufacturingNo', align: 'center' },
  { text: '管理状态', value: 'managerStateName', align: 'center', width: '120' },
  { text: '使用人', value: 'usePersonName', align: 'center' },
  { text: '有效日期', value: 'validDate', align: 'center', width: '120' },
])
const table = ref()
const dialogTableVisible = ref(false)// 控制对话框显隐
// 获取数据
const managerStateList = ref<selectType[]>([])
const getDict = () => {
  // 获取管理状态
  getDictByCode('managerState').then((response) => {
    managerStateList.value = response.data.map((item: { name: string; isSelectItemDisabled: boolean }) => {
      if (props.statusTypeName === '闲置' && item.name !== '在用(启封)') {
        item.isSelectItemDisabled = true
      }
      else if (props.statusTypeName === '封存' && (item.name !== '在用(启封)' && item.name !== '闲置')) {
        item.isSelectItemDisabled = true
      }
      else if (props.statusTypeName === '启封' && (item.name !== '封存' && item.name !== '闲置')) {
        item.isSelectItemDisabled = true
      }
      else if (props.statusTypeName === '报废' && (item.name !== '在用(启封)' && item.name !== '闲置' && item.name !== '封存')) {
        item.isSelectItemDisabled = true
      }
      else if (props.statusTypeName === '处置' && item.name !== '报废') {
        item.isSelectItemDisabled = true
      }
      return item
    })
  })
}
getDict()
// 获取数据列表
const fetchData = () => {
  loadingTable.value = true
  listQuery.value.limit = props.isMulti ? 20 : 5
  listPageApi(listQuery.value).then((res) => {
    list.value = res.data.rows.map((item: IdeviceList) => {
      return {
        ...item,
        validDate: item.validDate ? dayjs(item.validDate).format('YYYY-MM-DD') : item.validDate,
      }
    })
    total.value = res.data.total
    loadingTable.value = false
  }).catch((_) => {
    loadingTable.value = false
  })
}
watch(() => props.dialogSelectDiviceVisible, (newValue) => {
  dialogTableVisible.value = newValue
  fetchData()
  if (!newValue) {
    table.value.clearMulti() // 清除多选选中
  }
})
watch(() => props.statusTypeName, (val) => {
  if (val === '闲置') {
    defineMessageTest.value = '在用(启封)'
    listQuery.value.managerState = '1' // 启封 // 默认查询哪个状态
  }
  else if (val === '封存') {
    defineMessageTest.value = '闲置、在用(启封)'
    listQuery.value.managerState = '1' // 启封
  }
  else if (val === '启封') {
    defineMessageTest.value = '闲置、封存'
    listQuery.value.managerState = '3' // 封存
  }
  else if (val === '报废') {
    defineMessageTest.value = '闲置、封存、在用(启封)'
    listQuery.value.managerState = '1' // 启封
  }
  else if (val === '处置') {
    defineMessageTest.value = '报废'
    listQuery.value.managerState = '4' // 报废
  }
})
// 关闭对话框
const close = () => {
  emits('closeDialog')
}
// 确认
const confirm = () => {
  if (!checkoutList.value.length) {
    ElMessage.warning('请选中')
    return
  }
  emits('updateDeviceConfirm', checkoutList.value)
  close()
}
// 重置
const clearList = () => {
  listQuery.value.equipmentName = ''
  listQuery.value.equipmentNo = ''
  fetchData()
}
// 搜索
const searchList = () => {
  fetchData()
}
// 多选选中
const handleSelectionChange = (val: any) => {
  console.log('多选', val)
  checkoutList.value = val
}
// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
const changePage = (val: { size?: number; page?: number }) => {
  if (val && val.size) {
    listQuery.value.limit = val.size
  }
  if (val && val.page) {
    listQuery.value.offset = val.page
  }
  fetchData()
}
</script>

<template>
  <el-dialog v-model="dialogTableVisible" width="65%" title="选择设备" class="select-device-dialog" @close="close">
    <search-area
      :need-clear="true"
      @search="searchList" @clear="clearList"
    >
      <search-item>
        <el-input
          v-model.trim="listQuery.equipmentName"
          placeholder="设备名称"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.equipmentNo"
          placeholder="设备编号"
          clearable
        />
      </search-item>
      <search-item>
        <el-select v-model="listQuery.managerState" class="m-2" placeholder="管理状态" clearable>
          <el-option
            v-for="item in managerStateList"
            :key="item.id"
            :label="item.name"
            :value="item.value"
            :disabled="item.isSelectItemDisabled"
          />
        </el-select>
      </search-item>
    </search-area>
    <div style="padding: 12px;">
      <normal-table
        ref="table"
        :data="list"
        :total="total"
        :columns="columns"
        :query="listQuery"
        :is-multi="isMulti"
        is-showmulti-select
        :list-loading="loadingTable"
        :page-sizes="isMulti ? [20] : [5]"
        :height="260"
        @change="changePage"
        @multiSelect="handleSelectionChange"
      >
        <template #preColumns>
          <el-table-column label="#" width="55" align="center" fixed>
            <template #default="scope">
              {{ (listQuery.offset - 1) * listQuery.limit + scope.$index + 1 }}
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </div>
    <div style="font-size: 14px;">
      <span style="color: #f56c6c;">*注意：只能查询管理状态为 <span style="color: #3d7eff;">{{ defineMessageTest }}</span> 的设备</span>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="confirm">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
// 样式
.receive-dialog {
  .receive-dialog-item {
    display: flex;
    align-items: center;
    margin-bottom: 28px;

    .text {
      margin-right: 30px;
      white-space: nowrap;
    }
  }
}
</style>
