<script setup lang="ts">
import { computed, reactive, watch } from 'vue';
import { fetchUpdateBatch } from '@/service/api/mps/batch';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { useDict } from '@/hooks/business/dict';import { $t } from '@/locales';

defineOptions({
  name: 'BatchOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.Mps.Batch | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { options: preBatchStatusOptions } = useDict('pre_batch_status');
const { options: afterBatchStatusOptions } = useDict('after_batch_status');
const { options: mpsCheckStatusOptions } = useDict('mps_check_status');

const { formRef, validate, restoreValidation } = useNaiveForm();
const { createRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: '新增批量状态',
    edit: '编辑批量状态'
  };
  return titles[props.operateType];
});

type Model = Api.Mps.BatchOperateParams;

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
      batchMonth: '',
      preBatchDate: undefined,
      preBatchStatus: '',
      afterBatchDate: undefined,
      afterBatchStatus: '',
      checkStatus: '',
      checkBy: undefined,
      checkRemark: ''
  };
}

type RuleKey = Extract<
  keyof Model,
  | 'preBatchDate'
  | 'preBatchStatus'
  | 'afterBatchDate'
  | 'afterBatchStatus'
  | 'checkStatus'
  | 'checkBy'
>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  checkStatus: createRequiredRule('核对状态不能为空')
};

function handleUpdateModelWhenEdit() {
  if (props.operateType === 'add') {
    Object.assign(model, createDefaultModel());
    return;
  }

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, props.rowData);
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();

  const { batchMonth, preBatchDate, preBatchStatus, afterBatchDate, afterBatchStatus, checkStatus, checkBy, checkRemark } = model;

  // request
  if (props.operateType === 'add') {
    const { error } = await fetchCreateBatch({ batchMonth, preBatchDate, preBatchStatus, afterBatchDate, afterBatchStatus, checkStatus, checkBy, checkRemark });
    if (error) return;
  }

  if (props.operateType === 'edit') {
    const { error } = await fetchUpdateBatch({ batchMonth, checkStatus, checkRemark });
    if (error) return;
  }

  window.$message?.success($t('common.updateSuccess'));
  closeDrawer();
  emit('submitted');
}

watch(visible, () => {
  if (visible.value) {
    handleUpdateModelWhenEdit();
    restoreValidation();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" :title="title" display-directive="show" :width="800" class="max-w-90%">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules"
             label-placement="left"
             label-align="left"
             :show-label="true"
             :label-width="140">
        <NFormItem  label="预批量时间" path="preBatchDate">
          <NDatePicker style="width: 100%"
              :disabled="true"
            v-model:formatted-value="model.preBatchDate"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            clearable
          />
        </NFormItem>
        <NFormItem label="预批量状态" path="preBatchStatus">
          <NSelect
              :disabled="true"
            v-model:value="model.preBatchStatus"
            placeholder="请选择预批量状态"
            :options="preBatchStatusOptions"
            clearable
          />
        </NFormItem>
        <NFormItem label="正式批量时间" path="afterBatchDate">
          <NDatePicker style="width: 100%"
              :disabled="true"
            v-model:formatted-value="model.afterBatchDate"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            clearable
          />
        </NFormItem>
        <NFormItem label="正式批量状态" path="afterBatchStatus">
          <NSelect
              :disabled="true"
            v-model:value="model.afterBatchStatus"
            placeholder="请选择正式批量状态"
            :options="afterBatchStatusOptions"
            clearable
          />
        </NFormItem>
        <NFormItem label="核对状态" path="checkStatus">
          <NSelect
            v-model:value="model.checkStatus"
            placeholder="请选择核对状态"
            :options="mpsCheckStatusOptions"
            clearable
          />
        </NFormItem>
<!--        <NFormItem label="核对人" path="nickName">
          <NInput :disabled="true" v-model:value="model.nickName" placeholder="请输入核对人" />
        </NFormItem>-->
        <NFormItem label="备注" path="checkRemark">
          <NInput v-model:value="model.checkRemark" placeholder="请输入备注" />
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
