<template>
  <a-modal
    :title="mdl.id>0?'编辑':'预约  ' + date + ' ' + timeRangeText"
    style='top: 20px'
    width='1200px'
    v-model='visible'
    :ok-button-props='{ props: { disabled: disabledConfirm } }'
    @ok='handleSubmit'
  >
    <a-card title='会议室情况'>
      <a-tabs default-active-key='1' @change='callback'>
        <a-tab-pane key='1' tab='会议室详情'>
          <a-carousel autoplay>
            <div v-for='item in banner'>
              <img :src='item' />
            </div>
          </a-carousel>
          <a-descriptions title='' bordered>
            <a-descriptions-item label='会议室名称'>
              {{ roomDetail.name }}
            </a-descriptions-item>
            <a-descriptions-item label='会议室概况'>
              {{ roomDetail.floor }} | {{ roomDetail.roomNum }} | {{ roomDetail.capacityNum }}人 |
              {{ roomDetail.typeName }}
            </a-descriptions-item>
            <a-descriptions-item label='会议室设备'>
              {{ roomDetail.device }}
            </a-descriptions-item>
            <a-descriptions-item label='会议室描述'>
              {{ roomDetail.content }}
            </a-descriptions-item>
          </a-descriptions>
        </a-tab-pane>
        <a-tab-pane key='2' tab='预约情况' force-render>
          <a-table :columns='recordCol' :data-source='recordList'>
          </a-table>
        </a-tab-pane>
      </a-tabs>
    </a-card>
    <a-card :title='"我要预约  " + date + " " + timeRangeText' style='margin-top: 10px'>
      <a-empty v-show='disabledConfirm'>
        <span slot='description'>当前时段无法预约</span>
      </a-empty>
      <a-form :form='form' v-show='!disabledConfirm'>
        <a-form-item style='display: none'>
          <a-input v-decorator="['id']" />
        </a-form-item>
        <a-row>
          <a-col :span='20'>
            <a-form-item label='预约时间' :labelCol='{xs: { span: 24 }, sm: { span: 4 }}' :wrapperCol='wrapperCol'>
              <a-time-picker :disabled='disabledTime'
                             v-decorator="['start',{rules: [{ required: true, message: '选择会议时间' }]}]"
                             format='HH:mm' :disabledHours='disabledHours' :disabledMinutes='disabledMinutes'
                             hideDisabledOptions='true' />
              <a-time-picker :disabled='disabledTime'
                             v-decorator="['end',{rules: [{ required: true, message: '选择会议时间' }]}]"
                             style='margin-left: 10px' format='HH:mm' :disabledHours='disabledHours'
                             :disabledMinutes='disabledMinutes' hideDisabledOptions='true' />
              <a-button type='danger' v-if='isAdmin' style='margin-left: 20px' @click='handleUse'>
                提前占用
              </a-button>
            </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="['title',{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="['personNum',{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="['leader',{rules: [{ required: true, message: '输入参会领导' }]}]" />
            </a-form-item>
          </a-col>
          <a-col :span='10'>
            <a-form-item label='预约部门' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-select show-search v-decorator="['userOrgId',{rules: [{ required: true, message: '选择预约部门' }]}]"
                        placeholder='请选择预约部门'>
                <a-select-option v-for='item in depList' :value='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 label='预约人' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input placeholder='预约人'
                       v-decorator="['bookingUserName',{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="['bookingUserPhone',{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
                v-decorator="['service']">
                <a-checkbox v-for='item in serviceList' :value='item.value'>
                  {{ item.text }}
                </a-checkbox>
              </a-checkbox-group>
            </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="['remark']" style='height: 100px' />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

  </a-modal>
</template>
<script>
import {
  meetingRoomDetail, getDep, saveMeetingReservation, getOrderInfo, useRoom
} from '@/api/admin/meeting/meetingReservation'
import pick from 'lodash.pick'
import storage from 'store'
import moment from 'moment'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { getMeetingDict } from '@/api/admin/meeting/roomContent'
import { checkPermission } from '@/utils/permissions'

export default {
  name: 'RoomOrderModal',
  props: {},
  components: {},
  data() {
    return {
      visible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 }
      },
      wrapperCol: {
        xs: { span: 35 },
        sm: { span: 16 }
      },
      mdl: {},
      form: this.$form.createForm(this),
      rId: '', // 预约id
      timeRange: '',
      timeRangeText: '',
      date: '',
      id: '', // 会议室id
      depId: '',
      dep: '',
      banner: '',
      roomDetail: {},
      recordList: [],
      recordCol: [{
        title: '预约时间',
        dataIndex: 'time'
      }, {
        title: '预约单位',
        dataIndex: 'userOrg'
      }, {
        title: '预约人',
        dataIndex: 'bookingUserName'
      }, {
        title: '联系方式',
        dataIndex: 'bookingUserPhone'
      }],
      serviceList: [],
      serviceMap: {},
      disabledConfirm: false,
      depList: [],
      disabledTime: false,
      isAdmin: checkPermission('meeting:admin')
    }
  },
  beforeCreate() {
  },
  created() {
  },
  mounted() {
    // this.getDict()
  },
  methods: {
    getDict(roomServId) {
      let serveIdArr = roomServId.split(',')
      getMeetingDict().then((res) => {
        // 服务
        let dataObj = res.data
        let _serviceList = []
        for (let key in dataObj.services) {
          let eachObj = dataObj.services[key]
          const keys = Object.keys(eachObj)
          if (serveIdArr.indexOf(eachObj[keys[0]]) !== -1) {
            _serviceList.push({
              text: keys[0],
              value: eachObj[keys[0]]
            })
            this.serviceMap[eachObj[keys[0]]] = keys[0]
          }
        }
        this.serviceList = _serviceList
      })
    },
    getAllDep() {
      getDep().then(res => {
        let dep = res.data
        let depList = []
        for (let key in dep) {
          let eachObj = dep[key]
          depList.push({
            id: eachObj['orgId'].toString(),
            name: eachObj['orgName']
          })
        }
        this.depList = depList
      })
    },
    add(data) {
      console.log(data)
      this.id = data.id
      this.timeRange = data.timeRange
      if (this.timeRange == 1) {
        this.timeRangeText = '上午'
      }
      if (this.timeRange == 2) {
        this.timeRangeText = '下午'
      }
      if (this.timeRange == 3) {
        this.timeRangeText = '晚上'
      }
      if (this.timeRange == 4) {
        this.timeRangeText = '全天'
      }
      this.date = data.date
      this.depId = data.depId
      this.dep = data.dep
      this.form.resetFields()
      this.mdl = {}
      this.serviceList = []
      this.serviceMap = []
      this.visible = true
      this.getRoomInfo()
      this.getAllDep()
      if (data.status == 1) {
        this.disabledConfirm = true
      } else {
        this.disabledConfirm = false
      }
      // 给默认值赋值
      this.$nextTick(() => {
        this.form.setFieldsValue({
          id: '',
          userOrgId: this.depId.toString()
        })
      })
    },
    edit(data) {
      let act = data.act
      this.rId = data.rId
      if (act == 1) {
        // 选择的房间
        this.id = data.id
        // 重新选择时间、会议室
        this.timeRange = data.timeRange
        if (this.timeRange == 1) {
          this.timeRangeText = '上午'
        }
        if (this.timeRange == 2) {
          this.timeRangeText = '下午'
        }
        if (this.timeRange == 3) {
          this.timeRangeText = '晚上'
        }
        if (this.timeRange == 4) {
          this.timeRangeText = '全天'
        }
        this.date = data.date
        this.depId = data.depId
        this.dep = data.dep
        // 直接获取会议室信息
        this.getRoomInfo()
      } else if (act == 2) {
        // 重新编辑信息
        this.disabledTime = true
        console.log('编辑信息')
      } else {
        this.$message.error('非法操作！')
        return
      }
      this.form.resetFields()
      this.mdl = {}
      this.serviceList = []
      this.serviceMap = []
      this.visible = true
      this.getAllDep()
      if (data.status == 1) {
        this.disabledConfirm = true
      } else {
        this.disabledConfirm = false
      }
      getOrderInfo({ id: this.rId }).then((res) => {
        if (act == 1) {
          // 重新选择时间和会议室
          res.mr.start = ''
          res.mr.end = ''
          res.mr.service = [] // 清空服务
        } else {
          // 重新编辑信息，此时会议室信息要单独获取
          this.id = res.mr.roomId
          this.timeRange = res.mr.timeFormat
          if (this.timeRange == 1) {
            this.timeRangeText = '上午'
          }
          if (this.timeRange == 2) {
            this.timeRangeText = '下午'
          }
          if (this.timeRange == 3) {
            this.timeRangeText = '晚上'
          }
          if (this.timeRange == 4) {
            this.timeRangeText = '全天'
          }
          this.date = moment(res.mr.start).format('YYYY-MM-DD')
          this.getRoomInfo()
          res.mr.start = moment(res.mr.start)
          res.mr.end = moment(res.mr.end)
          let service = []
          for (let key in res.serve) {
            service.push(res.serve[key].value)
          }
          res.mr.service = service
        }
        res.mr.userOrgId = res.mr.userOrgId.toString()
        this.mdl = Object.assign(this.mdl, res.mr)
        this.visible = true
        this.$nextTick(() => {
          this.form.setFieldsValue(
            pick(
              this.mdl,
              'id',
              'start',
              'end',
              'title',
              'personNum',
              'leader',
              'userOrgId',
              'bookingUserName',
              'bookingUserPhone',
              'remark',
              'service'
            )
          )
        })
      })
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = false
          // 处理一下serviceList
          let service = []
          let serviceList = values.service
          for (let key in serviceList) {
            let eachObj = serviceList[key]
            service.push({
              name: this.serviceMap[eachObj],
              value: eachObj,
              remark: ''
            })
          }

          // 处理开始结束时间
          values.start = values.start.format(this.date + ' HH:mm:00')
          values.end = values.end.format(this.date + ' HH:mm:00')

          // 计算一下时间差
          var a = moment(values.start)
          var b = moment(values.end)
          var c = moment() // 当前时间
          var timeDiff = b.diff(a)
          var timeDiffNow = c.diff(a)
          if (timeDiff < 0) {
            // 异常
            this.$message.error('结束时间不能小于开始时间！')
            return
          }
          if (timeDiffNow > 0) {
            // 异常
            this.$message.error('开始时间请大于当前时间！！')
            return
          }
          values.mrdate = this.date
          values.timeFormat = this.timeRange
          if (values.timeFormat == 4) {
            // 全天，设置为0
            values.timeFormat = 0
          }
          // 处理获取orgName
          for (let key in this.depList) {
            if (this.depList[key]['id'] == values.userOrgId) {
              values.userOrg = this.depList[key]['name']
            }
          }
          values.roomId = this.id
          let data = {
            'mr': values,
            'serve': service
          }

          saveMeetingReservation(data).then((res) => {
            if (res.code === 0) {
              if (this.rId == '') {
                this.$message.success('预约成功，请等待审核！')
              } else {
                this.$message.success('信息已修改，请等待审核！')
              }
              this.$emit('ok')
              this.visible = false
            } else {
              this.$message.error(res.msg)
            }
          }).catch(() => {
            this.$message.error('系统错误，请稍后再试')
          }).finally(() => {
            // this.confirmLoading = false
          })
        }
      })
    },
    // 提前占用方法
    handleUse() {
      // 提前占用，获取时间范围
      let sTime = this.form.getFieldValue('start')
      let eTime = this.form.getFieldValue('end')
      if (sTime && eTime) {
        // 处理开始结束时间
        let data = {
          'mr': {
            'roomId': this.id,
            'start': sTime.format(this.date + ' HH:mm:00'),
            'end': eTime.format(this.date + ' HH:mm:00'),
            'mrdate': this.date,
            'timeFormat': '0'
          }
        }
        // 计算一下时间差
        var a = moment(data.mr.start)
        var b = moment(data.mr.end)
        var c = moment() // 当前时间
        var timeDiff = b.diff(a)
        var timeDiffNow = c.diff(a)
        if (timeDiff < 0) {
          // 异常
          this.$message.error('结束时间不能小于开始时间！')
          return
        }
        if (timeDiffNow > 0) {
          // 异常
          this.$message.error('开始时间请大于当前时间！！')
          return
        }
        useRoom(data).then(res => {
          if (res.code === 0) {
            this.$message.success('占用成功！')
            this.$emit('ok')
            this.visible = false
          } else {
            this.$message.error(res.msg)
          }
        })
      } else {
        this.$message.error('请选择占用时间！')
      }
    },
    getRoomInfo() {
      meetingRoomDetail({
        roomId: this.id
      }).then(res => {
        console.log('meetingRoomDetailRq', res)
        let detail = res.room // 详细信息
        let recordList = res.mr // 预约信息
        let bannerList = [] // 轮播图
        if (detail.imgs) {
          try {
            bannerList = detail.imgs.map(item => process.env.VUE_APP_MODEL_BASE_URL + item.url)
          } catch (error) {
            console.log(`JSON error : ${error}`)
          }
        }
        let newRecordList = []
        for (let key in recordList) {
          let eachObj = recordList[key]
          let sTime = eachObj['start']
          let eTime = eachObj['end']
          eachObj['date'] = moment(sTime).format('YYYY-MM-DD')
          eachObj['time'] = moment(sTime).format('YYYY-MM-DD HH:mm') + '~' + moment(eTime).format('HH:mm')
          newRecordList.push(eachObj)
        }
        this.recordList = newRecordList
        this.roomDetail = detail
        this.banner = bannerList
        this.getDict(detail.ext1)
      })
    },
    disabledHours() {
      if (this.timeRange == 1) {
        // 上午，9：00-12：00
        return [0, 1, 2, 3, 4, 5, 6, 7, 8, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
      }
      if (this.timeRange == 2) {
        // 下午，13：30-17：30
        return [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 18, 19, 20, 21, 22, 23, 24]
      }
      if (this.timeRange == 3) {
        // 晚上，17：30-24
        return [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
      }
    },
    disabledMinutes(nowH) {
      if (this.timeRange == 1) {
        // 上午，都可以
        if (nowH == 12) {
          let res = []
          for (let i = 1; i < 60; i++) {
            res.push(i)
          }
          return res
        }
      }
      if (this.timeRange == 2) {
        // 下午，13：00-13：29不能选
        if (nowH == 13) {
          let res = []
          for (let i = 0; i < 30; i++) {
            res.push(i)
          }
          return res
        }
        // 下午17：31-17：59不能选
        if (nowH == 17) {
          let res = []
          for (let i = 31; i < 60; i++) {
            res.push(i)
          }
          return res
        }
      }
      if (this.timeRange == 3) {
        // 晚上，17：00-17：30不能选
        if (nowH == 17) {
          let res = []
          for (let i = 0; i < 31; i++) {
            res.push(i)
          }
          return res
        }
      }
    }
  }
}

</script>

<style scoped>
/* For demo */
.ant-carousel >>> .slick-dots {
  height: auto;
}

.ant-carousel >>> .slick-slide img {
  border: 5px solid #fff;
  display: block;
  margin: auto;
  max-width: 300px;
}

.ant-carousel >>> .slick-thumb {
  bottom: -45px;
}

.ant-carousel >>> .slick-thumb li {
  width: 60px;
  height: 45px;
}

.ant-carousel >>> .slick-thumb li img {
  width: 100%;
  height: 100%;
  filter: grayscale(100%);
}

.ant-carousel >>> .slick-thumb li.slick-active img {
  filter: grayscale(0%);
}

.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>