<template>
  <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :fullscreen="false" width="60%" append-to-body>
    <el-form ref="dataForm" :rules="rules" :model="carForm" label-well-code="right" label-width="100px">
      <div class="form-div">
        <div class="form-left">
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="车牌号" prop="carCode">
                <el-input v-model.trim="carForm.carCode" :disabled="isDetailMode" type="text" placeholder="必填"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="车辆描述" prop="description">
                <el-input v-model.trim="carForm.description" :disabled="isDetailMode" type="text" placeholder="必填"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="车辆类型" prop="carType">
                <el-select v-model="carForm.carType" :disabled="isDetailMode" placeholder="请选择垃圾桶车辆类型">
                  <el-option
                    v-for="item in typeList"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="品牌型号" prop="brandModel">
                <el-input v-model.trim="carForm.brandModel" :disabled="isDetailMode" type="text" placeholder="品牌型号"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="准乘人数" prop="peopleNumber">
                <el-input v-model.trim="carForm.peopleNumber" :disabled="isDetailMode" type="text" placeholder=""/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item v-show="!isDetailMode" label="使用单位" prop="deptId">
                <dept-select v-model="carForm.deptId" :dept-show="true" :disabled="isDetailMode" placeholder="请选择使用单位"/>
              </el-form-item>
              <el-form-item v-show="isDetailMode" label="使用单位">
                <el-input v-model.trim="carForm.deptName" :disabled="isDetailMode" type="text" placeholder="无"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="使用人" prop="chargePerson">
                <el-input v-model.trim="carForm.userPerson" :disabled="isDetailMode" type="text" placeholder="使用人"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="使用人电话" prop="chargePhone">
                <el-input v-model.trim="carForm.userPhone" :disabled="isDetailMode" type="text" placeholder="使用人电话"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="责任人" prop="chargePerson">
                <el-input v-model.trim="carForm.chargePerson" :disabled="isDetailMode" type="text" placeholder="责任人"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="责任人电话" prop="chargePhone">
                <el-input v-model.trim="carForm.chargePhone" :disabled="isDetailMode" type="text" placeholder="责任人电话"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="购入日期" prop="purchaseDate">
                <el-date-picker
                  v-model.trim="carForm.purchaseDate"
                  :disabled="isDetailMode"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择购入日期"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="注册日期" prop="registerDate">
                <el-date-picker
                  v-model.trim="carForm.registerDate"
                  :disabled="isDetailMode"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择注册日期"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="发动机号" prop="engine">
                <el-input v-model.trim="carForm.engine" :disabled="isDetailMode" type="text" placeholder="发动机号"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注" prop="remarks">
                <el-input v-model.trim="carForm.remarks" :disabled="isDetailMode" type="text" placeholder="备注"/>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>

    </el-form>
    <div v-show="!isDetailMode" slot="footer" class="dialog-footer">
      <el-button :disabled="!canEdit" type="primary" @click="saveData">保存</el-button>
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getCarDetail, addCar, updateCar } from '@/api/sanitation/car'
import { Uploadimg } from '@/api/common'
import { getDictByType } from '@/api/common'
import DeptSelect from '@/components/DeptSelect/index'
export default {
  description: 'EditCar',
  components: {
    DeptSelect
  },
  data() {
    return {
      baseUrl: process.env.BASE_API + '/static/',
      photo: '', // 图片路径
      defaultPhoto: require('../../assets/global_images/photo.png'), // 默认图片路径
      dialogFormVisible: false, // 对话框是否显示
      dialogStatus: '', // 对话框类型：create,update,detail
      carForm: {
        sys: '1', // 环卫子系统
        id: '', // id
        carCode: '', // 车牌号
        description: '', // 车辆描述
        carType: '', // 车辆类型
        brandModel: '', // 品牌型号
        peopleNumber: '', // 准乘人数
        deptId: '', // 使用单位
        userPerson: '', // 使用人
        userPhone: '', // 使用人电话
        chargePerson: '', // 责任人
        chargePhone: '', // 责任人电话
        engine: '', // 发动机号
        purchaseDate: '', // 购入日期
        registerDate: '', // 登记日期
        remarks: '', // 备注
        deviceId: '' // 关联模块id
      }, // 表单
      textMap: {
        update: '编辑',
        create: '新增',
        detail: '详情'
      }, // 表头显示标题
      sexList: [
        { description: '男', value: '0' },
        { description: '女', value: '1' }
      ], // 性别列表
      typeList: [],
      rules: {
        carCode: [{ required: true, message: '车牌号不能为空', trigger: ['blur', 'change'] }],
        description: [{ required: true, message: '车辆描述不能为空', trigger: ['blur', 'change'] }],
        brandModel: [{ required: true, message: '位置不能为空', trigger: ['blur', 'change'] }],
        peopleNumber: [{ required: true, message: '准乘人数不能为空', trigger: ['blur', 'change'] }],
        deptId: [{ required: true, message: '使用单位不能为空', trigger: ['blur', 'change'] }],
        type: [{ required: true, message: '车辆类型必选', trigger: ['blur', 'change'] }]
      }, // 前端校验规则
      isEditMode: false, // 编辑模式
      isDetailMode: false, // 详情模式
      canEdit: true
    }
  },
  created() {
    this.fetchCarType()
  },
  methods: {
    /**
       * 初始化对话框
       * @param dialogStatus 对话框类型
       * @param dialogFormVisible 对话框是否可见
       * @param row 内容参数（编辑和详情需要）
       */
    initDialog: function(dialogStatus, dialogFormVisible, row = null) {
      this.dialogStatus = dialogStatus
      this.dialogFormVisible = dialogFormVisible
      if (dialogStatus === 'create') { // 如果是新增，清除验证
        this.resetForm()
        this.isEditMode = false
        this.isDetailMode = false
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
        this.canEdit = true
      } else if (dialogStatus === 'update') { // 如果是修改，将row中数据填写到输入框中
        this.fetchDetail(row.id)
        this.canEdit = true
        this.isEditMode = true
        this.isDetailMode = false
      } else {
        this.fetchDetail(row.id)
        this.canEdit = true
        this.isEditMode = true
        this.isDetailMode = true
      }
      if (this.carForm.photo && this.carForm.photo !== '') {
        this.photo = this.baseUrl + this.carForm.photo
      }
    },
    fetchDetail(id) {
      getCarDetail(id).then(response => {
        if (response.code === 200) {
          const row = response.data
          this.carForm = {
            sys: '1', // 子系统
            id: row.id, // id
            carCode: row.carCode, // 车牌号
            description: row.description, // 车辆描述
            carType: row.carType, // 车辆类型
            brandModel: row.brandModel, // 位置：社区/道路
            peopleNumber: row.peopleNumber, // 准乘人数
            deptId: row.deptId, // 使用单位
            deptName: row.deptName, // 使用单位
            userPerson: row.userPerson, // 使用人
            userPhone: row.userPhone, // 使用人电话
            chargePerson: row.chargePerson, // 责任人
            chargePhone: row.chargePhone, // 责任人电话
            remarks: row.remarks, // 备注
            engine: row.engine, // 发动机号
            purchaseDate: row.purchaseDate, // 购入日期
            registerDate: row.registerDate, // 登记日期
            deviceId: row.deviceId // 关联模块id
          }
        }
      })
    },
    // 重置表单
    resetForm() {
      this.carForm = {
        sys: '1', // 环卫子系统
        id: '', // id
        carCode: '', // 车牌号
        description: '', // 车辆描述
        carType: '', // 车辆类型
        brandModel: '', // 品牌型号
        peopleNumber: '', // 准乘人数
        deptId: '', // 使用单位
        userPerson: '', // 使用人
        userPhone: '', // 使用人电话
        chargePerson: '', // 责任人
        chargePhone: '', // 责任人电话
        engine: '', // 发动机号
        purchaseDate: '', // 购入日期
        registerDate: '', // 登记日期
        remarks: '', // 备注
        deviceId: '' // 关联模块id
      }
    },
    // 保存数据
    saveData: function() {
      if (this.dialogStatus === 'update') {
        this.updateData()
      } else if (this.dialogStatus === 'create') {
        this.createData()
      }
    },
    // 新增数据
    createData: function() {
      this.canEdit = false
      this.$refs['dataForm'].validate((valid) => {
        console.log(this.carForm)
        if (valid) {
          addCar(this.carForm).then(response => {
            if (response.code === 200) {
              this.$confirm('新增成功，是否继续新增?', '提示', {
                confirmButtonText: '是',
                cancelButtonText: '否',
                type: 'info'
              }).then(() => {
                this.resetForm()
                this.$nextTick(() => {
                  this.$refs['dataForm'].clearValidate()
                  this.canEdit = true
                })
              }).catch(() => {
                this.$emit('watchChild')
                this.dialogFormVisible = false
                this.canEdit = true
              })
            }
          }).catch((e) => {
            this.canEdit = true
          })
        } else {
          this.canEdit = true
        }
      })
    },
    // 修改数据
    updateData: function() {
      this.$refs['dataForm'].validate((valid) => {
        this.canEdit = false
        if (valid) {
          updateCar(this.carForm).then(response => {
            if (response.code === 200) {
              this.$message.success('修改成功')
              this.$emit('watchChild')
              this.dialogFormVisible = false
              this.canEdit = true
            }
          }).catch((e) => {
            this.canEdit = true
          })
        } else {
          this.canEdit = true
        }
      })
    },
    // 图片上传
    uploadFile(file) {
      console.log('uploadFile:' + file.file.description)
      Uploadimg(file).then(res => {
        if (res.carCode === 200) {
          this.photo = this.baseUrl + res.data
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    // 上传前判断文件格式及大小
    handleBeforeUpload(file) {
      const isJPG = (file.type === 'image/jpeg') || (file.type === 'image/png')
      let res = true
      const isLt2M = file.size / 1024 / 1024 < 5
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!')
        res = false
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 5MB!')
        res = false
      }
      return res
    },
    // 上传成功后回显
    handleSuccess(response, file) {
      console.log('handleSuccess')
      if (response.carCode === 200) {
        this.photo = this.baseUrl + response.data
      } else {
        this.$message.warning(response.message)
      }
    },
    // 获取垃圾桶车辆类型
    fetchCarType() {
      getDictByType('carType').then(response => {
        this.typeList = 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%;
  }
  .form-div{
    width:100%;
    height:100%;
    display:flex;
    justify-content: space-between;
  }
  .form-left{
    flex:1;
    height:100%;
  }
  .form-right{
    width: 180px;
    height:100%;
    .avatar{
      margin-bottom: 10px;
    }
    text-align: center;
  }
</style>
