/** ================================= 信息 - 现货商品信息 ================================**/

import APP from '@/services';
import { getUserId } from "@/services/bus/user";
import { getUserAccountType } from "@/services/bus/user";
import { commonSearch_go } from '@/services/go/index';
import { QueryQuoteDay } from '../../quote';
import {
    Ermcp3Brand, Ermcp3GoodsGroup,
    Ermcp3Wrstandard,
    ErmcpDeliveryGoodsDetailEx,
    ErmcpDeliveryGoodsReq,
    ErmcpDeliveryGoodsRsp, ErmcpMiddleGoodsChangeLog, ErmcpMiddleGoodsModel,
    Goods,
    Ermcp3MiddleGoodsDetail2
} from './interface';
import { Ermcp3MiddleGoodsDetail } from './interface/middlegoodsdetail'
import { Ermcp3DeliveryGoodsDetailReq, Ermcp3DeliveryGoodsDetail } from './interface/deliverygoodsdetail'
import { isOemByEnum, OemType } from '@/common/config/projectName';

/**
 * 查询现货商品 /Ermcp3/QueryDeliveryGoods
 * @param excluudecfg 排除已配置的现货商品 1-排除
 * @constructor
 */
export function QueryDeliveryGoods(req: ErmcpDeliveryGoodsReq): Promise<ErmcpDeliveryGoodsRsp[]> {
    const userid = getUserId(); // 所属机构id
    const usertype = getUserAccountType();  //  用户类型 2-机构 7-企业成员
    return commonSearch_go('/Ermcp3/QueryDeliveryGoods', { usertype, userid, ...req }).catch((err) => {
        throw new Error(`查询现货商品: ${err}`);
    });
}

/**
 * 查询商品品类 /Ermcp3/QueryGoodsWrstandard
 * @param deliverygoodsid 现货商品id
 * @constructor
 */
export function QueryGoodsWrstandard(deliverygoodsid: number): Promise<Ermcp3Wrstandard[]> {
    const userid = getUserId(); // 所属机构id
    const usertype = getUserAccountType(); //  用户类型 2-机构 7-企业成员
    return commonSearch_go('/Ermcp3/QueryGoodsWrstandard', { userid, usertype, deliverygoodsid }).catch((err) => {
        throw new Error(`查询商品品类: ${err}`);
    });
}

/**
 * 查询商品品牌 /Ermcp3/QueryGoodsbrand
 * @constructor
 */
export function QueryGoodsbrand(): Promise<Ermcp3Brand[]> {
    const userid = getUserId(); // 用户id
    const usertype = getUserAccountType();  // 用户类型 2-机构 7-企业成员
    return commonSearch_go('/Ermcp3/QueryGoodsbrand', { userid, usertype }).catch((err) => {
        throw new Error(`查询商品品牌: ${err}`);
    });
}

/**
 * 查询现货商品详情列表 /Ermcp3/QueryDeliveryGoodsDetail
 * @constructor
 */
export function GetDeliveryGoodsDetail(deliverygoodsid?: number): Promise<Ermcp3DeliveryGoodsDetail[]> {
    const param: Ermcp3DeliveryGoodsDetailReq = {
        userid: getUserId(),
        usertype: getUserAccountType(),
    }
    if (deliverygoodsid) {
        param.deliverygoodsid = deliverygoodsid;
    }
    return commonSearch_go('/Ermcp3/QueryDeliveryGoodsDetail', param).catch((err) => {
        throw new Error(`查询现货商品详情: ${err}`);
    });
}

/**
 * 查询现货商品详情 /Ermcp3/QueryDeliveryGoodsDetail ----------------------------------- 待优化废弃
 * @param deliverygoodsid 现货商品id
 * @constructor
 */
export function QueryDeliveryGoodsDetail(): Promise<ErmcpDeliveryGoodsDetailEx[]> {
    return commonSearch_go('/Ermcp3/QueryDeliveryGoodsDetail', { userid: getUserId(), usertype: getUserAccountType() }).then(res => {
        const result: ErmcpDeliveryGoodsDetailEx[] = [];
        // 新接口数据结构转化
        res.forEach((item: any) => {
            const data = {
                agreeunit: item.unitid,
                areauserid: item.areauserid,
                auditflag: 0, // 作废
                categoryid: 0, //作废
                deliverygoodscode: item.deliverygoodscode,
                deliverygoodsid: item.deliverygoodsid,
                deliverygoodsname: item.deliverygoodsname,
                deliverygoodstype: 0, // 作废
                dgstatus: item.dgstatus,
                enumdicname: '', // 作废
                goodsunitid: 0, // 作废
                isvalid: item.isvalid,
                qtydecimalplace: 0, // 作废
                remark: item.remark,
                standardqty: 0, // 作废
                standardqtyrange: 0, // 作废
            }

            const gblist = item.bdlst.map((e: any) => {
                return {
                    areauserid: 0, //作废
                    brandid: e.brandid,
                    brandname: e.brandname,
                    deliverygoodsid: 0, //作废
                }
            })

            const gmlist = item.wdlst.map((e: any) => {
                return {
                    areauserid: 0, //作废
                    convertfactor: 0, //作废
                    createtime: '', //作废
                    creatorid: 0, //作废
                    deliverygoodsid: e.deliverygoodsid,
                    enumdicname: e.enumdicname,
                    isvalid: 0, //作废
                    minivalue: 0, //作废
                    minivaluedp: 0, //作废
                    realminivalue: 0, //作废
                    realminivaluedp: 0,
                    remark: '', //作废
                    unitid: e.unitid,
                    updatetime: '', //作废
                    wrstandardcode: e.wrstandardcode,
                    wrstandardid: e.wrstandardid,
                    wrstandardname: e.wrstandardname,
                    //vatrate: e.vatrate // 新增-增值税率
                }
            })

            const mgList: Ermcp3MiddleGoodsDetail2[] = [];
            item.wdlst.forEach((e: any) => {
                e.mglst.forEach((v: any) => {
                    mgList.push({
                        convertratio: v.convertratio,
                        gplist: v.GPLST.map((t: any) => {
                            return {
                                convertratio: t.convertratio,
                                enumdicname: t.enumdicname,
                                exexchangecode: t.exexchangecode,
                                glist: t.GDLST.map((m: any) => {
                                    return {
                                        agreeunit: m.agreeunit,
                                        enumdicname: m.enumdicname,
                                        exexchangecode: '', // 作废
                                        goodscode: m.goodscode,
                                        goodsid: m.goodsid,
                                        goodsname: m.goodsname,
                                    }
                                }),
                                goodsgroupid: t.goodsgroupid,
                                goodsgroupname: t.goodsgroupname,
                                goodsunitid: t.goodunitid,
                                middlegoodsid: 0, //作废
                            }
                        }),
                        mg: {
                            areauserid: 0, //作废
                            createtime: '', //作废
                            enumdicname: v.enumdicname, //作废
                            evaluateratio: 0, //作废
                            goodsgroupid: 0, //作废
                            goodsunitid: 0, //作废
                            isvalid: 0, //作废
                            middlegoodscode: v.middlegoodscode, //作废
                            middlegoodsid: v.middlegoodsid, //作废
                            middlegoodsname: v.middlegoodsname, //作废
                            modifytime: '', //作废
                            needhedgeratio: 0, //作废
                            qtydecimalplace: 0, //作废
                            relatedgoodsid: 0, //作废
                            relatedgoodstype: 0, //作废
                            remark: '', //作废
                            //costratio:v.costratio, // 新增-成本权重
                            //deliverygoodsid:v.deliverygoodsid, // 新增-现货商品id
                            //unitid:v.unitid // 新增-单位id
                        },
                    })
                });
            });

            result.push({
                data,
                gblist,
                gmlist,
                mgList,
            })
        });

        APP.set('DeliveryGoodsList', result)
        return result
    }).catch((err) => {
        throw new Error(`查询现货商品详情: ${err}`);
    });
}

/**
 * 查询商品组 /Ermcp3/QueryGoodsGroup
 * @param excludecfg 排除套保品中已关联的商品组 1-排除
 * @constructor
 */
export function QueryGoodsfGroup(excludecfg?: number): Promise<Ermcp3GoodsGroup[]> {
    const userid = getUserId(); // 用户id
    const usertype = getUserAccountType(); // 用户类型 2-机构 7-企业成员
    const param = excludecfg ? { userid, excludecfg, usertype } : { userid, usertype }
    return commonSearch_go('/Ermcp3/QueryGoodsGroup', param).catch((err) => {
        throw new Error(`查询期货商品组: ${err}`);
    });
}

/** ================================= 信息 - 套保品种 ================================**/
/**
 * 查询套保品种(菜单:套保品种) /Ermcp/QueryMiddleGoods
 * @param status 状态 0-停用 1-正常
 * @constructor
 */
export function QueryMiddleGoods(status: number): Promise<ErmcpMiddleGoodsModel[]> {
    const userid = getUserId(); // 所属机构id
    return commonSearch_go('/Ermcp/QueryMiddleGoods', { userid, status }).catch((err) => {
        throw new Error(`查询套保品种: ${err}`);
    });
}

/**
 * 查询套保品种详情(套保品种/商品详情) /Ermcp3/QueryMiddleGoodsDetail
 * @param middlegoodsid 套保品种id
 * @constructor
 */
export function QueryMiddleGoodsDetail(middlegoodsid?: number): Promise<Ermcp3MiddleGoodsDetail[]> {
    const userid = getUserId(); // 用户id
    const usertype = getUserAccountType()  // 用户类型 2-机构 7-企业成员
    const param = middlegoodsid ? { userid, usertype, middlegoodsid } : { userid, usertype }

    return commonSearch_go('/Ermcp3/QueryMiddleGoodsDetail', param).catch((err) => {
        throw new Error(`查询套保品种详情(套保品种/商品详情): ${err}`);
    });
}

/**
 * 查询企业风管期货商品信息 /Ermcp/GetErmcpGoods （此接口需要优化，需要前端存入本地，目前项目赶，有时间优化)
 * @param lastUpdateTime 最后修改时间 - 闭区间，格式：yyyy-MM-dd HH:mm:ss
 * @constructor
 */
export function GetErmcpGoods(lastUpdateTime?: string): Promise<string> {
    const param = {
        ...(isOemByEnum(OemType.manager) ? { userid: getUserId() } : {}),
        ...(lastUpdateTime ? { lastUpdateTime } : {})
    }

    return commonSearch_go('/Ermcp/GetErmcpGoods', param).then(async res => {

        if (res.length) {
            const result = res.map((item: Goods) => item.goodscode.toUpperCase())
            // 登录的时候或者刷新的时候，需要获取一次盘面信息
            await QueryQuoteDay(result.join(','))
        }
        // console.log('查询企业风管期货商品信息', res);
        APP.set('Goods', res)
        return 'ok'
    }).catch((err) => {
        throw new Error(`查询企业风管期货商品信息: ${err}`);
    });
}

/**
 *  查询套保品种变更记录(菜单:套保品种/商品详情/变更记录) /Ermcp/QueryMiddleGoodsChangeLog
 * @param middlegoodsid 套保品种id
 * @constructor
 */
export function QueryMiddleGoodsChange(middlegoodsid: number): Promise<ErmcpMiddleGoodsChangeLog[]> {
    const userid = getUserId(); // 用户id
    return commonSearch_go('/Ermcp/QueryMiddleGoodsChangeLog', { userid, middlegoodsid }).catch((err) => {
        throw new Error(`查询套保品种详情(套保品种/商品详情): ${err}`);
    });
}

