import { shallowRef, reactive } from 'vue'
import { v4 } from 'uuid'
import { ClientType } from '@/constants/client'
import { Market } from '@/constants/market'
import { useDataTable } from '@/hooks/datatable'
import { queryDiamondList } from '@/services/api/goods'
import { zsBuyOrderDesting, zsBuyOrderDestingNegPrice, zsSellOrderDestingApply } from '@/services/api/trade'
import { useLoginStore } from '@/stores'
import moment from 'moment'
import Long from 'long'

const loginStore = useLoginStore()
const { userId, firstAccountId } = loginStore.$toRefs()

/**
 * 钻石买摘牌(立即购买)
 * @returns 
 */
export function useBuyOrderDesting(selectedRow: Ermcp.DiamondDetailsRsp) {
    const loading = shallowRef(false)

    const formSubmit = async () => {
        try {
            loading.value = true
            return await zsBuyOrderDesting({
                UserID: userId.value,
                AccountID: firstAccountId.value,
                RelatedWRTradeOrderID: Long.fromString(selectedRow.wrtradeorderid),
                OrderQty: selectedRow.remainqty,
                OrderSrc: 1,
                ClientSerialNo: v4(),
                ClientOrderTime: moment().format('YYYY-MM-DD HH:mm:ss'),
                ClientType: ClientType.Web,
                OperatorID: userId.value,
                MarketID: Market.GZ
            })
        } finally {
            loading.value = false
        }
    }

    return {
        loading,
        formSubmit
    }
}

/**
 * 钻石买摘牌(买询价)
 * @returns 
 */
export function useBuyOrderBargain(selectedRow: Ermcp.DiamondDetailsRsp) {
    const loading = shallowRef(false)

    const formData = reactive<Proto.ZSBuyOrderDestingNegPriceReq>({
        UserID: userId.value, // 用户ID，必填
        AccountID: firstAccountId.value, // 资金账号，必填
        RelatedOrderID: Long.fromString(selectedRow.wrtradeorderid), // 卖委托单号，必填
        OrderQty: selectedRow.remainqty, // 议价数量，2位小数，必填
        OrderSrc: 1, // 委托来源
        ClientType: ClientType.Web, // 终端类型
        OperatorID: userId.value, // 操作员账号ID
        MarketID: Market.GZ, // 市场ID,必填
        ApplyRemark: '' // 申请备注
    })

    const formSubmit = async () => {
        try {
            loading.value = true
            return await zsBuyOrderDestingNegPrice({
                ...formData,
                ClientSerialNo: v4(),
                ClientOrderTime: moment().format('YYYY-MM-DD HH:mm:ss')
            })
        } finally {
            loading.value = false
        }
    }

    return {
        loading,
        formData,
        formSubmit
    }
}

/**
 * 钻石卖摘牌(卖询价)
 * @returns 
 */
export function useSellOrderBargain(selectedRow: Ermcp.BuyOrderRsp) {
    const { dataList } = useDataTable<Ermcp.MyWRPositionRsp>()
    const loading = shallowRef(false)

    const formData = reactive<Proto.ZSSellOrderDestingApplyReq>({
        UserID: userId.value, // 用户ID，必填
        AccountID: firstAccountId.value, // 资金账户ID，必填
        BuyWRTradeOrderID: Long.fromString(selectedRow.wrtradeorderid), // 买挂牌委托单ID,必填
        WRStandardID: 0, // 现货商品ID，必填
        ApplyQty: 0, // 申请数量,必填，2位小数
        LadingBillID: Long.fromNumber(0), // 提单ID,必填
        SubNum: 0, // 提单子单号,必填
        ApplyRemark: '', // 备注
        ClientType: ClientType.Web, // 终端类型
        ClientSerialNo: '', // 客户端流水号
        MarketID: Market.GZ // 市场ID,必填
    })

    const columns = shallowRef<Ermcp.TableColumn[]>([
        { prop: 'price', label: '价格' },
        { prop: 'weight', label: '克拉重量' },
        { prop: 'priceper', label: '克拉单价' },
        { prop: 'warehousenamedisplay', label: '仓库' },
        { prop: 'zsshapetypedisplay', label: '形状', width: 200 },
        { prop: 'zscolortype1display', label: '颜色' },
        { prop: 'zsclaritytype1display', label: '净度' },
        { prop: 'zscuttype1display', label: '切工' },
        { prop: 'zspolishtype1display', label: '抛光' },
        { prop: 'zssymmetrytype1display', label: '对称' },
        { prop: 'zsfluorescencetype1display', label: '荧光' },
        { prop: 'sizedisplay', label: '尺寸' },
    ])

    const formSubmit = async () => {
        try {
            loading.value = true
            return await zsSellOrderDestingApply({
                ...formData,
                ClientSerialNo: v4()
            })
        } finally {
            loading.value = false
        }
    }

    // 获取商品列表
    const getDiamondList = async () => {
        const res = await queryDiamondList({
            wruserid: userId.value,
            zscategorys: selectedRow.zscategory.toString(),
        })
        dataList.value = res.data.filter((e) => e.ftotalqty - e.ffreezeqty > 0)
    }

    return {
        loading,
        dataList,
        columns,
        formData,
        formSubmit,
        getDiamondList,
    }
}