import { getbillRateApi, getChannelProviderApi, getCompanyEntityApi } from '@/api/base/basedata';
import { ListIitem } from '@/api/base/BaseDataModel';
import { addBillMainApi, addRecordBillMainApi, deleteBillMainApi, editBillMainApi, getBillMainListApi, getBillMainRecountListApi } from '@/api/billmain/billMain';
import { AddEditBillMainParams, BillMain, BillMainParam, BillMainRecount } from '@/api/billmain/billMainModle';
import { BaseTableProps } from '@/components/Table/src/types';
import { useMessage } from '@/hooks/useMessage';
import { useReturnData } from '@/utils/useReturnData';
import { EditType } from '@/type/BaseEnum';
import { formatDateTime } from '@/utils/dateFormate';
import { dateTimestr, getPreMonth, newDate } from '@/utils/dateTimeStr';
import { formattedData } from '@/utils/formattedData';
import { ref, reactive, computed, onMounted } from 'vue';
import {
    Edit,
    Refresh,
    Notification,
    Delete,
    House
} from "@element-plus/icons-vue";
import { BaseBillMainAction } from '@/type/BaseBillMainEnum';
import { getYearMonthList } from '@/utils/getYearMonthList';

type BillMainList = {
    rateVersionId: number,
    list: BillMain[]
    listBillRate: ListIitem[]//汇率版本
    channelProviderList: ListIitem[]//渠道商
    monthList: ListIitem[]//月份
    companyEntityList: ListIitem[]//主体公司
}

type SaveBillMain = {
    type: string,
    formProps: AddEditBillMainParams
}

const { createConfirm, createMessage } = useMessage()

// TODO 处理：应付账单基础业务
export default function useBillMainRate(billMainTableList: BaseTableProps) {
    // 定义列表查询的参数
    const listParm = reactive<Partial<BillMainParam>>({
        billName: '',
        billBeginDate: '',
        billEndDate: '',
        pageNum: 1,
        pageSize: 10,
        total: 0,
    })
    // 定义数据
    const billRateMain: BillMainList = reactive({
        rateVersionId: 0,
        list: [],
        listBillRate: [],
        channelProviderList: [],
        monthList: [],
        companyEntityList: []
    })
    // 操作类别
    const actionOptions = [
        {
            value: BaseBillMainAction.RECOUNT,
            label: "重算",
            type: "success",
            icon: Refresh,
            permissions: ['sys:BillMain:recount']
        },
        {
            value: BaseBillMainAction.EDIT,//状态
            label: "编辑",//文本
            type: "primary",//按钮样式
            icon: Edit,//按钮图标
            permissions: ['sys:BillMain:edit']
        },
        {
            value: BaseBillMainAction.DELETE,
            label: "删除",
            type: "danger",
            icon: Delete,
            permissions: ['sys:BillMain:delete']
        },
        {
            value: BaseBillMainAction.DETAILS,
            label: "明细",
            color: "#0078f3",
            icon: Notification,
            permissions: ['sys:BillMain:detail']
        },
        {
            value: BaseBillMainAction.MAIN,
            label: "账单汇总",
            color: "#626aef",
            icon: House,
            permissions: ['sys:BillMain:detail']
        },
        {
            value: BaseBillMainAction.SUPPLEMENT,
            label: "补录",
            color: "#36b5f1",
            icon: House,
            permissions: ['sys:BillMain:addRecord']
        },
    ]

    // 汇率版本id变化
    const getRateVersionId = computed(() => {
        return billRateMain.rateVersionId
    })
    const hanleSetRateVersionId = (rateVersionId) => {
        billRateMain.rateVersionId = rateVersionId
    }

    const { resData } = useReturnData()
    // 新增、编辑
    const addEditBillMainRef = ref<{ show: (type: string, row?: Recordable, error?: boolean) => void }>()
    // 重算弹窗组件 Ref
    const addBillMainRecountRef = ref<{ show: (row?: Recordable) => void }>()
    // 查看明细账单弹窗 Ref
    const viewBillDetailRef = ref<{ show: (row: Recordable) => void }>()
    // 查看账单主体弹窗 ref
    const viewBillMainRef = ref<{ show: (row: Recordable) => void }>()
    //新增
    const addBtn = () => {
        addEditBillMainRef.value?.show(EditType.ADD)
    }
    // 编辑
    const hanleActionColumns = (data: Recordable, actionType?: string) => {
        switch (actionType) {
            // 编辑
            case EditType.EDIT:
                addEditBillMainRef.value?.show(EditType.EDIT, data)
                break;
            // 删除
            case EditType.DELETE:
                createConfirm({
                    type: "warning",
                    message: "系统提示",
                    cancelButtonText: "取消",
                    confirmButtonText: "确定",
                    beforeClose: (action, instance, done) => {
                        // console.log(action,"==> cancel , confirm ", instance, ";action, instance");
                        if (action === "confirm") {
                            deleteBillMain(data.id)
                        }
                        done()
                    },
                })
                break;
            // 查看明细
            case EditType.VIEW:
                viewBillDetailRef.value?.show(data)
                break;
            case EditType.RECOUNT:
                // 重算
                addBillMainRecountRef.value?.show(data)
                break;
            case EditType.SUPPLEMENT:
                // 补录
                addEditBillMainRef.value?.show(EditType.SUPPLEMENT, data)
                break;
        }
    }
    /**
     * 新增或编辑-保存
     * @param data 子组件通知的数据
     * @param onclose 取消弹窗事件
     */
    const hanleSaveBillMain = async (data: SaveBillMain, onclose: Function) => {
        console.log(data, ":新增或编辑数据");
        switch (data.type) {
            // 添加
            case EditType.ADD:
                try {
                    const resAdd = await addBillMainApi(data.formProps)
                    // 响应数据
                    const codeAdd = resData(resAdd)
                    if (codeAdd !== 500) {
                        onclose()
                        // 刷新数据
                        initBillMainList()
                    }
                } catch (error) {
                }
                break;
            // 编辑
            case EditType.EDIT:
                try {
                    const resEdit = await editBillMainApi(data.formProps)
                    // 响应数据
                    const codeEdit = resData(resEdit)
                    if (codeEdit !== 500) {
                        onclose()
                        // 刷新数据
                        initBillMainList()
                    }
                } catch (error) {
                }
                break;
            // 补录
            case EditType.SUPPLEMENT:
                try {
                    if (data.formProps.billDetailDtoList.length === 0) {
                        createMessage.warning('请导入补录的数据！');
                        return
                    }
                    // console.log(data.formProps, ":data.formProps补录");
                    const resEdit = await addRecordBillMainApi(data.formProps)
                    // 响应数据
                    const codeEdit = resData(resEdit)
                    if (codeEdit !== 500) {
                        onclose()
                        // 刷新数据
                        initBillMainList()
                    }
                } catch (error) {
                }
                break;
            default:
                break;
        }
    }

    // 初始化账单分摊列表数据
    const initBillMainList = async () => {
        // 时间转换
        const currentDate = dateTimestr(new Date(), "yyyy/MM/dd")
        const prevDate = getPreMonth(currentDate)
        if (!listParm.billBeginDate) listParm.billBeginDate = prevDate //上个月时间
        if (!listParm.billEndDate) listParm.billEndDate = currentDate //当前时间
        const res = await getBillMainListApi(listParm)
        console.log(res, ":res");
        const { data, total } = formattedData(res)
        billMainTableList.dataSource = data
        listParm.total = total
    }
    // 汇率版本
    const getbillRateList = async () => {
        const res = await getbillRateApi()
        const data = resData(res)
        billRateMain.listBillRate = data
    }
    // 渠道商
    const getChannelProviderList = async () => {
        const res = await getChannelProviderApi()
        const data = resData(res)
        billRateMain.channelProviderList = data
    }
    // 公司主体
    const getCompanyEntityList = async () => {
        const res = await getCompanyEntityApi()
        const data = resData(res)
        billRateMain.companyEntityList = data
    }
    // 初始化列表数据
    const initList = () => {
        getbillRateList()
        getChannelProviderList()
        getCompanyEntityList()
        // 年-月列表
        billRateMain.monthList = getYearMonthList()
    }
    //页容量改变时触发
    const sizeChange = (size: number) => {
        listParm.pageSize = size;
        initBillMainList();
    }
    //页数改变时触发
    const currentChange = (page: number) => {
        listParm.pageNum = page;
        initBillMainList();
    }

    //搜索
    const searchBtn = () => {
        // 时间转换
        if (listParm.billBeginDate) listParm.billBeginDate = dateTimestr(newDate(formatDateTime(listParm.billBeginDate)), "yyyy/MM/dd")
        if (listParm.billEndDate) listParm.billEndDate = dateTimestr(newDate(formatDateTime(listParm.billEndDate)), "yyyy/MM/dd")
        initBillMainList();
    }
    //重置
    const resetBtn = () => {
        listParm.billName = '';
        listParm.billBeginDate = '';
        listParm.billEndDate = '';
        initBillMainList();
    }
    // 删除数据
    const deleteBillMain = async (id) => {
        const res = await deleteBillMainApi({ id })
        resData(res)
        initBillMainList()
    }

    // 重算
    const hanleSaveRecount = async (data: BillMainRecount, onclose: Function) => {
        try {
            const res = await getBillMainRecountListApi(data)
            const code = resData(res, "正在重算，请稍后")
            if (code !== 500) {
                onclose()
                initBillMainList()
            }
        } catch (error) {
        }
    }

    // 操作类型
    const hanleChangeAction = (row: Recordable) => {
        const types = row.types;
        // 账单分摊操作列表
        console.log(types, ":费用操作类型");

        switch (types) {
            // 账单分摊-编辑
            case BaseBillMainAction.EDIT:
                hanleActionColumns(row, EditType.EDIT)
                break;
            // 账单分摊-删除
            case BaseBillMainAction.DELETE:
                hanleActionColumns(row, EditType.DELETE)
                break;
            // 账单分摊-重算
            case BaseBillMainAction.RECOUNT:
                hanleActionColumns(row, EditType.RECOUNT)
                break;
            // 账单分摊-明细
            case BaseBillMainAction.DETAILS:
                hanleActionColumns(row, EditType.VIEW)
                break;
            // 账单分摊-主体
            case BaseBillMainAction.MAIN:
                viewBillMainRef.value?.show(row)
                break;
            // 账单分摊-主体
            case BaseBillMainAction.SUPPLEMENT:
                hanleActionColumns(row, EditType.SUPPLEMENT)
                break;
            default:
                break;
        }
    }

    // 初始化内容
    onMounted(() => {
        initList()
        initBillMainList()
    })

    return {
        searchBtn,
        resetBtn,
        sizeChange,
        currentChange,
        addBtn,
        hanleActionColumns,
        hanleSaveBillMain,
        hanleSaveRecount,
        hanleChangeAction,
        hanleSetRateVersionId,
        listParm,
        billRateMain,
        addEditBillMainRef,
        addBillMainRecountRef,
        viewBillDetailRef,
        viewBillMainRef,
        actionOptions,
        getRateVersionId
    }
}