<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    width="1200px"
    @closed="closedHandler"
    :close-on-click-modal="false"
    class="emergencyCarDialog"
  >
    <el-form
      ref="dataForm"
      :model="dataForm"
      size="small"
      label-width="300px"
      :rules="rules"
      :disabled="formDisabled"
      v-loading="loading"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="车辆图片"
            prop="emergencyCarUrl"
          >
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :headers="{ token: token }"
              accept="image/jpg, image/jpeg, image/png"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="dataForm.emergencyCarUrl"
                :src="dataForm.emergencyCarUrl"
                class="avatar"
              >
              <i
                v-else
                class="el-icon-plus avatar-uploader-icon"
              ></i>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="车辆使用单位(请填写单位全称)"
            prop="vehicleUsingUnit"
          >
            <el-input
              placeholder="请输入车辆使用单位"
              v-model="dataForm.vehicleUsingUnit"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="辖区（多个院区则填写主院区所属辖区）"
            prop="area"
          >
            <el-select
              v-model="dataForm.area"
              placeholder="请选择辖区"
              style="width: 100%"
            >
              <el-option
                v-for="item in areaList"
                :label="item.name"
                :key="item.id"
                :value="item.val"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="单位性质"
            prop="unitType"
          >
            <el-radio-group v-model="dataForm.unitType">
              <el-radio :label="1">公立医疗</el-radio>
              <el-radio :label="2">民营医院</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="车辆类型"
            prop="vechieType"
          >
            <el-select
              v-model="dataForm.vechieType"
              placeholder="请选择车辆类型"
              style="width: 100%"
            >
              <el-option
                v-for="item in vechieTypeList"
                :label="item.name"
                :key="item.id"
                :value="item.val"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="车辆管理负责人"
            prop="vehicleManager"
          >
            <el-input
              placeholder="请输入车辆管理负责人"
              v-model="dataForm.vehicleManager"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="是否为院前急救车(车辆用途)"
            prop="isPreHospitalVechie"
          >
            <el-radio-group v-model="dataForm.isPreHospitalVechie">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="2">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="负责人联系方式（11位手机号）"
            prop="contactPhone"
          >
            <el-input
              placeholder="请输入负责人联系方式"
              v-model="dataForm.contactPhone"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="车辆来源"
            prop="vechieSource"
          >
            <el-radio-group v-model="dataForm.vechieSource">
              <el-radio :label="1">购买</el-radio>
              <el-radio :label="2">捐赠</el-radio>
              <el-radio :label="3">划拨</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="车辆品牌"
            prop="vechieBrand"
          >
            <el-input
              placeholder="请输入车辆品牌"
              v-model="dataForm.vechieBrand"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="首次登记日期"
            prop="firstRegisterDate"
          >
            <el-date-picker
              type="datetime"
              placeholder="请选择首次登记日期"
              v-model="dataForm.firstRegisterDate"
              style="width: 100%;"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="车辆识别代码（11位车架号）"
            prop="vechieVinCode"
          >
            <el-input
              placeholder="请输入车辆识别代码"
              v-model="dataForm.vechieVinCode"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="车辆使用状态"
            prop="vechieUseStatus"
          >
            <el-radio-group v-model="dataForm.vechieUseStatus">
              <el-radio :label="1">在用</el-radio>
              <el-radio :label="2">闲置</el-radio>
              <el-radio :label="3">其他</el-radio>
            </el-radio-group>
            <el-input
              v-if="dataForm.vechieUseStatus === 3"
              placeholder="若选择其他，请手动输入车辆使用状态"
              v-model="dataForm.otherStatus"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="车辆是否上牌"
            prop="vechieIsLicense"
          >
            <el-radio-group v-model="dataForm.vechieIsLicense">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="2">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="车辆特殊用途"
            prop="vechieSpecialPurpose"
          >
            <el-select
              v-model="dataForm.vechieSpecialPurpose"
              placeholder="请选择车辆特殊用途"
              style="width: 100%"
            >
              <el-option
                v-for="item in vechieSpecialPurposeList"
                :label="item.name"
                :key="item.id"
                :value="item.val"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="车牌号"
            prop="licensePlateNumber"
          >
            <el-input
              placeholder="请输入车牌号"
              v-model="dataForm.licensePlateNumber"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="备注（若无可略过）"
            prop="remark"
          >
            <el-input
              placeholder="请输入备注"
              v-model="dataForm.remark"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span
      slot="footer"
      class="dialog-footer"
    >
      <el-button
        size="small"
        @click="dialogVisible = false"
      >取 消</el-button>
      <el-button
        type="primary"
        size="small"
        :disabled="formDisabled"
        @click="submitForm()"
      >确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getDic } from '../../../util/dict'
import { Auth } from '@/util/auth'
import { saveOrUpdateEmergencyCar, queryTeamEmergencyCarInfo } from '@/api/emergencyCar'
export default {
  name: 'emergencyCarDialog',
  computed: {
    title: function() {
      let str = '武汉市医疗急救车辆信息'
      if (this.type === 'add') {
        str += '填写'
      } else if (this.type === 'update') {
        str += '修改'
      } else if (this.type === 'detail') {
        str += '详情'
      }
      return str
    }
  },
  data() {
    const checkVechieUseStatus = (rule, value, callback) => {
      if (value === 3 && !(this.dataForm.otherStatus)) {
        callback(new Error('若选择其他，请手动输入车辆使用状态'))
      } else {
        callback()
      }
    }
    const checkContactPhone = (rule, value, callback) => {
      let reg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
      if (!reg.test(value)) {
        callback(new Error("请输入正确格式的联系方式"))
      } else {
        callback()
      }
    };
    return {
      dialogVisible: false,
      loading: false,
      uploadUrl: (process.env.NODE_ENV === 'production' && process.env.BASE_API ? process.env.BASE_API : '') + '/api/team/car/uploadEmergencyImage',
      formDisabled: false,
      token: Auth.getLoginInfo(),
      dataForm: {
        vehicleUsingUnit: '',
        area: '',
        unitType: '',
        vechieType: '',
        vehicleManager: '',
        isPreHospitalVechie: '',
        contactPhone: '',
        vechieSource: '',
        vechieBrand: '',
        firstRegisterDate: '',
        vechieVinCode: '',
        vechieUseStatus: '',
        vechieIsLicense: '',
        vechieSpecialPurpose: '',
        licensePlateNumber: '',
        remark: ''
      },
      rules: {
        vehicleUsingUnit: [
          { required: true, message: '请输入车辆使用单位' },
        ],
        emergencyCarUrl: [
          { required: true, message: '请上传车辆图片' },
        ],
        area: [
          { required: true, message: '请选择辖区' },
        ],
        unitType: [
          { required: true, message: '请选择单位性质' },
        ],
        vechieType: [
          { required: true, message: '请选择车辆类型' },
        ],
        vehicleManager: [
          { required: true, message: '请输入车辆管理负责人' },
        ],
        isPreHospitalVechie: [
          { required: true, message: '请选择是否为院前急救车' },
        ],
        contactPhone: [
          { required: true, message: '请输入负责人联系方式' },
          { validator: checkContactPhone }
        ],
        vechieSource: [
          { required: true, message: '请选择车辆来源' },
        ],
        vechieBrand: [
          { required: true, message: '请输入车辆品牌' },
        ],
        firstRegisterDate: [
          { required: true, message: '请选择首次登记日期' },
        ],
        vechieVinCode: [
          { required: true, max: 11, message: '请输入正确格式的车辆识别代码' }
        ],
        vechieUseStatus: [
          { required: true, message: '请选择车辆使用状态' },
          { validator: checkVechieUseStatus }
        ],
        vechieIsLicense: [
          { required: true, message: '请选择车辆是否上牌' },
        ],
        licensePlateNumber: [
          { required: true, message: '请输入车牌号' },
        ],
      },
      vechieTypeList: [],
      areaList: [],
      type: 'add',
      vechieSpecialPurposeList: []
    }
  },
  mounted() {
    // 获取字典
    getDic(['vechie_type', 'area', 'vechie_special_purpose']).then(res => {
      this.vechieTypeList = res.vechie_type
      this.areaList = res.area
      this.vechieSpecialPurposeList = res.vechie_special_purpose
    })
  },
  methods: {
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.search()
    },
    submitForm() {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          const params = {
            ...this.dataForm
          }
          saveOrUpdateEmergencyCar(params).then(res => {
            if (res.msg === 201) {
              this.dialogVisible = false
              this.$message.success(this.type === 'add' ? '新增成功！' : '修改成功')
              this.$emit('subsucc')
            } else {
              this.$message.error(res.content)
            }
          })
        }
      })
    },
    init(type, id) {
      this.dialogVisible = true
      this.loading = true
      this.type = type
      this.formDisabled = type === 'detail'
      if (type === 'update' || type === 'detail') {
        if (!id) {
          this.$message.error('救护车id不能为空')
          return
        }
        queryTeamEmergencyCarInfo({ id: id }).then(res => {
          if (res.msg === 201) {
            this.dataForm = res.respData
            this.$nextTick(() => {
              this.loading = false
              this.$refs.dataForm.clearValidate()
            })
          } else {
            this.$message.error(res.content);
          }
        })
      } else {
        this.dataForm = {}
        this.$nextTick(() => {
          this.loading = false
          this.$refs.dataForm.clearValidate()
        })
      }
    },
    closedHandler() {
      this.$refs.dataForm.resetFields()
    },
    handleAvatarSuccess(res, file) {
      if (res.msg === 201) {
        this.$set(this.dataForm, 'emergencyCarUrl', res.respData)
      } else {
        this.$message.error(res.content)
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error('上传车辆图片只能是 jpg/jpeg/png 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    }
  }
}
</script>


<style lang="scss">
.emergencyCarDialog {
  .el-input {
    // width: 200px;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
