import { ref, computed } from 'vue'
import { v4 } from 'uuid'
import Long from 'long'
import { message } from 'ant-design-vue'
import { queryTableList, handleComposeTable } from '@/common/export/commonTable'
import { Ermcp8EnableHedgeditemReq, Ermcp8EnableHedgeditemRsp, UnLinkErmcpHedgePlanRsp } from '@/services/go/ermcp/hedgedItem/interface'
import { queryErmcp8EnableHedgeditem } from '@/services/go/ermcp/hedgedItem'
import { HedgedItemRelatedPlanRsp } from '@/services/proto/hedgedItem/interface'
import { hedgedItemRelatedPlan } from '@/services/proto/hedgedItem'
import { getUserId } from '@/services/bus/user'

export function useForm(selectedRow: UnLinkErmcpHedgePlanRsp) {
    const { hedgeplanid, contracttype } = selectedRow;
    const { tableList, queryTable } = queryTableList<Ermcp8EnableHedgeditemRsp>(true, 2); // 表格列表数据
    const loading = ref<boolean>(false);
    const marketPrice = ref<number>(); // 现货市价
    const selectedRowKeys = ref<number[]>([]); // 表格选中的 rowKey 数据 :rowKey="(record,index)=>index"

    // 自定义表格选择项
    const rowSelection = computed(() => ({
        columnTitle: '选择',
        type: 'radio',
        selectedRowKeys: selectedRowKeys.value,
        onChange: (keys: number[]) => {
            selectedRowKeys.value = keys;
        },
    }))

    // 表格通用逻辑
    const { columns } = handleComposeTable<Ermcp8EnableHedgeditemRsp>({
        tableName: 'table_pcweb_hedgeditem_spot_plan_relation',
        queryFn: () => {
            const param: Ermcp8EnableHedgeditemReq = {
                userid: getUserId(),
                spottype: 0,
            }
            switch (contracttype) {
                // 采购合同
                case 1: {
                    param.spottype = 1;
                    break;
                }
                // 销售合同
                case -1: {
                    param.spottype = 2;
                    break;
                }
            }
            queryTable(queryErmcp8EnableHedgeditem, param);
        },
    })

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

        if (seledtedRows.length) {
            if (oriAvgPrice && oriAvgPrice > 0) {
                loading.value = true;
                const result: Promise<HedgedItemRelatedPlanRsp>[] = [];

                seledtedRows.forEach((e) => {
                    result.push(hedgedItemRelatedPlan({
                        HedgedItemID: Long.fromString(e.hedgeditemid),
                        RelatedHedgePlanInfos: {
                            HedgePlanID: Long.fromString(hedgeplanid),
                            OriAvgPrice: oriAvgPrice
                        },
                        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,
        marketPrice,
        rowSelection,
        columns,
        formSubmit,
    }
}