<template>
  <BasicModal
    v-bind="$attrs"
    destroyOnClose
    @register="registerModal"
    :title="getTitle"
    width="22%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { workDayDataFormSchema } from './data';

  import { WorkingDayEdit } from '/@/api/biz/management/working';

  const emit = defineEmits(['success', 'register']);

  const getTitle = computed(() => '工作日配置');
  const isUpdate = ref(false);
  const rowId = ref();

  const { createMessage } = useMessage();
  const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
    layout: 'vertical',
    showResetButton: false,
    labelWidth: 100,
    schemas: workDayDataFormSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async data => {
    await resetFields();
    setModalProps({ confirmLoading: false, canFullscreen: false });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      rowId.value = data.record.roleId;
      console.log(data);
      const works = [];
      data.record.forEach(item => {
        works.push(item.name);
      });
      await setFieldsValue({ works });
    }
  });

  // 提交按钮事件
  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      const workings = {
        monday: 0,
        tuesday: 0,
        wednesday: 0,
        thursday: 0,
        friday: 0,
        saturday: 0,
        sunday: 0,
      };
      Object.keys(workings).forEach(item => {
        if (values.works.indexOf(item) == -1) {
          workings[item] = 0;
        } else {
          workings[item] = 1;
        }
      });
      console.log('workings::::::::', workings);
      await WorkingDayEdit(workings);
      createMessage.success('工作日编辑成功！');
      closeModal();
      emit('success', {
        isUpdate: unref(isUpdate),
      });
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
