<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="['buildingId', {rules: [{ required: true, message: '请选择所属楼宇' }]}]"
                  @change='selectBuilding'>
          <a-select-option v-for='item in buildingList' :key='item.id'>{{ item.buildingName }}</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='展厅'>
        <a-select v-decorator="['showroomId',{rules: [{ required: true, message: '请选择展厅' }]}]"
                  placeholder='请选择展厅'>
          <a-select-option v-for='item in showRoomList' :key='item.id' :value='item.id'>
            {{ item.meetingName }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='主题'>
        <a-input placeholder='展厅主题' v-decorator="['title',{rules: [{ required: true, message: '主题'}]}]" />
      </a-form-item>
      <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='预约开始时间'>
        <a-date-picker
          format='YYYY-MM-DD HH:mm:ss'
          valueFormat='YYYY-MM-DD HH:mm:ss'
          v-decorator="['startTime',{rules: [{ required: true, message: '预约开始时间'}]}]"
          :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
          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:ss'
          valueFormat='YYYY-MM-DD HH:mm:ss'
          v-decorator="['endDate',{rules: [{ required: true, message: '预约结束时间'}]}]"
          :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
          type='date'
          placeholder='选择时间'
          style='width: 100%;'
        />
      </a-form-item>
      <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='拟参观区域'>
        <a-select
          mode='multiple'
          placeholder='拟参观区域'
          style='width: 200px'
          @change='handleChange'
          @popupScroll='popupScroll'
          v-decorator="['visitArea',{rules: [{ required: true, message: '请选择拟参观区域'}]}]"
        >
          <a-select-option value='展厅(2楼)'>
            展厅(2楼)
          </a-select-option>
          <a-select-option value='公共服务配套区(15 楼)'>
            公共服务配套区(15楼)
          </a-select-option>
          <a-select-option value='中电郑州、生态企业(16楼)'>
            中电郑州、生态企业(16楼)
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='预约人员'>
        <a-button type='dashed' icon='plus' @click='addRow' class='addRowBtn'>
          新增一行
        </a-button>
      </a-form-item>
      <div style='margin-left: 80px'>
        <div class='dynamic-wrap' :style="{ maxHeight: wrapHeight + 'px' }">
          <div v-for='item in keysList' :key='item'>
            <a-row :gutter='24'>
              <a-col :span='6'>
                <a-form-item label='名称' :labelCol='{span: 8}' :wrapperCol='{span: 16}'>
                  <a-input
                    placeholder='请填写名称'
                    v-decorator="[
                  `${title}Name[${item}]`,
                  {
                    initialValue: arr[item] ? arr[item].name : undefined,
                    rules: [{ required: true, message: '请填职位' }]

                  }
                ]"
                  />
                </a-form-item>
              </a-col>
              <a-col :span='6'>
                <a-form-item label='职位' :labelCol='{span: 9}' :wrapperCol='{span: 15}'>
                  <a-input
                    placeholder='请填职位'
                    v-decorator="[
                  `${title}Job[${item}]`,
                  {
                    initialValue: arr[item] ? arr[item].job : undefined,
                    rules: [{ required: true, message: '请填职位' }]
                  }
                ]"
                  />
                </a-form-item>
              </a-col>
              <a-col :span='6'>
                <a-form-item label='手机号' :labelCol='{span: 8}' :wrapperCol='{span: 16}'>
                  <a-input
                    placeholder='请填手机号'
                    v-decorator='[
                  `${title}Phone[${item}]`,
                  {
                    initialValue: arr[item] ? arr[item].phone : undefined,
                  }
                ]'
                  />
                </a-form-item>
              </a-col>
              <a-col :span='2' style='padding-left: 0px'>
                <a-form-item :labelCol='{span: 0}' :wrapperCol='{span: 24}'>
                  <template v-if='keysList.length > 1'>
                    <a-button type='dashed' icon='minus' @click='removeRow(item)' class='minusRowBtn'></a-button>
                  </template>
                </a-form-item>
              </a-col>
            </a-row>
          </div>

        </div>
      </div>
      <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='拟参观区域'>
        <a-select
          placeholder='选择参观目的'
          style='width: 200px'
          v-decorator="['visitType',{rules: [{ required: true, message: '拟参观区域'}]}]"
        >
          <a-select-option v-for='item in recordOptions' :key='item' :value='item.value'>
            {{ item.text }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='讲解需求'>
        <a-switch
          v-decorator="['explainNeedType',{valuePropName: 'checked' , rules: [{  message: '讲解需求'}]}]" />
      </a-form-item>
      <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='会议室需求'>
        <a-switch
          v-decorator="['meetingNeedType',{valuePropName: 'checked' ,rules: [{  message: '会议室需求'}]}]" />
      </a-form-item>
      <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='摄影需求'>
        <a-switch
          v-decorator="['photographType',{valuePropName: 'checked' ,rules: [{  message: '摄影需求'}]}]" />
      </a-form-item>
    </a-form>
  </a-modal>


</template>
<script>
import { saveShowroomRecord, get } from '@/api/admin/meeting/showroomRecord'
import { showroomListRq } from '@/api/admin/meeting/showroom'
import pick from 'lodash.pick'
import storage from 'store'
import moment from 'moment'
import { getDictArray } from '@/utils/dict'
import { getInfo } from '@/api/login'
import { getTenantList } from '@/api/tenant'
import { getParkList } from '@/api/admin/park'
import { getBuildingList } from '@/api/admin/building'
import { roomContentList } from '@/api/admin/meeting/reservation'

let id = 0
export default {
  name: 'ShowroomRecordModal',
  props: {
    title: {
      type: String,
      default: ''
    },
    wrapHeight: { // 表单容器的高度
      type: Number,
      default: 120
    },
    arr: {
      type: Array,
      default: function() {
        return []
      }
    }

  },
  components: {},

  data() {
    return {
      ids: 0,
      keysList: [],
      recordOptions: [],
      visible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      mdl: {},
      form: this.$form.createForm(this),
      tenantList: [], // 地区
      parkList: [], // 园区
      buildingList: [], // 楼宇
      showRoomList: [], // 展厅
      tenantEnable: false,
      parkEnable: false
    }
  },
  beforeCreate() {
  },
  async created() {
    this.form = this.$form.createForm(this)
    this.init()
    const recordData = await getDictArray('visit_type')
    // 下拉选项
    recordData.map(d => {
      this.recordOptions.push({ text: d.dictLabel, value: d.dictValue })
    })
  },
  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.buildingId = null // 楼宇
      this.mdl.showroomId = null // 展厅

      this.form.setFieldsValue({
        parkId: null, // 园区
        buildingId: null, // 楼宇
        showroomId: null // 展厅
      })
      // 查询园区
      getParkList({
        tenantId: id
      }).then(res => {
        this.parkList = res.rows
      })
    },
    // 选择园区 -> 查询楼宇
    selectPark(id) {
      // 清空数据
      this.mdl.buildingId = null // 楼宇
      this.mdl.showroomId = null // 展厅

      this.form.setFieldsValue({
        buildingId: null, // 楼宇
        showroomId: null // 展厅
      })
      // 查询楼宇
      getBuildingList({
        parkId: id
      }).then(res => {
        this.buildingList = res.rows
      })
    },
    // 选择楼宇 -> 查询展厅
    selectBuilding(id) {
      // 清空数据
      this.mdl.showroomId = null // 展厅

      this.form.setFieldsValue({
        showroomId: null // 展厅
      })
      showroomListRq({
        buildingId: id
      }).then(res => {
        console.log('showroomListRq', res)
        this.showRoomList = res.data
      })
    },
    init() {
      const arr = [0]
      if (this.arr.length !== 0) {
        for (let i = 1; i < (this.arr).length; i++) {
          arr.push(i)
          this.id = this.id + 1
        }
      }
      this.keysList = arr
    },
    // 移除某行
    removeRow(k) {
      if (this.keysList.length === 1) { // 如果存在可以移除所有行的情况，把条件改为this.keysList.length === 0即可
        return
      }
      this.keysList = this.keysList.filter(item => item !== k)
    },
    // 新增一行
    addRow() {
      this.ids = this.ids + 1
      this.keysList = this.keysList.concat(this.ids)
      console.log(this.keysList)
    },
    moment,
    handleChange(value) {
    },
    popupScroll() {
    },
    add() {
      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.getUserDetail()
      this.getTenantData()
      //
      this.visible = true
      if (record.id) {
        get(record.id).then(res => {
          res.visitArea = res.visitArea.split(',')
          let persons = JSON.parse(res.persons)
          let names = persons.map(item => item.name)
          let jobs = persons.map(item => item.job)
          let phones = persons.map(item => item.phone)
          this.form.setFieldsValue({
            visitType: res.visitType.toString(),
            visitArea: res.visitArea,
            Name: names,
            Job: jobs,
            Phone: phones
          })
        })
        // 选择地区 -> 查询园区
        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.buildingId) {
          this.mdl = JSON.parse(JSON.stringify(copyMdl))
          this.selectBuilding(copyMdl.buildingId)
        }
        // 防止替换
        this.mdl = JSON.parse(JSON.stringify(copyMdl))
      }
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.mdl, 'id', 'userId', 'title', 'stauts',
          'explainNeedType', 'meetingNeedType', 'photographType',
          'reservationNumber', 'cancelTime', 'cancelResaon',
          'startTime', 'endDate', 'deleteFlag', 'createBy', 'createTime',
          'updateBy', 'updateTime', 'remake',
          'tenantId', 'parkId', 'buildingId', 'showroomId'))
      })
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {

        if (!err) {
          console.log('Received values of form: ', values)
          this.confirmLoading = true
          const partOneArr = []
          values[`Name`].forEach((item, index) => {
            console.log(index)
            const obj = {
              id: new Date().getTime(),
              name: item,
              job: values[`Job`][index],
              phone: values[`Phone`][index]
            }
            partOneArr.push(obj)
          })
          values.persons = JSON.stringify(partOneArr)
          values.visitArea = values.visitArea.join(',')

          values.explainNeedType = values.explainNeedType === true ? 1 : 0
          values.meetingNeedType = values.meetingNeedType === true ? 1 : 0
          values.photographType = values.photographType === true ? 1 : 0


          saveShowroomRecord(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>

<style>
.dynamic-delete-button {
  cursor: pointer;
  position: relative;
  top: 4px;
  font-size: 24px;
  color: #999;
  transition: all 0.3s;
}

.dynamic-delete-button:hover {
  color: #777;
}

.dynamic-delete-button[disabled] {
  cursor: not-allowed;
  opacity: 0.5;
}
</style>
