<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 label='所属楼层' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-select v-decorator="['floor',{rules: [{ required: true, message: '选择所属楼层' }]}]"
                      placeholder='所属楼层'>
              <a-select-option v-for='item in typeList' :value='item.value'>
                {{ item.text }}
              </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="['name',{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="['typeName',{rules: [{ required: true, message: '选择会议室形式' }]}]"
                      placeholder='会议室形式'>
              <a-select-option v-for='item in shapeList' :value='item.value'>
                {{ item.text }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span='10'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='所属房间 '>
            <a-input placeholder='所属房间'
                     v-decorator="['roomNum',{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="['area',{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="['capacityNum',{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-checkbox-group :defaultValue='defaultCheckedList'
                              v-decorator="['device',{rules: [{ required: true, message: '请选择会议室设备' }]}]">
              <a-checkbox v-for='item in deviceList' :value='item.value'>
                {{ item.text }}
              </a-checkbox>
            </a-checkbox-group>
          </a-form-item>
        </a-col>
        <a-col :span='10'>
          <a-form-item label='是否启用' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-select v-decorator="['enable',{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='会议室描述 ' 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="['files', {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, getMeetingDict, getRoomInfo
} 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',
      uploadUrl: process.env.VUE_APP_API_BASE_URL + '/admin/meetingRoom/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: {},
      typeList: [],
      shapeList: [],
      deviceList: [],
      typeMap: {},
      shapeMap: {},
      deviceMap: {},
      // tenantList: [], // 地区
      // parkList: [], // 园区
      // buildingList: [], // 楼宇
      // buildingDetailList: [], // 楼层
      // roomList: [], // 房间
      tenantEnable: false,
      parkEnable: false,
      previewVisible: false,
      previewImage: '',
      fileList: []
    }
  },
  beforeCreate() {
  },
  created() {

  },
  mounted() {
    this.getDict()
  },
  methods: {
    getDict() {
      getMeetingDict().then((res) => {
        // 楼层
        let _typeList = []
        let _typeMap = {}
        let dataObj = res.data
        for (let key in dataObj.floors) {
          let eachObj = dataObj.floors[key]
          const keys = Object.keys(eachObj)
          _typeList.push({
            text: keys[0],
            value: keys[0]
          })
          this.typeMap[keys[0]] = eachObj[keys[0]]
          // this.typeMap.keys[0] = eachObj[keys[0]]
        }

        this.typeList = _typeList

        // 形状
        let _shapeList = []
        for (let key in dataObj.types) {
          let eachObj = dataObj.types[key]
          const keys = Object.keys(eachObj)
          _shapeList.push({
            text: keys[0],
            value: keys[0]
          })
          this.shapeMap[keys[0]] = eachObj[keys[0]]
        }
        this.shapeList = _shapeList

        // 设备
        let _deviceList = []
        for (let key in dataObj.devices) {
          let eachObj = dataObj.devices[key]
          const keys = Object.keys(eachObj)
          _deviceList.push({
            text: keys[0],
            value: keys[0]
          })
          this.deviceMap[keys[0]] = eachObj[keys[0]]
        }
        this.deviceList = _deviceList
      })
    },
    // 获取用户详细信息
    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
        //   })
        // }
        console.log(this.mdl)
      })
    },
    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 = {}
      this.fileList = []
      this.visible = true
    },
    edit(id) {
      this.form.resetFields()
      this.mdl = {}
      this.fileList = []
      getRoomInfo({ roomId: id }).then((res) => {
        let deviceStr = res.room.device
        if (deviceStr != '') {
          deviceStr = deviceStr.replaceAll(' ', '')
          let deviceArr = deviceStr.split('#')
          if (deviceArr[0] == '') {
            deviceArr.shift()
          }
          res.room.device = deviceArr
        }
        this.mdl = Object.assign(this.mdl, res.room)

        this.visible = true
        this.$nextTick(() => {
          this.form.setFieldsValue(
            pick(
              this.mdl,
              'id',
              'device',
              'typeName',
              'name',
              'capacityNum',
              'floor',
              'files',
              'startTime',
              'endDate',
              'money',
              'enable',
              'typeName',
              'content',
              'area',
              'roomNum'
            )
          )
        })
        // 图片
        console.log(this.mdl)
        if (this.mdl.imgs) {
          let files = []
          let fileId = []
          for (let key in this.mdl.imgs) {
            let eachObj = this.mdl.imgs[key]
            files.push({
              uid: '0',
              id: eachObj.id,
              url: process.env.VUE_APP_MODEL_BASE_URL + eachObj.url,
              status: 'done',
              name: eachObj.url
            })
            fileId.push(eachObj.id)
          }
          this.fileList = files
          this.mdl.files = fileId
        } else {
          this.fileList = []
        }
      })

      // // let copyMdl = JSON.parse(JSON.stringify(this.mdl))
      // // 查询地区
      // // this.getTenantData()
      // //
      // if (record.id != 0) { // 编辑
      // } else { // 新增
      // }
      // // 获取用户信息
      // this.getUserDetail()

      // //

    },
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values)
          this.confirmLoading = false

          // const indoorPicUrl = []
          const files = []

          this.fileList.forEach((file, index) => {
            // 添加原来的

            if (file.hasOwnProperty('url') && file.hasOwnProperty('id')) {
              // indoorPicUrl.push({ 'name': file.name, 'url': file.name, 'id': file.id })

              files.push(file.id)
            }
            if (file.hasOwnProperty('response') && file.status === 'done' && file.response.code === 0) {
              const data = file.response
              // indoorPicUrl.push({ 'name': data.fileName, 'url': data.fileName, 'uid': index })
              files.push(file.response.id)
            }

          })

          // 多个图片
          // values.indoorPicUrl = JSON.stringify(indoorPicUrl)
          values.files = files
          let deviceArr = values.device
          let deviceStr = ''
          for (let key in deviceArr) {
            let eachObj = deviceArr[key]
            deviceStr += '#' + eachObj + ' '
          }
          values.device = deviceStr
          values.floorId = this.typeMap[values.floor]
          values.typeId = this.shapeMap[values.typeName]

          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>