<!--suppress ALL -->
<template>
  <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" append-to-body :close-on-click-modal="false">
    <el-form ref="dataForm" :rules="rules" :model="factoryForm" label-well-code="right" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="厂家名称" prop="name">
            <el-input v-model.trim="factoryForm.name" :disabled="isEditMode" type="text" placeholder="必填"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开户行" prop="bank">
            <el-input v-model.trim="factoryForm.bank" type="text" placeholder="必填"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="厂家联系人" prop="personName">
            <el-input v-model.trim="factoryForm.personName" type="text" placeholder="必填"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="账号" prop="taxNumber">
            <el-input v-model.trim="factoryForm.taxNumber" type="text" placeholder="必填"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="地址" prop="address">
            <el-input v-model.trim="factoryForm.address" type="text" placeholder="必填"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="在产设备" prop="productingDevice">
            <el-select v-model="factoryForm.productingDevice" filterable multiple placeholder="在产设备" clearable value="">
              <el-option
                v-for="item in deviceList"
                :key="item.id"
                :label="item.productName"
                :value="item.productName"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="电话" prop="phone">
            <el-input v-model.trim="factoryForm.phone" type="text" placeholder="必填"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备报价表" >
            <el-upload
              :limit="1"
              :show-file-list="false"
              :http-request="uploadFile"
              :file-list="fileList"
              action="string"
              accept=".xls,.xlsx"
              class="edit_btn">
              <el-button slot="trigger" size="small">选择文件</el-button>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="saveData">提交</el-button>
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>

import { addFactory, updateFactory, getDeviceList } from '@/api/factory'
export default {
  name: 'EditFactory',
  data() {
    return {
      dialogFormVisible: false, // 对话框是否显示
      dialogStatus: '', // 对话框类型：create,update
      deviceList: null, // 在产设备列表
      factoryForm: {
        id: '',
        name: '',
        personName: '',
        address: '',
        phone: '',
        bank: '',
        taxNumber: '',
        productingDevice: [],
        equipmentQuotation: ''
      }, // 表单
      equipmentFile: null,
      textMap: {
        update: '编辑',
        create: '新增',
        detail: '详情'
      }, // 表头显示标题
      deviceTypeList: null, // 设备类型列表
      fileList: [],
      rules: {
        name: [{ required: true, message: '厂家名称不能为空', trigger: ['blur', 'change'] }],
        personName: [{ required: true, message: '厂家联系人不能为空', trigger: ['blur', 'change'] }],
        address: [{ required: true, message: '地址不能为空', trigger: ['blur', 'change'] }],
        phone: [{ required: true, message: '电话不能为空', trigger: ['blur', 'change'] }],
        bank: [{ required: true, message: '开户行不能为空', trigger: ['blur', 'change'] }],
        taxNumber: [{ required: true, message: '账号不能为空', trigger: ['blur', 'change'] }],
        productingDevice: [{ required: true, message: '请选择在产设备', trigger: 'change' }]
      }, // 前端校验规则
      isEditMode: false
    }
  },
  watch: {
  },
  mounted() {
    this.fetchDeviceList() // 获取在产设备列表
  },
  methods: {
    // 初始化对话框
    initDialog: function(dialogStatus, dialogFormVisible, row = null) {
      this.dialogStatus = dialogStatus
      this.dialogFormVisible = dialogFormVisible
      if (dialogStatus === 'create') { // 如果是新增，清除验证
        this.resetForm()
        this.isEditMode = false
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      } else if (dialogStatus === 'update') { // 如果是修改，将row中数据填写到输入框中
        this.factoryForm = {
          id: row.id,
          name: row.name,
          personName: row.personName,
          address: row.address,
          phone: row.phone,
          bank: row.bank,
          taxNumber: row.taxNumber,
          productingDevice: row.productingDevice.split(','),
          equipmentQuotation: row.equipmentQuotation
        }
        this.equipmentFile = null
        this.isEditMode = true
      }
    },
    // 重置表单
    resetForm() {
      this.equipmentFile = null
      this.factoryForm = {
        name: '',
        personName: '',
        address: '',
        phone: '',
        bank: '',
        taxNumber: '',
        productingDevice: [],
        equipmentQuotation: ''
      }
    },
    // 保存数据
    saveData: function() {
      console.log('!!!!!!!!!!!!!!!!!!!!!')
      console.log(this.factoryForm)
      console.log(this.equipmentFile)
      if (this.dialogStatus === 'update') {
        this.updateData()
      } else if (this.dialogStatus === 'create') {
        this.createData()
      }
    },

    // 新增数据
    createData: function() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addFactory(this.factoryForm.name, this.factoryForm.personName, this.factoryForm.address,
            this.factoryForm.phone, this.factoryForm.bank, this.factoryForm.taxNumber,
            this.factoryForm.productingDevice.join(','), this.factoryForm.equipmentQuotation, this.equipmentFile
          ).then(response => {
            if (response.code === 200) {
              this.$confirm('新增成功，是否继续新增?', '提示', {
                confirmButtonText: '是',
                cancelButtonText: '否',
                type: 'info'
              }).then(() => {
                this.resetForm()
                this.$nextTick(() => {
                  this.$refs['dataForm'].clearValidate()
                })
              }).catch(() => {
                this.$emit('watchChild')
                this.dialogFormVisible = false
              })
            }
          })
        }
      })
    },
    // 修改数据
    updateData: function() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateFactory(this.factoryForm.id, this.factoryForm.name, this.factoryForm.personName, this.factoryForm.address,
            this.factoryForm.phone, this.factoryForm.bank, this.factoryForm.taxNumber,
            this.factoryForm.productingDevice, this.factoryForm.equipmentQuotation, this.equipmentFile).then(response => {
            if (response.code === 200) {
              this.$message.success('修改成功')
              this.$emit('watchChild')
              this.dialogFormVisible = false
            }
          })
        }
      })
    },
    // 选择文件上传
    uploadFile(param) {
      // 判断文件大小是否符合要求
      const _file = param.file
      const isLt5M = _file.size / 1024 / 1024 < 5
      if (!isLt5M) {
        this.$message.error('请上传5M以下的excel文件')
        return false
      }
      // 全屏加载动画
      const loading = this.$loading({
        lock: true,
        text: '导入中,请稍后...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      this.equipmentFile = _file
      this.factoryForm.equipmentQuotation = this.equipmentFile.name
      this.fileList = []
      loading.close() // 关闭加载动画
    },
    // 获取在产设备列表
    fetchDeviceList() {
      getDeviceList().then(response => {
        this.deviceList = response.data
      })
    },
    cancel: function() {
      this.dialogFormVisible = false
      this.$emit('watchChild')
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .el-select{
    width: 100%;
  }
  .el-date-editor{
    width: 100%;
  }
</style>
