<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 {
  inspectionPlanAdd,
  inspectionPlanInfo,
  inspectionPlanUpdate
} from '#/api/property/inspectionManagement/inspectionPlan';
import {defaultFormValueGetter, useBeforeCloseDiff} from '#/utils/popup';

import {modalSchema} from './data';
import {personList} from "#/api/property/resident/person";
import {renderDictValue} from "#/utils/render";
import {inspectionRouteList} from "#/api/property/inspectionManagement/inspectionRoute";
import {InputNumber} from 'ant-design-vue'

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);
    await queryLineData()
    await queryPersonData()
    const {id} = modalApi.getData() as { id?: number | string };
    isUpdate.value = !!id;
    if (isUpdate.value && id) {
      const record = await inspectionPlanInfo(id);
      record.planDate = [record.startDate, record.endDate]
      if (record.inspectionPlanPeriod == '1') {
        record.inspectionMonth = record.inspectionMonth?.split(',')
        record.inspectionDay = record.inspectionDay?.split(',')
      } else {
        record.inspectionWorkday = record.inspectionWorkday?.split(',')
      }
      if (record.inspectionPlanStaffVoList && record.inspectionPlanStaffVoList.length) {
        record.userId = record.inspectionPlanStaffVoList.map(item => item.userId)
      }
      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]
      data.startTime = data.planDate[0]?.split(' ')[1]
      data.endTime = data.planDate[1]?.split(' ')[1]
    }
    if (data.inspectionPlanPeriod == '1') {
      data.inspectionMonth = data.inspectionMonth?.join(',')
      data.inspectionDay = data.inspectionDay?.join(',')
      data.inspectionWorkday = undefined
    } else {
      data.inspectionWorkday = data.inspectionWorkday?.join(',')
      data.inspectionMonth = undefined
      data.inspectionDay = undefined
    }
    if (data.userId) {
      data.inspectionPlanStaffBoList = []
      data.userId.forEach((item: any) => {
        data.inspectionPlanStaffBoList.push({
          userId: item,
          startTime: data.startDate,
          endTime: data.endDate
        })
      })
    }
    await (isUpdate.value ? inspectionPlanUpdate(data) : inspectionPlanAdd(data));
    resetInitialized();
    emit('reload');
    modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.lock(false);
  }
}

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

async function queryPersonData() {
  let params = {
    pageSize: 1000,
    pageNum: 1,
  }
  const res = await personList(params);
  const options = res.rows.map((user) => ({
    label: user.userName + '-' + renderDictValue(user.gender, 'sys_user_sex')
      + '-' + user.phone + '-' + user.unitName,
    value: user.id,
  }));
  formApi.updateSchema([{
    componentProps: () => ({
      options: options,
      showSearch: true,
      filterOption: filterOption,
      mode: 'multiple',
    }),
    fieldName: 'userId',
  }])
}

/**
 * 查询巡检路线数据
 */
async function queryLineData() {
  let params = {
    pageSize: 1000,
    pageNum: 1,
  }
  const res = await inspectionRouteList(params);
  const options = res.rows.map((item) => ({
    label: item.routeName,
    value: item.id,
  }));
  formApi.updateSchema([{
    componentProps: () => ({
      options: options,
      showSearch: true,
      filterOption: filterOption
    }),
    fieldName: 'inspectionRouteId',
  }])
}

const filterOption = (input: string, option: any) => {
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};
</script>

<template>
  <BasicModal :title="title">
    <BasicForm>
      <template #beforeTime="slotProps">
        <div class="before-time">
          <InputNumber id="inputNumber" v-bind="slotProps" :min="1"/>
          <span class="tail-text">分钟完成</span>
        </div>
      </template>
    </BasicForm>
  </BasicModal>
</template>
<style lang="scss" scoped>
.before-time {
  display: flex;

  .tail-text {
    width: 100px;
    font-size: 0.875rem;
    font-weight: 500;
    text-align: center;
    line-height: 32px;
  }
}

</style>
