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

import {useVbenModal} from '@vben/common-ui';
import {$t} from '@vben/locales';
import {cloneDeep} from '@vben/utils';

import {useVbenForm} from '#/adapter/form';
import {
  maintainPlanAdd,
  maintainPlanInfo,
  maintainPlanUpdate
} from '#/api/property/equipmentManagement/maintainPlan';
import {defaultFormValueGetter, useBeforeCloseDiff} from '#/utils/popup';

import {modalSchema} from './data';
import {getMachineTypeTree} from "#/api/property/machineType";
import {renderDictValue} from "#/utils/render";
import {userList} from "#/api/system/user";

const emit = defineEmits<{ reload: [] }>();

const isUpdate = ref(false);
const title = computed(() => {
  return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    // 默认占满一列
    formItemClass: 'col-span-1',
    // 默认label宽度 px
    labelWidth: 80,
    // 通用配置项 会影响到所有表单项
    componentProps: {
      class: 'w-full',
    }
  },
  schema: modalSchema(),
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});

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

const [BasicModal, modalApi] = useVbenModal({
  // 在这里更改宽度
  class: 'w-[70%]',
  fullscreenButton: false,
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);

    const {id} = modalApi.getData() as { id?: number | string };
    isUpdate.value = !!id;
    await setupTypeSelect();
    await queryPersonData()
    if (isUpdate.value && id) {
      const record = await maintainPlanInfo(id);
      record.planDate = [record.startDate, record.endDate]
      if (record.planPeriod == '1') {
        record.maintainMonth = record.maintainMonth?.split(',')
        record.maintainDay = record.maintainDay?.split(',')
      }
      if (record.machineMaintainPlanStaffVos) {
        record.userId =  record.machineMaintainPlanStaffVos.map(item=>item.userId.toString())
      }
      await formApi.setValues(record);
    }
    await markInitialized();

    modalApi.modalLoading(false);
  },
});

async function handleConfirm() {
  try {
    modalApi.lock(true);
    const {valid} = await formApi.validate();
    if (!valid) {
      return;
    }
    // getValues获取为一个readonly的对象 需要修改必须先深拷贝一次
    const data = cloneDeep(await formApi.getValues());
    if (data.planDate && data.planDate.length) {
      data.startDate = data.planDate[0]
      data.endDate = data.planDate[1]
    }
    if (data.planPeriod == '1') {
      data.maintainMonth = data.maintainMonth?.join(',')
      data.maintainDay = data.maintainDay?.join(',')
      data.maintainEveryday = undefined
    } else {
      data.maintainMonth = undefined
      data.maintainDay = undefined
    }
    data.machineMaintainPlanStaffBoList = []
    data.userId.forEach((item: string) => {
      data.machineMaintainPlanStaffBoList.push({
        userId: item
      })
    })
    await (isUpdate.value ? maintainPlanUpdate(data) : maintainPlanAdd(data));
    resetInitialized();
    emit('reload');
    modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.lock(false);
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}

/**
 *初始化设别类型数据
 */
async function setupTypeSelect() {
  const typeList = await getMachineTypeTree();
  formApi.updateSchema([
    {
      componentProps: () => ({
        class: 'w-full',
        fieldNames: {
          key: 'id',
          label: 'machineTypeName',
          value: 'id',
          children: 'children',
        },
        placeholder: '请选择',
        showSearch: true,
        treeData: typeList,
        treeDefaultExpandAll: true,
        treeLine: {showLeafIcon: false},
        // 筛选的字段
        treeNodeFilterProp: 'label',
        // 选中后显示在输入框的值
        treeNodeLabelProp: 'machineTypeName',
      }),
      fieldName: 'machineTypeId',
    },
  ]);
}

async function queryPersonData() {
  let params = {
    pageSize: 1000,
    pageNum: 1,
  }
  const res = await userList(params);
  const options = res.rows.map((user) => ({
    label: user.nickName + '-' + renderDictValue(user.sex, 'sys_user_sex')
      + '-' + user.phonenumber,
    value: user.userId.toString(),
  }));
  formApi.updateSchema([{
    componentProps: () => ({
      options: options,
      showSearch: true,
      optionFilterProp: 'label',
      optionLabelProp: 'label',
      mode: 'multiple',
    }),
    fieldName: 'userId',
  }])
}
</script>

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

