<template>
  <div>
    <el-form
      inline
      :model="form"
      ref="form"
      class="dialog-info"
      label-width="120px"
    >
      <el-form-item
        label="姓名"
        verify
        prop="name"
      >
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item
        label="性别"
        prop="sex">
        <el-select v-model="form.sex">
          <el-option
            label="男"
            :value="1"
          ></el-option>
          <el-option
            label="女"
            :value="2"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        can-be-empty
        :verify="verifyPhone"
        label="手机号"
        prop="phone">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item
        label="证件类型"
        prop="papers_type">
        <el-select v-model="form.papers_type">
          <el-option
            v-for="item in papersOption"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        key="id1"
        can-be-empty
        :verify="verifyId"
        v-if="form.papers_type==='ID_CARD'"
        label="证件号码"
        prop="papers_id">
        <ReaderInput
          type="ID"
          @change="form.name=$event.Name"
          v-model="form.papers_id"></ReaderInput>
      </el-form-item>
      <el-form-item
        v-else
        verify
        key="id2"
        label="证件号码"
        prop="papers_id">
        <el-input v-model="form.papers_id"></el-input>
      </el-form-item>
      <el-form-item
        label="区域"
        prop="selectedRegion">
        <el-cascader
          v-model="form.selectedRegion"
          :options="regionOptions"
          :props="cascaderProps"
          :show-all-levels="false"
          @change="regionChange"
        ></el-cascader>
      </el-form-item>
      <el-form-item
        label="地区"
        prop="selectedArea">
        <el-cascader
          :disabled="areaDisabled"
          v-model="form.selectedArea"
          :options="areaOptions"
          :props="cascaderProps"
          :show-all-levels="false"
          @change="areaChange"
        ></el-cascader>
      </el-form-item>
      <el-form-item
        label="客户类型"
        prop="type">
        <el-select v-model="form.type">
          <el-option
            label="普通"
            :value="1"
          ></el-option>
          <el-option
            label="其他"
            :value="2"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="状态"
        prop="status">
        <el-select v-model="form.status">
          <el-option
            label="正常"
            :value="1"
          ></el-option>
          <el-option
            label="黑名单"
            :value="0"
          ></el-option>
          <el-option
            label="灰名单"
            :value="3"
          ></el-option>
          <el-option
            label="其他"
            :value="2"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        prop="image"
        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 { apiVisitor } from '@/api/visitor'
import regionData from '@/assets/region.json'
import areaData from '@/assets/area.json'
import { papersType } from '@/assets/staticData'
import { verifyId, verifyPhone } from '@/utils/validate.js'
import ReaderInput from '@/components/ReaderInput'
export default {
  props: {
    dialogType: {
      type: String,
      default: 'edit'
    },
    currentItem: {
      type: Object,
      default: () => {}
    }
  },
  components: {
    ReaderInput
  },
  data () {
    return {
      visible: false,
      papersOption: Object.keys(papersType).map(key => {
        return {
          id: key,
          name: papersType[key]
        }
      }),
      form: {
        name: '',
        sex: 1,
        phone: '',
        papers_type: 'ID_CARD',
        papers_id: '',
        region: '',
        area: '',
        type: 1,
        status: 1,
        image: '',
        selectedRegion: [],
        selectedArea: []
      },
      regionOptions: regionData,
      areaOptions: [],
      cascaderProps: {
        label: 'name',
        value: 'name',
        children: 'children'
      },
      chineseRegion: ['华北', '东北', '华东', '中南', '西南', '西北']
    }
  },
  computed: {
    areaDisabled () {
      let region = this.form.selectedRegion[1]
      return this.chineseRegion.indexOf(region) === -1
    }
  },
  watch: {
    visible (val) {
      // 重置表单
      if (val) {
        this.reset()
        if (this.dialogType === 'edit' && this.currentItem) {
          this.form = { ...this.form, ...this.currentItem }
          if (this.form.region) {
            if (regionData[1].children.find(country => country.name === this.form.region)) {
              // 外国
              this.form.selectedRegion = ['海外', this.form.region]
            } else {
              this.form.selectedRegion = ['国内', this.form.region]
            }
            let list = areaData[this.form.region]
            this.areaOptions = list || []
            if (this.form.area) {
              for (let i = 0; i < list.length; i++) {
                let citys = list[i].children
                if (citys.find(c => c.name === this.form.area)) {
                  this.form.selectedArea = [list[i].name, this.form.area]
                  break
                }
              }
            }
          }
        }
      }
    }
  },
  methods: {
    verifyId,
    verifyPhone,
    handleClose () {
      this.$parent.handleClose()
    },
    reset () {
      this.$refs.form.resetFields()
      this.form.region = ''
      this.form.area = ''
    },
    // 改变区域选择器
    regionChange (arr) {
      this.form.region = arr[arr.length - 1]
      let provinceData = areaData[this.form.region]
      this.areaOptions = provinceData || []
      this.form.selectedArea = []
      this.form.area = ''
      console.log(this.areaDisabled)
    },
    // 改变城市选择器
    areaChange (arr) {
      this.form.area = arr[arr.length - 1]
    },
    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]
      }
    },
    submit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let url = this.dialogType === 'new' ? 'createCustomer' : 'updateCustomer'
          apiVisitor(url, this.form).then(res => {
            this.$message.success('添加成功')
            this.reset()
            this.handleClose()
            this.$emit('updateList')
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>
