
import type { BasicTableProps } from '@/components/VxeTable';
import { api_tmpReceiveAdd, api_tmpReceiveChangeStatus, api_tmpReceiveList, api_transferred } from '@/api/accountPeriod/accountPeriod';
import { TmpReceiveDto, TmpReceiveDtoAdd, TmpReceiveParam, TransferAccountsParams } from '@/api/accountPeriod/accountPeriodModel';
import { useDropDownData } from '@/hooks/useDropDownData';
import { useEleFormValidate } from '@/hooks/useEleFormValidate';
import { useQueryList } from '@/hooks/useQueryList';
import { TmpReceiverType } from '@/type/BaseEnum';
import { cloneDeep } from '@/utils/cloneDeep';
import { resCodeSuccess, useReturnData } from '@/utils/useReturnData';
import { ref, reactive, computed, onMounted, unref, nextTick } from 'vue';
import { menuStore } from '@/store/menu';
import { TransferStatus } from '@/type/BaseBusinessFeeseType';
import { formatDateTime } from '@/utils/dateFormate';
import { isArray } from '@/utils/is';
import { ListIitem } from '@/api/base/BaseDataModel';

const { resData } = useReturnData()
/**
 * 临时收货列表
 * @returns 
 */
function useTmpReceiverList(tmpReceiveOptions: BasicTableProps) {
    const menustore = menuStore();
    // 移动端适配显示
    const getIsPhone = computed(() => menustore.getIsPhone)
    const pageLayout = computed(() => {
        if (unref(getIsPhone)) return 'total, sizes, prev, pager, next'
        return 'total, sizes, prev, pager, next, jumper'
    })
    const { storeDropDownData, customertList, currencyList } = useDropDownData()
    const tmpReceiverListState = reactive({
        loading: false,
        imageUploadUrl: "",//凭证照片
        disabledArr: []  as number[],//禁用按钮
        dateArr: [],//查询时间范围
        deleteFlagList: [
            { value: false, label: '启用' },
            { value: true, label: '停用' },
        ],
        statusList: [
            { value: TransferStatus.ADD, label: '新增' },
            { value: TransferStatus.TRANSFERRED, label: '已转账' },
        ],
        imageUploadUrlList: [] as string[],//凭证列表
    })
    const tmpReceiverListParams = reactive<Partial<TmpReceiveParam>>({
        deleteFlag: false,
        beginDate: undefined,
        endDate: undefined,
        customerId: undefined,
        status: undefined,
        currencyCode: undefined,
        pageNum: 1,
        pageSize: 10,
        total: 10
    })
    const tmpReceiverFormRef = ref()
    const tmpReceiverAddRef = ref<{ show: Fn }>()
    // 转账弹窗
    const transferAccountsRef = ref<{ show: Fn }>()
    // 添加弹窗
    const addBtn = () => {
        unref(tmpReceiverAddRef)?.show(TmpReceiverType.ADD)
    }
    // 查看凭证
    const imagePreviewRef = ref()
    const hanleViewFile = (row: TmpReceiveDto) => {
        tmpReceiverListState.imageUploadUrlList = row.uploadFileList || []
        nextTick(() => {
            const imagePreviewDom = unref(imagePreviewRef);
            if (imagePreviewDom && imagePreviewDom.$el) {
                const targetDiv = imagePreviewDom.$el.querySelector(".el-image__preview");
                if (targetDiv) {
                    // @ts-ignore
                    targetDiv.click();
                }
            }
        })
    }
    // 初始化
    const initList = async () => {
        try {
            if (tmpReceiverListParams.beginDate) listParams.beginDate = formatDateTime(tmpReceiverListParams.beginDate);
            if (tmpReceiverListParams.endDate) listParams.endDate = formatDateTime(tmpReceiverListParams.endDate);
            tmpReceiverListState.loading = true
            const res = await api_tmpReceiveList(listParams)
            if (resCodeSuccess(res)) {
                tmpReceiveOptions.data = res.data.records
                tmpReceiverListParams.total = res.data.total
            }
        } finally {
            tmpReceiverListState.loading = false
        }
    }
    // 重置
    const { resetForm } = useEleFormValidate()
    const resetParams = () => {
        resetForm(tmpReceiverFormRef.value)
        tmpReceiverListParams.endDate = undefined
        tmpReceiverListState.dateArr = []
    }
    // 初始化列表、分页数据
    const { sizeChange, currentChange, searchBtn, resetBtn, listParams } = useQueryList<TmpReceiveParam>(initList, resetParams, tmpReceiverListParams)
    // 操作类型
    const hanleChangeAction = async (data: Recordable) => {
        const row = cloneDeep(data)
        delete row._X_ROW_KEY
        const types = row.types;
        switch (types) {
            // 编辑
            case TmpReceiverType.EDIT:
                unref(tmpReceiverAddRef)?.show(TmpReceiverType.EDIT, row)
                break;
            // 启用与停用
            case TmpReceiverType.FEESET_ACTIVE:
                activeTmpReceive(row.id, !row.deleteFlag)
                break;
            case TmpReceiverType.TRANSFERRED:
                unref(transferAccountsRef)?.show(row)
                break;
        }
    }
    // 转账操作
    const hanleSaveTransferAccounts = async (params: TransferAccountsParams, onclose: Fn, setLoading: Fn) => {
        try {
            const res = await api_transferred(params)
            const resCode = resData(res, '操作成功')
            if (resCode == 500) return
            onclose()
            initList()
        } finally {
            setLoading(false)
        }
    }
    // 启用/停用
    const activeTmpReceive = async (id: number, deleteFlag: boolean) => {
        const res = await api_tmpReceiveChangeStatus({ id, deleteFlag })
        const activeData = resData(res, '操作成功')
        if (activeData !== 500) initList()
    }
    // 添加
    const hanleSaveTmpReceiver = async (params: TmpReceiveDtoAdd, files: File[] , setLoading: Fn, onclose: Fn) => {
        if (params.type === TmpReceiverType.EDIT) {
            try {
                const res = await api_tmpReceiveAdd(params, files)
                const addData = resData(res, '编辑成功')
                if (addData == 500) return
                initList()
                onclose()
            } finally {
                setLoading(false)
            }
        } else {
            try {
                const res = await api_tmpReceiveAdd(params, files)
                const addData = resData(res, '添加成功')
                if (addData == 500) return
                initList()
                onclose()
            } finally {
                setLoading(false)
            }
        }
    }
    // 下拉按钮显示事件
    const changeVisibleChange = (val, row) => {
        if (val) {
            const transferred = row.status === TransferStatus.TRANSFERRED || row.deleteFlag || Number(row.tempLimit) === 0 ? TmpReceiverType.TRANSFERRED : -1
            const edit = row.status === TransferStatus.TRANSFERRED || !row.deleteFlag ? TmpReceiverType.EDIT : -1
            tmpReceiverListState.disabledArr = [transferred, edit]
        }
    }
    // 查询时间范围
    const changeDate = (dates: Date[]) => {
        if (isArray(dates)) {
            tmpReceiverListParams.beginDate = formatDateTime(dates[0]);
            tmpReceiverListParams.endDate = formatDateTime(dates[1]);
        } else {
            tmpReceiverListParams.beginDate = undefined
            tmpReceiverListParams.endDate = undefined
        }
    }
    onMounted(() => {
        storeDropDownData.addCustomertList()
        storeDropDownData.addAllPaymentPlatformList()
        storeDropDownData.addCurrencyList()
    })

    return {
        tmpReceiverListState,
        tmpReceiverListParams,
        customertList,
        currencyList,
        tmpReceiverFormRef,
        tmpReceiverAddRef,
        getIsPhone,
        pageLayout,
        sizeChange, 
        currentChange, 
        searchBtn, 
        resetBtn,
        addBtn,
        hanleChangeAction,
        hanleSaveTmpReceiver,
        activeTmpReceive,
        changeVisibleChange,
        changeDate,
        transferAccountsRef,
        hanleSaveTransferAccounts,
        imagePreviewRef,
        hanleViewFile
    }
}

export {
    useTmpReceiverList
}