import { commonResultInfo, getRequestResultInfo } from "@/common/methods/request";
import { validateCommon } from "@/common/setup/validate";
import { addWarehouseApply } from "@/services/proto/warehouse";
import { WarehouseApplyReq } from "@/services/proto/warehouse/interface";
import { message } from "ant-design-vue";
import { RuleObject } from "ant-design-vue/lib/form/interface";
import { reactive, Ref, ref } from "vue";
import { warehouseApplyRequestResultMsg } from "../setup";

export interface FormState {
    type: number // int32 类型 1 新增 2 修改
    warehouseid?: number // uint64 仓库ID
    warehousecode: string // string 仓库代码
    warehousename: string // string 仓库名称
    warehousetype: number | undefined  // int32 仓库类型 - 1 厂库  2 自有库  3 合作库
    provinceid?: number | undefined  // uint64 省
    cityid?: number | undefined  // uint64 市
    districtid?: number | undefined   // int32 区
    address?: string // string 详细地址
    contactname?: string // string 联系人
    contactnum?: string // string 联系电话
}
/**
 * 表单
 */
export function handleForm() {
    const formRef = ref();
    const formState = reactive<FormState>({
        type: 1,
        warehouseid: 0,
        warehousecode: '',
        warehousename: '',
        warehousetype: undefined,
        provinceid: undefined,
        cityid: undefined,
        districtid: undefined,
        address: '',
        contactname: '',
        contactnum: '',
    })
    // 验证仓库类型
    async function v_warehousetype(rule: RuleObject, value: number) {
        return validateCommon(value, '请选择仓库类型')
    }
    const rules = {
        warehousename: [{ required: true, message: '请输入仓库名称', trigger: 'blur' }],
        warehousecode: [{ required: true, message: '请输入仓库简称', trigger: 'blur' }],
        warehousetype: [{ required: true, validator: v_warehousetype, trigger: 'blur' }],

    }
    return { formRef, formState, rules }
}

/**
 * 仓库信息请求 针对操作类型 1 新增 2 修改
 * @param param WarehouseApplyReq
 * @param loading 
 * @returns 
 */
export function warehouseApply(param: WarehouseApplyReq, loading: Ref<boolean>) {
    // loading 效果
    loading.value = true
    // 获取提示信息
    const sign = getRequestResultInfo(warehouseApplyRequestResultMsg, param.type)  // 接口请求后的返回提示 这里统一进行管理
    // 接口调用
    const result = addWarehouseApply(param)
    // 接口调用结果处理，提示成功或者失败信息，并关闭loading效果
    return commonResultInfo(result, sign, loading)
}

/**
 * 
 * @param fn 
 * @param param 
 * @param loading 
 * @param messageInfo 
 * @returns 
 */
export async function reqestAction(fn: Function, param: WarehouseApplyReq, loading: Ref<boolean>, messageInfo: [string, string]) {
    loading.value = true;
    const [successInfo, errInfo] = messageInfo;
    try {
        const result = await fn(param)
        message.success(successInfo)
        return Promise.resolve(result)
    } catch (err) {
        const info = errInfo + err
        message.error(info)
        return Promise.reject(err)
    } finally {
        loading.value = false;
    }
}