<template>
  <a-modal
    title='操作'
    style='top: 20px;'
    :width='800'
    v-model='visible'
    :confirmLoading='confirmLoading'
    @ok='handleSubmit'
  >
    <a-form :form='form'>
      <a-form-item style='display:none'>
        <a-input v-decorator="['id']" />
      </a-form-item>
      <a-form-item style='display:none'>
        <a-input v-decorator="['version']" />
      </a-form-item>
      <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='被访单位'>
        <a-select v-decorator="['customerId',{rules: [{ required: true, message: '请选择被访单位' }]}]"
                  placeholder='请选择被访单位'
                  @change='getPersonList'>
          <a-select-option v-for='item in enterpriseList' :key='item.id' :value='item.id'>
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='被访人姓名'>
        <a-select v-decorator="['userId',{rules: [{ required: true, message: '请选择被访人姓名' }]}]"
                  placeholder='请选择被访人姓名'
                  @change='getPersonData'>
          <a-select-option v-for='item in personList' :key='item.id' :value='item.id'>
            {{ item.mobile + '-' + item.username }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='被访人手机号'>
        <a-input placeholder='被访人手机号'
                 v-decorator="['mobile',{rules: [{ required: true, message: '被访人手机号不能为空'}]}]" disabled />
      </a-form-item>
      <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='来访人姓名'>
        <a-input placeholder='请输入来访人姓名'
                 v-decorator="['name',{rules: [{ required: true, message: '来访人姓名不能为空'}]}]" />
      </a-form-item>
      <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='来访人联系方式'>
        <a-input placeholder='请输入来访人联系方式'
                 v-decorator="['phone',{rules: [{ required: true, message: '来访人联系方式不能为空'}]}]" />
      </a-form-item>
      <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='身份证类型'>
        <a-select v-decorator="['cardType',{rules: [{ required: true, message: '身份证类型不能为空' }]}]"
                  placeholder='请选择身份证类型'>
          <a-select-option v-for='item in idcardTypeList' :key='item.name' :value='item.name'>
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='身份证号'>
        <a-input placeholder='请输入身份证号'
                 v-decorator="['cardNo',{rules: [{ required: true, message: '身份证号不能为空'}]}]" />
      </a-form-item>
      <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='到访时间'>
        <a-date-picker
          format='YYYY-MM-DD HH:mm'
          valueFormat='YYYY-MM-DD HH:mm:ss'
          :show-time="{ format: 'HH:mm' }"
          v-decorator="['visitTime',{rules: [{ required: true, message: '到访时间不能为空'}]}]"
          type='date'
          placeholder='请选择到访时间'
          style='width: 100%;'
        />
      </a-form-item>
      <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='离开时间'>
        <a-date-picker
          format='YYYY-MM-DD HH:mm'
          valueFormat='YYYY-MM-DD HH:mm:ss'
          :show-time="{ format: 'HH:mm' }"
          v-decorator="['leaveTime',{rules: [{ required: true, message: '离开时间不能为空'}]}]"
          type='date'
          placeholder='请选择离开时间'
          style='width: 100%;'
        />
      </a-form-item>
      <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='来访事由'>
        <a-input placeholder='请输入来访事由'
                 v-decorator="['visitContent',{rules: [{ required: true, message: '来访事由不能为空'}]}]" />
      </a-form-item>
      <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='照片'>
        <a-upload
          v-decorator="['photo']"
          list-type='picture-card'
          class='avatar-uploader'
          :show-upload-list='false'
          :action='uploadUrl'
          :headers='headers'
          :before-upload='beforeUpload'
          @change='handleChange'
        >
          <img v-if='imageUrl' :src='imageUrl' style='width: 102px; height: 102px' />
          <div v-else>
            <a-icon :type="loading ? 'loading' : 'plus'" />
            <div class='ant-upload-text'> 上传</div>
          </div>
        </a-upload>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script>
import { saveVisitorPerson, selectUserByCustomer, selectCustomer } from '@/api/admin/meeting/visitorPerson'
import pick from 'lodash.pick'
import { getRoomListByFloorId } from '@/api/admin/meeting/roomContent'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'


export default {
  name: 'VisitorPersonModal',
  props: {},
  components: {},
  data() {
    return {
      visible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      mdl: {},
      form: this.$form.createForm(this),
      enterpriseList: [],
      personList: [],
      idcardTypeList: [{
        name: '居民身份证'
      }],
      uploadUrl: process.env.VUE_APP_API_BASE_URL + '/api/dfs/upload',
      imageUrl: '',
      headers: {
        Authorization: 'Bearer ' + storage.get(ACCESS_TOKEN)
      }
    }
  },
  beforeCreate() {
  },
  created() {
    // 查询企业
    selectCustomer().then(res => {
      console.log('selectCustomer', res)
      this.enterpriseList = res.data
    })
  },
  methods: {
    getPersonList(value) {
      console.log('getPersonList', value)
      selectUserByCustomer(value).then(res => {
        console.log('selectUserByCustomer', res)
        this.personList = res.data
        this.form.setFieldsValue({ mobile: null, userId: null })
      })
    },
    getPersonData(value) {
      console.log('getPersonData', value)
      this.form.setFieldsValue({ mobile: this.personList.find(item => item.id == value).mobile })
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('You can only upload JPG file!')
      }
      const isLt2M = file.size / 1024 < 500
      if (!isLt2M) {
        this.$message.error('图片必须小于 500kb!')
      }
      return isJpgOrPng && isLt2M
    },
    handleChange(info) {
      if (info.file.status === 'uploading') {
        this.loading = true
        return
      }
      if (info.file.status === 'done') {
        const { form: { setFieldsValue } } = this
        const result = info.file.response
        // 设置值
        this.$nextTick(() => {
          setFieldsValue({
            // 设置相对路径
            photo: result.fileName
          })
        })
        // Get this url from response in real world.
        this.getBase64(info.file.originFileObj, imageUrl => {
          this.imageUrl = imageUrl
          this.loading = false
        })
      }
    },
    getBase64(img, callback) {
      const reader = new FileReader()
      reader.addEventListener('load', () => callback(reader.result))
      reader.readAsDataURL(img)
    },
    add() {
      this.form.resetFields()
      this.edit({ id: 0 })
      this.imageUrl = null
    },
    edit(record) {
      this.mdl = Object.assign(record)
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.mdl, 'id', 'userId', 'customerId', 'intervieweeId', 'name', 'phone', 'joinTime', 'visitTime', 'leaveTime', 'visitContent', 'cardType', 'cardNo', 'status', 'createBy', 'createTime', 'updateBy', 'updateTime', 'version', 'deleteFlag', 'photo'))
      })
      if (this.mdl.photo) {
        this.imageUrl = process.env.VUE_APP_API_BASE_URL + this.mdl.photo
      }
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values)
          this.confirmLoading = true
          saveVisitorPerson(values).then(res => {
            if (res.code === 0) {
              this.$message.success('保存成功')
              this.$emit('ok')
              this.visible = false
            } else {
              this.$message.error(res.msg)
            }
          }).catch(() => {
            this.$message.error('系统错误，请稍后再试')
          }).finally(() => {
            this.confirmLoading = false
          })
        }
      })
    }
  },
  watch: {
    /*
      'selectedRows': function (selectedRows) {
        this.needTotalList = this.needTotalList.map(item => {
          return {
            ...item,
            total: selectedRows.reduce( (sum, val) => {
              return sum + val[item.dataIndex]
            }, 0)
          }
        })
      }
      */
  }
}
</script>
