<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 {
  groupAdd,
  groupInfo,
  groupUpdate
} from '#/api/property/attendanceManagement/attendanceGroupSettings';
import {defaultFormValueGetter, useBeforeCloseDiff} from '#/utils/popup';

import {
  clockingColumns,
  cycleColumns,
  modalSchema,
  noClockingColumns,
  weekdayColumns
} from './data';
import {Tag, Button, Table, Checkbox} from 'ant-design-vue'
import {getDictOptions} from "#/utils/dict";
import holidayCalendar from './holiday-calendar.vue'

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

const isUpdate = ref(false);
const weekdayData = ref<any[]>([])
const title = computed(() => {
  return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});
const settingData = ref<any>({
  isAutomatic: true,
})
const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    // 默认占满两列
    formItemClass: 'col-span-2',
    // 默认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-[80%]',
  fullscreenButton: false,
  maskClosable: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;
    if (isUpdate.value && id) {
      const record = await groupInfo(id);
      await formApi.setValues(record);
    } else {
      weekdayData.value = []
      getDictOptions('wy_kqgzr').forEach(item => {
        weekdayData.value.push({
          dayOfWeek: item.value,
          label: item.label,
          shift: item.value == '6' || item.value == '7' ? '休息' : '常规班次：08:00:00~12:00:00    14:00:00~17:00:00'
        })
      })
    }
    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());
    await (isUpdate.value ? groupUpdate(data) : groupAdd(data));
    resetInitialized();
    emit('reload');
    modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.lock(false);
  }
}

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

const [HolidayCalendar, holidayApi] = useVbenModal({
  connectedComponent: holidayCalendar,
});

/**
 * 查看法定节假日日历
 */
async function showHoliday() {
  holidayApi.open()
}

</script>

<template>
  <BasicModal :title="title">
    <BasicForm>
      <template #weekdaySetting>
        <div class="item-font">
          <span>快捷设置班次：</span>
          <Tag color="processing">常规班次：08:00:00~12:00:00 14:00:00~17:00:00</Tag>
          <Button type="link">更改班次</Button>
        </div>
      </template>
      <template #settingItem>
        <div class="item-font" style="width: 100%;">
          <Table style="width: 100%" bordered :columns="weekdayColumns" :data-source="weekdayData"
                 size="small" :pagination="false">
            <!--          <template #headerCell="{ column }">-->
            <!--          </template>-->
            <!--          <template #bodyCell="{ column, record }">-->
            <!--            <template>-->
            <!--              {{ record[column.field] }}-->
            <!--            </template>-->
            <!--          </template>-->
            <!--          <template #action="{row}">-->
            <!--            <Button type="link">更改班次</Button>-->
            <!--            <Button type="link">休息</Button>-->
            <!--          </template>-->
          </Table>
          <Checkbox class="item-padding-top" v-model:checked="settingData.isAutomatic">
            法定节假日自动排休
          </Checkbox>
          <!--     https://timor.tech/api/holiday/year/2024 国务院节假日安排API-->
          <Button type="link" @click="showHoliday">查看法定节假日日历</Button>
          <p class="item-padding-top item-font-weight">特殊日期：</p>
          <p class="item-padding">无需打卡日期：</p>
          <Table style="width: 80%" bordered :columns="noClockingColumns" :data-source="[]"
                 size="small" :pagination="false">
          </Table>
          <p class="item-padding">必须打卡日期：</p>
          <Table style="width: 80%" bordered :columns="clockingColumns" :data-source="[]"
                 size="small" :pagination="false">
          </Table>
        </div>
      </template>
      <template #attendanceShift>
        <Button size="small">选择班次</Button>
      </template>
      <template #shiftData>
        <Tag closable color="processing">早班</Tag>
      </template>
      <template #schedulingCycle>
        <span class="item-font">周期天数4天</span>
      </template>
      <template #cycleData>
        <Table style="width: 100%" bordered :columns="cycleColumns" :data-source="[]"
               size="small" :pagination="false">
        </Table>
      </template>
    </BasicForm>
    <HolidayCalendar></HolidayCalendar>
  </BasicModal>
</template>
<style lang="scss" scoped>
.item-font {
  font-size: 0.875rem;
}

.item-font-weight {
  font-weight: 500;
}

.item-padding-top {
  padding-top: 1.1rem;
}

.item-padding {
  padding: 1.1rem 0 0.5rem 0;
}
</style>

