<!--
 * @Author: ysh
 * @Date: 2024-06-21 18:51:51
 * @LastEditors: wrh
 * @LastEditTime: 2026-02-03 15:32:30
-->
<template>
  <div>
    <el-form :inline="true">
      <el-form-item label="出厂编号：">
        <el-input v-model="queryParams.code" clearable @keyup.enter.native="getList"></el-input>
      </el-form-item>
      <el-form-item label="设备状态：">
        <el-select v-model="queryParams.status" filterable clearable @change="getList">
          <el-option :value="'0'" label="被领用"></el-option>
          <el-option :value="'1'" label="可领用"></el-option>
          <el-option :value="'2'" label="维修中"></el-option>
          <el-option :value="'3'" label="已停用"></el-option>
          <el-option :value="'4'" label="已报废"></el-option>
          <el-option :value="'5'" label="已处置"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="设备名称：">
        <el-select v-model="queryParams.name" filterable @change="getList" clearable>
          <el-option v-for="item in nameList" :key="item.name" :label="item.name" :value="item.name">
          </el-option>
        </el-select>
        <!-- <el-input v-model="queryParams.name" clearable></el-input> -->
      </el-form-item>
      <el-form-item label="品牌：">
        <el-input v-model="queryParams.brand" clearable @keyup.enter.native="getList"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getList" type="primary">搜索</el-button>
      </el-form-item>
    </el-form>
    <el-table border ref="chooseDeviceRef" :data="list" @selection-change="handleSelectionChange" :row-key="getRowKeys"
      @current-change="handleCurrentChange" @row-dblclick="confirmChooseBySingle" :highlight-current-row="!multiple"
      :selectable="isSelectable">
      <el-table-column type="selection" width="50" align="center" :reserve-selection="true" v-if="multiple" />
      <el-table-column label="设备状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="statusType(scope.row.status)">
            {{ statusTypeText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="出厂编号" align="center" prop="code" />
      <el-table-column label="设备品牌" align="center" prop="brand" />
      <el-table-column label="设备名称" align="center" prop="name" />
      <el-table-column label="规格型号" align="center" prop="series" />
      <el-table-column label="存放地址" align="center" prop="place" />
      <!-- <el-table-column label="单日成本" align="center" prop="dayCost" /> -->
      <el-table-column label="检定证书" align="center" width="200" prop="document" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-link type="primary" :href="`${baseUrl}${'/profile/upload' + scope.row.document}`">
            {{ getFileName(scope.row.document) }}
          </el-link>
        </template>
      </el-table-column>
    </el-table>
    <div style="text-align: right;">
      <el-pagination @current-change="getList" :current-page.sync="queryParams.pageNum"
        :page-size="queryParams.pageSize" layout="total, prev, pager, next" :total="total">
      </el-pagination>
    </div>
    <div>
      已选设备：
      <el-tag v-if="multiple" v-for="item in chooseList" style="margin: 5px;" :key="item.deviceIdId">
        {{ item.name + '-' + item.series + '-' + item.brand }}
      </el-tag>
      <el-tag v-if="!multiple" style="margin: 5px;">{{ formatChooseList() }}</el-tag>
      <div style="text-align: center;margin-top: 20px;">
        <el-button type="primary" @click="confirmChoose">确认选择</el-button>
        <el-button @click="clearChoose">清空选择</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { listDevice, listDeviceName } from "@/api/oa/device/device";
import { multiply } from 'ol/transform';
export default {
  props: {
    multiple: {
      type: Boolean,
      default: true
    },
    selectedDeviceIds: {
      type: Array,
      default: () => []
    }
  },
  watch: {
    multiple(newval) {
      if (newval) {
        this.chooseList = []
      } else {
        this.chooseList = {}
      }
      this.getList();
      this.getNameList();
    }
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: '仪器设备',
        status: '1',
      },
      list: [],
      form: {},
      total: 0,
      loading: false,
      chooseList: undefined,
      nameList: [],
    }
  },
  created() {
    if (this.multiply) {
      this.chooseList = []
    } else {
      this.chooseList = {}
    }
    this.getList();
    this.getNameList();
  },
  methods: {
    getList() {
      this.loading = true;
      listDevice(this.queryParams).then(response => {
        this.list = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getNameList() {
      listDeviceName().then(res => {
        this.nameList = res.data.filter(function (item) {
          return item !== null;
        });
      })
    },
    handleSelectionChange(val) {
      this.chooseList = val
    },
    handleCurrentChange(val) {
      if (!this.multiple) {
        this.chooseList = val
      }
    },
    getRowKeys(row) {
      return row.deviceId;
    },
    confirmChoose() {
      if (!this.chooseList || (Array.isArray(this.chooseList) && this.chooseList.length === 0) ||
          (typeof this.chooseList === 'object' && !Array.isArray(this.chooseList) && Object.keys(this.chooseList).length === 0)) {
        return;
      }
      let devices = Array.isArray(this.chooseList) ? this.chooseList : [this.chooseList];
      // 找出已存在的设备
      const existedDevices = devices.filter(d => this.selectedDeviceIds.includes(d.deviceId));
      // 过滤掉已存在的设备
      devices = devices.filter(d => !this.selectedDeviceIds.includes(d.deviceId));
      if (devices.length === 0) {
        const names = existedDevices.map(d => `${d.name}-${d.series}-${d.brand}`).join('、');
        this.$message.warning(`所选设备【${names}】已存在，无法重复添加`);
        return;
      }
      if (existedDevices.length > 0) {
        const names = existedDevices.map(d => `${d.name}-${d.series}-${d.brand}`).join('、');
        this.$message.warning(`设备【${names}】已存在，已自动过滤`);
      }
      this.$emit('chooseList', this.multiple ? devices : devices[0]);
      this.clearChoose();
    },
    confirmChooseBySingle() {
      if (!this.multiple) {
        if (this.chooseList)
          this.$emit('chooseList', this.chooseList)
      }
    },
    clearChoose() {
      if (this.multiple)
        this.$refs.chooseDeviceRef.clearSelection();
      else {
        this.chooseList = {}
      }
    },
    statusTypeText(row) {
      if (row == '0') {
        return '被领用'
      }
      if (row == '1') {
        return '可领用'
      }
      if (row == '2') {
        return '维修中'
      }
      if (row == '3') {
        return '已停用'
      }
      if (row == '4') {
        return '已报废'
      }
      if (row == '5') {
        return '已处置'
      }
    },
    statusType(row) {
      if (row == '0') {
        return 'warning'
      }
      if (row == '1') {
        return 'success'
      }
      if (row == '2') {
        return 'primary'
      }
      if (row == '3') {
        return 'danger'
      }
      if (row == '4') {
        return 'info'
      }
      if (row == '5') {
        return ''
      }
    },
    formatChooseList() {
      if (this.chooseList.name) {
        return this.chooseList.name + '-' + this.chooseList.series + '-' + this.chooseList.brand
      } else {
        return null
      }
    },
    isSelectable(row) {
      return !this.selectedDeviceIds.includes(row.deviceId);
    }
  }
}
</script>

<style lang="scss" scoped></style>