import { shallowRef, reactive } from 'vue'
import { v4 } from 'uuid'
import { ClientType } from '@/constants/client'
import { useDataTable } from '@/hooks/datatable'
import { Market } from '@/constants/market'
import { queryDiamondList } from '@/services/api/goods'
import { zsBuyOrderListing, zsSellOrderListing, wrListingCancelOrder } from '@/services/api/trade'
import { useLoginStore } from '@/stores'
import {
    Category,
    getCurrencyTypeList,
    getShapeTypeList,
    getColorTypeList,
    getCutTypeList,
    getClarityTypeList,
    getPolishTypeList,
    getSymmetryTypeList,
    getFluorescenceTypeList,
    getCrystalTypeList,
    getFancyColorType1List,
    getStyleTypeList,
} from '@/constants/diamond'
import moment from 'moment'
import Long from 'long'

/**
 * 钻石求购挂牌
 * @returns 
 */
export function useBuyOrderListing() {
    const { getUserId, getFirstAccountId } = useLoginStore()
    const loading = shallowRef(false)
    const performanceId = shallowRef<number>() // 选中的履约模板ID
    const currencyId = shallowRef<number>() // 选中的货币类型ID
    const formData = reactive<Proto.GZBuyOrderDetailExInfo>({
        UserID: getUserId(),
        AccountID: getFirstAccountId(),
        ZSCategory: Category.Diamond,
        ZSCurrencyType: [],
        ZSShapeType: [],
        ZSColorType: [],
        ZSClarityType: [],
        ZSCutType: [],
        ZSSymmetryType: [],
        ZSPolishType: [],
        ZSFluorescenceType: [],
        Size: [],
        ZSCrystalType: [],
        Origin: '',
        ZSStyleType: [],
        ZSCZColor1Type: [],
    })

    const enums = {
        categoryList: [
            { label: '单颗裸钻', value: Category.Diamond },
            { label: '单颗彩钻', value: Category.Fancy }
        ],
        currencyTypeList: getCurrencyTypeList(),
        shapeTypeList: getShapeTypeList(),
        colorTypeList: getColorTypeList(),
        cutTypeList: getCutTypeList(),
        clarityTypeList: getClarityTypeList(),
        polishTypeList: getPolishTypeList(),
        symmetryTypeList: getSymmetryTypeList(),
        fluorescenceTypeList: getFluorescenceTypeList(),
        crystalTypeList: getCrystalTypeList(),
        fancyColorType1List: getFancyColorType1List(),
        styleTypeList: getStyleTypeList(),
    }

    const formSubmit = () => {
        loading.value = true
        if (formData.Size.some((val) => !val)) {
            formData.Size = []
        }
        return zsBuyOrderListing({
            data: {
                Header: {
                    AccountID: getFirstAccountId(),
                },
                UserID: getUserId(),
                AccountID: getFirstAccountId(),
                MarketID: Market.GZ,
                OrderSrc: 1,
                ClientType: ClientType.Web,
                ClientSerialNo: v4(),
                PerformanceTemplateID: performanceId.value,
                GZ_BuyOrderDetailExInfo: formData
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        performanceId,
        currencyId,
        formData,
        enums,
        formSubmit,
    }
}

/**
 * 钻石出售挂牌
 * @returns 
 */
export function useSellOrderListing(selectedRow?: Ermcp.MyWRPositionRsp) {
    const { getUserId, getFirstAccountId } = useLoginStore()
    const { dataList } = useDataTable<Ermcp.MyWRPositionRsp>()
    const { zscategory, wrstandardid = 0, ladingbillid = '0', subnum = 0, ftotalqty = 0, ffreezeqty = 0 } = selectedRow ?? {}
    const submitLoading = shallowRef(false)
    const tableLoading = shallowRef(false)
    const selectedCategoryId = shallowRef(zscategory ?? Category.Diamond)

    const categoryList = [
        { label: '单颗裸钻', value: Category.Diamond },
        { label: '单颗彩钻', value: Category.Fancy }
    ]

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

    const formData = reactive<Proto.ZSSellOrderListingReq>({
        Header: {
            AccountID: getFirstAccountId(),
        },
        UserID: getUserId(),
        AccountID: getFirstAccountId(),
        WRStandardID: wrstandardid,
        OrderQty: ftotalqty - ffreezeqty,
        LadingBillID: Long.fromString(ladingbillid),
        SubNum: subnum,
        TimevalidType: 4, // 4:一直有效
        OrderSrc: 1,
        ClientSerialNo: '',
        ClientOrderTime: '',
        ClientType: ClientType.Web,
        MarketID: Market.GZ,
    })

    // 获取商品列表
    const getDiamondList = () => {
        dataList.value = []
        formData.WRStandardID = 0
        tableLoading.value = true
        queryDiamondList({
            data: {
                wruserid: getUserId(),
                zscategorys: selectedCategoryId.value.toString(),
            },
            success: (res) => {
                dataList.value = res.data.filter((e) => e.ftotalqty - e.ffreezeqty > 0)
            },
            complete: () => {
                tableLoading.value = false
            }
        })
    }

    const formSubmit = () => {
        submitLoading.value = true
        return zsSellOrderListing({
            data: {
                ...formData,
                ClientSerialNo: v4(),
                ClientOrderTime: moment().format('YYYY-MM-DD HH:mm:ss')
            },
            complete: () => {
                submitLoading.value = false
            }
        })
    }

    return {
        submitLoading,
        tableLoading,
        formData,
        dataList,
        columns,
        categoryList,
        selectedCategoryId,
        getDiamondList,
        formSubmit,
    }
}

/**
 * 钻石挂牌撤单
 */
export function useListingCancel(wrtradeorderid: string, buyorsell: number) {
    const { getUserId, getFirstAccountId } = useLoginStore()
    const loading = shallowRef(false)
    const userId = getUserId()
    const accountId = getFirstAccountId()

    const formSubmit = () => {
        loading.value = true
        return wrListingCancelOrder({
            data: {
                Header: {
                    AccountID: accountId,
                },
                UserID: userId, // 用户ID
                AccountID: accountId, // 资金账号
                OldWRTradeOrderID: Long.fromString(wrtradeorderid), // 目标仓单贸易委托单ID
                OrderSrc: 1, // 委托来源
                ClientType: ClientType.Web, // 终端类型
                OperatorID: userId, // 操作员账号ID
                BuyOrSell: buyorsell, // 买卖方向
                ClientSerialNo: v4(),
                ClientOrderTime: moment().format('YYYY-MM-DD HH:mm:ss')
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        formSubmit,
    }
}