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,
    getFancyColorType3List,
    getStyleTypeList,
} from '@/constants/diamond'
import moment from 'moment'
import Long from 'long'

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

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

    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(),
        fancyColorType3List: getFancyColorType3List(),
        styleTypeList: getStyleTypeList(),
    }

    const formSubmit = async () => {
        try {
            loading.value = true
            if (formData.Size.some((val) => !val)) {
                formData.Size = []
            }

            return await zsBuyOrderListing({
                UserID: userId.value,
                AccountID: firstAccountId.value,
                MarketID: Market.GZ,
                OrderSrc: 1,
                ClientType: ClientType.Web,
                ClientSerialNo: v4(),
                PerformanceTemplateID: performanceId.value,
                GZ_BuyOrderDetailExInfo: formData
            })
        } finally {
            loading.value = false
        }
    }

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

/**
 * 钻石出售挂牌
 * @returns 
 */
export function useSellOrderListing(selectedRow?: Ermcp.MyWRPositionRsp) {
    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: '仓库' },
        { 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: '尺寸' },
        { prop: 'price', label: '价格' },
        { prop: 'weight', label: '克拉重量' },
    ])

    const formData = reactive<Proto.ZSSellOrderListingReq>({
        UserID: userId.value,
        AccountID: firstAccountId.value,
        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({
            wruserid: userId.value,
            zscategorys: selectedCategoryId.value.toString(),
        }).then((res) => {
            dataList.value = res.data.filter((e) => e.ftotalqty - e.ffreezeqty > 0)
        }).finally(() => {
            tableLoading.value = false
        })
    }

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

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

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

    const formSubmit = async () => {
        try {
            loading.value = true
            return await wrListingCancelOrder({
                UserID: userId.value,
                AccountID: firstAccountId.value,
                OldWRTradeOrderID: Long.fromString(wrtradeorderid || '0'),
                OrderSrc: 1,
                ClientType: ClientType.Web,
                OperatorID: userId.value,
                BuyOrSell: buyorsell,
                ClientSerialNo: v4(),
                ClientOrderTime: moment().format('YYYY-MM-DD HH:mm:ss')
            })
        } finally {
            loading.value = false
        }
    }

    return {
        loading,
        formSubmit,
    }
}