<template>
  <at-table
    @load="loadData"
    :data="data"
    :page-result="pageResult"
    ref="AtTable"
    :dialogTitle="dialogTitle"
    :dialogVisible="dialogVisible"
    :dialogWidth="'800px'"
    @handleDialogCancel="handleDialogCancel"
    @handleDialogClose="handleDialogClose"
    @handleDialogSubmit="handleDialogSubmit"
    @row-dblclick="handleRowDBClick"
  >
    <template v-slot:searchInput>
      <el-form
        ref="searchForm"
        :model="searchForm"
        label-width="80px"
        class="search-top"
        @submit.native.prevent
      >
        <el-input
          v-model="searchForm.theme"
          placeholder="请输入会议主题"
          @keyup.enter.native="handleSearch"
          clearable
          @input="handleSearch"
        />
        <dict-select
          v-model="searchForm.meetingType"
          :dict-code="'hylx'"
          placeholder="请选择会议类型"
          clearable
          style="width: 100%"
          @keyup.enter.native="handleSearch"
          @input="handleSearch"
        ></dict-select>

        <el-date-picker
          v-model="searchForm.startTime"
          type="date"
          placeholder="请选择开始时间"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
          clearable
          style="width: 100%"
          @keyup.enter.native="handleSearch"
          @change="handleSearch"
        ></el-date-picker>

        <el-button
          size="small"
          @click="handleSearch"
          type="primary"
          class="el-icon-search search-btn"
        >
          查询
        </el-button>
        <el-button
          size="small"
          @click="handleReset"
          type="primary"
          plain
          class="el-icon-refresh"
        >
          重置
        </el-button>
      </el-form>
    </template>
    <template v-slot:operationBtn>
      <el-button size="small" type="primary" @click="handleAdd">
        预约会议
      </el-button>
      <ht-delete-button :url="deleteUrl" :htTable="$refs.AtTable">
        删除会议
      </ht-delete-button>
    </template>
    <template>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="55" align="center" />
      <el-table-column
        prop="theme"
        label="会议主题"
        align="center"
        :show-overflow-tooltip="true"
      >
        <template v-slot="{row}">
          <el-link type="primary" @click="handleRowDBClick(row)">
            {{ row.theme }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column
        prop="meetingType"
        label="会议类型"
        align="center"
        :show-overflow-tooltip="true"
        :filters="getDictData('hylx')"
      >
        <template v-slot="{row}">
          {{ getDictName('hylx', row.meetingType) || '-' }}
        </template>
      </el-table-column>
      <el-table-column
        prop="startTime"
        label="开始时间"
        align="center"
        :show-overflow-tooltip="true"
      >
      </el-table-column>
      <el-table-column
        prop="endTime"
        label="结束时间"
        align="center"
        :show-overflow-tooltip="true"
      >
      </el-table-column>
      <el-table-column
        prop="places"
        label="地点"
        align="center"
        :show-overflow-tooltip="true"
      >
        <template v-slot="{row}">
          {{
            row.places.length > 0
              ? row.places.map((item) => item.name).join(',')
              : '-'
          }}
        </template>
      </el-table-column>
      <el-table-column
        prop="host"
        label="主持人"
        align="center"
        :show-overflow-tooltip="true"
      >
        <template v-slot="{row}">
          {{ row.host ? row.host : '-' }}
        </template>
      </el-table-column>
      <el-table-column
        prop="meetingStatus"
        label="会议状态"
        align="center"
        :show-overflow-tooltip="true"
      >
        <template v-slot="{row}">
          {{ getDictName('hyzt', row.meetingStatus) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="remark"
        label="备注"
        align="center"
        :show-overflow-tooltip="true"
      >
      </el-table-column>
      <el-table-column label="操作" align="center" width="150px">
        <template v-slot="{row}">
          <el-dropdown
            size="mini"
            split-button
            @command="handleCommand"
            @click="handleCommand({row: row, command: 'cancel'})"
          >
            <span> <i></i> 取消会议 </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :command="{row: row, command: 'end'}">
                结束会议
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </template>
    <template v-slot:dialogContent>
      <el-form
        ref="ruleForm"
        data-vv-scope="form"
        :model="form"
        :rules="rules"
        label-width="100px"
        v-if="dialogVisible"
        v-loading="loading"
      >
        <el-row>
          <el-form-item label="会议主题" prop="theme">
            <el-input
              v-model="form.theme"
              placeholder="请输入会议主题"
              clearable
            ></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="会议类型" prop="meetingType">
            <dict-select
              v-model="form.meetingType"
              :dict-code="'hylx'"
              placeholder="请选择会议类型"
              clearable
              style="width: 100%"
              @select="changeMeetingType"
            ></dict-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="参会人" prop="user">
            <eip-user-selector
              v-model="form.user"
              :permission="permission"
              append-to-body
              placeholder="请选择参会人"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
              v-model="form.startTime"
              type="datetime"
              placeholder="请选择开始时间"
              value-format="yyyy-MM-dd HH:mm"
              format="yyyy-MM-dd HH:mm"
              clearable
              style="width: 100%"
              @change="changeStartTime"
            ></el-date-picker>
          </el-form-item>
        </el-row>
        <el-row :gutter="24">
          <el-form-item label="结束时间" prop="endTime">
            <el-col :span="12">
              <el-select
                v-model="endTimeKey"
                clearable
                placeholder="请选择结束时间"
                @change="changeEndTimeOptions"
              >
                <el-option
                  v-for="item in optionsEndTime"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-col>

            <el-col :span="12">
              <el-date-picker
                :disabled="disabledEndTime"
                v-model="form.endTime"
                type="datetime"
                placeholder="请选择结束时间"
                value-format="yyyy-MM-dd HH:mm"
                format="yyyy-MM-dd HH:mm"
                clearable
                style="width: 100%"
                @change="changeEndTime"
              ></el-date-picker>
            </el-col>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="会议室" prop="place">
            <eip-place-selector
              :single="single"
              :placeList_="form.places"
              @showTag="showTag"
              @closeTag="closeTag"
              v-model="form.place"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="form.remark"
              placeholder="请输入备注"
              clearable
              type="textarea"
              rows="3"
            ></el-input>
          </el-form-item>
        </el-row>
      </el-form>

      <div class="collapse-box">
        <el-collapse v-model="activeNames">
          <el-collapse-item title="更多设置" name="1">
            <el-form :model="moreForm" label-width="160px">
              <el-row>
                <el-form-item label="提醒时间">
                  <dict-select
                    v-model="moreForm.remindTime"
                    :dict-code="'tx'"
                    placeholder="请选择提醒时间"
                    clearable
                    style="width: 100%"
                  ></dict-select>
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item label="主持人">
                  <el-input
                    v-model="moreForm.host"
                    placeholder="请输入主持人"
                    clearable
                  ></el-input>
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item label="开会密码">
                  <el-input
                    v-model="moreForm.password"
                    placeholder="请输入开会密码"
                    clearable
                  ></el-input>
                </el-form-item>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="开启等候室">
                    <el-switch
                      v-model="moreForm.isWaitRoom"
                      active-value="1"
                      inactive-value="0"
                    ></el-switch>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label-width="220px"
                    label="允许成员在主持人进会前加入"
                  >
                    <el-switch
                      v-model="moreForm.isOpen"
                      active-value="1"
                      inactive-value="0"
                    ></el-switch>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-form-item label="会议开始时来电提醒">
                  <dict-select
                    v-model="moreForm.remindUser"
                    :dict-code="'hykssldtx'"
                    placeholder="请选择会议类型"
                    clearable
                    style="width: 100%"
                  ></dict-select>
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item label="成员入会时静音">
                  <dict-select
                    v-model="moreForm.mute"
                    :dict-code="'cyrhsjy'"
                    placeholder="请选择会议类型"
                    clearable
                    style="width: 100%"
                  ></dict-select>
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item label="入会成员限制">
                  <dict-select
                    v-model="moreForm.limitUser"
                    :dict-code="'rhcyxz'"
                    placeholder="请选择入会成员限制"
                    clearable
                    style="width: 100%"
                  ></dict-select>
                </el-form-item>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="开启屏幕水印">
                    <el-switch
                      v-model="moreForm.isWatermark"
                      active-value="1"
                      inactive-value="0"
                    ></el-switch>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-collapse-item>
        </el-collapse>
      </div>
    </template>
  </at-table>
</template>

<script>
import eipUserSelector from '@/components/eipControl/selector/EipUserSelector.vue'
import eipPlaceSelector from '@/components/selector/EipPlaceSelector.vue'
export default {
  name: 'MyMeeting',
  components: {
    eipUserSelector,
    eipPlaceSelector,
  },
  data() {
    return {
      data: [],
      searchForm: {
        name: '',
      },
      dialogTitle: '',
      dialogVisible: false,
      pageResult: {
        page: 1,
        pageSize: 20,
        total: 0,
      },
      form: {},
      disabledEndTime: true,
      endTimeKey: '1',
      places: [],
      users: [],
      userName: '',
      permission: 'b',
      single: false,
      loading: false,
      userInfo: null,
      activeNames: [],
      moreForm: {
        remindTime: '4',
        remindUser: '2',
        limitUser: '1',
        mute: '3',
      },
      optionsEndTime: [
        {
          value: '1',
          label: '1小时',
        },
        {
          value: '2',
          label: '2小时',
        },
        {
          value: '3',
          label: '3小时',
        },
        {
          value: '4',
          label: '自定义',
        },
      ],
      rules: {
        theme: {
          required: true,
          message: '请输入会议主题',
          trigger: 'blur',
        },
        meetingType: {
          required: true,
          message: '请输入会议类型',
          trigger: 'blur',
        },
        startTime: {
          required: true,
          message: '请输入开始时间',
          trigger: 'blur',
        },
        endTime: {
          required: true,
          message: '请输入结束时间',
          trigger: 'blur',
        },
        place: {
          required: true,
          message: '请选择会议室',
          trigger: 'blur',
        },
        user: {
          required: true,
          message: '请选择参会人',
          trigger: 'blur',
        },
      },
    }
  },
  computed: {
    deleteUrl: function () {
      return `${window.context.xqhk}/meeting/v1/removes`
    },
  },
  created() {
    this.getUserInfo()
  },
  methods: {
    loadData(param, cb) {
      let query = [
        {
          group: 'main',
          operation: 'EQUAL',
          parentGroup: '',
          property: 'meeting_status_',
          relation: 'AND',
          value: 1,
        },
        {
          group: 'main',
          operation: 'EQUAL',
          parentGroup: '',
          property: 'meeting_status_',
          relation: 'OR',
          value: 2,
        },
      ]
      let search = {
        theme_: this.searchForm.theme,
        meeting_type_: this.searchForm.meetingType,
        start_time_: this.searchForm.startTime,
      }
      for (let i in search) {
        if (search[i]) {
          query.push({
            group: 'advance',
            operation: 'LIKE',
            property: i,
            relation: 'AND',
            value: search[i],
          })
        }
      }
      if (param.querys && param.querys.length) {
        param.querys.push(...query)
      } else {
        param.querys = query
      }
      this.$http
        .post(`${window.context.xqhk}/meeting/v1/getJson`, param)
        .then(
          (resp) => {
            let response = resp.data.value
            this.data = response.rows
            this.pageResult = {
              page: response.page,
              pageSize: response.pageSize,
              total: response.total,
            }
          },
          (error) => {
            reject(error)
          }
        )
        .finally(() => cb())
    },
    handleSearch() {
      this.$refs.AtTable.load()
    },
    handleReset() {
      this.searchForm = {
        theme: '',
        meetingType: '',
        startTime: '',
      }
      this.$refs.AtTable.load()
    },
    handleDialogCancel() {
      this.dialogVisible = false
    },
    handleDialogClose() {
      this.dialogVisible = false
    },
    handleDialogSubmit(formName) {
      let url
      // 将表单数据格式化成后台需要的格式
      this.formatPamrs()
      this.form = {
        ...this.form,
        ...this.moreForm,
        users: [...this.users],
      }
    
      if (this.dialogTitle == '修改') {
        url = '/meeting/v1/updateMeeting'
      } else {
        url = '/meeting/v1/saveMeeting'
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true
          this.$http.post('${xqhk}' + url, this.form).then((res) => {
            if (res.status == 200) {
              this.$message.success(res.data.message)
              this.dialogVisible = false
              this.$refs.AtTable.load()
            } else {
              this.$message.error(res.data.message)
            }
            this.loading = false
          })
        }
      })
    },
    handleRowDBClick(row) {
      if(row.meetingType = '1'){
        this.single = true
      }else{
        this.single = false
      }
      this.endTimeKey = '1'
      let date = new Date()
      row.startTime = date.getFullYear() + '-' + row.startTime + ':00'
      row.endTime = date.getFullYear() + '-' + row.endTime + ':00'
      row.user = []
      row.users.forEach(item => {
        row.user.push(item.userName)
      })
      row.place = []
      row.places.forEach(item => {
        row.place.push(item.placeName)
      })
      row.user = row.user.join(',')
      row.place = row.place.join(',')
      this.form = row
      this.moreForm = row
      this.dialogTitle = '修改'
      this.dialogVisible = true
    },
    handleAdd() {
      this.single = false
      this.endTimeKey = '1'
      this.form = {
        endTime: '',
        startTime: '',
        place: '',
        users: [],
        places: [],
      }
      this.moreForm = {
        remindTime: '4',
        remindUser: '2',
        limitUser: '1',
        mute: '3',
      }
      this.form.startTime = this.formatTime()
      this.form.endTime = this.formatTime(1)
      this.dialogTitle = '新增'
      this.dialogVisible = true
    },
    handleCommand(data) {
      let {row, command} = data
      if (command == 'cancel') {
        row.meetingStatus = 4
      } else {
        row.meetingStatus = 3
      }
      let date = new Date()
      row.startTime = date.getFullYear() + '-' + row.startTime + ':00'
      row.endTime = date.getFullYear() + '-' + row.endTime + ':00'
      this.$http.post('${xqhk}/meeting/v1/updateMeeting', row).then((res) => {
        if (res.status == 200) {
          this.$message.success('操作成功')
        } else {
          this.$message.error('操作失败')
        }
        this.$refs.AtTable.load()
      })
    },
    changeMeetingType(val) {
      this.form = {
        ...this.form,
        place: '',
        user: '',
        places: [],
        users: [],
      }
      if (val == '1') {
        this.single = true
      } else {
        this.single = false
      }
    },
    getUserInfo() {
      let params = {
        pageBean: {
          pageSize: -1,
        },
      }
      this.$http
        .post('${uc}/api/user/v1/users/queryByType', params)
        .then((rep) => {
          this.userInfo = rep.data.rows
        })
    },
    formatPamrs() {
      this.users = []
      this.form.places = []
      let userList = (this.form.user && this.form.user.split(',')) || []
      this.places.forEach((item) => {
        this.form.places.push({
          placeId: item.id,
          placeName: item.name,
        })
      })

      userList.forEach((item) => {
        this.userInfo.forEach((user) => {
          if (user.fullname == item) {
            this.users.push({
              userId: user.id,
              userName: user.fullname,
            })
          }
        })
      })
    },
    changeEndTimeOptions(count) {
      if (count == 4) {
        this.disabledEndTime = false
      } else {
        this.disabledEndTime = true
      }
      const time = this.form.startTime
      this.form.endTime = this.formatTime(count, time)
    },
    changeEndTime(time) {
      const endTime = new Date(time)
      const startTime = new Date(this.form.startTime)
      if (endTime < startTime) {
        this.form.endTime = ''
        this.$message.error('结束时间不能小于开始时间')
      }else {
        this.form.endTime = this.formatTime(null,time)
      }
    },
    changeStartTime(time) {
      this.form.startTime = this.formatTime(null,time)
      this.form.endTime = this.formatTime(this.endTimeKey, time)
    },
    formatTime(addHours, time) {
      addHours = Number(addHours) || 0
      const nowDate = time ? new Date(time) : new Date()
      let date = {
        year: nowDate.getFullYear(),
        month: nowDate.getMonth() + 1,
        day: nowDate.getDate(),
        hours: nowDate.getHours() + addHours, //获取当前小时数(0-23)
        minutes: nowDate.getMinutes(), //获取当前分钟数(0-59)
      }
      let key = date.minutes % 10
      if (key != 0) {
        date.minutes = date.minutes + (10 - key)
        if (date.minutes >= 60) {
          date.minutes = date.minutes - 60
          date.newHours = date.newHours + 1
        }
      }
      if (date.hours >= 24) {
        date.hours = date.hours - 24
        date.day = date.day + 1
      }
      let newmonth = date.month > 10 ? date.month : '0' + date.month
      let day = date.day > 10 ? date.day : '0' + date.day
      let newHours = date.hours < 10 ? '0' + date.hours : date.hours
      let newMinutes = date.minutes < 10 ? '0' + date.minutes : date.minutes

      return (
        date.year +
        '-' +
        newmonth +
        '-' +
        day +
        ' ' +
        newHours +
        ':' +
        newMinutes +
        ':00'
      )
    },
    showTag(rows) {
      this.$refs.ruleForm.clearValidate()
      this.places = rows
    },
    closeTag(rows) {
      this.places = rows
      this.form.place = rows.map((item) => item.name).join(',')
    },
  },
}
</script>

<style lang="scss" scoped>
@import '@/assets/css/common.scss';
.collapse-box {
  margin: 10px 20px 20px;
}
</style>
