<template>
  <div>
    <el-form
      inline
      :model="form"
      ref="form"
      class="dialog-info"
      label-width="120px"
    >
      <el-form-item
        verify
        prop="name"
        label="姓名">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item
        :verify="verifyId"
        label="身份证号"
        prop="idcard">
        <ReaderInput
          type="ID"
          v-model="form.idcard"></ReaderInput>
      </el-form-item>
      <el-form-item
        :verify="verifyPhone"
        prop="phone"
        label="手机号">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item
        verify
        prop="tour_card"
        label="导游证">
        <el-input v-model="form.tour_card"></el-input>
      </el-form-item>
      <el-form-item
        verify
        prop="areaArray"
        label="地区">
        <el-cascader
          v-model="form.areaArray"
          :options="provinceAndCityData"
        ></el-cascader>
      </el-form-item>
      <el-form-item
        v-if="allowAgency"
        verify
        prop="travelAgencyId"
        :label="`${agencyName()}`">
        <el-select v-model="form.travelAgencyId">
          <el-option
            v-for="item in agencyList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        v-else
        prop="travelAgencyId"
        :label="`${agencyName()}`">
        <el-select v-model="form.travelAgencyId">
          <el-option
            v-for="item in agencyList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        verify
        prop="image"
        class="is-required"
        label="照片">
        <el-upload
          class="avatar-uploader"
          action=""
          :show-file-list="false"
          :auto-upload="false"
          :on-change="handleAvatarSuccess">
          <img
            v-if="form.image"
            :src="`data:image/jpeg;base64,${form.image}`"
            class="avatar">
          <i
            v-else
            class="el-icon-plus avatar-uploader-icon"
          ></i>
        </el-upload>
      </el-form-item>
    </el-form>
    <div class="dialog-btn-wrap">
      <el-button
        v-if="dialogType === 'new'"
        @click="reset">
        重置
      </el-button>
      <el-button
        @click="submit"
        type="primary">
        保存
      </el-button>
    </div>
  </div>
</template>

<script>
import ReaderInput from '@/components/ReaderInput'
import { verifyId, verifyPhone } from '@/utils/validate.js'
import { apiUpdateGuide, apiAddGuide, getSingleGuide } from '@/api/travelAgency'
import { provinceAndCityData, CodeToText, TextToCode } from 'element-china-area-data'

export default {
  components: {
    ReaderInput
  },
  props: {
    dialogType: {
      type: String,
      default: 'edit'
    },
    currentItem: {
      type: Object,
      default: () => {}
    },
    agencyList: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      visible: false,
      form: {
        area: '',
        areaArray: [],
        idcard: '',
        image: '',
        name: '',
        phone: '',
        tour_card: '',
        travelAgencyId: ''
      },
      areaProps: {
        label: 'name',
        value: 'name',
        children: 'children'
      },
      provinceAndCityData
    }
  },
  computed: {
    allowAgency () {
      const value = this.$store.state.app.systemConfig.find(i => i.configKey === 'guide_bind_travel_agency').configValue
      return value !== '0'
    }
  },
  watch: {
    visible (val) {
      // 重置表单
      if (val) {
        this.reset()

        if (this.dialogType === 'edit' && this.currentItem) {
          this.form = Object.assign({}, this.form, this.currentItem)
          getSingleGuide(this.currentItem.id).then(res => {
            this.form.image = res.image
          })
          this.form.areaArray = this.textToCode(this.form.area)
        }
      }
    }
  },
  methods: {
    verifyId,
    verifyPhone,
    reset () {
      this.$refs.form.resetFields()
      this.form.area = []
    },
    codeToText (arr) {
      if (arr.length === 2) {
        return `${CodeToText[arr[0]]} ${CodeToText[arr[1]]}`
      } else {
        return `${CodeToText[arr[0]]}`
      }
    },
    textToCode (str) {
      let strArr = str.split(' ')
      if (strArr.length === 2) {
        return [TextToCode[strArr[0]].code, TextToCode[strArr[0]][strArr[1]].code]
      } else {
        return [TextToCode[strArr[0]].code]
      }
    },
    // 上传照片
    handleAvatarSuccess (res, file) {
      const isJPG = res.raw.type === 'image/jpeg' || res.raw.type === 'image/png'
      const isLt2M = res.raw.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('图片只能是 JPG或PNG 格式!')
        return
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!')
        return
      }
      let reader = new FileReader()
      reader.readAsDataURL(res.raw)
      reader.onload = (e) => {
        this.form.image = e.target.result.split(',')[1]
      }
    },
    handleClose () {
      this.$parent.handleClose()
    },
    submit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.form.area = this.codeToText(this.form.areaArray)
          if (this.dialogType === 'new') {
            this.createGuide()
          } else if (this.dialogType === 'edit') {
            this.updateGuide()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    createGuide () {
      apiAddGuide(this.form).then(res => {
        this.$message.success('添加成功')
        this.reset()
        this.handleClose()
        this.$emit('updateList')
      })
    },
    updateGuide () {
      apiUpdateGuide(this.form).then(res => {
        this.$message.success('编辑成功')
        this.handleClose()
        this.$emit('updateList')
      })
    }
  }
}
</script>
