<template>
  <div ref="mod">
    <a-modal
      :get-container="() => $refs.mod"
      :open="open"
      :title="title"
      :mask-closable="true"
      @cancel="cancel"
      :footer="null"
    >
      <a-form ref="formRef" :model="formState" :label-col="{ style: { width: '100px' } }">
        <a-form-item v-if="props.type === 'build'" label="单元楼栋" name="buildingNum">
          <div style="display: flex">
            <a-input
              v-model:value.trim="formState.buildingNum"
              placeholder="请输入单元楼栋，示例：2栋、3幢、A5"
              @keydown.enter="addItem(formState.buildingNum)"
            >
              <template #suffix>
                <a-tooltip title="建议添加单位，如: 栋、幢">
                  <info-circle-outlined style="color: rgba(0, 0, 0, 0.45)" />
                </a-tooltip>
              </template>
            </a-input>
            <a-button type="link" @click="addItem(formState.buildingNum)">添加</a-button>
          </div>
        </a-form-item>

        <a-form-item v-if="props.type === 'floor'" label="楼层数量" name="floorNum">
          <div style="display: flex">
            <a-input
              v-model:value.trim="formState.floorNum"
              placeholder="请输入楼层，示例：11楼、30层、33层"
              @keydown.enter="addItem(formState.floorNum)"
            >
              <template #suffix>
                <a-tooltip title="建议输入数字+楼/层，如：11楼、30层、33层">
                  <info-circle-outlined style="color: rgba(0, 0, 0, 0.45)" />
                </a-tooltip>
              </template>
            </a-input>
            <a-button type="link" @click="addItem(formState.floorNum)">添加</a-button>
          </div>
        </a-form-item>

        <a-form-item label="已添加">
          <a-space wrap class="addList">
            <a-tag
              v-for="(item, index) in addList"
              :key="index"
              closable
              @close="closeTag($event, index)"
              >{{ item.tinfoName }}</a-tag
            >
          </a-space>
          <span style="color: gray"> {{ addList.length === 0 ? '暂无数据，请添加' : '' }}</span>
        </a-form-item>
      </a-form>

      <div class="footer">
        <a-space>
          <a-button @click="cancel">取消</a-button>
          <a-button type="primary" :loading="submitLoading" @click="submit">确定</a-button>
        </a-space>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { message, type FormInstance } from 'ant-design-vue'
import * as tenantApi from '@/api/tenant'
import { InfoCircleOutlined } from '@ant-design/icons-vue'

defineOptions({
  name: 'addCommunity',
})

const formRef = ref<FormInstance>()

type Props = {
  open: boolean
  type: 'build' | 'floor'
  query: {
    tenantId: string
    parentId?: string
  }
}
const emit = defineEmits<{
  (e: 'update:open', value: boolean): void
  (e: 'success', value: void): void
}>()

const props = withDefaults(defineProps<Props>(), {
  open: false,
  type: 'build',
  query: () => ({
    tenantId: '',
  }),
})

const title = computed(() => {
  return props.type === 'build' ? '新增楼栋' : '新增楼层'
})

interface FormState {
  buildingNum: string // 楼栋号
  floorNum: string // 楼层数量
}

const formState = reactive<FormState>({
  buildingNum: '',
  floorNum: '',
})

const cancel = () => {
  formRef?.value?.resetFields()
  addList.value = []
  emit('update:open', false)
}

const addList = ref<{ tinfoName: string; sort?: number }[]>([])

// 添加楼栋或楼层
const addItem = (name: string) => {
  if (!name) {
    message.warning('请输入名称')
    return
  }
  addList.value.push({
    tinfoName: name,
  })
  formState.buildingNum = ''
  formState.floorNum = ''
  formRef?.value?.resetFields()
}

// 删除已添加的楼栋或楼层
const closeTag = (e: Event, index: number) => {
  console.log('删除某个tag', e, index)
  addList.value.splice(index, 1)
}

// 新增楼栋保存
const saveBuilding = async () => {
  submitLoading.value = true
  return tenantApi
    .queryAddBuilding({
      tenantId: props.query.tenantId,
      buildingInfos: addList.value,
    })
    .then((res) => {
      console.log('添加成功', res)
      submitLoading.value = false
      message.success('添加成功')
      emit('success')
      cancel()
    })
    .catch(() => {
      submitLoading.value = false
    })
}

const saveFloor = async () => {
  submitLoading.value = true
  return tenantApi
    .queryAddFloor({
      tenantId: props.query.tenantId,
      parentId: props.query.parentId!,
      floorInfos: addList.value,
    })
    .then((res) => {
      console.log('添加成功', res)
      submitLoading.value = false
      message.success('添加成功')
      emit('success')
      cancel()
    })
    .catch(() => {
      submitLoading.value = false
    })
}

const submitLoading = ref(false)
// 确定
const submit = async () => {
  if (!addList.value.length) {
    message.warning('请添加楼栋或楼层')
    return
  }
  addList.value.forEach((item, index) => {
    item.sort = index + 1
  })
  if (props.type === 'build') {
    await saveBuilding()
  }
  if (props.type === 'floor') {
    await saveFloor()
  }
}
</script>

<style scoped lang="less">
:deep(.ant-modal) {
  .addList {
    min-height: 100px;
    padding: 5px 0;
    display: flex;
    align-content: flex-start;
  }
  .footer {
    text-align: right;
  }
}
</style>
