<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    width="1000px"
    append-to-body
    @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-select
              v-model="dataForm.vehicleUsingUnit"
              placeholder="请选择车辆使用单位"
              style="width: 100%"
              filterable
              remote
              :loading="selectLoading"
              :remote-method="remoteMethod"
              :clearable="true"
              :title="dataForm.vehicleUsingUnit"
              @change="changeHandler2"
            >
              <el-option
                v-for="item in hospitalList"
                :label="item.hospitalName"
                :key="item.id"
                :value="item.hospitalName"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="单位性质："
            prop="unitType"
          >
            <el-radio-group
              class="radio-group-type4"
              :disabled="true"
              v-model="dataForm.unitType"
            >
              <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="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="vechieTypeNew"
          >
            <el-select
              v-model="dataForm.vechieTypeNew"
              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="是否为院前救护车："
            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"
              @change="changeHandler"
            >
              <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="4">无特殊设备</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-form-item
            label="附件上传："
            prop="fileList"
          >
            <fileUpload :setFileList="fileList" ref="fileUpload" />
          </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 { queryHospitalList } from '@/api/common'
import { saveOrUpdateEmergencyCar, queryTeamEmergencyCarInfo } from '@/api/emergencyCar'
import fileUpload from '../../../components/fileUpload.vue'
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
    }
  },
  components: {
    fileUpload
  },
  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,
      fileList: [],
      uploadUrl: '/mdxtpt/teamwork/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: []
      },
      hospitalList: [],
      selectLoading: false,
      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: '请输入车牌号' },
        ],
        specialDevice: [
          { 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
    })
    //获取可选择的医院
    queryHospitalList().then(res => {
      this.hospitalList = res.respData
    })
    console.log(process.env.NODE_ENV)
  },
  methods: {
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.search()
    },
    submitForm() {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          const params = {
            ...this.dataForm,
            fileList: this.$refs.fileUpload.getFileList(),
            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不能为空')
          this.dialogVisible = false
          this.loading = false
          return
        }
        queryTeamEmergencyCarInfo({ id: id }).then(res => {
          if (res.msg === 201) {
            this.dataForm = {
              ...res.respData,
              specialDevice: res.respData.specialDevice ? res.respData.specialDevice.split(',') : []
            }
            this.remoteMethod(res.respData.vehicleUsingUnit)
            this.fileList = res.respData.fileList || []
            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()
      this.fileList = []
    },
    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;
    },
    remoteMethod(query) {
      this.selectLoading = true;
      queryHospitalList(query).then(res => {
        this.hospitalList = res.respData
        this.selectLoading = false;
      })
    },
    changeHandler() {
      if (this.dataForm.vechieUseStatus === 3) {
        if (!this.dataForm.otherStatus) {
          this.$set(this.dataForm, 'otherStatus', '注销，报废，查封，逾期未检验，达到报废标准公告牌证作废，违法未处理，转出，锁定')
        }
      }
    },
    changeHandler2(name) {
      const item = this.hospitalList.find(i => i.hospitalName === name)
      if (item) {
        this.dataForm.unitType = item.unitType
      }
    }
  }
}
</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;
      }
    }
  }
  .radio-group-type4 {
    font-size: 14px;
    line-height: 32px;
  }
  .el-input.is-disabled .el-input__inner {
    border: 1px solid #40a2de;
    background-color: #fff;
    color: #606266;
  }
  .el-radio__input.is-disabled + span.el-radio__label {
    color: #606266;
  }
  .el-radio__input.is-disabled.is-checked .el-radio__inner {
    background-color: #fff;
    border-color: #40a2de;
  }
  .el-radio__input.is-disabled.is-checked .el-radio__inner::after {
    background-color: #40a2de;
  }
  .el-radio__input.is-disabled .el-radio__inner {
    border: 1px solid #40a2de;
    background-color: #fff;
  }
  .el-radio__input.is-checked + span.el-radio__label {
    color: #017bce;
  }
  .el-checkbox__input.is-disabled+span.el-checkbox__label{
    color: #606266;
  }
  .el-checkbox__input.is-checked.is-disabled+span.el-checkbox__label{
    color: #017bce;
  }
  .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner{
    background-color: #017BCE;
    border-color: #017BCE;
  }
  .el-checkbox__input.is-disabled .el-checkbox__inner{
    background-color: #fff;
    border-color: #40a2de;
  }
  .el-button--primary.is-disabled, .el-button--primary.is-disabled:hover, .el-button--primary.is-disabled:focus, .el-button--primary.is-disabled:active{
    background-color: #017BCE;
    border-color: #017BCE;
    color: #fff;
  }
  .el-textarea.is-disabled .el-textarea__inner{
    background-color: #fff;
    border-color: #40a2de;
    color: #606266;
  }
}
</style>
