import { reactive, ref, shallowRef, computed } from 'vue'
import { v4 } from 'uuid'
import { ClientType, OrderSrc } from '@/constants/client'
import { loginStore } from '@/stores'
import {
    spotPresaleDestingOrder,
    spotPresaleTransferCancel,
    spotPresaleTransferDesting,
    spotPresaleTransferListing,
    spotPresalePlayment,
    wrListingCancelOrder,
    spotPresaleDeliveryConfirm,
    wrOutApply,
    spotPresaleBreachOfContractApply,
    hdWROrder,
    hdWRDealOrder,
    thjProfitDrawApply,
} from '@/services/api/trade'
import { formatDate } from "@/filters";
import Long from 'long'
import { BuyOrSell } from '@/constants/order'

const { loginId, userId, firstAccountId } = loginStore.$mapGetters()

// 采购摘牌
export function usePurchaseOrderDesting() {
    const loading = shallowRef(false)

    const formData = ref<Partial<Proto.SpotPresaleDestingOrderReq>>({
        UserID: userId.value, // 用户ID，必填
        AccountID: firstAccountId.value, // 资金账号，必填
        ClientType: ClientType.Web, // 终端类型
        UpdatorID: loginId.value, // 操作人，必填
        Qty: 5,
    })

    const formSubmit = () => {
        loading.value = true
        return spotPresaleDestingOrder({
            data: {
                ...formData.value,
                Qty: Number(formData.value.Qty),
                ClientSerialNo: v4() // 客户端流水号
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        formData,
        formSubmit,
    }
}

// 铁合金现货预售交收确认
export function useSpotPresaleDeliveryConfirm() {
    const loading = shallowRef(false)

    const confirmSubmit = (id: string) => {
        loading.value = true
        return spotPresaleDeliveryConfirm({
            data: {
                UserID: userId.value,
                Remark: '',
                WRTradeDetailID: Long.fromString(id),
                ClientSerialNo: v4(), // 客户端流水号
                ClientType: ClientType.Web // 终端类型
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        confirmSubmit
    }
}

// 铁合金现货预售违约申请
export function useSpotPresaleBreachOfContractApply() {
    const loading = shallowRef(false)

    const applySubmit = (id: string) => {
        loading.value = true
        return spotPresaleBreachOfContractApply({
            data: {
                UserID: userId.value,
                WRTradeDetailID: Long.fromString(id),
                ClientSerialNo: v4(), // 客户端流水号
                ClientType: ClientType.Web // 终端类型
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        applySubmit,
    }
}

// 铁合金现货预售付款处理接口
export function useSpotPresalePlayment() {
    const loading = shallowRef(false)

    const formData = reactive<Partial<Proto.SpotPresalePlaymentReq>>({
        UserID: userId.value, // 用户ID，必填
        ClientType: ClientType.Web, // 终端类型
        ClientSerialNo: v4(), // 客户端流水号
    })

    const playmentSubmit = (id: string) => {
        loading.value = true
        return spotPresalePlayment({
            data: {
                ...formData,
                WRTradeDetailID: Long.fromString(id),
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        playmentSubmit
    }
}

// 铁合金现货预售转让挂牌接口
export function useSpotPresaleTransferListing() {
    const loading = shallowRef(false)

    const formData = reactive<Partial<Proto.SpotPresaleTransferListingReq>>({
        UserID: userId.value, // 用户ID，必填
        ClientType: ClientType.Web, // 终端类型
        ClientSerialNo: v4(), // 客户端流水号
    })

    const listingSubmit = (id: string) => {
        /// 转让价格不能为0
        if (!formData.TransferPrice) {
            return Promise.reject('转让价格不能为0')
        }
        loading.value = true
        return spotPresaleTransferListing({
            data: {
                ...formData,
                WRTradeDetailID: Long.fromString(id),
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        formData,
        listingSubmit
    }
}

// 铁合金现货预售转让撤销接口请求
export function useSpotPresaleTransferCancel() {
    const loading = shallowRef(false)

    const transferCancelSubmit = (wrtradedetailid?: string) => {
        loading.value = true
        return spotPresaleTransferCancel({
            data: {
                UserID: userId.value,
                WRTradeDetailID: Long.fromString(wrtradedetailid ?? '0'),
                ClientSerialNo: v4(), // 客户端流水号
                ClientType: ClientType.Web // 终端类型
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        transferCancelSubmit
    }
}

// 铁合金现货预售转让摘牌接口请求
export function useSpotPresaleTransferDesting() {
    const loading = shallowRef(false)

    const formData = reactive<Proto.SpotPresaleTransferDestingReq>({
        UserID: userId.value,
        AccountID: firstAccountId.value,
        TransferID: Long.fromNumber(0),
        ClientType: ClientType.Web // 终端类型
    })

    const destingSubmit = () => {
        loading.value = true
        return spotPresaleTransferDesting({
            data: {
                ...formData,
                ClientSerialNo: v4(), // 客户端流水号
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        formData,
        destingSubmit
    }
}

// 挂牌撤单请求接口
export function useWrListingCancelOrder() {
    const loading = shallowRef(false)

    const cancelSubmit = (id: string, buyorsell: number) => {
        loading.value = true
        return wrListingCancelOrder({
            data: {
                UserID: userId.value,
                AccountID: firstAccountId.value,
                OperatorID: loginId.value,
                OrderSrc: OrderSrc.ORDERSRC_CLIENT,
                OldWRTradeOrderID: Long.fromString(id),
                ClientOrderTime: formatDate(new Date().toString(), 'YYYY-MM-DD HH:mm:ss'),
                ClientSerialNo: v4(), // 客户端流水号
                ClientType: ClientType.Web, // 终端类型
                BuyOrSell: buyorsell,
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        cancelSubmit
    }
}

// 仓单明细提货请求接口
export function useWrOutInApply(holdlb?: Model.HoldLBRsp) {
    const loading = shallowRef(false)
    const orderQty = shallowRef(0.0)
    const checked = shallowRef(3)

    const formData = reactive<Partial<Proto.WROutApplyReq>>({
        AppointmentRemark: '',
        UserID: userId.value,             // 用户ID，必填
        AccountID: firstAccountId.value,  // 申请人账户ID
        CreatorID: loginId.value,         // 创建人ID
        WRStandardID: holdlb?.wrstandardid,
        WarehouseID: holdlb?.warehouseid,
        ClientSerialID: new Date().getTime(),    // 客户端流水号
        AppointmentModel: checked.value,
        AppointmentDate: formatDate(new Date().toISOString(), 'YYYY-MM-DD'),
    })

    const applySubmit = () => {
        loading.value = true
        return wrOutApply({
            data: {
                ...formData,
                WROutInDetails: [{
                    LadingBillID: holdlb?.ladingbillid,
                    SubNum: holdlb?.subnum,
                    Qty: orderQty.value,
                    OutQty: orderQty.value,
                }]
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        formData,
        applySubmit,
        orderQty,
        checked
    }
}

// 仓单明细挂牌请求接口
export function useHdWROrder() {
    const loading = shallowRef(false)

    const formData = reactive<Proto.HdWROrderReq>({
        Header: {
            AccountID: firstAccountId.value,
        },
        IsSpecified: 0,
        PriceFactor: 1.0,
        FirstRatio: 0.0,
        CanBargain: 0,
        CanPart: 1,
        UserID: userId.value,
        AccountID: firstAccountId.value,
        OperatorID: loginId.value,
        ClientType: ClientType.Web,
        BuyOrSell: BuyOrSell.Sell,
        WRPriceType: 1,
        MarginFlag: 0,
        TimevalidType: 4,
        HasWr: 1,
        PerformanceTemplateID: -1,
    })

    const amount = computed(() => {
        const { OrderQty = 0, FixedPrice = 0 } = formData
        return (OrderQty * FixedPrice).toFixed(2)
    })

    const listingSubmit = () => {
        const date = new Date().toISOString()
        loading.value = true
        return hdWROrder({
            data: {
                ...formData,
                TradeDate: formatDate(date, 'YYYYMMDD'),
                ClientSerialNo: v4(),
                ClientOrderTime: formatDate(date),
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        formData,
        listingSubmit,
        amount
    }
}

// 仓单摘牌
export function useHdWRDealOrder() {
    const loading = shallowRef(false)

    const formData = reactive<Proto.HdWRDealOrderReq>({
        UserID: userId.value, // 用户ID
        AccountID: firstAccountId.value, // 资金账号
        RelatedWRTradeOrderID: Long.fromNumber(0), // 关联委托单号(摘牌委托关联挂牌委托单ID)
        WRTransferUserID: userId.value, // 仓单受让用户
        OrderQty: 0, // 委托数量
        OrderSrc: OrderSrc.ORDERSRC_CLIENT, // 委托来源
        ClientSerialNo: '', // 客户端流水号
        ClientOrderTime: '', // 客户端委托时间
        ClientType: ClientType.Web, // 终端类型
        OperatorID: loginId.value, // 操作员账号ID
        TradeDate: '', // 交易日
        HasWr: 1, // 是否有仓单-0:没有仓单1:有仓单
        IsFinancing: 0, // 是否融资购买(买摘牌时有效)-0:否1:是
    })

    const formSubmit = () => {
        const date = new Date().toISOString()
        loading.value = true
        return hdWRDealOrder({
            data: {
                ...formData,
                TradeDate: formatDate(date, 'YYYYMMDD'),
                ClientSerialNo: v4(),
                ClientOrderTime: formatDate(date),
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        formData,
        formSubmit,
    }
}

// 铁合金收益支取申请接口
export function useTHJProfitDrawApplyReq() {
    const loading = shallowRef(false)

    const formData = reactive<Proto.THJProfitDrawApplyReq>({
        UserID: userId.value, // 用户ID
        ApplySrc: ClientType.Web,
        ApplyerID: loginId.value,
        ClientType: ClientType.Web
    })

    const onSubmit = (drawMonth: string, amount: number) => {
        loading.value = true
        return thjProfitDrawApply({
            data: {
                ...formData,
                DrawMonth: formatDate(drawMonth, 'YYYYMM'),
                DrawAmount: amount,
                ClientSerialNo: v4(),
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        formData,
        onSubmit,
    }
}