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

// 我的履约
export function usePerformance(buyorsell?: BuyOrSell) {
    const { getUserId } = useLoginStore()
    const { dataList, total, pageIndex, pageSize, inputList, buttonList, filterMethod, getQueryParam } = useDataTable<Ermcp.MyPerformancRsp>()
    const loading = shallowRef(false)
    const columns = shallowRef(getTableColumns('order'))

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

    inputList.value = [
        { label: '商品', keys: ['goodsno'] },
    ]

    filterMethod.onReset = () => {
        filterData.value = {
            history: false,
            date: []
        }
        getPerformanceList()
    }

    filterMethod.onSearch = () => {
        getPerformanceList()
    }

    const getPerformanceList = () => {
        const { history: ishis, date } = filterData.value
        const [begindate, enddate] = ishis && Array.isArray(date) ? date : []
        const param = getQueryParam()
        loading.value = true

        return queryMyPerformance({
            data: {
                userid: getUserId(),
                page: pageIndex.value,
                pagesize: pageSize.value,
                buyorsell,
                zsallproperties: param.goodsno,
                ishis,
                begindate,
                enddate,
            },
            success: (res) => {
                total.value = res.total
                dataList.value = res.data
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        dataList,
        total,
        pageIndex,
        pageSize,
        filterData,
        columns,
        inputList,
        buttonList,
        getPerformanceList,
    }
}

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

    const formData = reactive<Proto.PerformanceManualConfirmReq>({
        PerformancePlanStepID: Long.fromString(selectedRow.curstepid), // uint64 履约计划步骤ID
        PerformanceExecuteSide: 1, // uint32 履约步骤执行方 1买方 2 卖方
        StepRemark: '',
    })

    const formSubmit = () => {
        loading.value = true
        return performanceManualConfirm({
            data: formData,
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        formData,
        formSubmit
    }
}

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

    const formData = reactive<Proto.PerformanceDelayApplyReq>({
        PerformancePlanStepID: Long.fromString(selectedRow.curstepid), // uint64 履约计划步骤ID
        applicant: getUserId(), // uint64 申请人
    })

    const formSubmit = () => {
        loading.value = true
        return performanceDelayApply({
            data: formData,
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        formData,
        formSubmit
    }
}

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

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

    const formSubmit = () => {
        loading.value = true
        return performanceContractedApply({
            data: formData,
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        formData,
        formSubmit
    }
}

// 履约修改联络信息
export function usePerformanceModify(selectedRow: Ermcp.MyPerformancRsp) {
    const { getFirstAccountId } = useLoginStore()
    const loading = shallowRef(false)
    const formData = reactive<{ address?: Ermcp.UserReceiveInfoRsp, invoice?: Ermcp.WrUserReceiptInfoRsp, contactInfo?: string }>({})

    const formSubmit = () => {
        loading.value = true

        const jsonParam = {
            ContactInfo: formData.contactInfo,
            ReceiveInfo: '',
            ReceiptInfo: ''
        }

        if (formData.address) {
            const { provincename, cityname, districtname, address } = formData.address
            jsonParam.ReceiveInfo = [provincename, cityname, districtname, address].join(' ')
        }

        if (formData.invoice) {
            Object.entries(formData.invoice).forEach(([key, value]) => {
                if (value !== '') {
                    switch (key) {
                        case 'receipttype': {
                            jsonParam.ReceiptInfo += '发票类型:' + getReceiptTypeName(Number(value)) + '\n'
                            break
                        }
                        case 'username': {
                            jsonParam.ReceiptInfo += '户名:' + value + '\n'
                            break
                        }
                        case 'address': {
                            jsonParam.ReceiptInfo += '地址:' + value + '\n'
                            break
                        }
                        case 'contactinfo': {
                            jsonParam.ReceiptInfo += '联系方式:' + value + '\n'
                            break
                        }
                        case 'idnum': {
                            jsonParam.ReceiptInfo += '身份证号码:' + value + '\n'
                            break
                        }
                        case 'receiptaccount': {
                            jsonParam.ReceiptInfo += '发票帐号:' + value + '\n'
                            break
                        }
                        case 'receiptbank': {
                            jsonParam.ReceiptInfo += '发票开户行:' + value + '\n'
                            break
                        }
                        case 'taxpayerid': {
                            jsonParam.ReceiptInfo += '纳税人识别号:' + value + '\n'
                            break
                        }
                    }
                }
            })
        }

        return performanceModifyContact({
            data: {
                PerformancePlanID: Long.fromString(selectedRow.performanceplanid), // uint64 履约计划ID
                AccountID: getFirstAccountId(), // uint64 账号
                ContactInfo: JSON.stringify(jsonParam), // string 联络信息
            },
            complete: () => {
                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 = () => {
        loading.value = true
        return queryWrPerformancePlanStep({
            data: {
                planid,
            },
            success: (res) => {
                dataList.value = res.data
            },
            complete: () => {
                loading.value = false
            }
        })
    }

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