<template>
  <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" custom-class="dict-dialog" append-to-body>
    <el-form ref="dataForm" :rules="rules" :model="projForm" label-position="lefts" label-width="120px">
      <el-form-item label="项目名称" prop="projectName">
        <el-input v-model.trim="projForm.projectName" :disabled="dialogStatus === 'detail'" type="text" placeholder="必填"/>
      </el-form-item>
      <el-form-item label="项目简称" prop="projectSimpleName">
        <el-input v-model.trim="projForm.projectSimpleName" :disabled="dialogStatus === 'detail'" type="text" placeholder="必填"/>
      </el-form-item>
      <el-form-item label="项目经理" prop="projectManager">
        <el-select v-model="projForm.projectManager" :disabled="dialogStatus === 'detail'" filterable placeholder="项目经理" clearable value="必选">
          <el-option
            v-for="item in principalList"
            :key="item.id"
            :label="item.name"
            :value="item.name"/>
        </el-select>
      </el-form-item>
      <el-form-item label="项目开始日期" prop="projectStartTime">
        <el-date-picker
          v-model="projForm.projectStartTime"
          :disabled="dialogStatus === 'detail'"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          type="date"
          placeholder="请选择开始日期"
          clearable
        />
      </el-form-item>
      <el-form-item label="项目结束日期" prop="projectEndTime">
        <el-date-picker
          v-model="projForm.projectEndTime"
          :disabled="dialogStatus === 'detail'"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          type="date"
          placeholder="请选择结束日期"
          clearable
        />
      </el-form-item>
      <el-form-item label="生产设备类型" prop="devTpeIds">
        <el-select v-model="devTpeIds" :disabled="dialogStatus === 'detail'" filterable placeholder="设备类型" clearable value="必选" multiple>
          <el-option
            v-for="item in deviceTypeList"
            :key="item.id"
            :label="item.productName"
            :value="item.id"/>
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button v-if="dialogStatus !== 'detail'" type="primary" @click="saveData">提交</el-button>
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addProject, updateProject } from '@/api/factoryManager/project'
import { getPrincipalList } from '@/api/devicetype'
import { getDeviceList } from '@/api/factory'
export default {
  name: 'EditProject',
  data() {
    var validatePass2 = (rule, value, callback) => {
      if (!value) {
        callback(new Error('项目结束日期不能为空'))
      } else if (new Date(value).getTime() < new Date(this.projForm.projectStartTime).getTime()) {
        callback(new Error('结束日期应大于开始日期'))
      } else {
        callback()
      }
    }
    return {
      principalList: null, // 项目经理列表
      dialogFormVisible: false, // 对话框是否显示
      dialogStatus: '', // 对话框类型：create,update
      projForm: {
        id: '',
        projectName: '',
        projectSimpleName: '',
        devTpeIds: '',
        projectManager: '',
        projectStartTime: '', // 项目开始日期
        projectEndTime: '' // 项目结束日期
      }, // 表单
      devTpeIds: [],
      details: [], // 字典详情解构
      deviceTypeList: null, // 设备类型列表
      textMap: {
        update: '编辑',
        create: '新增',
        detail: '详情'
      }, // 表头显示标题
      rules: {
        projectStartTime: [{ required: true, message: '项目开始日期不能为空', trigger: 'change' }],
        projectEndTime: [{ validator: validatePass2, required: true, trigger: ['blur', 'change'] }],
        projectName: [{ required: true, message: '项目名称不能为空', trigger: ['blur'] }],
        projectSimpleName: [{ required: true, message: '项目简称不能为空', trigger: ['blur'] }],
        projectManager: [{ required: true, message: '项目经理不能为空', trigger: ['change'] }],
        devTpeIds: [{ required: true, message: '生产设备类型不能为空', trigger: ['blur'] }]
      } // 前端校验规则
    }
  },
  created() {
    this.fetchPrincipalList()
    this.fetchDeviceList()
  },
  methods: {
    fetchDeviceList() {
      getDeviceList().then(response => {
        this.deviceTypeList = response.data
        console.log(this.deviceTypeList)
      })
    },
    // 获取项目经理列表
    fetchPrincipalList() {
      getPrincipalList('pl,pm').then(response => {
        this.principalList = response.data
      })
    },
    // 初始化对话框
    initDialog: function(dialogStatus, dialogFormVisible, row = null) {
      this.dialogStatus = dialogStatus
      this.dialogFormVisible = dialogFormVisible
      // this.fetchPcode()
      if (dialogStatus === 'create') { // 如果是新增，清除验证
        this.resetForm()
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      } else if (dialogStatus === 'update' || dialogStatus === 'detail') { // 如果是修改，将row中数据填写到输入框中
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
        this.projForm = {
          id: row.id,
          projectName: row.projectName,
          projectSimpleName: row.projectSimpleName,
          devTpeIds: row.devTpeIds,
          projectManager: row.projectManager,
          projectStartTime: row.projectStartTime,
          projectEndTime: row.projectEndTime
        }
        this.devTpeIds = row.devTpeIds.split(',')
      }
    },
    // 保存数据
    saveData: function() {
      this.projForm.devTpeIds = ''
      for (var i = 0; i < this.devTpeIds.length; i++) {
        if (i < this.devTpeIds.length - 1) { this.projForm.devTpeIds = this.projForm.devTpeIds + this.devTpeIds[i] + ',' } else { this.projForm.devTpeIds = this.projForm.devTpeIds + this.devTpeIds[i] }
      }
      if (this.dialogStatus === 'update') {
        this.updateData()
      } else if (this.dialogStatus === 'create') {
        this.createData()
      }
    },
    cancel: function() {
      this.dialogFormVisible = false
      this.$emit('watchChild')
    },
    // 重置表单
    resetForm() {
      this.projForm = {
        id: '',
        projectName: '',
        projectSimpleName: '',
        devTpeIds: '',
        projectManager: ''
      }
      this.devTpeIds = []
      this.details = []
    },
    // 新增数据
    createData: function() {
      this.$refs['dataForm'].validate((valid) => {
        console.log(this.projForm)
        if (valid) {
          addProject(this.projForm).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) {
          updateProject(this.projForm).then(response => {
            if (response.code === 200) {
              this.$message.success('修改成功')
              this.$emit('watchChild')
              this.dialogFormVisible = false
            }
          })
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .el-select{
    width: 100%;
  }
  .el-date-editor{
    width: 100%;
  }
</style>
<style rel="stylesheet/scss" lang="scss" >
  .dict-dialog{
    // width:900px;
    .divider{
      height: 5px;
      border-bottom: 1px dashed #e7eaec;
      margin-bottom: 15px;
    }
  }
</style>
