<template>
  <a-modal
    :title="mdl.id>0?'编辑':'新增'"
    style='top: 20px'
    width='1200px'
    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-row>
        <a-col :span='10'>
          <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-col>
        <a-col :span='10'>
          <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-col>
      </a-row>

      <a-row>
        <a-col :span='10'>
          <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-col>
        <a-col :span='10'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='所属楼层'>
            <a-select v-decorator="['buildId',{rules: [{ required: true, message: '请选择所属楼层' }]}]"
                      placeholder='所属楼层'
                      @change='selectBuildingDetail'>
              <a-select-option v-for='item in buildingDetailList' :key='item.id' :value='item.id'>
                {{ item.floorName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row>
        <a-col :span='10'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='所属房间'>
            <a-select v-decorator="['roomId',{rules: [{ required: true, message: '选择所属房间' }]}]"
                      placeholder='所属房间'
                      @change='selectRoom'>
              <a-select-option v-for='item in roomList' :key='item.id' :value='item.id'>
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span='10'>
          <a-form-item label='会议室面积' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-input placeholder='会议室面积'
                     v-decorator="['area',{rules: [{ required: true, message: '请输入会议室面积' }]}]"
                     disabled='disabled' />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row>
        <a-col :span='10'>
          <a-form-item label='会议室名称' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-input placeholder='会议室名称'
                     v-decorator="['meetingName',{rules: [{ required: true, message: '输入会议室名称' }]}]" />
          </a-form-item>
        </a-col>
        <a-col :span='10'>
          <a-form-item label='会议室类型' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-select v-decorator="['type',{rules: [{ required: true, message: '输入会议室类型' }]}]"
                      placeholder='会议室类型'>
              <a-select-option :value='1'>
                会议室
              </a-select-option>
              <a-select-option :value='2'>
                路演厅
              </a-select-option>
              <a-select-option :value='3'>
                洽谈室
              </a-select-option>
              <a-select-option :value='4'>
                直播间
              </a-select-option>
              <a-select-option :value='5'>
                茶室
              </a-select-option>
              <a-select-option :value='6'>
                长阳会客厅
              </a-select-option>
              <a-select-option :value='7'>
                多功能厅
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span='10'>
          <a-form-item label='容纳人数' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-input placeholder='容纳人数'
                     v-decorator="['capacityNum',{rules: [{ required: true, message: '输入容纳人数' }]}]" />
          </a-form-item>
        </a-col>
        <a-col :span='10'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='会议室地址 '>
            <a-input placeholder='会议室地址'
                     v-decorator="['address',{rules: [{ required: true, message: '输入会议室地址' }]}]" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span='10'>
          <a-form-item label='排列形状' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-select v-decorator="['shape',{rules: [{ required: true, message: '输入排列形状' }]}]"
                      placeholder='排列形状'>
              <a-select-option value='围桌式'>
                围桌式
              </a-select-option>
              <a-select-option value='课桌式'>
                课桌式
              </a-select-option>
              <a-select-option value='长方形'>
                长方形
              </a-select-option>
              <a-select-option value='U形'>
                U形
              </a-select-option>
              <a-select-option value='鱼骨形'>
                鱼骨形
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span='10'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='负责人'>
            <a-input placeholder='负责人'
                     v-decorator="['headName',{rules: [{ required: true, message: '输入负责人' }]}]" />
          </a-form-item>
        </a-col>
        <a-col :span='10'>
          <a-form-item label='负责人联系方式' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-input placeholder='负责人联系方式'
                     v-decorator="['headPhone',{rules: [{ required: true, message: '输入负责人联系方式'}]}]" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span='10'>
          <a-form-item label='预约开始时间' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-time-picker v-decorator="['startTime',{rules: [{ required: true, message: '请选择预约开始时间'}]}]"
                           format='HH:mm'
                           valueFormat='YYYY-MM-DD HH:mm:ss'
                           placeholder='选择时间'
                           :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
                           style='width: 100%;' />
          </a-form-item>
        </a-col>
        <a-col :span='10'>
          <a-form-item label='预约结束时间' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-time-picker v-decorator="['endDate',{rules: [{ required: true, message: '请选择预约结束时间'}]}]"
                           format='HH:mm'
                           valueFormat='YYYY-MM-DD HH:mm:ss'
                           placeholder='选择时间'
                           :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
                           style='width: 100%;' />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row>
        <a-col :span='10'>
          <a-form-item label='是否使用优惠劵' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-select v-decorator="['isTicket',{rules: [{ required: true, message: '请选择优惠券'}]}]"
                      placeholder='是否使用优惠劵'>
              <a-select-option :value='0'>
                是
              </a-select-option>
              <a-select-option :value='1'>
                否
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row>
        <a-col :span='10'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='是否收费'>
            <a-select v-decorator="['isToll',{rules: [{ required: true, message: '请选择是否收费'}]}]"
                      @change='selectChangeIsToll' placeholder='是否收费'>
              <a-select-option :value='0'>
                是
              </a-select-option>
              <a-select-option :value='1'>
                否
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span='10'>
          <a-form-item v-if='mdl.isToll === 0' :labelCol='labelCol' :wrapperCol='wrapperCol' label='收费金额 '>
            <a-input placeholder='收费金额 '
                     v-decorator="['money',{rules: [{ required: true, message: '请输入收费金额'}]}]" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span='10'>
          <a-form-item label='起租时长' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-input placeholder='起租时长'
                     v-decorator="['duration',{rules: [{ required: true, message: '请输入起租时长'}]}]" />
          </a-form-item>
        </a-col>
        <a-col :span='10'>
          <a-form-item label='是否启用' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-select v-decorator="['isShow',{rules: [{ required: true, message: '请选择是否启用'}]}]"
                      placeholder='是否启用'>
              <a-select-option :value='0'>
                是
              </a-select-option>
              <a-select-option :value='1'>
                否
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span='10'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='金额备注 '>
            <a-textarea placeholder='如：起租时长为x小时,超过x小时后,按照每小时x元计算 ' v-decorator="['remake']"
                        style='height: 100px' />
          </a-form-item>
        </a-col>
        <a-col :span='10'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='会议室描述 '>
            <a-textarea placeholder='会议室描述 ' v-decorator="['content']" style='height: 100px' />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span='10'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='室内图片'>
            <a-upload
              v-decorator="['indoorPicUrl', {rules: [{ required: true, message: '上传室内图片' }]}]"
              list-type='picture-card'
              class='avatar-uploader'
              :file-list='fileList'
              :action='uploadUrl'
              :headers='headers'
              @preview='handlePreview'
              @change='handleChangeFileList'
            >
              <div v-if='fileList.length < 4'>
                <a-icon type='plus' />
                <div class='ant-upload-text'> 上传</div>
              </div>
            </a-upload>
            <a-modal :visible='previewVisible' :footer='null' @cancel='handleCancel'>
              <img style='width: 100%' :src='previewImage' />
            </a-modal>
          </a-form-item>
        </a-col>
      </a-row>

    </a-form>
  </a-modal>
</template>
<script>
import {
  saveRoomContent,
  getRoomListByFloorId,
  selectRoomById
} from '@/api/admin/meeting/roomContent'
import pick from 'lodash.pick'
import storage from 'store'
import moment from 'moment'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { getInfo } from '@/api/login'
import { getTenantList } from '@/api/tenant'
import { getParkList } from '@/api/admin/park'
import { getBuildingList } from '@/api/admin/building'
import { getBuildingDetailList } from '@/api/admin/buildingDetail'

export default {
  name: 'RoomContentModal',
  props: {},
  components: {},
  data() {
    return {
      visible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 }
      },
      uploadUrl: process.env.VUE_APP_API_BASE_URL + '/api/dfs/upload',
      imageUrl: '',
      headers: {
        Authorization: 'Bearer ' + storage.get(ACCESS_TOKEN)
      },
      loading: false,
      wrapperCol: {
        xs: { span: 35 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      mdl: {},
      typeData: [],
      form: this.$form.createForm(this),
      userDetail: {},
      tenantList: [], // 地区
      parkList: [], // 园区
      buildingList: [], // 楼宇
      buildingDetailList: [], // 楼层
      roomList: [], // 房间
      tenantEnable: false,
      parkEnable: false,
      previewVisible: false,
      previewImage: '',
      fileList: []
    }
  },
  beforeCreate() {
  },
  created() {

  },
  mounted() {
  },
  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.buildId = null // 楼层
      this.mdl.roomId = null // 所属房间
      this.mdl.area = null // 会议室面积

      this.form.setFieldsValue({
        parkId: null, // 园区
        buildingId: null, // 楼宇
        buildId: null, // 楼层
        roomId: null, // 所属房间
        area: null // 会议室面积
      })
      // 查询园区
      getParkList({
        tenantId: id
      }).then(res => {
        this.parkList = res.rows
      })
    },
    // 选择园区 -> 查询楼宇
    selectPark(id) {
      // 清空数据
      this.mdl.buildingId = null // 楼宇
      this.mdl.buildId = null // 楼层
      this.mdl.roomId = null // 所属房间
      this.mdl.area = null // 会议室面积

      this.form.setFieldsValue({
        buildingId: null, // 楼宇
        buildId: null, // 楼层
        roomId: null, // 所属房间
        area: null // 会议室面积
      })
      // 查询楼宇
      getBuildingList({
        parkId: id
      }).then(res => {
        this.buildingList = res.rows
      })
    },
    // 选择楼宇 -> 查询楼层
    selectBuilding(id) {
      // 清空数据
      this.mdl.buildId = null // 楼层
      this.mdl.roomId = null // 所属房间
      this.mdl.area = null // 会议室面积

      this.form.setFieldsValue({
        buildId: null, // 楼层
        roomId: null, // 所属房间
        area: null // 会议室面积
      })
      // 查询楼层
      getBuildingDetailList({
        buildingId: id
      }).then(res => {
        this.buildingDetailList = res.rows
      })
    },
    // 选择楼层 -> 查询房间
    selectBuildingDetail(buildingDetailId) {
      // 查询房间
      this.getRoomListByFloorIdMethod(buildingDetailId)
    },
    // 查询房间
    getRoomListByFloorIdMethod(buildingDetailId, id) {
      // 清空数据
      this.mdl.roomId = null // 所属房间
      this.mdl.area = null // 会议室面积

      this.form.setFieldsValue({
        roomId: null, // 所属房间
        area: null // 会议室面积
      })
      // 查询房间
      getRoomListByFloorId({
        'id': id,
        'buildingDetailId': buildingDetailId,
        'type': 0
      }).then((res) => {
        this.roomList = res.data
      })
    },
    // 选择房间 -> 查询面积
    selectRoom(id) {
      // 清空数据
      this.mdl.area = null // 会议室面积

      this.form.setFieldsValue({
        area: null // 会议室面积
      })
      // 查询面积
      selectRoomById({
        'id': id
      }).then((res) => {
        this.form.setFieldsValue({
          area: res.data.area
        })
      })
    },
    //
    selectChangeIsToll(value) {
      this.mdl.isToll = value
    },
    moment,
    //
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64FileList(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    handleCancel() {
      this.previewVisible = false
    },
    // 上传banner
    handleChangeFileList({ fileList }) {
      this.fileList = fileList
    },
    add() {
      this.form.resetFields()
      this.mdl.indoorPicUrl = null
      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 != 0) { // 编辑
        // 选择地区 -> 查询园区
        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)
        }
        // 选择楼层 -> 查询房间
        if (copyMdl.buildId) {
          this.mdl = JSON.parse(JSON.stringify(copyMdl))
          this.getRoomListByFloorIdMethod(copyMdl.buildId, copyMdl.roomId)
        }
        // 防止替换
        this.mdl = JSON.parse(JSON.stringify(copyMdl))

      } else { // 新增

      }
      // 获取用户信息
      this.getUserDetail()
      // 图片
      if (this.mdl.indoorPicUrl) {
        this.mdl.indoorPicUrl = JSON.parse(this.mdl.indoorPicUrl)
        this.mdl.indoorPicUrl.forEach((item, i) => {
          item.url = process.env.VUE_APP_API_BASE_URL + item.url
        })
        this.fileList = this.mdl.indoorPicUrl
      } else {
        this.fileList = []
      }
      //
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(
          pick(
            this.mdl,
            'id',
            'type',
            'meetingName',
            'capacityNum',
            'expandNum',
            'indoorPicUrl',
            'startTime',
            'endDate',
            'money',
            'isShow',
            'shape',
            'area',
            'address',
            'headName',
            'headPhone',
            'isTicket',
            'isToll',
            'money',
            'remake',
            'duration',
            'content',
            'tenantId',
            'parkId',
            'buildingId',
            'buildId',
            'roomId'
          )
        )
      })
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values)
          this.confirmLoading = true
          const indoorPicUrl = []
          this.fileList.forEach((file, index) => {
            // 添加原来的
            if (file.hasOwnProperty('name') && file.hasOwnProperty('url') && file.hasOwnProperty('uid')) {
              indoorPicUrl.push({ 'name': file.name, 'url': file.name, 'uid': index })
            }
            if (file.status === 'done' && file.response.code === 0) {
              const data = file.response
              indoorPicUrl.push({ 'name': data.fileName, 'url': data.fileName, 'uid': index })
            }
          })
          // 多个图片
          values.indoorPicUrl = JSON.stringify(indoorPicUrl)
          saveRoomContent(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
            })
        }
      })
    }
  }
}

function getBase64(img, callback) {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result))
  reader.readAsDataURL(img)
}
</script>

<style scoped>
.self-item-cell {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.self-item-cell .self-item {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  width: 50%;
}

.self-item-cell .self-item:first-of-type {
  margin-right: 10px;
}

.self-item-cell .self-item .title {
  margin-right: 10px;
}

.self-item-cell .self-item .input {
  flex: 1;

}
</style>