<template>
  <el-form
    ref="form"
    :rules="rules"
    label-width="100px"
    :model="form"
    class="device-add"
  >
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="产线" prop="proLineId">
          <el-select
            v-model="form.proLineId"
            placeholder="产线"
            style="width: 100%"
            @change="getUnitModule"
          >
            <el-option
              v-for="item in productionLineList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="单元" prop="unitId">
          <el-select
            v-model="form.unitId"
            placeholder="单元"
            style="width: 100%"
            @change="getEqCode"
          >
            <el-option
              v-for="item in unitModuleList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="form.name" placeholder="设备名称"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="设备规格" prop="spec">
          <el-input v-model="form.spec" placeholder="设备规格"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="设备编码" prop="code">
          <el-input
            v-model="form.code"
            placeholder="设备编码"
            disabled
          ></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="基础寿命" prop="baseLife">
          <el-input-number
            v-model="form.baseLife"
            placeholder="基础寿命"
            :min="0"
            :max="999999999"
            :precision="2"
            style="width: 100%"
          ></el-input-number>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="购买价格/万元" prop="price">
          <el-input-number
            v-model="form.price"
            placeholder="购买价格/万元"
            :min="0"
            :max="999999999"
            :precision="2"
            style="width: 100%"
          ></el-input-number>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="供应商" prop="supplier">
          <el-input v-model="form.supplier" placeholder="供应商"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="采购日期" prop="purchaseDate">
          <el-date-picker
            v-model="form.purchaseDate"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            placeholder="采购日期"
            style="width: 100%"
          >
          </el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="生产日期" prop="productDate">
          <el-date-picker
            v-model="form.productDate"
            type="date"
            placeholder="生产日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            style="width: 100%"
          >
          </el-date-picker>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="备注"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="状态" prop="enabled" v-show="isEdit">
          <el-select
            v-model="form.enabled"
            placeholder="状态"
            style="width: 100%"
          >
            <el-option
              v-for="(item, i) in stateList"
              :key="i"
              :label="item.dataName"
              :value="item.dataCode"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="设备图片" prop="imgId">
          <div v-if="deviceImg" style="position: relative" class="img-box">
            <el-image
              :src="deviceImg"
              class="avatar"
              :preview-src-list="srcList"
            >
            </el-image>
            <i
              class="el-icon-circle-close avatar-close-icon"
              @click="clearImg()"
            ></i>
          </div>
          <el-upload
            v-else
            :data="dataObj"
            name="files"
            class="device-uploader"
            :action="uploadApi"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :headers="{ token }"
          >
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>
<script>
import {
  addEquipment,
  getEquipment,
  equipmentUpdate,
  getEqCode,
  getUnitList
} from '@/api/basicConfig'
import { commonUploadPath } from '@/api/app'
import { getToken } from '@/utils/auth'
import moment from 'moment'
export default {
  name: 'ConsumablesAdd',
  data() {
    return {
      form: {
        id: '',
        proLineId: '',
        unitId: '',
        name: '',
        spec: '',
        code: '',
        baseLife: '',
        price: '',
        imgId: '',
        supplier: '',
        purchaseDate: moment().format('YYYY-MM-DD'),
        productDate: moment().format('YYYY-MM-DD'),
        remark: '',
        enabled: 1
      },
      deviceImg: '',
      srcList: [],
      rules: {
        proLineId: [
          { required: true, message: '请选择产线', trigger: 'change' }
        ],
        unitId: [{ required: true, message: '请选择单元', trigger: 'change' }],
        name: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
        spec: [{ required: true, message: '请输入设备规格', trigger: 'blur' }],
        code: [{ required: true, message: '请输入设备编码', trigger: 'blur' }]
      },
      isEdit: false,
      productionLineList: JSON.parse(localStorage.getItem('publicList'))
        .proLineVoList,
      stateList: JSON.parse(localStorage.getItem('publicList')).enabledVoList,
      unitModuleList: [],
      uploadApi: commonUploadPath,
      token: getToken(),
      dataObj: { typeCode: 'equipmentImage' }
    }
  },
  methods: {
    init(id) {
      if (id) {
        this.form.id = id
        this.isEdit = true
        getEquipment({ id }).then((res) => {
          if (res.code === 0) {
            this.form.proLineId = res.data.proLineId
            getUnitList(this.form.proLineId).then((res) => {
              this.unitModuleList = res.data || []
            })
            this.form.unitId = res.data.unitId
            this.form.name = res.data.name
            this.form.spec = res.data.spec
            this.form.code = res.data.code
            this.form.baseLife = res.data.baseLife
            this.form.price = res.data.price
            this.form.imgId = res.data.imgId
            if (res.data.imgId) {
              this.deviceImg = process.env.VUE_APP_VIEW_PIC + res.data.imgId
              this.srcList = [this.deviceImg]
            }
            this.form.supplier = res.data.supplier
            this.form.purchaseDate = res.data.purchaseDate
              ? res.data.purchaseDate
              : ''
            this.form.productDate = res.data.productDate
              ? res.data.productDate
              : ''
            this.form.remark = res.data.remark
            this.form.enabled = res.data.enabled
          }
        })
      } else {
        this.form.id = ''
        this.isEdit = false
      }
    },
    getUnitModule(val) {
      getUnitList(val).then((res) => {
        this.unitModuleList = res.data || []
        this.form.unitId = ''
        this.form.code = ''
      })
    },
    getEqCode() {
      if (this.form.proLineId && this.form.unitId) {
        let sequence = ''
        this.unitModuleList &&
          this.unitModuleList.map((item) => {
            if (item.id === this.form.unitId) {
              sequence = item.sequence
            }
          })
        getEqCode({
          proLineId: this.form.proLineId,
          sequence: sequence
        }).then((res) => {
          this.form.code = res.data
        })
      }
    },
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.isEdit) {
            equipmentUpdate({ ...this.form }).then((res) => {
              if (res.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500
                })
                this.$emit('successSubmit')
              }
            })
          } else {
            addEquipment({ ...this.form }).then((res) => {
              if (res.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500
                })
                this.$emit('successSubmit')
              }
            })
          }
        } else {
          return false
        }
      })
    },
    formClear() {
      this.$refs.form.resetFields()
      this.deviceImg = ''
      this.srcList = []
    },
    handleAvatarSuccess(res) {
      this.form.imgId = res.data[0].id
      this.deviceImg = process.env.VUE_APP_VIEW_PIC + res.data[0].id
      this.srcList = [this.deviceImg]
    },
    clearImg() {
      this.deviceImg = ''
      this.srcList = []
      this.form.imgId = ''
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === ('image/jpeg' || 'image/png')
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG / PNG格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>
<style lang="scss">
.device-add {
  .device-uploader {
    width: 178px;
    height: 178px;
    display: block;
    .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .el-upload:hover {
      border-color: #409eff;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
  }
}
</style>
<style lang="scss" scoped>
.img-box {
  border: 1px dashed #d9d9d9;
  .avatar {
    width: 100%;
    cursor: pointer;
  }
  .avatar-close-icon {
    font-size: 24px;
    position: absolute;
    right: -10px;
    top: -10px;
    cursor: pointer;
  }
}
</style>
