<template>
  <el-dialog :title="textMap[dialogStatus]" :close-on-click-modal="false" :visible.sync="dialogFormVisible" append-to-body>
    <el-form ref="dataForm" :rules="rules" :model="dataForm" label-well-code="right" label-width="110px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="车牌号" prop="plateNumber">
            <el-input v-model.trim="dataForm.plateNumber" :readonly="isEditMode" :disabled="isDetailMode" :maxlength="15" clearable type="text" placeholder="必填" show-word-limit/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="车辆性质" prop="property">
            <el-radio-group v-model="dataForm.property" :disabled="isDetailMode">
              <el-radio v-for="item in carProperties" :key="item.value" :label="item.value">{{ item.name }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属部门" prop="deptid">
            <!--<span v-show="isDetailMode">{{ dataForm.deptName }}</span>-->
            <el-select :disabled="isDetailMode" v-model="dataForm.deptid" placeholder="请选择所属部门" filterable clearable @change="getStaffList">
              <el-option v-for="item in deptList" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
            <!--<dept-select v-show="!isDetailMode" v-model="dataForm.deptid" :dept-show="true" :need-top="true" placeholder="所属组织" @change="fetchStaffList"/>-->
          </el-form-item>
        </el-col>
        <el-col v-if="dataForm.property==='2'" :span="12">
          <el-form-item label="车主" prop="ownerId">
            <!--<span v-show="isDetailMode">{{ dataForm.ownerName }}</span>-->
            <el-select :disabled="isDetailMode" v-model="dataForm.ownerId" placeholder="请选择车主" filterable clearable @change="autoStaffPhone">
              <el-option v-for="item in staffList" :key="item.id" :label="item.name" :value="item.id"/>
            </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="dataForm.phone" :disabled="isDetailMode" type="text" placeholder="联系电话"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model.trim="dataForm.remark" :disabled="isDetailMode" type="text" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div v-show="!isDetailMode" slot="footer" class="dialog-footer">
      <el-button :loading="btnLoading" type="primary" @click="saveData">保存</el-button>
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import DeptSelect from '@/components/DeptSelect'
import { getStaffByDept } from '@/api/staff'
import { addCar, editCar } from '@/api/car'
import { phoneValidator, plateValidator } from '@/utils/validate'
import { getDeptTreeList } from '@/api/dept'
export default {
  name: 'CarAdd',
  components: { DeptSelect },
  data() {
    return {
      dialogFormVisible: false, // 对话框是否显示
      dialogStatus: '', // 对话框类型：create,update,detail
      dataForm: {
        id: '', // id
        plateNumber: '', // 车牌号
        property: '', // 车辆性质
        deptid: '', // 所属部门
        ownerId: '', // 车主
        phone: '', // 车主联系电话
        remark: '', // 备注
        deptName: '', // 部门名称
        ownerName: ''// 车主名
      }, // 表单
      textMap: {
        update: '编辑车辆',
        create: '新增车辆',
        detail: '详情'
      }, // 表头显示标题
      rules: {
        phone: [{ required: true, trigger: ['blur', 'change'], validator: phoneValidator }],
        plateNumber: [{ required: true, trigger: ['blur', 'change'], validator: plateValidator }],
        ownerId: [{ required: true, trigger: ['blur', 'change'], message: '请选择车主' }]
      }, // 前端校验规则
      carProperties: [], // 车辆性质字典值
      staffList: [], // 车主人员列表
      deptList: [],
      isEditMode: false, // 是否编辑模式
      isDetailMode: false, // 是否详情模式
      btnLoading: true // 保存按钮是否不允许点击
    }
  },
  created() {
    this.fetchStaffList()
  },
  methods: {
    // 初始化对话框
    initDialog: function(dialogStatus, dialogFormVisible, row = null) {
      this.btnLoading = false
      this.dialogStatus = dialogStatus
      this.dialogFormVisible = dialogFormVisible
      this.dataForm.controllerLine = ''

      // 从父组件取字典值列表
      this.carProperties = this.$parent.carProperties
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      if (dialogStatus === 'create') { // 如果是新增，清除验证
        this.resetForm()
        this.isEditMode = false
        this.isDetailMode = false
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      } else if (dialogStatus === 'update') { // 如果是修改，将row中数据填写到输入框中
        this.isDetailMode = false
        this.isEditMode = true

        this.dataForm = {
          id: row.id,
          plateNumber: row.plateNumber,
          property: row.property,
          deptid: row.deptid,
          ownerId: row.ownerId,
          phone: row.phone,
          remark: row.remark
        }
        this.getStaffList()
      } else if (dialogStatus === 'detail') {
        this.isDetailMode = true
        this.isEditMode = false

        this.dataForm = {
          id: row.id,
          plateNumber: row.plateNumber,
          property: row.property,
          ownerId: row.ownerId,
          phone: row.phone,
          remark: row.remark,
          deptName: row.deptName,
          ownerName: row.ownerName
        }
        this.getStaffList()
      }
    },
    // 清除数据
    resetForm() {
      this.dataForm = {
        id: '', // id
        plateNumber: '', // 车牌号
        property: '', // 车辆性质
        deptid: '', // 所属部门
        ownerId: '', // 车主
        phone: '', // 车主联系电话
        remark: '', // 备注
        deptName: '', // 部门名称
        ownerName: ''// 车主名
      }

      this.btnLoading = false
    },
    fetchStaffList() {
      getDeptTreeList().then(response => {
        const list = response.data.list
        for (let i = 0; i < list.length; i++) {
          if (list[i].pid !== '-1' && list[i].pid !== '0') {
            this.deptList.push(list[i])
          }
        }
      })
      getStaffByDept({ deptId: this.dataForm.deptid }).then(response => {
        this.staffList = response.data
        console.log(response)
      })
    },
    getStaffList(){
      getStaffByDept({ deptId: this.dataForm.deptid }).then(response => {
        this.staffList = response.data
        console.log(response)
      })
    },
    autoStaffPhone() {
      const id = this.dataForm.ownerId
      if (id !== '') {
        const selectedStaff = this.staffList.filter(item => {
          if (item.id.indexOf(id) >= 0) {
            return item
          }
        })
        this.dataForm.phone = selectedStaff[0].phone
      } else {
        this.dataForm.phone = ''
      }
    },
    // 保存数据
    saveData: function() {
      this.btnLoading = true

      if (this.dialogStatus === 'update') {
        this.updateData()
      } else if (this.dialogStatus === 'create') {
        this.createData()
      }
    },
    // 新增数据
    createData: function() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addCar(this.dataForm).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
              })
            } else {
              this.$message.error(response.message)
              this.btnLoading = false
            }
          }).catch(() => {
            this.btnLoading = false
          })
        } else {
          this.btnLoading = false
        }
      })
    },
    // 修改数据
    updateData: function() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          editCar(this.dataForm).then(response => {
            if (response.code === 200) {
              this.$message.success('修改成功')
              this.cancel()
            } else {
              this.btnLoading = false
            }
          }).catch(() => {
            this.btnLoading = false
          })
        } else {
          this.btnLoading = false
        }
      })
    },
    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%;
  }
  .dialog-footer {
    margin-top: -20px;
    text-align: center;
  }
</style>
