<template>
  <Dialog ref="dialogRef" v-model="dialogVisible" :title="isDetailTitle">
    <el-scrollbar ref="targetRef" max-height="70vh">
      <el-form
        @submit.prevent
        ref="formRef"
        :model="dataForm"
        :rules="dataRule"
        :label-width="labelWidth"
      >
        <div style="margin-top: 10px">
          <el-row>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item label="房间用途" prop="buildName" size="default">
                <el-radio-group v-model="dataForm.roomUsage" size="default">
                  <el-radio-button
                    style=""
                    v-for="(item, index) in getStrDictOptionsFun(DICT_TYPE.ROOM_PURPOSE)"
                    :label="item.label"
                    :value="item.value"
                    :key="index"
                  />
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item label="房间名称" prop="roomName">
                <el-input :maxlength="6" v-model="dataForm.roomName" :show-word-limit="true" />
              </el-form-item>
            </el-col>
          </el-row>

          <div v-if="dataForm.roomUsage === '1'">
            <el-row>
              <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                <el-form-item label="房间设置" prop="">
                  <div style="display: flex; flex-direction: row; align-items: center">
                    <div
                      @click="iconClick(1)"
                      style="
                        width: 40px;
                        height: 40px;
                        border-radius: 40px;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        cursor: pointer;
                      "
                      :style="{
                        border: icon1 ? '#409eff solid 1px' : '#eeeeee solid 1px',
                        backgroundColor: icon1 ? '#ffffff' : '#eeeeee'
                      }"
                    >
                      <img
                        v-if="icon1"
                        src="@/assets/imgs/nan.png"
                        style="width: 20px; height: 22px"
                        alt=""
                      />
                      <img
                        v-else
                        src="@/assets/imgs/nan-2.png"
                        style="width: 20px; height: 22px"
                        alt=""
                      />
                    </div>
                    <div
                      @click="iconClick(2)"
                      style="
                        margin-left: 12px;
                        width: 40px;
                        height: 40px;
                        border-radius: 40px;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        cursor: pointer;
                      "
                      :style="{
                        border: icon2 ? '#409eff solid 1px' : '#eeeeee solid 1px',
                        backgroundColor: icon2 ? '#ffffff' : '#eeeeee'
                      }"
                    >
                      <img
                        v-if="icon2"
                        src="@/assets/imgs/nv.png"
                        style="width: 20px; height: 22px"
                        alt=""
                      />
                      <img
                        v-else
                        src="@/assets/imgs/nv-2.png"
                        style="width: 20px; height: 22px"
                        alt=""
                      />
                    </div>
                    <div
                      @click="iconClick(3)"
                      style="
                        margin-left: 12px;
                        width: 40px;
                        height: 40px;
                        border-radius: 40px;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        cursor: pointer;
                      "
                      :style="{
                        border: icon3 ? '#409eff solid 1px' : '#eeeeee solid 1px',
                        backgroundColor: icon3 ? '#ffffff' : '#eeeeee'
                      }"
                    >
                      <img
                        v-if="icon3"
                        src="@/assets/imgs/matong.png"
                        style="width: 20px; height: 22px"
                        alt=""
                      />
                      <img
                        v-else
                        src="@/assets/imgs/matong-2.png"
                        style="width: 20px; height: 22px"
                        alt=""
                      />
                    </div>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                <el-form-item label="房间区域" prop="roomArea">
                  <el-radio-group v-model="dataForm.roomArea">
                    <el-radio-button
                      @click="clickRoomArea(item.value)"
                      border
                      v-for="(item, index) in getStrDictOptionsFun(DICT_TYPE.ROOM_AREA_ARR)"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                <el-form-item label="长者类型" prop="elderStatus">
                  <el-radio-group v-model="dataForm.elderType">
                    <el-radio-button
                      border
                      @click="clickElderType(item.value)"
                      v-for="(item, index) in getStrDictOptionsFun(DICT_TYPE.ELDERLY_HEALTH_STATUS)"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                <el-form-item label="房间朝向" prop="roomOrientation">
                  <el-radio-group v-model="dataForm.orientation">
                    <el-radio-button
                      border
                      @click="clickOrientation(item.value)"
                      v-for="(item, index) in getStrDictOptionsFun(DICT_TYPE.ROOM_ORIENTATION)"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <div v-else>
            <el-row>
              <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                <el-form-item label="封面图" prop="panoramicUrl">
                  <el-row>
                    <div @click="iconCK(item)" v-for="(item, index) in iconList" :key="index">
                      <img
                        :class="{ iconS: item.select, iconS2: !item.select }"
                        :src="item.icon"
                        style="margin-right: 18px"
                        alt=""
                      />
                    </div>
                  </el-row>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <el-row>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item label="全景URL" prop="panoramicUrl">
                <el-input
                  v-model="dataForm.panoramicUrl"
                  type="textarea"
                  :maxlength="1000"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item label="房间图片" prop="roomFullUrl">
                <el-upload
                  :file-list="dataForm.roomImageLists"
                  :action="uploadUrl"
                  list-type="picture-card"
                  :http-request="httpRequest"
                  :on-change="roomImageListChange"
                  :on-remove="handleRemove"
                  class="my-custom-upload"
                >
                  <el-icon><Plus /></el-icon>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item label="房间视频" prop="roomFullUrl">
                <el-upload
                  v-model="dataForm.roomVideoLists"
                  :action="uploadUrl"
                  :beforeUpload="beforeAvatarUpload"
                  :http-request="httpRequest"
                  :on-remove="handleRemoveVideo"
                >
                  <el-button type="primary">点击上传</el-button>
                  <template #tip>
                    <div class="el-upload__tip"> 视频文件最大支持30M </div>
                  </template>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider v-show="dataForm.roomUsage === '1'" style="margin-top: 10px" />
          <el-row v-show="dataForm.roomUsage === '1'">
            <el-col :span="6">
              <el-button  @click="addFloor" :icon="CirclePlus" style="margin-bottom: 20px"
                >添加床位</el-button
              >
            </el-col>
            <el-col :span="16">
              <el-text />
            </el-col>
          </el-row>

          <div
            v-show="dataForm.roomUsage === '1'"
            v-loading="loadingBed"
            v-for="(item, index) in dataForm.bedList"
            :key="index"
          >
            <el-row v-show="!item.isDelete">
              <el-col :xs="23" :sm="23" :md="23" :lg="11" :xl="11">
                <el-form-item label="床位号" prop="bedName">
                  <el-input v-model="item.bedName" :maxlength="20" />
                </el-form-item>
              </el-col>
              <el-col :xs="23" :sm="23" :md="23" :lg="11" :xl="11">
                <el-form-item label="显示顺序" prop="sort">
                  <el-input v-model="item.sort" :maxlength="5" />
                </el-form-item>
              </el-col>
              <el-col :span="2">
                <div
                  @click="deleteFloor(index)"
                  style="
                    height: 30px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    width: 3vw;
                  "
                >
                  <el-icon :size="16" color="#ff0000">
                    <Remove />
                  </el-icon>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-form>
    </el-scrollbar>

    <template #footer>
      <el-button @click="handleClosed">关闭</el-button>
      <el-button v-loading="formLoading" type="primary" @click="submitForm">确定</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { computed, ref } from 'vue'
import {DICT_TYPE, getDictLabel, getStrDictOptions} from '@/utils/dict'
import { elderlyBakAdd, getElderlyBakInfo } from '@/api/elderly/bak/check-out'
import {addRoom, checkBedById, editRoom} from '@/api/system/badManage'
import { FormRules, UploadProps, UploadUserFile } from 'element-plus'
import { useMediaQuery } from '@vueuse/core'
import { CirclePlus, Remove, OfficeBuilding, Plus } from '@element-plus/icons-vue'
import { useUpload } from '@/components/UploadFile/src/useUpload'
const { targetRef, scrollToBottom } = useFocusScroll();

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const floorNum = ref('')

const roomFileList = ref<UploadUserFile[]>([])
// const roomFileListVideo = ref<UploadUserFile[]>([]);
const { uploadUrl, httpRequest } = useUpload()

const icon1 = ref(false)
const icon2 = ref(false)
const icon3 = ref(false)

const dialogRef = ref()
import i1 from '../../../../assets/imgs/bed12.png'
import i2 from '../../../../assets/imgs/bed11.png'
import {useFocusScroll} from "@/utils/useFocusScroll";

const iconList = ref([
  { icon: i1, select: true },
  { icon: i2, select: false }
])

const dialogVisible = ref(false) // 弹窗
const formRef = ref() // 表单 Ref
const isDetail = ref(false) // 是否详情打开
const loadingBed = ref(false) // 是否详情打开
const isDetailTitle = ref('新增房间') // 是否详情打开
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
let dataForm = ref({
  // 表单字段
  tenantId: undefined,
  id: 0,
  floorId: '',
  roomName: '',
  roomUsage: '',
  roomArea: undefined,
  elderType: undefined,
  orientation: undefined,
  roomSettings: '',
  panoramicUrl: '',
  roomImage: '',
  roomVideo: '',
  coverImage: '',
  roomVideoLists: [],
  roomImageLists: [],
  bedList: [] // "id": 0,  "bedName": "", "status": 0, "roomId": 0,"sort": 0
})
// 表单规则
const dataRule = reactive<FormRules>({
  roomName: [{ required: true, message: '房间名称不能为空', trigger: 'blur' }]
  // buildNum: [{required: true, message: '退住原因不能为空', trigger: 'blur'}],
})

const clickOrientation = (v) => {
  console.log(v, dataForm.value.orientation)
  if (v === dataForm.value.orientation) {
    setTimeout(() => {
      dataForm.value.orientation = null
      console.log(v, dataForm.value.orientation)
    }, 100)
  }
}

const clickElderType = (v) => {
  if (v === dataForm.value.elderType) {
    setTimeout(() => {
      dataForm.value.elderType = null
    }, 100)
  }
}

const clickRoomArea = (v) => {
  if (v === dataForm.value.roomArea) {
    setTimeout(() => {
      dataForm.value.roomArea = null
    }, 100)
  }
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  console.log('上传前', rawFile)
  if (rawFile.type !== 'mp4/rmvb/wmv') {
    message.error('不支持的视频格式！！')
    return false
  } else if (rawFile.size / 1024 / 1024 > 30) {
    message.error('文件不能超过30M')
    return false
  }
  return true
}

const iconCK = async (item: any) => {
  for (const itemElement of iconList.value) {
    itemElement.select = false
  }
  item.select = true
}

// 计算窗口大小
const currentWidth = useMediaQuery('(max-width: 800px)')
// 计算文字大小
const labelWidth = computed(() => {
  return currentWidth.value ? '80px' : '80px'
})

const selectElderRef = ref() // 选择老人ref

const iconClick = (type) => {
  if (type === 1) {
    icon1.value = !icon1.value
  }
  if (type === 2) {
    icon2.value = !icon2.value
  }
  if (type === 3) {
    icon3.value = !icon3.value
  }
  dataForm.value.roomSettings = `${icon1.value ? '男' : ''},${icon2.value ? '女' : ''},${icon3.value ? '卫生间' : ''}`
}

const getStrDictOptionsFun = (type) => {
  const res = getStrDictOptions(type)
  if (res) {
    try {
      switch (type) {
        case DICT_TYPE.ROOM_PURPOSE:
          if (dataForm.value.roomUsage === '') {
            dataForm.value.roomUsage = res[0].value.toString()
          }
        //   break;
        // case DICT_TYPE.ROOM_AREA_ARR:
        //   if(dataForm.value.roomArea===''){
        //     dataForm.value.roomArea = res[0].value.toString()
        //   }
        //   break;
        // case DICT_TYPE.ELDERLY_HEALTH_STATUS:
        //   if(dataForm.value.elderType===''){
        //     dataForm.value.elderType = res[0].value.toString()
        //   }
        //   break;
        // case DICT_TYPE.ROOM_ORIENTATION:
        //   if(dataForm.value.orientation===''){
        //     dataForm.value.orientation = res[0].value.toString()
        //   }
        //   break;
      }
    } catch (e) {}
  }
  return res
}

/** 打开弹窗 */
const open = async (tId, floorId, value?: any, detail: boolean = false) => {
  resetForm()
  dialogVisible.value = true
  dataForm.value.floorId = floorId || undefined
  dataForm.value.tenantId = tId
  console.log('楼层ID:', value)
  if (floorId === undefined) {
    message.error('没有楼层，无法添加房间')
    return
  }

  isDetail.value = detail
  if (isDetail.value) {
    isDetailTitle.value = '编辑房间'
    let jsonBean = value
    dataForm.value.id = jsonBean.id
    dataForm.value.floorId = jsonBean.floorId
    dataForm.value.roomName = jsonBean.roomName
    dataForm.value.roomUsage = jsonBean.roomUsage
    dataForm.value.coverImage = jsonBean.coverImage

    for (const jsonBeanElement of iconList.value) {
      let s = jsonBeanElement.icon.toString().split('/')
      let i = s[s.length - 1]
      if (i === dataForm.value.coverImage) {
        jsonBeanElement.select = true
      } else {
        jsonBeanElement.select = false
      }
    }
    dataForm.value.roomArea = jsonBean.roomArea
    dataForm.value.elderType = jsonBean.elderType
    dataForm.value.orientation = jsonBean.orientation
    dataForm.value.roomSettings = jsonBean.roomSettings
    dataForm.value.panoramicUrl = jsonBean.panoramicUrl
    try {
      dataForm.value.roomImageLists = JSON.parse(jsonBean.roomImage) || []
    } catch (e) {
      console.log('A', e)
    }
    try {
      dataForm.value.roomVideoLists = JSON.parse(jsonBean.roomVideo) || []
    } catch (e) {
      console.error('B', e)
    }
    dataForm.value.roomImage = ''
    dataForm.value.roomVideo = ''
    dataForm.value.bedList = JSON.parse(JSON.stringify(jsonBean.bedList)) //拷贝

    try {
      let roomSettings = (jsonBean.roomSettings || '').split(',')
      for (let i = 0; i < roomSettings.length; i++) {
        if (roomSettings[i] === '男') {
          icon1.value = true
        }
        if (roomSettings[i] === '女') {
          icon2.value = true
        }
        if (roomSettings[i] === '卫生间') {
          icon3.value = true
        }
      }
    } catch (e) {}

    console.log("收到的房间数据:",dataForm.value)
  }
}

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
  try {
    for (let i = 0; i < dataForm.value.roomImageLists.length; i++) {
      if (uploadFile.uid === dataForm.value.roomImageLists[i].uid) {
        dataForm.value.roomImageLists.splice(i, 1)
        break
      }
    }
  } catch (e) {
    console.log(e)
  }
}
const handleRemoveVideo: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

const roomImageListChange = (e: any) => {
  try {
    console.log('添加图片', e)
    dataForm.value.roomImageLists.push({ url: e.response.data, uid: e.uid })
  } catch (e) {}
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  console.log('listImage2', dataForm.value.roomImageLists)
  try {
    for (const validElement of iconList.value) {
      if (validElement.select) {
        let s = validElement.icon.toString().split('/')
        dataForm.value.coverImage = s[s.length - 1]
      }
    }
  } catch (e) {}

  try {
    if (dataForm.value.roomImageLists.length > 0) {
      dataForm.value.roomImage = JSON.stringify(dataForm.value.roomImageLists)
    }
    if (dataForm.value.roomVideoLists.length > 0) {
      dataForm.value.roomVideo = JSON.stringify(dataForm.value.roomVideoLists)
    }
  } catch (e) {
    console.log(e)
  }
  if(getDictLabel(DICT_TYPE.ROOM_PURPOSE,dataForm.value.roomUsage)=='托养' && dataForm.value.bedList.length==0) {
    message.error('最少需要添加一个床位')
    scrollToBottom()

  }else {
    try {

      for (const validElement of dataForm.value.bedList) {
        if (validElement.bedName == '') {
          message.error('请输入床位号')
          return
        }
        if (validElement.sort != '' && validElement.sort != null) {
          console.log('循序：', validElement.sort)
          if (!/^\d+$/.test(validElement.sort)) {
            // 验证输入是否只包含数字
            message.error('显示顺序只能输入数字')
            return
          }
        }
      }
    } catch (err) {}

    try {
      if (dataForm.value.floorId === '') {
        message.error('没有楼层，无法添加房间')
        return
      }
    } catch (err) {}

    console.log('参数', dataForm.value)
    // 校验表单
    if (!formRef.value) return
    const valid = await formRef.value.validate()
    if (!valid) return
    // 提交请求
    formLoading.value = true
    try {
      let res
      if (isDetail.value) {
        res = await editRoom(dataForm.value)
      } else {
        res = await addRoom(dataForm.value)
      }
      if (res) {
        message.success(t('common.updateSuccess'))
        // dialogVisible.value = false
        // 发送操作成功的事件
        emit('success')
      }
    } catch (e) {
      console.log('异常', e)
    } finally {
      formLoading.value = false
      dialogVisible.value = false
    }
  }

}

/** 重置表单 */
const resetForm = () => {
  dataForm.value = {
    tenantId: undefined,
    id: 0,
    floorId: '',
    roomName: '',
    roomUsage: '',
    roomArea: undefined,
    elderType: undefined,
    orientation: undefined,
    roomSettings: '',
    panoramicUrl: '',
    roomImage: '',
    roomVideo: '',
    coverImage: '',
    roomVideoLists: [],
    roomImageLists: [],
    bedList: [] // "id": 0,  "bedName": "", "status": 0, "roomId": 0,"sort": 0
  }
  icon1.value = false
  icon2.value = false
  icon3.value = false
  formRef.value?.resetFields()
}

// 关闭表单
const handleClosed = () => {
  dialogVisible.value = false
  resetForm()
}

// 获取老人
const getItems = () => {
  nextTick(() => {
    selectElderRef.value.open()
  })
}

const floorList = ref([])

const addFloor = () => {
  //floorNum.value++;
  dataForm.value.bedList.push({ bedName: '', sort: '' ,isDelete:false})
  nextTick(()=>{
    scrollToBottom()
  })

}

const deleteFloor = (index) => {
    loadingBed.value=true
  //编辑的
  if(dataForm.value.bedList[index].id!=undefined && dataForm.value.bedList[index].id!==null){
    //根据ID查询床位是否被使用
    checkBedById(dataForm.value.bedList[index].id).then((res)=>{
      console.log(res)
      if(!res){
        dataForm.value.bedList[index].isDelete = true
      }else {
        message.error('床位已被入住，无法删除!')
      }
      loadingBed.value=false
    }).catch((e)=>{ loadingBed.value=false})

  }else {//新增的直接删
    dataForm.value.bedList.splice(index, 1)
    loadingBed.value=false
  }


}
</script>

<style lang="scss" scoped>
//:deep(.el-upload--picture-card){
//    /* 修改文件列表的样式 */
//    width: 100px; /* 示例：限制文件列表的最大高度 */
//    height: 100px;
//}
//:deep(.el-upload-list__item){
//  /* 修改文件列表的样式 */
//  width: 100px; /* 示例：限制文件列表的最大高度 */
//  height: 100px;
//}

.iconS {
  width: 86px;
  height: 86px;
  border-radius: 8px;
  border: #605be2 solid 1px;
}

.iconS:hover {
  transform: scale(0.98);
}
.iconS2 {
  width: 86px;
  height: 86px;
  border-radius: 8px;
  border: #ffffff solid 1px;
}

.iconS2:hover {
  transform: scale(0.98);
}
</style>
