import { getPayCurrencyTypeEnumList } from "@/common/constants/enumsList";
import { getGoodsUnitEnumItemName } from "@/common/constants/enumsName";
import { commonResultInfo, getRequestResultInfo } from "@/common/methods/request";
import { validateCommon } from "@/common/setup/validate";
import APP from '@/services';
import { QueryCustomInfo } from "@/services/go/ermcp/customInfo";
import { QueryCustomInfoType } from "@/services/go/ermcp/customInfo/interface";
import { QueryDeliveryGoods } from "@/services/go/ermcp/goodsInfo";
import { Ermcp3Brand, Ermcp3Wrstandard, ErmcpDeliveryGoodsDetailEx, ErmcpDeliveryGoodsRsp } from "@/services/go/ermcp/goodsInfo/interface";
import { orderContract, spotContractStatus } from "@/services/proto/spotcontract";
import {
    GldErmcpSpotContractOperateReq,
    SpotContractOperateReq
} from "@/services/proto/spotcontract/interface";
import { ContractStateSign, GldContractStateSign } from "@/views/information/spot-contract/setup";
import { message } from "ant-design-vue";
import { RuleObject } from "ant-design-vue/lib/form/interface";
import Long from 'long';
import moment, { Moment } from "moment";
import { reactive, ref, Ref, UnwrapRef } from "vue";
import { FormState } from './interface';


/**
 * 合同操作相关 针对操作类型 1: 保存草稿  2: 提交申请 3: 删除成功 4:审核通过
 * @param reqs GldErmcpSpotContractOperateReq
 * @param loading
 * @returns
 */
export function orderContractControl(reqs: GldErmcpSpotContractOperateReq, loading: Ref<boolean>): Promise<string> {
    //处理 合同id
    if (reqs.SpotContractID) {
        reqs.SpotContractID = Long.fromString(reqs.SpotContractID)
    }
    // loading 效果
    loading.value = true
    // 获取提示信息
    const sign = getRequestResultInfo(GldContractStateSign, reqs.OperateType)  // 接口请求后的返回提示 这里统一进行管理
    // 接口调用
    const result = orderContract(reqs)
    // 接口调用结果处理，提示成功或者失败信息，并关闭loading效果
    return commonResultInfo(result, sign, loading)
}

/**
 * 修改合同类型 针对操作类型 4:审核拒绝 6:正常完结 5:撤销
 * @param reqs
 * @param loading
 * @returns
 */
export function orderContractOperateControl(reqs: SpotContractOperateReq, loading: Ref<boolean>): Promise<string> {
    //处理 合同id
    if (reqs.SpotContractID) {
        reqs.SpotContractID = Long.fromString(reqs.SpotContractID)
    }
    // loading 效果
    loading.value = true
    // 获取提示信息
    const sign = getRequestResultInfo(ContractStateSign, reqs.OperateType)  // 接口请求后的返回提示 这里统一进行管理
    // 接口调用
    const result = spotContractStatus(reqs)
    // 接口调用结果处理，提示成功或者失败信息，并关闭loading效果
    return commonResultInfo(result, sign, loading)
}


/**
 * 新增和修改的表单数据
 * @returns
 */
export function handleFromState() {
    function initFormData() {
        return {
            ContractNo: '', // 现货合同编号
            ContractType: 1, // int32 现货合同类型-1:采购-1:销售
            BizType: 1, // uint32 业务类型 - 1:套保 2:套利
            BuyUserID: undefined, // uint64 采购方ID
            SellUserID: undefined,// uint64 客户ID
            ContractAttachment: '',// bytes 合同附件
            DeliveryGoodsID: undefined, // 现货品种ID
            WrStandardID: undefined,  // uint64 现货商品ID
            SpotGoodsBrandID: undefined, // uint64 现货品牌ID
            ConvertFactor: undefined,// double 标仓系数
            SpotGoodsDesc: '', // string 商品型号
            PriceType: 1, // uint32 定价类型-1:一口价2:点价3:暂定价
            Qty: '', // double 数量
            Price: '',// double 价格暂定价[1:一口价、3:暂定价]
            Amount: null, // double 金额[1:一口价、3:暂定价]
            DeliveryStartDate: '', // string 交收期(开始)
            DeliveryEndDate: '', // string 交收期(结束)
            ContractMargin: null, // double 合同保证金
            SaleUserID: undefined, // uint64 业务员ID
            MerUserID: undefined, // uint64 跟单员ID
            AccountID: undefined, // uint64 期货账户ID
            Remark: '', // string 合同备注
            CurrencyID: undefined, // 结算币种ID
            GoodsID: undefined, // uint64 点价合约ID-0:为现货，其它为期货商品合约ID[2:点价3:暂定价]
            PriceMove: null,// double 升贴水[2:点价3:暂定价]
            StartDate: '', //                       点价开始时间
            EndDate: '', //                           点价结束时间
            TradeUserID: undefined, //           交易员ID
        }
    }
    const formState: UnwrapRef<FormState> = reactive(initFormData())
    // 业务类型
    const businessType = [
        { key: 1, value: '套保' },
        { key: 2, value: '套利' },
    ];

    return { formState, businessType, initFormData }
}

/**
 * 表单新增和修改验证规则
 */
export function handleFormRule(formState: UnwrapRef<FormState>) {
    // 验证合同类型
    async function v_ContractType(rule: RuleObject, value: number) {
        return validateCommon(value, '请选择合同类型')
    }

    // 验证业务类型
    // async function v_BizType(rule: RuleObject, value: number) {
    //     return validateCommon(value, '请选择业务类型')
    // }

    // 验证业务类型
    async function v_BuyUser(rule: RuleObject, value: number) {
        return validateCommon(value, '请选择采购方')
    }

    // 验证业务类型
    async function v_SellUser(rule: RuleObject, value: number) {
        return validateCommon(value, '请选择销售方')
    }

    // 验证现货品种
    async function v_DeliveryGoods(rule: RuleObject, value: number) {
        return validateCommon(value, '请选择现货品种')
    }

    // 验证品类
    async function v_WrStandard(rule: RuleObject, value: number) {
        const errorInfo = formState.DeliveryGoodsID ? '请选择商品' : '请先选择现货品种'
        return validateCommon(value, errorInfo)
    }

    // 验证品牌
    async function v_SpotGoodsBrand(rule: RuleObject, value: number) {
        const errorInfo = formState.DeliveryGoodsID ? '请选择品牌' : '请先选择现货品种'
        return validateCommon(value, errorInfo)
    }

    // 验证定价类型
    async function v_PriceType(rule: RuleObject, value: number) {
        return validateCommon(value, '请选择定价类型')
    }

    // 验证结算币种
    async function v_Currency(rule: RuleObject, value: number) {
        return validateCommon(value, '请选择结算币种')
    }

    // 验证点价合约
    async function v_Goods(rule: RuleObject, value: number) {
        return validateCommon(value, '请选择点价合约')
    }
    const rules = {
        ContractNo: [{ required: true, message: '请输入合同编号', trigger: 'blur' }],
        ContractType: [{ required: true, validator: v_ContractType, trigger: 'change' }],
        // BizType: [{ required: true, validator: v_BizType, trigger: 'change' }],
        BuyUserID: [{ required: true, validator: v_BuyUser, trigger: 'change' }],
        SellUserID: [{ required: true, validator: v_SellUser, trigger: 'change' }],
        DeliveryGoodsID: [{ required: true, validator: v_DeliveryGoods, trigger: 'change' }],
        WrStandardID: [{ required: true, validator: v_WrStandard, trigger: 'blur' }],
        SpotGoodsBrandID: [{ required: true, validator: v_SpotGoodsBrand, trigger: 'blur' }],
        GoodsID: [{ required: true, validator: v_Goods, trigger: 'blur' }],
        // ConvertFactor: [{ required: true, message: '请选择品类', trigger: 'blur' }],
        SpotGoodsDesc: [{ required: true, message: '请输入商品规格', trigger: 'blur' }],
        PriceType: [{ required: true, validator: v_PriceType, trigger: 'blur' }],
        CurrencyID: [{ required: true, validator: v_Currency, trigger: 'blur' }],
        Qty: [{ required: true, message: '请输入数量', trigger: 'blur' }],
        Price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
        PriceMove: [{ required: true, message: '请输入升贴水', trigger: 'blur', type: 'number' }],
    };
    return { rules }
}

/**
 * 合同类型
 */
export function handleContract(formState: UnwrapRef<FormState>) {
    // 合同类型
    const contractType = [
        { key: 1, value: '采购' },
        { key: -1, value: '销售' },
    ];
    const isSell = ref<boolean>(false)  // true => 销售 false => 采购
    /**
     * 合同类型变更
     */
    function contractChange(value: number) {
        if (value === 1) {
            isSell.value = false
            formState.SellUserID = undefined;
        } else {
            isSell.value = true
            formState.BuyUserID = undefined
        }
    }

    const customList = ref<QueryCustomInfoType[]>([])

    function queryCustomList() {
        QueryCustomInfo(3)
            .then((res) => {
                customList.value = res.filter(e => (e.status === 4))
                console.log('客户资料', customList);
            })
            .catch((err) => {
                message.error(err);
            })
    }

    return { contractType, isSell, contractChange, customList, queryCustomList }
}


/**
 * 处理现货商品
 */
export function handleDeliveryGoods(formState: UnwrapRef<FormState>) {
    // 现货品种
    const deliveryGoodsList = ref<ErmcpDeliveryGoodsRsp[]>([])
    // 品牌
    const gblist = ref<Ermcp3Brand[]>([])
    // 品类列表
    const gmlist = ref<Ermcp3Wrstandard[]>([])

    // 查询现货商品
    function getDeliveryGoods() {
        QueryDeliveryGoods({}).then(res => {
            console.log('查询现货商品', res);
            deliveryGoodsList.value = res;
        }).catch(err => {
            message.error(err)
        })
    }

    // 切换现货商品
    function deliveryGoodsChange(value: number | undefined) {
        if (value !== undefined) {
            getDeliveryGoodsDetail(value)
        } else {
            gblist.value.length = 0
            gmlist.value.length = 0
        }
        formState.WrStandardID = undefined;
        formState.SpotGoodsBrandID = undefined;
        formState.ConvertFactor = undefined;
    }

    // 查询现货商品详情
    function getDeliveryGoodsDetail(deliverygoodsid: number) {
        const temp = APP.get('DeliveryGoodsList').find((e: ErmcpDeliveryGoodsDetailEx) => e.data.deliverygoodsid === deliverygoodsid)
        if (temp) {
            gblist.value = temp.gblist
            gmlist.value = temp.gmlist
        }
    }

    const numberUnit = ref<string>('')

    // 品类变更
    function WrStandardChange(value: number) {
        const obj = gmlist.value.find((e) => e.wrstandardid === value);
        if (obj) {
            //标仓系数
            formState.ConvertFactor = obj.convertfactor;
            // 单位
            numberUnit.value = getGoodsUnitEnumItemName(obj.unitid)
        }
    }

    return {
        deliveryGoodsList,
        gblist,
        gmlist,
        numberUnit,
        WrStandardChange,
        getDeliveryGoods,
        getDeliveryGoodsDetail,
        deliveryGoodsChange
    }
}

/**
 * 价格信息
 */
export function handlePrice(formState: UnwrapRef<FormState>) {
    // 定价类型
    const priceType = [
        { key: 1, value: '一口价' },
        { key: 2, value: '点价' },
        { key: 3, value: '暂定价' },
    ];
    // 币种
    const payCurrency = getPayCurrencyTypeEnumList()
    console.log('payCurrency', payCurrency);
    // 目前写死，获取枚举信息里面没有 单位名称，后期进行优化
    const payCurrencyUnit = ref<string>('元')

    // 切换币种
    function parCurrencyChange(value: number) {
        const obj = payCurrency.find(e => e.enumitemname === value)
        console.log('切换币种', obj);

        // payCurrencyUnit.value = obj?.enumdicname
    }

    return { priceType, payCurrency, payCurrencyUnit, parCurrencyChange }
}

/**
 * 处理日期
 */
export function handleDate() {
    // 交收期
    const deliveryDate = ref<Moment[]>([])
    // 点价期
    const priceDate = ref<Moment[]>([]);

    function disabledDate(current: Moment) {
        // Can not select days before today and today
        return current && current < moment().endOf('day');
    }

    return { deliveryDate, priceDate, disabledDate }
}
/**
 * 处理金额
 */
export function handleAmout(formState: UnwrapRef<FormState>) {
    function getAmout() {
        const { Price, Qty } = formState
        formState.Amount = (Price && Qty) ? Number(Price) * Number(Qty) : 0
    }
    return { getAmout }
}