<template>
  <!-- 基于 Element UI 新增和修改弹窗 -->
  <el-dialog
      :title="!dataForm.id ? '添加' : '修改'"
      :close-on-click-modal="false"
      :visible.sync="visible">
    <!-- 新增和修改表单 -->
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataSubmit()" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="会议室名称" prop="roomName">
            <el-input v-model="dataForm.roomName" placeholder="会议室名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="会议室位置" prop="roomLocation">
            <el-input v-model="dataForm.roomLocation" placeholder="会议室位置"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="容纳人数" prop="capacity">
            <el-input-number v-model="dataForm.capacity" placeholder="容纳人数" :min="0" style="width: 100%"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="总座位数" prop="totalSeats">
            <el-input-number v-model="dataForm.totalSeats" placeholder="总座位数" :min="0" style="width: 100%"></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="固定座位数" prop="fixedSeats">
            <el-input-number v-model="dataForm.fixedSeats" placeholder="固定座位数" :min="0" style="width: 100%"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="可移动座位数" prop="movableSeats">
            <el-input-number v-model="dataForm.movableSeats" placeholder="可移动座位数" :min="0" style="width: 100%"></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="座位布局类型" prop="seatLayout">
            <el-select v-model="dataForm.seatLayout" placeholder="请选择座位布局类型" :style="{ width: '100%' }">
              <el-option v-if="!dict.type.seat_layout" label="无数据" value="" disabled/>
              <el-option
                v-else
                v-for="dict in dict.type.seat_layout"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="配套设备" prop="equipmentConfig">
            <el-select v-model="dataForm.equipmentConfig" placeholder="请选择配套设备" :style="{ width: '100%' }" multiple>
              <el-option v-if="!dict.type.equipment_config" label="无数据" value="" disabled/>
              <el-option
                v-else
                v-for="dict in dict.type.equipment_config"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="收费标准" prop="chargeStandard">
            <el-input v-model="dataForm.chargeStandard" placeholder="收费标准"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="可预约时间段" prop="reserveTimeRange">
            <el-time-picker
              v-model="dataForm.reserveTimeRange"
              is-range
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="HH:mm"
              format="HH:mm"
              style="width: 100%">
            </el-time-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="会议室状态" prop="roomStatus">
            <el-select v-model="dataForm.roomStatus" placeholder="请选择会议室状态" :style="{ width: '100%' }">
              <el-option v-if="!dict.type.room_status" label="无数据" value="" disabled/>
              <el-option
                v-else
                v-for="dict in dict.type.room_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="会议室照片" prop="fileId">
        <FileUploadVO
          :value="roomFiles"
          @input="updateRoomFiles"
        ></FileUploadVO>
      </el-form-item>
      <el-form-item label="会议室描述" prop="description">
        <el-input v-model="dataForm.description" placeholder="会议室描述"  type="textarea" :rows="3"></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="dataForm.remark" placeholder="备注"  type="textarea" :rows="3"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import * as api from '@/api/cmmeetingroom.js'
  import FileUploadVO from '@/components/FileUploadVO/index.vue'
  export default {
    components: {
      FileUploadVO
    },
    dicts: ['room_status','seat_layout','equipment_config'],
    data () {
      return {
        visible: false,
        roomFiles: [], // 会议室文件列表
        dataForm: {
          id: 0,
          roomName: '' ,
          roomLocation: '' ,
          capacity: '' ,
          totalSeats: '' ,
          fixedSeats: '' ,
          movableSeats: '' ,
          seatLayout: '' ,
          equipmentConfig: [] ,
          chargeStandard: '' ,
          reserveTimeRange: null ,
          fileId: '' ,
          roomStatus: '' ,
          description: '' ,
          remark: '' ,
          files: []
        },
        dataRule: {
          roomName: [
            { required: true, message: '会议室名称  为必填项', trigger: 'blur' }
          ],
          // roomLocation: [
          //   { required: true, message: '会议室位置  为必填项', trigger: 'blur' }
          // ],
          // capacity: [
          //   { required: true, message: '容纳人数  为必填项', trigger: 'blur' }
          // ],
          // totalSeats: [
          //   { required: true, message: '总座位数  为必填项', trigger: 'blur' }
          // ],
          // fixedSeats: [
          //   { required: true, message: '固定座位数  为必填项', trigger: 'blur' }
          // ],
          // movableSeats: [
          //   { required: true, message: '可移动座位数  为必填项', trigger: 'blur' }
          // ],
          // seatLayout: [
          //   { required: true, message: '座位布局类型（圆桌式/剧院式/课桌式等）  为必填项', trigger: 'blur' }
          // ],
          // equipmentConfig: [
          //   { required: true, message: '配套设备  为必填项', trigger: 'blur' }
          // ],
          // chargeStandard: [
          //   { required: true, message: '收费标准  为必填项', trigger: 'blur' }
          // ],
          // reserveTimeRange: [
          //   { required: true, message: '可预约时间段  为必填项', trigger: 'blur' }
          // ],
          // fileId: [
          //   { required: true, message: '文件id  为必填项', trigger: 'blur' }
          // ],
          roomStatus: [
            { required: true, message: '会议室状态  为必填项', trigger: 'blur' }
          ],
          // description: [
          //   { required: true, message: '会议室描述  为必填项', trigger: 'blur' }
          // ],
          // remark: [
          //   { required: true, message: '备注  为必填项', trigger: 'blur' }
          // ],
        }
      }
    },
    methods: {
      // 更新会议室文件列表
      updateRoomFiles(files) {
        this.roomFiles = files
        if (files && files.length > 0) {
          this.dataForm.files = files.map(file => {
            let attDir = file.attDir || file.attachFileUrl || ''
            if (attDir.startsWith('/file/public/')) {
              attDir = attDir.replace('/file/public/', '')
            } else if (attDir.startsWith('/file/')) {
              attDir = attDir.replace('/file/', '')
            }

            return {
              attId: file.id || file.attId || '',
              name: file.name || file.oldName || '',
              attDir: attDir,
              attSize: file.attSize || '',
              attType: file.attType || '',
              fileName: file.name || file.oldName || '',
              filePath: attDir,
              url: attDir,
              createTime: null,
              createdBy: null,
              createTimeStr: null,
              delFlag: '0',
              updateBy: null,
              updateTime: null,
              i18nCode: '',
              i18nLanguage: '',
              originalFileName: file.name || file.oldName || '',
              position: 0,
              remark: file.remark || '',
              sort: 0,
              status: ''
            }
          })
        } else {
          this.dataForm.files = []
        }
      },
      init (id) { // 初始化表单验证规则
        this.dataForm.id = id || 0
        this.visible = true
        this.$nextTick(function() {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            api.cmmeetingroomDetailApi(id).then(function(res) {
              this.dataForm = res;
              if (this.dataForm.reserveTimeRange && typeof this.dataForm.reserveTimeRange === 'string') {
                this.dataForm.reserveTimeRange = this.dataForm.reserveTimeRange.split('-')
              }
              // 将 equipmentConfig 从字符串转换为数组
              if (this.dataForm.equipmentConfig && typeof this.dataForm.equipmentConfig === 'string') {
                this.dataForm.equipmentConfig = this.dataForm.equipmentConfig.split('、')
              }
              // 将 roomStatus 转换为字符串，以便与字典值匹配
              if (this.dataForm.roomStatus !== null && this.dataForm.roomStatus !== undefined) {
                this.dataForm.roomStatus = this.dataForm.roomStatus.toString()
              }
              if (this.dataForm.files && this.dataForm.files.length > 0) {
                this.roomFiles = this.dataForm.files.map((file, index) => ({
                  attachFileUrl: file.attDir || file.filePath || file.url || '',
                  attDir: file.attDir || file.filePath || file.url || '',
                  name: file.name || file.fileName || '',
                  oldName: file.name || file.fileName || '',
                  attId: file.attId || '',
                  uid: file.id || file.fileId || index + new Date().getTime()
                }))
              } else {
                this.roomFiles = []
              }
            }.bind(this))
          } else {
            this.roomFiles = []
            this.dataForm.files = []
          }
        }.bind(this))
      },
      // 表单数据提交
      dataSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const submitData = { ...this.dataForm }
            if (Array.isArray(submitData.reserveTimeRange) && submitData.reserveTimeRange.length === 2) {
              submitData.reserveTimeRange = submitData.reserveTimeRange.join('-')
            }
            // 将 equipmentConfig 数组转换为用、分割的字符串
            if (Array.isArray(submitData.equipmentConfig)) {
              submitData.equipmentConfig = submitData.equipmentConfig.join('、')
            }
            // 将 roomStatus 转换为整数
            if (submitData.roomStatus !== '') {
              submitData.roomStatus = parseInt(submitData.roomStatus)
            }
            if (this.dataForm.id) {
              api.cmmeetingroomUpdateApi(submitData).then(function(res) {
                this.$message.success('保存成功')
                this.visible = false
                this.$emit('refreshDataList')
              }.bind(this));
            } else {
              api.cmmeetingroomCreateApi(submitData).then(function(res) {
                this.$message.success('新增成功')
                this.visible = false
                this.$emit('refreshDataList')
              }.bind(this));
            }
          }
        })
      }
    }
  }
</script>
