<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    width="1000px"
    @closed="closedHandler"
    :close-on-click-modal="false"
    class="emergencyCarDialog"
  >
    <el-form
      ref="dataForm"
      :model="dataForm"
      size="small"
      label-width="218px"
      :rules="rules"
      :disabled="formDisabled"
      v-loading="loading"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="车辆使用单位(全称)："
            prop="vehicleUsingUnit"
          >
            <el-input
              placeholder="请输入车辆使用单位"
              v-model="dataForm.vehicleUsingUnit"
            />
          </el-form-item>
          <el-form-item
            label="单位性质："
            prop="unitType"
          >
            <el-radio-group
              class="radio-group-type1"
              v-model="dataForm.unitType"
            >
              <el-radio :label="1">公立医疗</el-radio>
              <el-radio :label="2">民营医院</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="车辆管理负责人："
            prop="vehicleManager"
          >
            <el-input
              placeholder="请输入车辆管理负责人"
              v-model="dataForm.vehicleManager"
            />
          </el-form-item>
          <el-form-item
            label="负责人11位手机号："
            prop="contactPhone"
          >
            <el-input
              placeholder="请输入负责人联系方式"
              v-model="dataForm.contactPhone"
            />
          </el-form-item>
          <el-form-item
            label="车辆品牌："
            prop="vechieBrand"
          >
            <el-input
              placeholder="请输入车辆品牌"
              v-model="dataForm.vechieBrand"
            />
          </el-form-item>
          <el-form-item
            label="车辆识别代码(17位车架号)："
            prop="vechieVinCode"
          >
            <el-input
              placeholder="请输入车辆识别代码"
              v-model="dataForm.vechieVinCode"
            />
          </el-form-item>
          <el-form-item
            label="车辆是否上牌："
            prop="vechieIsLicense"
          >
            <el-radio-group
              class="radio-group-type1"
              v-model="dataForm.vechieIsLicense"
            >
              <el-radio :label="1">是</el-radio>
              <el-radio :label="2">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="车牌号："
            v-if="dataForm.vechieIsLicense !== 2"
            prop="licensePlateNumber"
          >
            <el-input
              placeholder="请输入车牌号"
              v-model="dataForm.licensePlateNumber"
            />
          </el-form-item>
          <el-form-item
            label="车辆图片"
            v-if="dataForm.vechieIsLicense !== 2"
            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"
            >
              <el-button
                size="small"
                slot="trigger"
                type="primary"
              >点击上传</el-button>
              <div
                class="avatar"
                v-if="dataForm.emergencyCarUrl"
              >
                <el-image
                  class="avatar_img"
                  :src="dataForm.emergencyCarUrl"
                  :preview-src-list="[
                    dataForm.emergencyCarUrl
                  ]"
                >
                </el-image>
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item
            label="备注(选填)："
            prop="remark"
          >
            <el-input
              type="textarea"
              :rows="3"
              resize="none"
              placeholder="请输入备注"
              v-model="dataForm.remark"
            />
          </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-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-form-item
            label="是否为院前急救车："
            v-if="dataForm.vechieType === 3"
            prop="isPreHospitalVechie"
          >
            <el-radio-group
              class="radio-group-type1"
              v-model="dataForm.isPreHospitalVechie"
            >
              <el-radio :label="1">是</el-radio>
              <el-radio :label="2">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="是否为120急救车："
            prop="isEmergencyCar"
          >
            <el-radio-group
              class="radio-group-type1"
              v-model="dataForm.isEmergencyCar"
            >
              <el-radio :label="1">是</el-radio>
              <el-radio :label="2">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="车辆来源："
            prop="vechieSource"
          >
            <el-radio-group
              class="radio-group-type2"
              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-form-item
            label="首次登记日期："
            prop="firstRegisterDate"
          >
            <el-date-picker
              type="datetime"
              placeholder="请选择首次登记日期"
              v-model="dataForm.firstRegisterDate"
              style="width: 100%;"
              prefix-icon="el-icon-date"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
            ></el-date-picker>
          </el-form-item>
          <el-form-item
            label="车辆使用状态："
            prop="vechieUseStatus"
          >
            <el-radio-group
              class="radio-group-type2"
              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"
              type="textarea"
              :rows="3"
              resize="none"
              placeholder="若选择其他，请手动输入车辆使用状态"
              v-model="dataForm.otherStatus"
            />
          </el-form-item>
          <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-form-item
            label="特殊设备(选填)："
            prop="specialDevice"
            class="radio-group-type3"
          >
            <el-checkbox-group v-model="dataForm.specialDevice">
              <el-checkbox label="1">车载CT</el-checkbox>
              <el-checkbox label="2">车载ECMO</el-checkbox>
              <el-checkbox label="3">其他</el-checkbox>
            </el-checkbox-group>
            <el-input
              v-if="dataForm.specialDevice.indexOf('3') > -1"
              type="textarea"
              :rows="3"
              resize="none"
              placeholder="若选择其他，请手动输入特殊设备"
              v-model="dataForm.specialDeviceOther"
            />
          </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/base/uploadImage ',
      formDisabled: false,
      token: Auth.getLoginInfo(),
      dataForm: {
        vehicleUsingUnit: '',
        area: '',
        unitType: '',
        vechieType: '',
        vehicleManager: '',
        isPreHospitalVechie: '',
        contactPhone: '',
        vechieSource: '',
        vechieBrand: '',
        firstRegisterDate: '',
        vechieVinCode: '',
        vechieUseStatus: '',
        vechieIsLicense: '',
        vechieSpecialPurpose: '',
        licensePlateNumber: '',
        remark: '',
        specialDevice: []
      },
      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: 17, message: '请输入正确格式的车辆识别代码' }
        ],
        vechieUseStatus: [
          { required: true, message: '请选择车辆使用状态' },
          { validator: checkVechieUseStatus }
        ],
        vechieSpecialPurpose: [
          { required: true, message: '请选择车辆特殊用途' },
        ],
        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,
            specialDevice: this.dataForm.specialDevice.join()
          }

          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,
              specialDevice: res.respData.specialDevice ? res.respData.specialDevice.split(',') : []
            }
            this.$nextTick(() => {
              this.loading = false
              this.$refs.dataForm.clearValidate()
            })
          } else {
            this.$message.error(res.content);
          }
        })
      } else {
        this.dataForm = {
          specialDevice: []
        }
        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 {
    width: 84px;
    height: 84px;
    display: block;
    position: relative;
    margin-top: 10px;
    border: 1px solid #c0ccda;
    border-radius: 6px;
    .avatar_img {
      width: 100%;
      height: 100%;
    }
  }
  .el-dialog__body {
    padding: 32px 64px 0 60px;
    box-sizing: border-box;
  }
  .radio-group-type1 {
    .el-radio {
      margin-right: 48px;
      &:last-child {
        margin-right: 0;
      }
    }
  }
  .radio-group-type2 {
    .el-radio {
      margin-right: 32px;
      &:last-child {
        margin-right: 0;
      }
    }
  }
  .radio-group-type3 {
    .el-checkbox {
      margin-right: 8px;
      &:last-child {
        margin-right: 0;
      }
    }
  }
}
</style>
