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 { requestResultLoadingAndInfo } from '@/common/methods/request/resultInfo'
import { PriceType } from '@/@next/constants/enum/priceType'
import { Ermcp8EnableHedgeditemReq, Ermcp8EnableHedgeditemRsp, UnLinkSpotContractRsp } from '@/services/go/ermcp/hedgedItem/interface'
import { queryErmcp8EnableHedgeditem } from '@/services/go/ermcp/hedgedItem'
import { ContractRelatedHedgedItemReq } from '@/services/proto/hedgedItem/interface'
import { contractRelatedHedgedItem } from '@/services/proto/hedgedItem'
import { getUserId } from '@/services/bus/user'

export function useForm(selectedRow: UnLinkSpotContractRsp) {
    const { spotcontractid, qty, contracttype } = selectedRow;
    const { tableList, queryTable } = queryTableList<Ermcp8EnableHedgeditemRsp>(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?.relatedqty ?? 0;
            }
            return pre;
        }, 0);
    })

    // 自定义表格选择项
    const rowSelection = computed(() => ({
        columnTitle: '选择',
        type: selectedRow.pricetype === PriceType.Fixed ? 'checkbox' : 'radio',
        selectedRowKeys: selectedRowKeys.value,
        onChange: (keys: number[]) => {
            selectedRowKeys.value = keys;
        },
        onSelect: (record: Ermcp8EnableHedgeditemRsp, selected: boolean) => {
            if (!selected) {
                // 未选中的取消关联量
                record.relatedqty = undefined;
            }
        },
    }))

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

    // 表格列
    const columns = computed(() => {
        const result = composeTable.columns.value;
        result.push({
            title: '关联量',
            align: 'center',
            key: 'relatedqty',
            slots: {
                customRender: 'relatedqty'
            }
        })
        // result.forEach((e) => {
        //     // 高亮选中的行
        //     e.customCell = (record, index) => ({
        //         style: {
        //             backgroundColor: selectedRowKeys.value.includes(index) ? '#172B56' : undefined
        //         },
        //     })
        // })
        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.relatedqty && e.relatedqty > 0)) {
                if (currentQty.value > qty) {
                    message.error('关联数量不能大于合同数量');
                } else {
                    const param: ContractRelatedHedgedItemReq = {
                        SpotContractID: Long.fromString(spotcontractid),
                        HedgedItemInfos: [],
                        ClientTicket: v4(),
                    }

                    seledtedRows.forEach((e) => {
                        param.HedgedItemInfos.push({
                            HedgedItemID: Long.fromString(e.hedgeditemid),
                            RelatedQty: e.relatedqty!
                        })
                    })

                    requestResultLoadingAndInfo(contractRelatedHedgedItem, param, loading, ['关联成功', '关联失败：']).then(() => {
                        callback && callback();
                    }).catch(() => {
                        loading.value = false;
                    })
                }

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

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