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

defineOptions({
  name: 'MtlAttributeOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.Material.GoodsProperty | 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.GoodsProperty,
  | 'GOODS_PROPERTY_CODE'
  | 'GOODS_PROPERTY_NAME'
  | 'GOODS_PROPERTY_REMARK'
  | 'GOODS_PROPERTY_ORDER'
  | 'GOODS_PROPERTY_FIELDTYPE'
  | 'GOODS_PROPERTY_FLAG'
  | 'GOODS_PROPERTY_VALID'
  | 'GOODS_PROPERTY_DATASOURCE'
  | 'GOODS_TYPE_ID'
>;

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

function createDefaultModel(): Model {
  return {
    GOODS_PROPERTY_CODE: '',
    GOODS_PROPERTY_NAME: '',
    GOODS_PROPERTY_REMARK: '',
    GOODS_PROPERTY_ORDER: 0,
    GOODS_PROPERTY_FIELDTYPE: '',
    GOODS_PROPERTY_FLAG: null,
    GOODS_PROPERTY_VALID: null,
    GOODS_TYPE_ID: null,
    GOODS_PROPERTY_DATASOURCE: ''
  };
}

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

const rules: Record<RuleKey, App.Global.FormRule> = {
  GOODS_PROPERTY_CODE: defaultRequiredRule,
  GOODS_PROPERTY_NAME: defaultRequiredRule,
  GOODS_PROPERTY_REMARK: {},
  GOODS_PROPERTY_ORDER: defaultRequiredRule,
  GOODS_PROPERTY_FIELDTYPE: defaultRequiredRule,
  GOODS_PROPERTY_FLAG: defaultRequiredRule,
  GOODS_TYPE_ID: defaultRequiredRule,
  GOODS_PROPERTY_VALID: {},
  GOODS_PROPERTY_DATASOURCE: defaultRequiredRule
};

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

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, props.rowData);
    // 检查 rowData 中的 GOODS_PROPERTY_VALID 是否为 'NULL'
    if (model.GOODS_PROPERTY_VALID === 'NULL') {
      model.GOODS_PROPERTY_VALID = null; // 将其设置为空
    }
  }
}

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

async function handleSubmit() {
  // console.log(model);
  // return;
  await validate();
  if (props.operateType === 'edit') {
    // 修改信息
    const delinfo = await UpDateGoodsPropertyInfo(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 AddGoodsPropertyInfo(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 fetchGetGoodsTypeList(getcodedata);
  if (!error) {
    const options = data.data.records.map(item => ({
      label: item.GOODS_TYPE_NAME,
      value: item.GOODS_TYPE_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="GOODS_TYPE_ID">
          <NSelect v-model:value="model.GOODS_TYPE_ID" :options="roleOptions" />
        </NFormItem>
        <NFormItem label="库存编码" path="GOODS_PROPERTY_CODE">
          <NInput v-model:value="model.GOODS_PROPERTY_CODE" placeholder="请输入库存编码" />
        </NFormItem>
        <NFormItem label="名称" path="GOODS_PROPERTY_NAME">
          <NInput v-model:value="model.GOODS_PROPERTY_NAME" placeholder="请输入库存属性名称" />
        </NFormItem>
        <NFormItem label="计划编码" path="GOODS_PROPERTY_REMARK">
          <NInput v-model:value="model.GOODS_PROPERTY_REMARK" placeholder="请输入计划编码" />
        </NFormItem>
        <NFormItem label="显示类型" path="GOODS_PROPERTY_FIELDTYPE">
          <NInput v-model:value="model.GOODS_PROPERTY_FIELDTYPE" placeholder="显示类型" />
        </NFormItem>
        <NFormItem label="排序" path="GOODS_PROPERTY_ORDER">
          <NInputNumber v-model:value="model.GOODS_PROPERTY_ORDER" clearable />
        </NFormItem>
        <NFormItem label="同步SG186" path="GOODS_PROPERTY_FLAG">
          <NSelect v-model:value="model.GOODS_PROPERTY_FLAG" :options="translateOptions(enablePropertyFLAGOptions)" />
        </NFormItem>
        <NFormItem label="是否必选" path="GOODS_PROPERTY_VALID">
          <NSelect v-model:value="model.GOODS_PROPERTY_VALID" :options="translateOptions(enablePropertyFLAGOptions)" />
        </NFormItem>
        <NFormItem label="数据源" path="GOODS_PROPERTY_DATASOURCE">
          <NInput v-model:value="model.GOODS_PROPERTY_DATASOURCE" 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>
