<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';
import { enablePropertyFLAGOptions } from '@/constants/business';
import { AddGoodsCategoryInfo, UpDateGoodsCategoryInfo, fetchGetGoodsCategoryList } from '@/service/api/planmg';

defineOptions({
  name: 'MtlCategoryOperateDrawer'
});

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

const props = defineProps<Props>();

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

const emit = defineEmits<Emits>();

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

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

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: '新增物料类别',
    edit: '编辑物料类别'
  };
  return titles[props.operateType];
});

type Model = Pick<
  Api.Material.GoodsCategory,
  | 'GOODS_CLASS_ID'
  | 'GOODS_CLASS_CODE'
  | 'GOODS_CLASS_NAME'
  | 'GOODS_CLASS_REMARK'
  | 'GOODS_CLASS_FLAG'
  | 'GOODS_CLASS_PARENT_ID'
>;

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

function createDefaultModel(): Model {
  return {
    GOODS_CLASS_CODE: '',
    GOODS_CLASS_ID: 0,
    GOODS_CLASS_PARENT_ID: null,
    GOODS_CLASS_NAME: '',
    GOODS_CLASS_REMARK: '',
    GOODS_CLASS_FLAG: ''
  };
}

type RuleKey = Exclude<keyof Model, 'roleDesc'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  GOODS_CLASS_ID: defaultRequiredRule,
  GOODS_CLASS_CODE: defaultRequiredRule,
  GOODS_CLASS_NAME: defaultRequiredRule,
  GOODS_CLASS_PARENT_ID: defaultRequiredRule,
  GOODS_CLASS_REMARK: {},
  GOODS_CLASS_FLAG: defaultRequiredRule
};

function handleInitModel() {
  Object.assign(model, createDefaultModel());

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

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

async function handleSubmit() {
  // console.log(model);
  // return;
  await validate();
  if (props.operateType === 'edit') {
    // 修改信息
    const delinfo = await UpDateGoodsCategoryInfo(model);
    if (delinfo.response !== undefined) {
      if (delinfo.response.data.code === '0000') {
        window.$message?.success(delinfo.response.data.msg as string);
        closeDrawer();
        emit('submitted');
      }
    }
  } else {
    // 新增账户
    const delinfo = await AddGoodsCategoryInfo(model);
    if (delinfo.response !== undefined) {
      if (delinfo.response.data.code === '0000') {
        window.$message?.success(delinfo.response.data.msg as string);
        closeDrawer();
        emit('submitted');
      }
    }
  }
}
const roleOptions = ref<CommonType.Option<string>[]>([]);

async function getRoleOptions() {
  const getcodedata = {
    size: 0,
    current: 0
  };
  const { error, data } = await fetchGetGoodsCategoryList(getcodedata);
  if (!error) {
    const options = data.data.records.map(item => ({
      label: item.GOODS_CLASS_NAME,
      value: item.GOODS_CLASS_ID
    }));
    roleOptions.value = [...options];
  }
}
watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
    getRoleOptions();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" display-directive="show" :width="360">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules">
        <NFormItem label="父类别" path="userRoles">
          <NSelect v-model:value="model.GOODS_CLASS_PARENT_ID" :options="roleOptions" />
        </NFormItem>
        <NFormItem label="类别名称" path="GOODS_CLASS_NAME">
          <NInput v-model:value="model.GOODS_CLASS_NAME" placeholder="请输入物料类别名称" />
        </NFormItem>
        <NFormItem label="编码" path="GOODS_CLASS_CODE">
          <NInput v-model:value="model.GOODS_CLASS_CODE" placeholder="请输入物料类别编码" />
        </NFormItem>
        <NFormItem label="状态" path="GOODS_CLASS_FLAG">
          <NRadioGroup v-model:value="model.GOODS_CLASS_FLAG">
            <NRadio
              v-for="item in enablePropertyFLAGOptions"
              :key="item.value"
              :value="item.value"
              :label="$t(item.label)"
            />
          </NRadioGroup>
        </NFormItem>
        <NFormItem label="备注" path="GOODS_CLASS_REMARK">
          <NInput v-model:value="model.GOODS_CLASS_REMARK" 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>
