<template>
  <Dialog v-model="dialogVisible" title="添加楼栋">
    <el-form 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="12" :xl="12">
            <el-form-item label="楼栋名称" prop="buildName" style="margin: 0 0; padding: 0 0">
              <el-input
                v-model="dataForm.buildName"
                style="margin: 0 0; padding: 0 0"
                :maxlength="20"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
            <el-form-item label="显示顺序" prop="sort">
              <el-input :maxlength="5" v-model="dataForm.sort" />
            </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="floorCount" style="margin: 0 0; padding: 0 0">
              <el-input
                v-model="dataForm.floorCount"
                style="margin: 0 0; padding: 0 0"
                :maxlength="6"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider style="margin-top: 10px" />
        <el-row>
          <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>

        <el-scrollbar max-height="50vh">
          <div
            v-loading="loadingBed"
            v-for="(item, index) in dataForm.floorList"
            :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="floorName">
                  <el-input :maxlength="6" v-model="item.floorName" />
                </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 :maxlength="5" v-model="item.sort" />
                </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>
        </el-scrollbar>
      </div>
    </el-form>

    <template #footer>
      <el-button @click="handleClosed" :type="isDetail ? 'danger' : ''">{{
        isDetail ? '删除' : '关闭'
      }}</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 { elderlyBakAdd, getElderlyBakInfo } from '@/api/elderly/bak/check-out'
import { FormRules } from 'element-plus'
import { useMediaQuery } from '@vueuse/core'
import { CirclePlus, Remove, OfficeBuilding } from '@element-plus/icons-vue'
import {
  addBuild,
  getBuildListId,
  deleteBuildListId,
  editBuild,
  checkBuildFloorById
} from '@/api/system/badManage'
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const floorNum = ref(1)
const dialogVisible = ref(false) // 弹窗
const formRef = ref() // 表单 Ref
const isDetail = ref(false) // 是否详情打开
const loadingBed = ref(false) // 是否详情打开
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
let dataForm = ref({
  // 表单字段
  id: undefined,
  buildName: undefined,
  sort: undefined,
  floorCount: undefined,
  floorList: [
    {
      floorName: '1层',
      sort: 1
    }
  ],
  tenantId: undefined,
})
// 表单规则
const dataRule = reactive<FormRules>({
  buildName: [{ required: true, message: '楼栋名称不能为空', trigger: 'blur' }],
  floorCount: [{ required: true, message: '楼层高度不正确', trigger: 'blur' }]
})

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

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

/** 打开弹窗 */
const open = async (tId, id?: any, detail: boolean = false) => {
  resetForm()

  dialogVisible.value = true
  dataForm.value.id = id || undefined
  isDetail.value = detail
  dataForm.value.tenantId = tId
  if (id) {
    try {
      const res = await getBuildListId(id)
      dataForm.value = res
    } catch (err) {}
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  try {
    if (!/^\d+$/.test(dataForm.value.sort)) {
      // 验证输入是否只包含数字
      message.error('显示顺序只能输入数字')
      return
    }
    if (!/^\d+$/.test(dataForm.value.floorCount)) {
      // 验证输入是否只包含数字
      message.error('楼层高度只能输入数字')
      return
    }
    for (const validElement of dataForm.value.floorList) {
      if (validElement.floorName == '') {
        message.error('请输入楼层号')
        return
      }
      if (validElement.sort != '') {
        if (!/^\d+$/.test(validElement.sort)) {
          // 验证输入是否只包含数字
          message.error('显示顺序只能输入数字')
          return
        }
      }
    }
  } catch (err) {}

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

/** 重置表单 */
const resetForm = () => {
  dataForm.value = {
    floorList: [
      {
        floorName: '1层',
        sort: 1
      }
    ],
    id: undefined,
    buildName: undefined,
    sort: undefined,
    floorCount: undefined,
    tenantId: undefined
  }
  isDetail.value = false
  floorNum.value = 1
  formRef.value?.resetFields()
}

// 关闭表单
const handleClosed = async () => {
  if (isDetail.value) {
    try {
      // 删除的二次确认
      await message.confirm('确定要删除该楼栋?')
      // 删除
      const res = await deleteBuildListId(dataForm.value.id)
      if (res) {
        resetForm()
        message.success(t('删除成功'))
        dialogVisible.value = false
        // 发送操作成功的事件
        emit('success')
      }
    } catch {}
  } else {
    resetForm()
    dialogVisible.value = false
  }
}

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

const addFloor = () => {
  floorNum.value++
  dataForm.value.floorList.push({ sort: '', floorName: '' ,isDelete:false})
}
const deleteFloor = (index) => {
  if (dataForm.value.floorList.length <= 1) {
    message.warning('最少需要一个楼层')
    return
  } else {
    loadingBed.value=true

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

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

  }
}

const successAddBuild = () => {}

function clickBuildIcon(item) {
  console.log(item)
}
function clickBuildItem(item) {
  //console.log(item.name)
}
</script>

<style lang="scss" scoped></style>
