import { ref, computed } from 'vue'
import { v4 } from 'uuid'
import Long from 'long'
import { message } from 'ant-design-vue'
import { geLoginID_number } from '@/services/bus/login'
import { queryTableList, handleComposeTable } from '@/common/export/commonTable'
import { InternalEnableTradeDetailReq, InternalEnableTradeDetailRsp, InternalUncorrelatedTradeDetailRsp } from '@/services/go/ermcp/hedgedItem/interface'
import { queryInternalEnableTradeDetail } from '@/services/go/ermcp/hedgedItem'
import { InnerTradeLinkRsp } from '@/services/proto/hedgedItem/interface'
import { innerTradeLink } from '@/services/proto/hedgedItem'
import { getAreaUserId } from '@/services/bus/user'

export function useForm(selectedRow: InternalUncorrelatedTradeDetailRsp) {
    const { tradeid, goodsid, tradelot, relatedlot } = selectedRow;
    const { tableList, queryTable } = queryTableList<InternalEnableTradeDetailRsp>(true, 2); // 表格列表数据
    const loading = ref<boolean>(false);
    const selectedRowKeys = ref<number[]>([]); // 表格选中的 rowKey 数据 :rowKey="(record,index)=>index"

    // 计算当前关联数量
    const currentQty = computed(() => {
        return tableList.value.reduce((pre, cur, index) => {
            if (selectedRowKeys.value.includes(index)) {
                pre += cur?.relatedlot ?? 0;
            }
            return pre;
        }, 0);
    })

    // 自定义表格选择项
    const rowSelection = computed(() => ({
        columnTitle: '选择',
        selectedRowKeys: selectedRowKeys.value,
        onChange: (keys: number[]) => {
            selectedRowKeys.value = keys;
        },
        onSelect: (record: InternalEnableTradeDetailRsp, selected: boolean) => {
            if (!selected) {
                // 未选中的取消关联量
                record.relatedlot = undefined;
            }
        },
    }))

    // 计算本次关联数量
    const calcRelatedqty = (record: InternalEnableTradeDetailRsp) => {
        const { relatedlot, agreeunit, convertratio } = record;
        if (relatedlot) {
            return relatedlot * agreeunit * convertratio;
        }
        return 0;
    }

    // 表格通用逻辑
    const composeTable = handleComposeTable<InternalEnableTradeDetailRsp>({
        tableName: 'table_pcweb_hedgeditem_futures_in_relation',
        queryFn: () => {
            const param: InternalEnableTradeDetailReq = {
                areauserid: getAreaUserId(),
                goodsid: goodsid,
            }
            queryTable(queryInternalEnableTradeDetail, param);
        },
    })

    // 表格列
    const columns = computed(() => {
        const result = composeTable.columns.value;
        result.push(...[
            {
                title: '关联手数',
                align: 'center',
                key: 'relatedlot',
                slots: {
                    customRender: 'relatedlot'
                }
            },
            {
                title: '关联数量',
                align: 'center',
                key: 'relatedqty',
                slots: {
                    customRender: 'relatedqty'
                }
            }
        ])
        return result;
    })

    // 表单提交
    const formSubmit = (callback?: () => void) => {
        const keys = selectedRowKeys.value;
        const seledtedRows = tableList.value.filter((e, index) => keys.includes(index));

        if (seledtedRows.length) {
            if (seledtedRows.every((e) => e.relatedlot && e.relatedlot > 0)) {
                if (currentQty.value + relatedlot > tradelot) {
                    message.error('当前关联手数不能大于可关联手数');
                } else {
                    loading.value = true;
                    const result: Promise<InnerTradeLinkRsp>[] = [];

                    seledtedRows.forEach((e) => {
                        result.push(innerTradeLink({
                            TradeId: Long.fromString(tradeid), // 内部成交单号
                            HedgeFlag: 13, // 投机套保标志
                            SpotContractID: Long.fromString(e.hedgeditemid), // 现货合同ID
                            RelatedLot: e.relatedlot!, // 关联手数
                            RelatedMode: 2, // 关联模式
                            CreatorSrc: 2, // 创建来源
                            CreatorID: geLoginID_number()!, // 创建人
                            ClientTicket: v4() // 客户端流水号
                        }))
                    })

                    Promise.all(result).then(() => {
                        message.success('关联成功');
                        callback && callback();
                    }).catch((err) => {
                        message.error('关联失败：' + err);
                    }).finally(() => {
                        loading.value = false;
                    })
                }

            } else {
                message.error('请输入关联手数');
            }
        } else {
            message.error('请选择关联订单');
        }
    }

    return {
        loading,
        tableList,
        selectedRowKeys,
        rowSelection,
        currentQty,
        columns,
        calcRelatedqty,
        formSubmit,
    }
}