<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="选择搜索条件">
        <el-select v-model="queryParams.searchField" placeholder="请选择搜索条件" clearable>
          <el-option
            v-for="dict in dict.type.buyer_device_search_fields"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="queryParams.keyword"
          placeholder="请输入关键词搜索"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="购入时间" prop="buyDate">
        <el-date-picker
          clearable
          v-model="queryParams.buyDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择购入时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="专用设备" prop="professionalDevice">
        <el-select v-model="queryParams.professionalDevice"
                   style="width: 120px" placeholder="请选择是否" clearable>
          <el-option
            v-for="dict in dict.type.common_true_false"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备状态">
        <el-select v-model="queryParams.status" style="width: 120px" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.common_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['buyer:device:add']"
        >新增设备
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-upload
          ref="fileUpload"
          class="upload-demo"
          :action="uploadUrl"
          multiple
          :headers="headers"
          :on-error="handleUploadError"
          :before-upload="handleBeforeUpload"
          :on-success="handleUploadSuccess"
          :on-exceed="handleExceed"
          :limit="limit"
          :show-file-list="false"
          :file-list="fileList"
        >
          <el-button
            type="primary"
            size="mini"
            v-hasPermi="['buyer:device:add']"
          >导入Excel
          </el-button>
        </el-upload>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          size="mini"
          @click="handleExport"
        >下载EXCEL模板
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['buyer:device:remove']"
        >批量删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table stripe v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设备编码" align="center" prop="code" />
      <el-table-column label="设备名称" align="center" prop="name" />
      <el-table-column label="原值（元）" align="center" prop="originalValue" />
      <el-table-column label="残值率（%）" align="center" prop="crippleValueRate" />
      <el-table-column label="购入时间" align="center" prop="buyDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.buyDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="生产单位" align="center" prop="productionUnit" />
      <el-table-column label="折旧年限" align="center" prop="depreciableLife" />
      <el-table-column label="专用设备" align="center" prop="professionalDevice">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.common_true_false" :value="scope.row.professionalDevice" />
        </template>
      </el-table-column>
      <el-table-column label="设备状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.common_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['buyer:device:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['buyer:device:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改企业信息管理设备对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="设备编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入设备编码" />
        </el-form-item>
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="原值（元）" prop="originalValue">
          <el-input v-model="form.originalValue" type="number" placeholder="请输入原值" />
        </el-form-item>
        <el-form-item label="残值率（%）" prop="crippleValueRate">
          <el-input v-model="form.crippleValueRate" type="number" placeholder="请输入残值率" />
        </el-form-item>
        <el-form-item label="购入时间" prop="buyDate">
          <el-date-picker
            clearable
            v-model="form.buyDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择购入时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="生产单位" prop="productionUnit">
          <el-input v-model="form.productionUnit" placeholder="请输入生产单位" />
        </el-form-item>
        <el-form-item label="折旧年限" prop="depreciableLife">
          <el-input v-model="form.depreciableLife" type="number" placeholder="请输入折旧年限" />
        </el-form-item>
        <el-form-item label="专用设备" prop="professionalDevice">
          <el-radio-group v-model="form.professionalDevice">
            <el-radio
              v-for="dict in dict.type.common_true_false"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="设备状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.common_status"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="停用日期" prop="stopDate" v-if="form.status === '2'">
          <el-date-picker
            clearable
            v-model="form.stopDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择停用日期"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDevice, getDevice, delDevice, addDevice, updateDevice, checkDeviceExits } from '@/api/buyer/device'
import { getToken } from '@/utils/auth'

export default {
  name: 'Device',
  dicts: [
    'buyer_device_search_fields',
    'common_true_false',
    'common_status'
  ],
  data() {
    let checkOriginalValue = (rule, value, callback) => {
      if (parseInt(value) < parseInt(this.form.crippleValueRate)) {
        callback(new Error('原值应大于残值'))
      } else {
        callback()
      }
    }
    let checkStopDate = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择停用时间'))
      } else {
        callback()
      }
    }
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 企业信息管理设备表格数据
      deviceList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        searchField: null,
        keyword: null,
        buyDate: null,
        professionalDevice: null,
        status: null,
        stopDate: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        code: [
          { required: true, message: '请填写设备编码', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请填写设备名称', trigger: 'blur' }
        ],
        originalValue: [
          { required: true, message: '请填写原值', trigger: 'blur' },
          { required: true, validator: checkOriginalValue, trigger: 'blur' },
          { pattern: /^[1-9\.]\d*|0$/, message: '原值不能为负数',trigger: 'blur'}
        ],
        crippleValueRate: [
          { required: true, message: '请填写残值率', trigger: 'blur' },
          { pattern: /^(?:0|[1-9][0-9]?|100)(\.[0-9]{0,2})?$/, message: '残值率范围在0-100有效',trigger: 'blur'}
        ],
        buyDate: [
          { required: true, message: '请选择购入时间', trigger: 'blur' }
        ],
        productionUnit: [
          { max: 200, message: "名称限制200个字符", trigger: "change" }
        ],
        depreciableLife: [
          { required: true, message: '请填写折旧年限', trigger: 'blur' },
          { pattern: /^[1-9]\d*|0$/, message: '折旧年限不能为负数',trigger: 'blur'}
        ],
        professionalDevice: [
          { required: true, message: '请选择是否专用设备', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择设备状态', trigger: 'blur' }
        ],
        stopDate: [
          { validator: checkStopDate, trigger: 'blur' }
        ]
      },
      fileList: [],
      uploadUrl: process.env.VUE_APP_BASE_API + '/buyer/device/importTable',
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      fileType: ['xls', 'xlsx', 'csv'],
      limit: 1
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询企业信息管理设备列表 */
    getList() {
      this.loading = true
      listDevice(this.addSearchField(this.queryParams, this.queryParams.searchField, this.queryParams.keyword)).then(response => {
        this.deviceList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remarks: null,
        delFlag: null,
        deptId: null,
        code: null,
        name: null,
        originalValue: null,
        crippleValueRate: null,
        buyDate: null,
        productionUnit: null,
        depreciableLife: null,
        professionalDevice: null,
        status: '0',
        stopDate: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams= {
        pageNum: 1,
          pageSize: 10,
          searchField: null,
          keyword: null,
          buyDate: null,
          professionalDevice: null,
          status: null,
          stopDate: null
      }
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.form.id = null
      this.title = '添加企业信息管理设备'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getDevice(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改企业信息管理设备'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDevice(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            checkDeviceExits({ code: this.form.code }).then(res => {
              if (res.repeat) {
                this.$modal.msgWarning(res.msg)
              } else {
                addDevice(this.form).then(response => {
                  this.$modal.msgSuccess('新增成功')
                  this.open = false
                  this.getList()
                })
              }
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除企业信息管理设备选中的数据项？').then(function() {
        return delDevice(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('buyer/device/downTemplate', {}, `科研设备台账模板.xlsx`)
    },
    // 导入失败
    handleUploadError(err) {
      this.$modal.msgError('导入失败，请重试')
      this.$modal.closeLoading()
    },
    // 导入前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      if (this.fileType) {
        let fileExtension = ''
        if (file.name.lastIndexOf('.') > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
        }
        const isTypeOk = this.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) return true
          if (fileExtension && fileExtension.indexOf(type) > -1) return true
          return false
        })
        if (!isTypeOk) {
          this.$modal.msgError(`文件格式不正确, 请导入${this.fileType.join('/')}格式文件!`)
          return false
        }
      }
      // 校检文件大小
      this.$modal.loading('正在导入文件，请稍候...')
      return true
    },
    // 导入成功回调
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        this.$modal.closeLoading()
        this.$modal.msgSuccess('导入成功')
        this.$refs.fileUpload.handleRemove(file)
        this.getList()
      } else {
        this.$modal.closeLoading()
        this.$modal.msgError(res.msg)
        this.$refs.fileUpload.handleRemove(file)
      }
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`导入文件数量不能超过 ${this.limit} 个!`)
    }
  }
}
</script>
