<script setup lang="ts">
import { ref } from 'vue'

import { cloneDeep } from '@vben/utils'
import { useVbenModal } from '@vben/common-ui'
import { useVbenForm } from '#/adapter/form'
import { queryByUnitId } from '#/api/property/floor'
import { refAdd, refQuery } from '#/api/sis/elevatorInfo'
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup'

const dataForm = ref<any>()
const title = ref('楼层授权')

const [BasicForm, formApi] = useVbenForm({
  // 所有表单项共用，可单独在表单内覆盖
  commonConfig: {
    // 默认占满两列
    formItemClass: 'col-span-1',
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  layout: 'horizontal',
  schema: [
    {
      component: 'CheckboxGroup',
      componentProps: {
        name: 'cname',
        options: [],
      },
      defaultValue: [],
      fieldName: 'floorNums',
      label: '楼层'
    }],
  wrapperClass: 'grid-cols-1',
  showDefaultActions: false
})

const [BasicModal, modalApi] = useVbenModal({
  // 在这里更改宽度
  class: 'w-[700px]',
  fullscreenButton: false,
  loading: true,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpened: handleInit,
})

function handleInit() {
  dataForm.value = modalApi.getData()
  const { unitId } = modalApi.getData()
  queryByUnitId(unitId).then((res) => {
    const arr: any[] = []
    res.forEach((item) => {
      arr.push({
        label: item.floorName,
        value: item.floorNumber,
      })
    })

    formApi.updateSchema([
      {
        fieldName: 'floorNums',
        componentProps: { options: arr },
      }
    ])
    handleChecked()
  })
}

function handleChecked() {
  const { elevatorId } = modalApi.getData()
  refQuery(elevatorId).then((res) => {
    const arr: any[] = []
    res.forEach((item) => {
      arr.push(item.floorNum)
    })
    formApi.setFieldValue('floorNums', arr)
  }).finally(() => {
    modalApi.setState({ loading: false });
  })
}



const { resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
)

async function handleConfirm() {
  // getValues获取为一个readonly的对象 需要修改必须先深拷贝一次
  const data = cloneDeep(await formApi.getValues())
  const params = {
    elevatorId: dataForm.value.elevatorId,
    floorNums: data.floorNums
  }
  refAdd(params).finally(() => {
    modalApi.close()
  })
}

async function handleClosed() {
  await formApi.resetForm()
  resetInitialized()
}
</script>

<template>
  <BasicModal :title="title">
    <BasicForm />
  </BasicModal>
</template>
