import { ref, reactive, computed } from 'vue'
import Long from 'long'
import { validateAction } from '@/common/setup/form'
import { requestResultLoadingAndInfo } from '@/common/methods/request/resultInfo'
import { InternalEnableTradeDetailReq, InternalEnableTradeDetailRsp } from '@/services/go/ermcp/hedgedItem/interface'
import { queryInternalEnableTradeDetail } from '@/services/go/ermcp/hedgedItem'
import { ManageAmendOrderReq } from '@/services/proto/hedgedItem/interface'
import { manageAmendOrder } from '@/services/proto/hedgedItem'
import { getAreaUserId } from '@/services/bus/user'
import { getGoodsQuoteList } from '@/services/bus/goods'
import { getTableColumns } from "@/common/export/table"
import { geLoginID_number } from '@/services/bus/login'
import { useTradeAccount } from '@/hooks/account'

export function useForm() {
    const { futuresAccountList: accountList } = useTradeAccount();
    const loading = ref<boolean>(false);
    const formElement = ref<HTMLElement>();
    const tableList = ref<InternalEnableTradeDetailRsp[]>([]);
    const goodsList = ref(getGoodsQuoteList()); // 合约列表
    const selectedRowKeys = ref<number[]>([]); // 表格选中的 rowKey 数据 :rowKey="(record,index)=>index"

    const formData = reactive<ManageAmendOrderReq>({
        AccountID: undefined, // 内部期货子账户
        BuyOrSell: undefined, // 方向-0:买
        GoodsID: undefined, // 商品ID
        ChannelBuildType: undefined, // 下单类型(开平标志-0:无
        CloseType: 0, // 平仓类型(平仓标志-0:平仓
        TradePrice: undefined, // 成交价格
        TradeQty: undefined, // 成交数量
        CreatorSrc: 2, // 创建人来源-1:管理端
        CreatorID: geLoginID_number()!, // 创建人ID
        HedgeFlag: 0, // 4:套期保值5:单边6:移仓
        SpotContractID: 0, // RelatedTradeType=4:套期保值时
    })

    const rules = {
        GoodsID: [{ required: true, type: 'number', message: '请选择期货合约' }],
        BuyOrSell: [{ required: true, type: 'number', message: '请选择方向' }],
        AccountID: [{ required: true, type: 'number', message: '请选择账户' }],
        ChannelBuildType: [{ required: true, type: 'number', message: '请选择下单类型' }],
        TradePrice: [{ required: true, trigger: 'blur', type: 'number', message: '请输入价格' }],
        TradeQty: [{ required: true, trigger: 'blur', type: 'number', message: '请输入数量' }]
    }

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

    // 选择期货合约
    const changeGoods = () => {
        tableList.value = [];
        if (formData.GoodsID) {
            const param: InternalEnableTradeDetailReq = {
                areauserid: getAreaUserId(),
                goodsid: formData.GoodsID,
            }
            queryInternalEnableTradeDetail(param).then((res) => {
                tableList.value = res;
            })
        }
    }

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

        if (seledtedRows.length) {
            formData.HedgeFlag = 13;
            formData.SpotContractID = Long.fromString(seledtedRows[0].hedgeditemid);
        } else {
            formData.HedgeFlag = 0;
            formData.SpotContractID = 0;
        }

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

    const { columns, registerColumn } = getTableColumns();
    registerColumn('table_pcweb_hedgeditem_futures_in_relation');

    return {
        formElement,
        formData,
        loading,
        rules,
        goodsList,
        accountList,
        tableList,
        selectedRowKeys,
        rowSelection,
        columns,
        changeGoods,
        formSubmit,
    }
}