import type { BasicTableProps, VxeGridInstance } from '@/components/VxeTable';
import { DownloadArrearsData, GetArrears, GetTransferWarehouseLogs, SendArrearsFile } from '@/api/notification/notification';
import { ArrearsReminderParam } from '@/api/notification/notificationModel';
import { useDropDownData } from '@/hooks/useDropDownData';
import { useEleFormValidate } from '@/hooks/useEleFormValidate';
import { useQueryList } from '@/hooks/useQueryList';
import { usePersonnel } from '@/store/list_personnel';
import { addDays, getFormatDate } from '@/utils/dateTimeStr';
import { downloadByData } from '@/utils/download';
import { resCodeSuccess } from '@/utils/useReturnData';
import { ref, reactive, unref, computed, onBeforeMount } from 'vue';
import { formatDateTime } from '@/utils/dateFormate';
import { Department } from '@/type/BaseBusinessFeeseType';
import { userStore } from '@/store/user';
import { useMessage } from '@/hooks/useMessage';

const { createMessage } = useMessage()
/**
 * 欠费通知查询
 * @returns 
 */
function useArrearsReminder(arrearsReminderListGridOptions: BasicTableProps) {
    const searchFormRef = ref()
    const arrearsReminderParams = reactive<ArrearsReminderParam>({
        CustomerId: undefined,
        SealId: undefined,
        OwningWarehouse: undefined,
        CanReceiver: undefined,
        CreateTime: [],
    })
    const arrearsReminderTableRef = ref<VxeGridInstance>()

    const arrearsReminderState = reactive({
        pageNum: 1,
        pageSize: 10,
        loading: false,
        total: 0,
        paginatedData: [],
        newsPaginatedData: [],
        dialogDetails: [],
        // === 详情 ===
        dialogDetail: false,
        detailLoading: false,
        detailPageIndex: 1,
        detailPageSize: 20,
        detailTotal: 0,
        canReceiverList: [
            { value: true, label: '可重新收货' },
            { value: false, label: '不可重新收货' },
        ],
        getOwningWarehouseTypes: [
            {
                label: "未知",
                value: 0
            },
            {
                label: "广州仓库",
                value: 1
            },
            {
                label: "郑州仓库",
                value: 2
            }
        ],
        exportLoad: false
    })

    // 用户信息
    const userstore = userStore()
    const getSysUserRoleDto = computed(() => userstore.sysUserRoleDto)
    // 判断不是业务员
    const hiddenSell = computed(() => unref(getSysUserRoleDto).roleId !== Department.SELL)

    const storePersonnel = usePersonnel()
    const { storeDropDownData, customertList } = useDropDownData()
    const endDate = addDays(new Date(), 1)
    const startDate = addDays(endDate, -30)
    onBeforeMount(() => {
        storePersonnel.addGetSalesmanUserList()
        storeDropDownData.addCustomertList()
        arrearsReminderParams.CreateTime = [
            getFormatDate(startDate),
            getFormatDate(endDate)
        ]
        if (!unref(hiddenSell)) arrearsReminderParams.SealId = unref(getSysUserRoleDto).oldId
        searchBtn()
    })

    const { resetForm } = useEleFormValidate()
    // 重置
    const resetBtn = () => {
        arrearsReminderState.pageNum = 1
        arrearsReminderState.pageSize = 10
        arrearsReminderParams.CreateTime = [
            getFormatDate(startDate),
            getFormatDate(endDate)
        ]
        resetForm(searchFormRef.value)
        if (!unref(hiddenSell)) arrearsReminderParams.SealId = unref(getSysUserRoleDto).oldId
        searchBtn()
    }
    // 初始化列表
    const searchBtn = async () => {
        try {
            arrearsReminderState.loading = true
            arrearsReminderListGridOptions.loading = true
            const res = await GetArrears(arrearsReminderParams)
            const result = res.data
            if (resCodeSuccess(result)) {
                arrearsReminderState.paginatedData = result.Data || result.data
                arrearsReminderState.total = arrearsReminderState.paginatedData.length
                getTableList();
            }
        } finally {
            arrearsReminderState.loading = false
            arrearsReminderListGridOptions.loading = false
        }
    }
    // 前端分页
    const sizeChange = (val) => {
        arrearsReminderState.pageNum = 1;
        arrearsReminderState.pageSize = val;
        getTableList();
    }
    const currentChange = (val) => {
        arrearsReminderState.pageNum = val;
        getTableList();
    }
    //获取表格数据
    const getTableList = () => {
        arrearsReminderState.total = arrearsReminderState.paginatedData.length;      //总条数
        arrearsReminderState.newsPaginatedData = getNeedArr(arrearsReminderState.paginatedData, arrearsReminderState.pageSize)[arrearsReminderState.pageNum - 1]  //当前页的表格数据
    }
    // 前端处理分页
    const getNeedArr = (array, size) => {//获取所需指定长度分割的数组;参数1为用于分割的总数组,参数2为分割数组后每个小数组的长度
        const length = array.length;
        //判断不是数组，或者size没有设置，size小于1，就返回空数组
        if (!length || !size || size < 1) {
            return [];
        }
        let index = 0;
        let resIndex = 0;
        let result = new Array(Math.ceil(length / size));
        while (index < length) {
            result[resIndex++] = array.slice(index, (index += size));
        }
        return result;
    }
    // 通知
    const notice = (data) => {
        data.loading = true
        SendArrearsFile({
            CreateTime: arrearsReminderParams.CreateTime,
            customerId: data.CustomerId
        }).then(r => {
            createMessage.success("通知成功")
        }).catch(r => {
            createMessage.error(r)
        }).finally(() => {
            data.loading = false
        })
    }
    // 导出
    const onExport = async () => {
        arrearsReminderState.exportLoad = true;
        try {
            const res = await DownloadArrearsData({
                CustomerId: arrearsReminderParams.CustomerId,
                SealId: arrearsReminderParams.SealId,
                OwningWarehouse: arrearsReminderParams.OwningWarehouse,
                CanReceiver: arrearsReminderParams.CanReceiver,
                CreateTime: arrearsReminderParams.CreateTime
            });
            if (res && arrearsReminderParams.CreateTime) {
                const fileName = `行运易${arrearsReminderParams.CreateTime[0]}-${arrearsReminderParams.CreateTime[1]}欠费提醒.xlsx`
                // 通过blod导出模板
                downloadByData(res.data, fileName);
            }
        } catch (error: any) {
            createMessage.error(error)
        } finally {
            arrearsReminderState.exportLoad = false;
        }
    }
    // 详情
    const showDetail = (data) => {
        arrearsReminderState.dialogDetail = true;
        arrearsReminderState.detailLoading = true;
        GetTransferWarehouseLogs({
            CreateTime: arrearsReminderParams.CreateTime,
            customerId: data.CustomerId,
            LastOperUserId: data.LastOperUserId
        }).then((res: any) => {
            const data = res.data.data || res.data.Data || res.data || [];
            arrearsReminderState.dialogDetails = data;
            arrearsReminderState.detailTotal = data.length;
            detailSizeChange(20)
        }).catch((error) => {
            createMessage.error(error)
        }).finally(() => {
            arrearsReminderState.detailLoading = false;
        })
    }
    const detailSizeChange = (newSize) => {
        arrearsReminderState.detailPageSize = newSize
        arrearsReminderState.detailPageIndex = 1;
    }
    const detailPagerSearch = (newPage) => {
        arrearsReminderState.detailPageIndex = newPage
    }
    const getDialogDetails = computed(() => {
        return arrearsReminderState.dialogDetails.slice(
            (arrearsReminderState.detailPageIndex - 1) * arrearsReminderState.detailPageSize,
            arrearsReminderState.detailPageIndex * arrearsReminderState.detailPageSize
        )
    })

    return {
        searchFormRef,
        arrearsReminderParams,
        arrearsReminderTableRef,
        arrearsReminderState,
        getDialogDetails,
        sizeChange,
        currentChange,
        searchBtn,
        resetBtn,
        showDetail,
        notice,
        onExport,
        detailSizeChange,
        detailPagerSearch,
        storePersonnel,
        customertList,
        hiddenSell,
    }
}

/**
 * 表格配置
 * @returns 
 */
function useArrearsReminderListModle() {
    const arrearsReminderListGridOptions = reactive<BasicTableProps>({
        id: 'arrearsReminder_list_table',
        border: true,
        keepSource: true,
        showOverflow: true,
        height: 520,
        loading: false,
        stripe: true,
        rowConfig: {
            isHover: true
        },
        customConfig: {
            storage: {
                visible: true
            }
        },
        columnConfig: {
            resizable: true
        },
        columns: [
            // { type: "checkbox", width: 45, visible: true },
            { type: "seq", width: 55, title: '序号' },
            { field: 'Abbreviation', title: '客户', minWidth: 80 },
            { field: 'NickName', title: '业务员', minWidth: 80 },
            { field: 'QtyAsArrears', title: '问题件数', minWidth: 80 },
            { field: 'TransferWarehouseQty', title: '转运件数', minWidth: 80, slots: { default: "qtyAsArrears" } },
            { field: 'FeeSumAsArrears', title: '问题件费用', minWidth: 90 },
            { field: 'CustomerBalance', title: '客户余额', minWidth: 90 },
            { field: 'ExpectBalance', title: '预计余额', minWidth: 90 },
            {
                field: 'LastTimeAsArrears',
                title: '问题最后产生时间',
                minWidth: 166,
                formatter: ({ row }) => {
                    if (!row.LastTimeAsArrears) return ''
                    return formatDateTime(row.LastTimeAsArrears)
                }
            },
            {
                field: 'LastTimeAsRecharge',
                title: '最后充值时间',
                minWidth: 166,
                formatter: ({ row }) => {
                    if (!row.LastTimeAsRecharge) return ''
                    return formatDateTime(row.LastTimeAsRecharge)
                }
            },
            { field: 'LastTimeAsOpenReceipt', title: '临时收货时间', minWidth: 166 },
            { field: 'LastFeeAsOpenReceipt', title: '临时收货金额', minWidth: 105 },
            { field: 'CanReceiver', title: '可重新收货', minWidth: 90, slots: { default: "canReceiver" } },
            { field: 'OwningWarehouse', title: '扫描仓库', minWidth: 90 },
            { field: 'LastOperName', title: '扫描人', minWidth: 90 },
            {
                field: 'LastNoticeTime',
                title: '最后通知时间',
                minWidth: 166,
                formatter: ({ row }) => {
                    if (!row.LastNoticeTime) return ''
                    return formatDateTime(row.LastNoticeTime)
                }
            },
            { title: '操作', slots: { default: 'actions' }, width: 106, fixed: 'right' }
        ],
        data: []
    })

    return {
        arrearsReminderListGridOptions
    }
}

export {
    useArrearsReminder,
    useArrearsReminderListModle
}