import { api_GetCentralBankRate } from '@/api/home/home';
import { api_Exchange } from '@/api/usermoneysum/apiUserMoneySum';
import { ExchangeParams } from '@/api/usermoneysum/apiUserMoneySumModel';
import { useDropDownData } from '@/hooks/useDropDownData';
import { useEleFormValidate } from '@/hooks/useEleFormValidate';
import { useReturnData } from '@/utils/useReturnData';
import { ref, reactive, onMounted } from 'vue';

const { resData } = useReturnData()
/**
 * 汇兑
 */
function useExchangeConvert() {
    const { storeDropDownData, customertList, currencyList, branchCompanyCustomers } = useDropDownData()
    const stateExchangeConvert = reactive({})
    const exchangeConvertDialogRef = ref<{ show: Fn }>()
    const exchangeConvertFormRef = ref()
    const exchangeConvertForm = reactive<ExchangeParams>({
        customerId: undefined,//客户编号
        currencyCode: undefined,//原币种
        feeAmount: undefined,//金额
        targetCurrencyCode: "CNY",//目标币种
        exchangeRate: undefined,//汇率
        orgId: undefined,//分公司
        remark: undefined,//备注
    })
    const exchangeConvertState = reactive({
        submitLoading: false
    })
    const { formValidate, resetForm } = useEleFormValidate();


    // 打开对话弹窗
    const hanleOpenExchangeconvert = () => {
        exchangeConvertDialogRef.value?.show()
    }

    // 填充汇率
    const changeExchangeRate = async (val) => {
        const res = await api_GetCentralBankRate({ currencyCode: val })
        if (res.code == 200 && res.data) {
            exchangeConvertForm.exchangeRate = res.data.currencyRate
        } else {
            exchangeConvertForm.exchangeRate = 1
        }
    }

    // 确定
    const hanleSave = async (data: ExchangeParams) => {
        try {
            exchangeConvertState.submitLoading = true
            const res = await api_Exchange(exchangeConvertForm)
            resData(res, '操作成功')
        } finally {
            exchangeConvertState.submitLoading = false
        }
    }
    // 重置
    const hanleReset = () => {
        resetForm(exchangeConvertFormRef.value)
    }

    // 初始化列表
    const initList = async () => {
        storeDropDownData.addCustomertList()
        storeDropDownData.addCurrencyList()
        storeDropDownData.addBranchCompanyCustomers()
    }

    onMounted(initList)

    return {
        exchangeConvertDialogRef,
        exchangeConvertFormRef,
        stateExchangeConvert,
        exchangeConvertForm,
        exchangeConvertState,
        hanleOpenExchangeconvert,
        hanleSave,
        changeExchangeRate,
        hanleReset,
        customertList,
        currencyList,
        branchCompanyCustomers
    }
}

export {
    useExchangeConvert
}