import { handleDeliveryRelation } from "@/common/setup/deliveryRelation";
import { getSelectedAccountId } from "@/services/bus/account";
import { getQuoteDayInfoByCode } from "@/services/bus/goods";
import { QueryDeliveryRelationRsp } from "@/services/go/delivery/interface";
import { QueryTradePositionRsp } from "@/services/go/ermcp/order/interface";
import { queryWrDeliveryAvalidHoldLB } from "@/services/go/wrtrade";
import { QueryWrDeliveryAvalidHoldLBReq } from "@/services/go/wrtrade/interface";
import { ref } from "vue";
import { DBType } from "./interface";

// 选中的交收合约
const selected = ref<DBType>()
const checked = ref<string>();
// 交割商品
const deliveryGoods = ref<QueryDeliveryRelationRsp | undefined>();

// 查询合约交收可点选仓单
export function getTableList(goodsid: number) {
    // 交割商品
    const { getItemDeliveryRelationByGoodsId } = handleDeliveryRelation()
    const param: QueryWrDeliveryAvalidHoldLBReq = {
        goodsid,
        accountid: getSelectedAccountId(),
    };
    const tableList = ref<DBType[]>([]);
    queryWrDeliveryAvalidHoldLB(param).then((res) => {
        tableList.value = res.map((e, i) => {
            if (i) {
                return { ...e, checked: false, num: 0 };
            } else {
                // 默认勾选第一个
                checked.value = e.ladingbillid
                const result = { ...e, checked: true, num: 0 };
                selected.value = result
                deliveryGoods.value = getItemDeliveryRelationByGoodsId(e.goodsid).value
                return result
            }
        });
    });
    return { tableList }
}



export function handleCheck() {
    // 交割商品
    const { getItemDeliveryRelationByGoodsId } = handleDeliveryRelation()

    function checkGroupChange(checkedValue: string[]) {
        checked.value = checkedValue[checkedValue.length - 1];
    }
    function isChecked(value: string) {
        return value === checked.value;
    }
    function checkboxChange(item: DBType) {
        selected.value = item;
        deliveryGoods.value = getItemDeliveryRelationByGoodsId(item.goodsid).value
    }
    // true 基差点价; false 挂牌点选
    function isBaseSpread() {
        if (deliveryGoods.value) {
            // 1和3是订单交易 挂牌转让
            // 2和4是基差点价
            const arr = [2, 4]
            return arr.includes(deliveryGoods.value.deliverytype)
        } else {
            return false
        }
    }
    return { checked, selected, deliveryGoods, checkGroupChange, isChecked, checkboxChange, isBaseSpread }
}

export function handleCalculation(selectedRow: QueryTradePositionRsp) {
    // 商品合约单位
    const { agreeunit, goodscode, decimalplace, enableqty } = selectedRow
    function selctedNum() {
        return selected.value ? selected.value.num : '--'
    }
    // 选中数量的 最小变动值 = 合约单位 * 最小交割系数 * 仓单商品的单位r2
    function getStepValue() {
        if (deliveryGoods.value) {
            const { rratio2, mindeliveryqty } = deliveryGoods.value
            return agreeunit * mindeliveryqty * rratio2
        } else {
            return agreeunit
        }
    }
    // 可交收数量 = 合约可用手数 * 合约单位 * 最小交割系数 * (仓单商品的单位r2/合约商品的单位r1)
    function getCanSettlementNum() {
        if (deliveryGoods.value) {
            const { rratio1, rratio2, mindeliveryqty } = deliveryGoods.value
            const result = enableqty * agreeunit * mindeliveryqty * (rratio2 / rratio1)
            return result.toFixed(2)
        } else {
            return '--'
        }
    }
    // (选中的数量 / (合约单位 * 最小交割系数 * (仓单商品的单位r2/合约商品的单位r1)))
    function XQty() {
        let result = 0
        if (selected.value?.num) {
            if (deliveryGoods.value) {
                const { rratio1, rratio2, mindeliveryqty, xdeliveryratio, pdeliveryratio } = deliveryGoods.value
                result = selected.value.num / (agreeunit * mindeliveryqty * (rratio2 / rratio1))
            }
        }
        return result
    }
    // 需要合约手数 = (选中的数量 / (合约单位 * 最小交割系数 * (仓单商品的单位r2/合约商品的单位r1))) / (p1合约系数 / x合约系数)
    function PQty() {
        let result = XQty()
        if (result) {
            if (deliveryGoods.value) {
                const { xdeliveryratio, pdeliveryratio } = deliveryGoods.value
                result = result / pdeliveryratio / xdeliveryratio
            }
        }
        return result
    }
    // 需要合约手数 = (选中的数量 / (合约单位 * 最小交割系数 * (仓单商品的单位r2/合约商品的单位r1))) / (p1合约系数 / x合约系数)
    function getNeedContractNum() {
        const result = PQty()
        return result ? result.toFixed(decimalplace) : '--'
    }
    // 预估货款 = 需要合约手数  * 合约交割价 * 合约单位 + 升贴水
    function getEstimatedPayment() {
        const num = getNeedContractNum()
        const price = getDeliveryGoodsPrice()
        let result = 0
        if (selected.value) {
            if (num !== '--' && price !== '--') {
                if (deliveryGoods.value) {
                    result = (+num) * (+price) * agreeunit + selected.value.pricemove
                }
            }
        }
        return result ? result.toFixed(decimalplace) : '--'
    }
    /**
     * 合约交割价取价规则
     * 1.优先实时结算价
     * 2.其次卖一价
     * 3.再次是买一价与成交价中的最高价
     * 4.最后取昨日结算价
     * 所有权(X): 不取交割价，默认设为0，不影响交割流程
     */
    function getDeliveryGoodsPrice() {
        const item = getQuoteDayInfoByCode(goodscode);
        const has = (value: any) => value && value !== '--'
        let result = 0
        if (item) {
            const { settle, ask, bid, last, presettle } = item
            if (has(settle)) {
                result = settle
            } else if (has(ask)) {
                result = ask
            } else if (has(bid) && has(last)) {
                result = Math.max(bid, last)
            } else if (has(presettle)) {
                result = presettle
            }
        }
        return has(result) ? result.toFixed(decimalplace) : '--'
    }

    // 增加
    function increase(value: DBType) {
        if (value.num < value.avalidqty) {
            value.num += getStepValue()
            value.num = +value.num.toFixed(decimalplace)
        }
    }
    // 减少
    function decrease(value: DBType) {
        if (value.num > 0) {
            value.num -= getStepValue()
            value.num = +value.num.toFixed(decimalplace)
        }
    }
    return { getStepValue, getCanSettlementNum, getNeedContractNum, getEstimatedPayment, XQty, PQty, getDeliveryGoodsPrice, increase, decrease, selctedNum }
}