<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="['tenantId', {rules: [{ required: true, message: '请选择所属地区' }]}]"
                  @change='selectTenant'
                  :disabled='tenantEnable'>
          <a-select-option v-for='item in tenantList' :key='item.id'>{{ item.name }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='所属园区'>
        <a-select v-decorator="['parkId', {rules: [{ required: true, message: '请选择所属园区' }]}]"
                  @change='selectPark'
                  :disabled='parkEnable'>
          <a-select-option v-for='item in parkList' :key='item.id'>{{ item.name }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='被访单位'>
        <a-select v-decorator="['customerId',{rules: [{ required: true, message: '请选择被访单位' }]}]"
                  placeholder='请选择被访单位'
                  @change='selectEnterprise'>
          <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='selectPerson'>-->
<!--          <a-select-option v-for='item in personList' :key='item.id' :value='item.id'>-->
<!--            {{ item.mobile + '-' + item.username }}-->
<!--          </a-select-option>-->
<!--        </a-select>-->
        <a-input placeholder='被访人手机号'
                 v-decorator="['userName',{rules: [{ required: true, message: '被访人手机号不能为空'}]}]"  />
      </a-form-item>
      <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='被访人手机号'>
        <a-input placeholder='被访人手机号'
                 v-decorator="['userMobile',{rules: [{ required: true, message: '被访人手机号不能为空'}]}]"  />
      </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 { getInfo } from '@/api/login'
import { getTenantList } from '@/api/tenant'
import { getParkList } from '@/api/admin/park'
import pick from 'lodash.pick'
import { getRoomListByFloorId } from '@/api/admin/meeting/roomContent'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { getBuildingList } from '@/api/admin/building'


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),
      idcardTypeList: [{
        name: '居民身份证'
      }],
      uploadUrl: process.env.VUE_APP_API_BASE_URL + '/api/dfs/upload',
      imageUrl: '',
      headers: {
        Authorization: 'Bearer ' + storage.get(ACCESS_TOKEN)
      },
      userDetail: {},
      tenantList: [], // 地区
      parkList: [], // 园区
      enterpriseList: [], // 企业
      personList: [],  // 人员
      tenantEnable: false,
      parkEnable: false
    }
  },
  beforeCreate() {
  },
  created() {

  },
  methods: {
    // 获取用户详细信息
    getUserDetail() {
      getInfo().then(res => {
        console.log('getUserDetail', res)
        this.userDetail = res
        // 园区：5
        if (this.userDetail.roleIds && this.userDetail.roleIds.length > 0 && this.userDetail.roleIds[0] == 5) {
          //
          // 判断：是新增就查询园区
          let { id } = this.mdl
          if (!id) {
            // 选择地区 -> 查询园区
            this.selectTenant(this.userDetail.tenantId)
            // 选择园区 -> 查询楼宇
            this.selectPark(this.userDetail.parkId)
          }
          //
          // 不可编辑
          this.tenantEnable = true
          this.parkEnable = true
          // 关联地区和园区
          this.mdl.parkId = this.userDetail.parkId
          this.mdl.tenantId = this.userDetail.tenantId
          this.form.setFieldsValue({
            parkId: this.mdl.parkId,
            tenantId: this.mdl.tenantId
          })
        }
      })
    },
    // 查询地区
    getTenantData() {
      getTenantList().then(res => {
        this.tenantList = res.rows
      })
    },
    // 选择地区 -> 查询园区
    selectTenant(id) {
      console.log('selectTenant', id)
      // 清空数据
      this.mdl.parkId = null // 园区
      this.mdl.customerId = null // 企业
      this.mdl.userId = null // 人员
      this.mdl.mobile = null // 手机号

      this.form.setFieldsValue({
        parkId: null, // 园区
        customerId: null, // 企业
        userId: null, // 人员
        mobile: null // 手机号
      })
      // 查询园区
      getParkList({
        tenantId: id
      }).then(res => {
        this.parkList = res.rows
      })
    },
    // 选择园区 -> 查询企业
    selectPark(id) {
      // 清空数据
      this.mdl.customerId = null // 企业
      this.mdl.userId = null // 人员
      this.mdl.mobile = null // 手机号

      this.form.setFieldsValue({
        customerId: null, // 企业
        userId: null, // 人员
        mobile: null // 手机号
      })
      // 查询企业
      selectCustomer({
        parkId: id
      }).then(res => {
        console.log('selectCustomer', res)
        this.enterpriseList = res.data
      })
    },
    // 选择企业 -> 查询人员
    selectEnterprise(id, userId) {
      // 清空数据
      this.mdl.userId = null // 人员
      this.mdl.mobile = null // 手机号

      this.form.setFieldsValue({
        userId: null, // 人员
        mobile: null // 手机号
      })
      // 查询人员
      selectUserByCustomer(id).then(res => {
        console.log('selectUserByCustomer', res)
        this.personList = res.data
        // 选择人员 -> 赋值"手机号"
        if (userId) {
          this.selectPerson(userId)
        }
      })
    },
    // 选择人员 -> 赋值"手机号"
    selectPerson(id) {
      // 清空数据
      this.mdl.mobile = null // 手机号

      this.form.setFieldsValue({
        mobile: null // 手机号
      })
      console.log('this.personList', this.personList)
      console.log('id', id)
      this.form.setFieldsValue({ mobile: this.personList.find(item => item.id == id).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 < 5000
      if (!isLt2M) {
        this.$message.error('图片必须小于 5M!')
      }
      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.mdl = {}
      this.form.resetFields()
      this.edit({ id: 0 })
    },
    edit(record) {
      this.mdl = Object.assign(this.mdl, record)
      let copyMdl = JSON.parse(JSON.stringify(this.mdl))
      // 查询地区
      this.getTenantData()
      //
      if (record.id) { // 编辑
        // 选择地区 -> 查询园区
        if (copyMdl.tenantId) {
          this.mdl = JSON.parse(JSON.stringify(copyMdl))
          this.selectTenant(copyMdl.tenantId)
        }
        // 选择园区 -> 查询企业
        if (copyMdl.parkId) {
          this.mdl = JSON.parse(JSON.stringify(copyMdl))
          this.selectPark(copyMdl.parkId)
        }
        // 选择企业 -> 查询人员 , 选择人员 -> 赋值"手机号"
        if (copyMdl.customerId) {
          this.mdl = JSON.parse(JSON.stringify(copyMdl))
          this.selectEnterprise(copyMdl.customerId, copyMdl.userId)
        }
        // 防止替换
        this.mdl = JSON.parse(JSON.stringify(copyMdl))

      } else { // 新增

      }
      // 获取用户信息
      this.getUserDetail()
      //
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.mdl, 'id', 'tenantId', 'parkId', 'customerId', 'userId', 'mobile', '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
      } else {
        this.imageUrl = null
      }
    },
    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>
