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 { FilterSelect, FilterButton } from '@/hooks/datatable/interface'
import { getTableColumns } from '@/business/table'
import { queryMyBargainApply, queryMyDelistingApply, zsBuyOrderDestingNegPriceOperate, zsSellOrderDestingApplyOperate } from '@/services/api/trade'
import { useLoginStore } from '@/stores'
import { BuyOrSell } from '@/constants/order'
import Long from 'long'

/**
 * 我的询价
 */
export function useBargain() {
    const { getUserId } = useLoginStore()
    const { dataList, total, pageIndex, pageSize } = useDataTable<Ermcp.MyBargainApplyRsp | Ermcp.MyDelistingApplyRsp>()
    const loading = shallowRef(false)
    const columns = shallowRef<Ermcp.TableColumn[]>([])

    const selectList = reactive<FilterSelect<{ buyorsell: number, status: number }>[]>([
        {
            label: '询价',
            key: 'buyorsell',
            selectedValue: BuyOrSell.Buy,
            options: [
                { label: '求购申请', value: BuyOrSell.Buy },
                { label: '出售申请', value: BuyOrSell.Sell }
            ],
        },
        {
            label: '状态',
            key: 'status',
            selectedValue: 1,
            options: [
                { label: '全部', value: 0 },
                { label: '待确认', value: 1 }
            ],
        },
    ])

    const buttonList: FilterButton[] = [
        {
            lable: '查询',
            className: 'el-button--primary',
            onClick: () => {
                pageIndex.value = 1
                getBargainOrderList()
            }
        },
    ]

    // 获取我的询价列表
    const getBargainOrderList = () => {
        loading.value = true
        dataList.value = []

        const [buyOrSell, applyStatus] = selectList
        const param: Ermcp.MyBargainApplyReq | Ermcp.MyDelistingApplyReq = {
            type: 0,
            page: pageIndex.value,
            pagesize: pageSize.value,
            userid: getUserId(),
            applystatus: applyStatus.selectedValue || undefined,
        }

        switch (buyOrSell.selectedValue) {
            case BuyOrSell.Buy: {
                columns.value = getTableColumns('listing_bargain_buy')
                return queryMyBargainApply({
                    data: param,
                    success: (res) => {
                        total.value = res.total
                        dataList.value = res.data
                    },
                    complete: () => {
                        loading.value = false
                    }
                })
            }
            case BuyOrSell.Sell: {
                columns.value = getTableColumns('listing_bargain_sell')
                return queryMyDelistingApply({
                    data: param,
                    success: (res) => {
                        total.value = res.total
                        dataList.value = res.data
                    },
                    complete: () => {
                        loading.value = false
                    }
                })
            }
            default: {
                return Promise.reject('参数错误')
            }
        }
    }

    return {
        loading,
        dataList,
        total,
        pageIndex,
        pageSize,
        columns,
        selectList,
        buttonList,
        getBargainOrderList,
    }
}

/**
 * 询价消息-买方询价
 */
export function useBuyBargain() {
    const { getUserId } = useLoginStore()
    const { dataList, total, pageIndex, pageSize } = useDataTable<Ermcp.MyBargainApplyRsp>()
    const loading = shallowRef(false)
    const columns = shallowRef(getTableColumns('bargain_buy'))

    const selectList = reactive<FilterSelect<{ buyorsell: number, status: number }>[]>([
        {
            label: '状态',
            key: 'status',
            selectedValue: 1,
            options: [
                { label: '全部', value: 0 },
                { label: '待确认', value: 1 }
            ],
        },
    ])

    const buttonList: FilterButton[] = [
        {
            lable: '查询',
            className: 'el-button--primary',
            onClick: () => {
                pageIndex.value = 1
                getBargainOrderList()
            }
        },
    ]

    // 获取询价列表
    const getBargainOrderList = () => {
        loading.value = true
        return queryMyBargainApply({
            data: {
                type: 1,
                page: pageIndex.value,
                pagesize: pageSize.value,
                userid: getUserId(),
                applystatus: selectList[0].selectedValue || undefined,
            },
            success: (res) => {
                total.value = res.total
                dataList.value = res.data
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        dataList,
        total,
        pageIndex,
        pageSize,
        columns,
        selectList,
        buttonList,
        getBargainOrderList,
    }
}

/**
 * 询价消息-卖方询价
 */
export function useSellBargain() {
    const { getUserId } = useLoginStore()
    const { dataList, total, pageIndex, pageSize } = useDataTable<Ermcp.MyDelistingApplyRsp>()
    const loading = shallowRef(false)
    const columns = shallowRef(getTableColumns('bargain_sell'))

    const selectList = reactive<FilterSelect<{ buyorsell: number, status: number }>[]>([
        {
            label: '状态',
            key: 'status',
            selectedValue: 1,
            options: [
                { label: '全部', value: 0 },
                { label: '待确认', value: 1 }
            ],
        },
    ])

    const buttonList: FilterButton[] = [
        {
            lable: '查询',
            className: 'el-button--primary',
            onClick: () => {
                pageIndex.value = 1
                getBargainOrderList()
            }
        },
    ]

    // 获取询价列表
    const getBargainOrderList = () => {
        loading.value = true
        return queryMyDelistingApply({
            data: {
                type: 1,
                page: pageIndex.value,
                pagesize: pageSize.value,
                userid: getUserId(),
                applystatus: selectList[0].selectedValue || undefined,
            },
            success: (res) => {
                total.value = res.total
                dataList.value = res.data
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        dataList,
        total,
        pageIndex,
        pageSize,
        columns,
        selectList,
        buttonList,
        getBargainOrderList,
    }
}

/**
 * 钻石询价操作
 * @returns 
 */
export function useBargainOperate(selectedRow: Ermcp.MyBargainApplyRsp | Ermcp.MyDelistingApplyRsp) {
    const { loginInfo } = useLoginStore()
    const { UserID, AccountIDs } = loginInfo.value
    const loading = shallowRef(false)

    const formData = reactive<{ AuditRemark: string }>({
        AuditRemark: ''
    })

    const formSubmit = (OperateType: 0 | 1 | 2 | 3) => {
        loading.value = true

        // 买询价操作
        if ('wrbargainid' in selectedRow) {
            return zsBuyOrderDestingNegPriceOperate({
                data: {
                    Header: {
                        AccountID: AccountIDs[0],
                    },
                    UserID, // 用户ID，必填
                    AccountID: AccountIDs[0], // 资金账号，必填
                    WRBargainID: Long.fromString(selectedRow.wrbargainid), // 议价申请单ID，必填
                    OperateType, // 操作类型，1：撤销2:拒绝3:同意
                    AuditRemark: formData.AuditRemark,
                    MarketID: Market.GZ, // 市场ID,必填
                    ClientType: ClientType.Web, // 终端类型
                    OrderSrc: 1, // 委托来源
                    ClientSerialNo: v4() // 客户端流水号
                },
                complete: () => {
                    loading.value = false
                }
            })
        }

        // 卖询价操作
        if ('selldelistingapplyid' in selectedRow) {
            return zsSellOrderDestingApplyOperate({
                data: {
                    Header: {
                        AccountID: AccountIDs[0],
                    },
                    UserID, // 用户ID，必填
                    AccountID: AccountIDs[0], // 资金账号，必填
                    SellDelistingApplyID: Long.fromString(selectedRow.selldelistingapplyid), // 卖摘牌申请ID，必填
                    OperateType, // 操作类型，1：撤销2:拒绝3:同意
                    AuditRemark: formData.AuditRemark,
                    MarketID: Market.GZ, // 市场ID,必填
                    ClientType: ClientType.Web, // 终端类型
                    OrderSrc: 1, // 委托来源
                    ClientSerialNo: v4(), // 客户端流水号
                },
                complete: () => {
                    loading.value = false
                }
            })
        }

        loading.value = false
        return Promise.reject('参数错误')
    }

    return {
        loading,
        formData,
        formSubmit,
    }
}