<template>
  <div class="app-container">
    <!--头部选项-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <el-input v-model="query.equipmentNum" placeholder="请输入设备编号" style="width: 200px;" class="filter-item" clearable @keyup.enter.native="crud.toQuery" />
        <el-input v-model="query.customName" placeholder="请输入新名称" style="width: 200px;" class="filter-item" clearable @keyup.enter.native="crud.toQuery" />
        <el-input v-model="query.unitPrice" placeholder="请输入单价" style="width: 150px;" class="filter-item" clearable @keyup.enter.native="crud.toQuery" />
        <!-- <el-cascader
          ref="queryCascader"
          v-model="query.classCode"
          class="filter-item"
          :options="dicAssetTree"
          :props="{ value: 'id', label: 'name', checkStrictly: true }"
          :show-all-levels="false"
          clearable
          filterable
          placeholder="选择设备名称"
          @change="queryCascaderChange"
        /> -->
        <el-select v-model="query.measureState" placeholder="请选择计量状态" style="width: 150px;" class="filter-item" clearable>
          <el-option v-for="item in measureStateList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-select v-model="query.ifOverdue" placeholder="请选择超期状态" style="width: 150px;" class="filter-item" clearable>
          <el-option v-for="item in ifOverdueList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-select v-model="query.useState" placeholder="请选择使用状况" style="width: 150px;" class="filter-item" clearable>
          <el-option v-for="item in useStateList" :key="item.value" :label="item.label" :value="item.id" />
        </el-select>
        <TreeSelect ref="queryTreeSelect" :props="treeSelectProps" placeholder-select="请选择使用部门" :options="departmentTree" :clearable="true" :accordion="true" class="filter-item" @getValue="getDepartmentId($event)" />
        <query :crud="crud" />
      </div>
      <crud :permission="permission">
        <el-upload
          slot="right"
          class="filter-item"
          :show-file-list="false"
          :before-upload="beforeUpload"
          accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          action=""
        >
          <el-button type="primary" icon="el-icon-upload">
            上传数据
          </el-button>
        </el-upload>
        <el-button slot="right" class="filter-item" type="primary" icon="el-icon-edit-outline" :disabled="crud.selections.length !== 1" @click="moveAdministration(crud.selections)">
          领用、借用管理
        </el-button>
        <el-button slot="right" class="filter-item" icon="el-icon-download" type="warning" @click="exportExcel">
          导出数据
        </el-button>
      </crud>
    </div>
    <!--表格内容-->
    <CustomTable ref="customTable" :col-configs="colConfigs" :selection="false" :columns="columns" :crud="crud" :row-class-name="getTableRowClassName">
      <el-table-column slot="operation" align="center" width="100" label="操作">
        <template slot-scope="scope">
          <Edit :permission="permission" :data="scope.row" :disabled-edit="false" />
        </template>
      </el-table-column>
    </CustomTable>
    <pagination />
    <div style="float: right;margin-top:-18px;">
      <div style="width: 50px;float:left;margin-left: 20px;">
        预警：
      </div>
      <div class="identification" style="background-color:#FF8C00;" />
      <div style="width: 80px;float:left;margin-left: 50px;">
        超期：
      </div>
      <div class="identification" style="background-color:red;" />
    </div>
    <el-dialog :before-close="crud.cancelCU" :visible="crud.status.editor > 0" :title="crud.status.title">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" inline>
        <el-tabs v-model="activeName">
          <el-tab-pane label="基本信息" name="first">
            <el-form-item label="资产编号：" prop="assetNum">
              <el-input v-model="form.assetNum" placeholder="请填写资产编号" clearable type="text" />
            </el-form-item>
            <el-form-item label="设备编号：" prop="equipmentNum">
              <el-input v-model="form.equipmentNum" style="width: 215px;" placeholder="请填写资产编号" clearable type="text" />
            </el-form-item>
            <el-form-item label="新名称：" prop="customName">
              <el-input v-model="form.customName" placeholder="请填写新名称" clearable type="text" />
            </el-form-item>
            <el-form-item label="设备名称：" prop="classCode">
              <el-cascader
                ref="cascaders"
                v-model="parentId"
                :options="dicAssetTree"
                :props="{ value: 'id', label: 'name', checkStrictly: true }"
                :show-all-levels="false"
                clearable
                filterable
                placeholder="选择设备名称"
                style="width: 100%"
                @change="cascaderChange"
              />
            </el-form-item>
            <el-form-item label="品牌：" prop="brand">
              <el-input v-model="form.brand" placeholder="请填写品牌" clearable type="text" />
            </el-form-item>
            <el-form-item label="规格型号：" prop="specifications">
              <el-input v-model="form.specifications" style="width: 215px;" placeholder="请填写规格型号" clearable type="text" />
            </el-form-item>
            <el-form-item label="出厂编号：" prop="factoryNum">
              <el-input v-model="form.factoryNum" placeholder="请填写出厂编号" clearable type="text" />
            </el-form-item>
            <el-form-item label="存放地点：" prop="location">
              <el-input v-model="form.location" style="width: 215px;" placeholder="请填写存放地点" clearable type="text" />
            </el-form-item>
            <el-form-item label="购置日期：" prop="achieveDate">
              <el-date-picker v-model="form.achieveDate" style="width: 215px;" value-format="yyyy-MM-dd" clearable type="date" placeholder="选择购置日期" />
            </el-form-item>
            <el-form-item label="投入使用日期：" prop="commissioningDate">
              <el-date-picker v-model="form.commissioningDate" value-format="yyyy-MM-dd" style="width: 215px;" clearable type="date" placeholder="选择投入使用日期" />
            </el-form-item>
            <el-form-item label="备注：" prop="remark">
              <el-input v-model="form.remark" style="width: 560px;" maxlength="200" type="textarea" placeholder="请填写备注信息" />
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="费用信息" name="second">
            <el-form-item label="设备数量：" prop="quantity">
              <el-input v-model="form.quantity" placeholder="请填写设备数量" clearable type="number" />
            </el-form-item>
            <el-form-item label="单价：" prop="unitPrice">
              <el-input v-model="form.unitPrice" placeholder="请填写设备单价" clearable type="number" />
            </el-form-item>
            <el-form-item label="总价：" prop="totalPrice">
              <el-input v-model="form.totalPrice" placeholder="请填写设备总价" clearable type="number" />
            </el-form-item>
            <el-form-item label="价值类型：" prop="valueType">
              <el-select v-model="form.valueType" placeholder="请选择价值类型" clearable>
                <el-option v-for="item in valueTypeList" :key="item.value" :label="item.label" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="资产来源：" prop="assetSource">
              <el-select v-model="form.assetSource" placeholder="请选择资产来源" clearable>
                <el-option v-for="item in assetSourceList" :key="item.value" :label="item.label" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="经费来源：" prop="fundingSource">
              <el-select v-model="form.fundingSource" placeholder="请选择经费来源" clearable>
                <el-option v-for="item in fundingSourceList" :key="item.value" :label="item.label" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="采购组织形式：" prop="procurementType">
              <el-select v-model="form.procurementType" placeholder="请选择采购组织形式" clearable>
                <el-option v-for="item in procurementTypeList" :key="item.value" :label="item.label" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="累计折扣：" prop="discount">
              <el-input v-model="form.discount" placeholder="请填写累计折扣" clearable type="number" />
            </el-form-item>
            <el-form-item label="账面净值：" prop="netWorth">
              <el-input v-model="form.netWorth" placeholder="请填写账面净值" clearable type="number" />
            </el-form-item>
            <el-form-item label="折旧状态：" prop="depreciationState">
              <el-select v-model="form.depreciationState" placeholder="请选择折旧状态" clearable>
                <el-option v-for="item in depreciationStateList" :key="item.value" :label="item.label" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="是否入账：" prop="bookedState">
              <el-select v-model="form.bookedState" placeholder="请选择入账状态" clearable>
                <el-option v-for="item in bookedStateList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="使用信息" name="third">
            <el-form-item label="使用科室：" prop="departmentId">
              <TreeSelect
                v-if="crud.status.editor > 0"
                :props="treeSelectProps"
                :options="departmentTree"
                :value="departmentId"
                :clearable="true"
                :accordion="true"
                style="width: 215px;"
                @getValue="getDepartmentValue($event)"
              />
            </el-form-item>
            <el-form-item label="使用人：" prop="principal">
              <el-select v-model="form.principal" filterable placeholder="请选择使用人" clearable>
                <el-option v-for="item in userList" :key="item.id" :label="item.nickname" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="产权单位：" prop="propertyUnit">
              <el-input v-model="form.propertyUnit" placeholder="请填写产权单位" clearable type="text" />
            </el-form-item>
            <el-form-item label="使用年限：" prop="useYear">
              <el-input v-model="form.useYear" placeholder="请填写使用年限" clearable type="number" />
            </el-form-item>
            <el-form-item label="使用状况：" prop="useState">
              <el-select v-model="form.useState" placeholder="请选择使用状况" clearable>
                <el-option v-for="item in useStateList" :key="item.value" :label="item.label" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="使用方向：" prop="useDirection">
              <el-select v-model="form.useDirection" placeholder="请选择使用方向" clearable>
                <el-option v-for="item in useDirectionList" :key="item.value" :label="item.label" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="使用用途：" prop="usePurpose">
              <el-select v-model="form.usePurpose" placeholder="请选择使用用途" clearable>
                <el-option v-for="item in usePurposeList" :key="item.value" :label="item.label" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="计量状态：" prop="measureState">
              <el-select v-model="form.measureState" placeholder="请选择计量状态" clearable @change="changeMeasure">
                <el-option v-for="item in measureStateList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item v-show="ifMeasure" label="校验周期：" prop="earlyWarningCycle">
              <el-select v-model="form.earlyWarningCycle" placeholder="请选择校验周期" clearable>
                <el-option v-for="item in cycleList" :key="item.value" :label="item.label" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item v-show="ifMeasure" label="去年校验日期：" prop="checkLastDate">
              <el-date-picker v-model="form.checkLastDate" style="width: 215px;" value-format="yyyy-MM-dd" clearable type="date" placeholder="选择去年校验日期" />
            </el-form-item>
            <el-form-item v-show="ifMeasure" label="今年校验日期：" prop="checkDate">
              <el-date-picker v-model="form.checkDate" style="width: 215px;" value-format="yyyy-MM-dd" clearable type="date" placeholder="选择今年校验日期" />
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="crud.cancelCU">
          取 消
        </el-button>
        <el-button type="primary" @click="crud.submitCU">
          确 认
        </el-button>
      </div>
    </el-dialog>
    <move v-if="moveDialogVisible" ref="move" :instrument-id="instrumentId" :department-tree="departmentTree" @close="resetChecks" />
  </div>
</template>

<script>
import CRUD, { form, header, presenter } from '@/components/Crud/crud'
import Crud from '@/components/Crud'
import Query from '@/components/Crud/Query'
import Edit from '@/components/Crud/Edit'
import CustomTable from '@/components/Crud/Table'
import Pagination from '@/components/Crud/Pagination'
import CrudInstrument from '@/api/instrument'
import TreeSelect from '@/components/TreeSelect'
// import { uploadInstrumentData } from '@/api/file'
import { getDicDataListByTypeName } from '@/api/dic_data'
import { getDepartmentTreeList, getAssetTreeFn } from '@/api/common'
import Move from './components/Move'
import { downloadFile, parseTime } from '@/utils'

// crud交由presenter持有
const defaultCrud = presenter(CRUD({
  title: '仪器设备',
  url: '/instrument/list',
  orderBy: ['id asc'],
  crudMethod: { ...CrudInstrument }
}))

// 设置初始form
const defaultForm = form({
  id: null,
  assetNum: '',
  equipmentNum: '',
  customName: '',
  equipmentName: '',
  classCode: '',
  brand: '',
  specifications: '',
  factoryNum: '',
  location: '',
  achieveDate: '',
  commissioningDate: '',
  remark: '',
  quantity: '',
  unitPrice: '',
  totalPrice: '',
  valueType: '',
  assetSource: '',
  fundingSource: '',
  procurementType: '',
  discount: '',
  netWorth: '',
  depreciationState: '',
  bookedState: '',
  departmentId: '',
  principal: '',
  propertyUnit: '',
  useState: '',
  useDirection: '',
  useYear: '',
  usePurpose: '',
  measureState: '',
  earlyWarningCycle: '',
  checkLastDate: '',
  checkDate: ''
})

// 自定义模板内容
const PrefixPlusText = {
  props: ['value', 'functions'],
  template: `
    <el-tag v-if="functions(value) === '在用'" effect="dark"><span v-html="functions(value)"></span></el-tag>
    <el-tag v-else-if="functions(value) === '停用'" type="danger" effect="dark"><span v-html="functions(value)"></span></el-tag>
    <el-tag v-else-if="functions(value) === '待报废'" type="warning" effect="dark"><span v-html="functions(value)"></span></el-tag>
    <el-tag v-else type="info" effect="dark"><span v-html="functions(value)"></span></el-tag>
  `
}

export default {
  name: 'InstrumentList',
  components: { Pagination, Query, Crud, CustomTable, Edit, TreeSelect, Move },
  mixins: [defaultCrud, defaultForm, header()],
  data() {
    return {
      colConfigs: [
        { prop: 'equipmentNum', label: '设备编号', align: 'center' },
        { prop: 'customName', label: '新名称', align: 'center' },
        { prop: 'brand', label: '品牌', align: 'center' },
        { prop: 'factoryNum', label: '出厂编号', align: 'center' },
        { prop: 'achieveDate', label: '购置时间', align: 'center' },
        { prop: 'quantity', label: '数量', align: 'center' },
        { prop: 'unitPrice', label: '单价', align: 'center' },
        { prop: 'totalPrice', label: '总价', align: 'center' },
        { prop: 'departmentId', label: '使用部门', align: 'center', formatter: this.formatter.formatterDepartmentName },
        { prop: 'principal', label: '使用人', align: 'center', formatter: this.formatter.formatterNickName },
        { prop: 'useState', label: '使用状况', align: 'center', component: PrefixPlusText, componentFunction: this.formatterDicData },
        { slot: 'operation' }
      ],
      permission: {
        add: ['instrument:add'],
        edit: ['instrument:update'],
        del: ['instrument:delete']
      },
      dicAssetTree: [],
      parentId: [],
      activeName: 'first',
      valueTypeList: [],
      assetSourceList: [],
      fundingSourceList: [],
      procurementTypeList: [],
      depreciationStateList: [],
      bookedStateList: [
        { label: '已入账', value: true },
        { label: '未入账', value: false }
      ],
      departmentTree: [],
      departmentId: 0,
      treeSelectProps: {
        children: 'children',
        label: 'name',
        value: 'id'
      },
      userList: this.$store.getters.allUser,
      useStateList: [],
      useDirectionList: [],
      usePurposeList: [],
      measureStateList: [
        { value: true, label: '计量' },
        { value: false, label: '非计量' }
      ],
      ifOverdueList: [
        { value: 0, label: '正常' },
        { value: 1, label: '预警' },
        { value: 2, label: '超期' }
      ],
      cycleList: [],
      rules: {
        departmentId: [
          { required: true, message: '请选择使用部门', trigger: 'blur' }
        ],
        quantity: [
          { required: true, message: '请填写设备数量', trigger: 'blur' }
        ],
        unitPrice: [
          { required: true, message: '请填写设备单价', trigger: 'blur' }
        ],
        totalPrice: [
          { required: true, message: '请填写设备总价', trigger: 'blur' }
        ],
        useState: [
          { required: true, message: '请选择使用状况', trigger: 'blur' }
        ],
        useYear: [
          { required: true, message: '请填写使用年限', trigger: 'blur' }
        ],
        measureState: [
          { required: true, message: '请选择计量状态', trigger: 'blur' }
        ],
        principal: [
          { required: true, message: '请选择使用人', trigger: 'blur' }
        ],
        propertyUnit: [
          { required: true, message: '请输入产权单位', trigger: 'blur' }
        ]
      },
      instrumentId: 0,
      moveDialogVisible: false,
      ifMeasure: false
    }
  },
  mounted() {
    this.initDicDataList()
    this.getDepartmentTree()
    this.getDicAssetTreeList()
  },
  methods: {
    // 获取固定资产代码列表
    getDicAssetTreeList() {
      getAssetTreeFn().then(data => {
        this.dicAssetTree = data
      })
    },
    // 刷新之后重置部门查询的值
    [CRUD.HOOK.afterResetQuery]() {
      if (this.$refs.queryTreeSelect) {
        this.$refs.queryTreeSelect.clearHandle()
      }
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU]() {
      this.activeName = 'first'
    },
    // 编辑框打开后做的操作
    [CRUD.HOOK.afterToEdit](crud, form) {
      this.departmentId = form.departmentId
      this.ifMeasure = form.measureState
    },
    // 编辑框取消后的操作
    [CRUD.HOOK.afterEditCancel]() {
      this.departmentId = 0
      this.ifMeasure = false
    },
    // EXCEL上传方法
    beforeUpload(file) {
      const isExcel = file.type === 'application/vnd.ms-excel' || file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      if (!isExcel) {
        this.$notify.error('只能上传xls/xlsx格式的文件')
        return false
      }
      const fd = new FormData()
      fd.append('file', file)
      fd.append('type', 3)
    //   uploadInstrumentData(fd).then(() => {
    //     this.$notify.success('导入数据成功。')
    //     this.crud.toQuery()
    //   })
    },
    // 资产代码级联选择框改变事件
    cascaderChange() {
      this.$nextTick(() => {
        const checkNode = this.$refs.cascaders.getCheckedNodes()
        if (checkNode && checkNode[0]) {
          this.form.equipmentName = checkNode[0].label
          this.form.classCode = checkNode[0].value
        } else {
          this.form.equipmentName = ''
          this.form.classCode = ''
        }
      })
    },
    queryCascaderChange() {
      this.$nextTick(() => {
        const checkNode = this.$refs.queryCascader.getCheckedNodes()
        if (checkNode && checkNode[0]) {
          this.query.classCode = checkNode[0].value
        } else {
          this.query.classCode = ''
        }
      })
    },
    // 初始化字典相关列表
    initDicDataList() {
      // 价值类型列表
      getDicDataListByTypeName({ typeCode: 'value_type' }).then(data => { this.valueTypeList = data })
      // 资产来源列表
      getDicDataListByTypeName({ typeCode: 'asset_source' }).then(data => { this.assetSourceList = data })
      // 经费来源列表
      getDicDataListByTypeName({ typeCode: 'funding_source' }).then(data => { this.fundingSourceList = data })
      // 采购组织形式列表
      getDicDataListByTypeName({ typeCode: 'procurement_type' }).then(data => { this.procurementTypeList = data })
      // 折旧状态列表
      getDicDataListByTypeName({ typeCode: 'depreciation_state' }).then(data => { this.depreciationStateList = data })
      // 使用状况列表
      getDicDataListByTypeName({ typeCode: 'use_state' }).then(data => { this.useStateList = data })
      // 使用方向列表
      getDicDataListByTypeName({ typeCode: 'use_direction' }).then(data => { this.useDirectionList = data })
      // 使用用途列表
      getDicDataListByTypeName({ typeCode: 'use_purpose' }).then(data => { this.usePurposeList = data })
      // 预警周期列表
      getDicDataListByTypeName({ typeCode: 'verification_cycle' }).then(data => { this.cycleList = data })
    },
    // 部门选择回调事件
    getDepartmentValue(value) {
      this.form.departmentId = value
    },
    // 获取部门树形结构
    getDepartmentTree() {
      getDepartmentTreeList().then(data => {
        this.departmentTree = data
      })
    },
    //  关闭所有弹窗
    resetChecks() {
      this.moveDialogVisible = false
    },
    //  给检索条件赋值（部门主键）
    getDepartmentId(value) {
      this.query.departmentId = value === 0 ? '' : value
    },
    //  更改行超期、预警字体颜色
    getTableRowClassName({ row }) {
      let color = ''
      switch (row.ifOverdue) {
        case 2:
          color = 'table-row-color-red'
          break
        case 1:
          color = 'table-row-color-orange'
          break
        default:
          color = ''
          break
      }
      return color
    },
    //  仪器设备领用、借用管理
    moveAdministration(selections) {
      if (selections instanceof Array) {
        this.moveDialogVisible = true
        this.instrumentId = selections[0].id
        this.$nextTick(() => {
          this.$refs.move.init()
        })
      }
    },
    //  选择计量状态变动
    changeMeasure(val) {
      this.ifMeasure = val
    },
    // 导出Excel
    exportExcel() {
      CrudInstrument.exportExcel(this.crud.query).then(data => {
        downloadFile(data, parseTime(new Date()) + '-' + this.crud.title + '数据', 'xlsx')
      })
    },
    formatterDicData(cellValue) {
      if (cellValue != null) {
        let label = ''
        this.useStateList.filter(dicData => dicData.id === cellValue).forEach(dicData => {
          label = dicData.label
        })
        return label
      }
      return null
    }
  }
}
</script>
<style>
  input::-webkit-outer-spin-button,
  input::-webkit-inner-spin-button {
    -webkit-appearance: none !important;
    margin: 0;
  }
  .identification{
    width: 30px;
    height:15px;
    display: inline-block;
    border:gray 1px solid;
    border-radius:15px;
    float: left;
  }
</style>
