import { shallowRef, ref, reactive } from 'vue'
import { useDataTable } from '@/hooks/datatable'
import { getTableColumns } from '@/business/table'
import { queryMyPerformance, performanceManualConfirm, performanceDelayApply, performanceContractedApply, performanceModifyContact, queryWrPerformancePlanStep } from '@/services/api/performance'
import { useLoginStore } from '@/stores'
import { BuyOrSell } from '@/constants/order'
import Long from 'long'

const loginStore = useLoginStore()
const { userId, firstAccountId } = loginStore.$toRefs()

// 我的履约
export function usePerformance(buyorsell?: BuyOrSell) {
    const { dataList, total, pageIndex, pageSize } = useDataTable<Ermcp.MyPerformancRsp>()
    const loading = shallowRef(false)

    const filterData = ref<{ history: boolean, date: string[] }>({
        history: false,
        date: []
    })

    const getPerformanceList = async (params: Partial<Ermcp.MyPerformancReq> = {}) => {
        try {
            loading.value = true
            const { history: ishis, date } = filterData.value
            const [begindate, enddate] = ishis && Array.isArray(date) ? date : []

            const res = await queryMyPerformance({
                userid: userId.value,
                page: pageIndex.value,
                pagesize: pageSize.value,
                buyorsell,
                zsallproperties: params.zsallproperties,
                ishis,
                begindate,
                enddate,
            })

            total.value = res.total
            dataList.value = res.data
        } finally {
            loading.value = false
        }
    }

    return {
        loading,
        dataList,
        total,
        pageIndex,
        pageSize,
        filterData,
        getPerformanceList,
    }
}

// 履约手动申请
export function usePerformanceManual({ curstepid }: Ermcp.MyPerformancRsp) {
    const loading = shallowRef(false)

    const formData = reactive<Partial<Proto.PerformanceManualConfirmReq>>({
        PerformanceExecuteSide: 1, // uint32 履约步骤执行方 1买方 2 卖方
        StepRemark: '',
    })

    if (curstepid) {
        formData.PerformancePlanStepID = Long.fromString(curstepid)
    }

    const formSubmit = async () => {
        try {
            loading.value = true
            return await performanceManualConfirm(formData)
        } finally {
            loading.value = false
        }
    }

    return {
        loading,
        formData,
        formSubmit
    }
}

// 履约延期申请
export function usePerformanceDelay({ curstepid }: Ermcp.MyPerformancRsp) {
    const loading = shallowRef(false)

    const formData = reactive<Partial<Proto.PerformanceDelayApplyReq>>({
        applicant: userId.value, // uint64 申请人
    })

    if (curstepid) {
        formData.PerformancePlanStepID = Long.fromString(curstepid)
    }

    const formSubmit = async () => {
        try {
            loading.value = true
            return await performanceDelayApply(formData)
        } finally {
            loading.value = false
        }
    }

    return {
        loading,
        formData,
        formSubmit
    }
}

// 履约违约申请
export function usePerformanceContracted(selectedRow: Ermcp.MyPerformancRsp) {
    const loading = shallowRef(false)

    const formData = reactive<Proto.PerformanceContractedApplyReq>({
        PerformancePlanID: Long.fromString(selectedRow.performanceplanid), // uint64 履约计划ID
        BreachType: selectedRow.buyorsell === BuyOrSell.Buy ? 2 : 1, // uint32 违约方类型
        Applicant: userId.value, // uint64 违约申请人
    })

    const formSubmit = async () => {
        try {
            loading.value = true
            return await performanceContractedApply(formData)
        } finally {
            loading.value = false
        }
    }

    return {
        loading,
        formData,
        formSubmit
    }
}

// 履约修改联络信息
export function usePerformanceModify(selectedRow: Ermcp.MyPerformancRsp) {
    const loading = shallowRef(false)
    const formData = reactive({
        ContactInfo: '',
        ReceiveInfo: '',
        ReceiptInfo: ''
    })

    const formSubmit = async () => {
        try {
            loading.value = true
            return await performanceModifyContact({
                PerformancePlanID: Long.fromString(selectedRow.performanceplanid),
                AccountID: firstAccountId.value,
                ContactInfo: JSON.stringify(formData), // string 联络信息
            })
        } finally {
            loading.value = false
        }
    }

    return {
        loading,
        formData,
        formSubmit
    }
}

// 履约计划步骤
export function usePerformancePlanStep(planid: string) {
    const { dataList } = useDataTable<Ermcp.WrPerformancePlanStepRsp>()
    const loading = shallowRef(false)
    const columns = shallowRef(getTableColumns('order_step'))

    const getPlanStepList = async () => {
        try {
            loading.value = true
            const res = await queryWrPerformancePlanStep({
                planid,
            })
            dataList.value = res.data
        } finally {
            loading.value = false
        }
    }

    return {
        loading,
        dataList,
        columns,
        getPlanStepList,
    }
}