/*
 * @Author: Fly
 * @Date: 2025-12-10 15:03:29
 * @LastEditTime: 2025-12-25 10:29:09
 * @Description: 
 */
import { Message, MessageBox } from 'element-ui';
import { getDicts } from "@/api/system/dict/data";
import { getConfigKey, updateConfigByKey } from "@/api/system/config";
import { parseTime, resetForm, addDateRange, selectDictLabel, selectDictLabels, handleTree } from "@/utils/ruoyi";
import { download } from '@/utils/request';
import Decimal from 'decimal.js';

import {
    getOptionItem,
    getOptionLabel,
    PayTypeOption,
    RefundStatusOption,
    PayStatusOption,
    OrderStatusOption,
    SubsidyStatusOption,
    ShopTypeOption,
    ShopStatusOption,
    AuditStatusOption,
    PurposeTypeOption,
    WithdrawalStatusOption,
    WithdrawalMethodOption,
    WithdrawalSourceOption,
    AgentLevelOption
} from "@/utils/statusEnum.js";


// 字典标签组件
// import DictTag from '@/components/DictTag';
const DictTag = () => import('@/components/DictTag');
// 分页组件
// import Pagination from "@/components/Pagination";
const Pagination = () => import('@/components/Pagination');

// 自定义表格工具组件
// import RightToolbar from "@/components/RightToolbar";
const RightToolbar = () => import('@/components/RightToolbar');
// 富文本组件
// import Editor from "@/components/Editor";
const Editor = () => import('@/components/Editor');
// 文件上传组件
// import FileUpload from "@/components/FileUpload";
const FileUpload = () => import('@/components/FileUpload');
// 图片上传组件
// import ImageUpload from "@/components/ImageUpload";
const ImageUpload = () => import('@/components/ImageUpload');
// 图片预览组件
// import ImagePreview from "@/components/ImagePreview";
const ImagePreview = () => import('@/components/ImagePreview');
// 公共抽屉
// import Drawer from "@/components/Drawer";
const Drawer = () => import('@/components/Drawer');
// 状态标签组件
// import StatusTag from "@/components/StatusTag";
const StatusTag = () => import('@/components/StatusTag');



/**
 * 抽屉宽度
 * @param {number} defaultWidth - 默认宽度
 * @returns {string} - 抽屉宽度
 */
const DrawerWidth = (defaultWidth = 900) => {
    let w = (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth);
    if (w > defaultWidth) {
        return defaultWidth
    } else {
        return '90%'
    }
}


const getOption = (Option, value, isObj = false) => {
    try {
        if (isObj) {
            const Obj = getOptionItem(Option, value);
            return Obj || value
        } else {
            const label = getOptionLabel(Option, value)
            return label || value
        }
    } catch (error) {
        return value
    }
}



export default {
    install(Vue) {
        // 挂载全局对象// 全局方法挂载
        Vue.prototype.ELsize = 'small'; // medium, small, mini
        Vue.prototype.ELTableSize = 'medium'; // medium, small, mini
        Vue.prototype.TableBorder = true; // medium, small, mini
        Vue.prototype.getDicts = getDicts;
        Vue.prototype.getConfigKey = getConfigKey;
        Vue.prototype.updateConfigByKey = updateConfigByKey;
        Vue.prototype.parseTime = parseTime;
        Vue.prototype.resetForm = resetForm;
        Vue.prototype.addDateRange = addDateRange;
        Vue.prototype.selectDictLabel = selectDictLabel;
        Vue.prototype.selectDictLabels = selectDictLabels;
        Vue.prototype.handleTree = handleTree;
        Vue.prototype.download = download;

        // 全局组件挂载
        Vue.component('DictTag', DictTag);
        Vue.component('Pagination', Pagination);
        Vue.component('RightToolbar', RightToolbar);
        Vue.component('Editor', Editor);
        Vue.component('FileUpload', FileUpload);
        Vue.component('ImageUpload', ImageUpload);
        Vue.component('ImagePreview', ImagePreview);
        Vue.component('Drawer', Drawer);
        Vue.component('StatusTag', StatusTag);
        Vue.prototype.$drawerWidth = DrawerWidth; // 抽屉宽度


        // Vue.prototype.$getSelectArea = getSelectArea; // 获取片区
        // Vue.prototype.$roleLevel = roleLevel; // 角色列表

        // Vue.component('selectStore', selectStore);  // 门店下拉
        // Vue.component('selectCoupon', selectCoupon); // 可用优惠券下拉
        // Vue.component('selectDept', selectDept); // 片区

        /**
         * 获取表格序号
         * @param {Object} pages - 分页参数
         * @param {number} pages.pageNum - 当前页码
         * @param {number} pages.pageSize - 每页数量
         * @param {number} index - 当前行索引
         * @returns {number} - 表格序号
         */
        Object.defineProperty(Vue.prototype, '$getTableIndex', {
            value: (pages, index) => {
                const { pageNum, pageSize } = pages;
                return (pageNum - 1) * pageSize + index;
            }
        });

        /**
         * 过滤非数字字符
         */
        Object.defineProperty(Vue.prototype, '$numberFilter', {
            value: (num) => {
                // console.log( 'numberFilter = ' , num);
                try {
                    return num.replace(/[^0-9]/g, '');
                } catch (error) {
                    return num;
                }
            }
        });


        /**
         * 加法计算
         * @param {string|number} num1 - 操作数1
         * @param {string|number} num2 - 操作数2
         * @returns {string} - 计算结果
         */
        Object.defineProperty(Vue.prototype, '$addCalculate', {
            value: (num1, num2) => {
                const decimal1 = new Decimal(num1);
                const decimal2 = new Decimal(num2);
                return decimal1.plus(decimal2).toString();
            }
        });

        /**
         * 减法计算
         * @param {string|number} num1 - 操作数1
         * @param {string|number} num2 - 操作数2
         * @returns {string} - 计算结果
         */
        Object.defineProperty(Vue.prototype, '$subtractCalculate', {
            value: (num1, num2) => {
                const decimal1 = new Decimal(num1);
                const decimal2 = new Decimal(num2);
                return decimal1.minus(decimal2).toString();
            }
        });

        /**
        * 乘法计算
        * @param {string|number} num1 - 操作数1
        * @param {string|number} num2 - 操作数2
        * @returns {string} - 计算结果
        */
        Object.defineProperty(Vue.prototype, '$multiplyCalculate', {
            value: (num1, num2) => {
                const decimal1 = new Decimal(num1);
                const decimal2 = new Decimal(num2);
                return decimal1.times(decimal2).toString();
            }
        });

        /**
         * 除法计算
         * @param {string|number} num1 - 操作数1
         * @param {string|number} num2 - 操作数2
         * @returns {string} - 计算结果
         */
        Object.defineProperty(Vue.prototype, '$divideCalculate', {
            value: (num1, num2) => {
                const decimal1 = new Decimal(num1);
                const decimal2 = new Decimal(num2);
                return decimal1.dividedBy(decimal2).toString();
            }
        });
        /**
         * 下载图片
         * @param {string} url - 图片URL
         * @param {string} fileName - 文件名
         */
        Object.defineProperty(Vue.prototype, '$downloadImage', {
            value: (url, fileName) => {
                // const a = document.createElement('a');
                // a.href = url;
                // a.download = fileName;
                // a.click();

                try {
                    if (!url) {
                        Vue.prototype.$warningMsg('未配置下载地址');
                        return;
                    }
                    const link = document.createElement('a');
                    link.href = url;
                    link.download = fileName || new Date().getTime(); // 下载的文件名
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                } catch (error) {
                    Vue.prototype.$errorMsg('下载失败');
                }
            }
        });




        /**
         * 警告弹窗
         * @param {*} msg 
         * @returns 
         */
        Vue.prototype.$warningMsg = (msg) => {
            // console.log('msg = ', msg);
            if (!msg) return;
            Message.closeAll();
            Message.warning(msg);
        }

        /**
         * 成功弹窗
         * @param {*} msg 
         * @returns 
         */
        Vue.prototype.$successMsg = (msg) => {
            // console.log('msg = ', msg);
            if (!msg) return;
            Message.closeAll();
            Message.success(msg);
        }

        /**
         * 错误弹窗
         * @param {*} msg 
         * @returns 
         */
        Vue.prototype.$errorMsg = (msg) => {
            if (!msg) return;
            Message.closeAll();
            Message.error(msg);
        }

        /**
         * 确认弹窗
         * @param {Object} Params - 弹窗参数
         * @param {string} Params.text - 弹窗内容
         * @param {string} [Params.title='提示'] - 弹窗标题
         * @param {string} [Params.confirmButtonText='确定'] - 确认按钮文字
         * @param {string} [Params.cancelButtonText='取消'] - 取消按钮文字
         * @param {string} [Params.type='warning'] - 消息类型
         * @param {boolean} [Params.showClose=true] - 是否显示关闭按钮
         * @param {boolean} [Params.showCancelButton=true] - 是否显示取消按钮
         * @param {boolean} [Params.showConfirmButton=true] - 是否显示确认按钮
         * @param {function} [Params.cancelCallback] - 取消回调函数
         * @param {function} [Params.closeCallback] - 关闭回调函数
         * @param {function} [Params.confirmCallback] - 确认回调函数
         * @param {function} [Params.allCancelCallback] - 所有取消回调函数
         * @param {function} [Params.ApiFn] - 接口函数
         */
        Vue.prototype.$MessageBoxConfirm = (Params) => {
            const { text, title = '提示', confirmButtonText = '确定', cancelButtonText = '取消', type = 'warning', showClose = true, showCancelButton = true,
                showConfirmButton = true, cancelCallback, closeCallback, confirmCallback, allCancelCallback } = Params || {};
            MessageBox.confirm(text, title, {
                distinguishCancelAndClose: true,
                confirmButtonText, // 确认按钮文字
                cancelButtonText,  // 取消按钮文字
                showCancelButton,  // 是否显示取消按钮
                showConfirmButton, // 是否显示确认按钮
                showClose,         // 是否显示关闭按钮
                type,              // 消息类型
                closeOnClickModal: true, // 点击模态框外部是否关闭弹窗
                closeOnPressEscape: true, // 按下 ESC 键是否关闭弹窗
                beforeClose: (action, instance, done) => {
                    if (action === 'confirm') {
                        if (confirmCallback) {
                            instance.confirmButtonLoading = true;
                            instance.showCancelButton = false;
                            instance.closeOnClickModal = false;
                            instance.closeOnPressEscape = false;
                            instance.showClose = false;
                            instance.confirmButtonText = '执行中...';
                            confirmCallback(() => {
                                done();
                                setTimeout(() => {
                                    instance.confirmButtonLoading = false;
                                    instance.showCancelButton = true;
                                    instance.closeOnClickModal = true;
                                    instance.closeOnPressEscape = true;
                                    instance.showClose = true;
                                }, 300);
                            });
                        } else {
                            Vue.prototype.$warningMsg('请处理点击确认按钮事件');
                        };
                    } else {
                        // 当存在取消回调或关闭回调时，处理取消和关闭操作
                        if (allCancelCallback) {
                            allCancelCallback();
                        } else if (cancelCallback && action === 'cancel') {
                            cancelCallback();
                        } else if (closeCallback && action === 'close') {
                            closeCallback && closeCallback();
                        };
                        done();
                    }
                }
            }).then(() => {
                // Message.success('保存修改');

            }).catch(action => {
                // Message.success('停留在当前页面1' + action);
                // // cancel close
                // if (action === 'cancel') {
                //     // 取消
                // } else {
                //     // 关闭
                // }
                // this.$message({
                //     type: 'info',
                //     message: action === 'cancel'
                //         ? '放弃保存并离开页面'
                //         : '停留在当前页面'
                // })
            })
        }









        /**
         * 表格空值处理
         * @param {*} value - 表格项值
         * @returns {*} - 处理后的值
         */
        Vue.filter('TableItemEmpty', (value) => {
            return value && value !== null && value !== undefined || value === 0 ? value : '--';
        });


        /**
         * 支付方式过滤
         * @param {*} value - 支付方式值
         * @returns {*} - 处理后的值
         */
        Vue.filter('PayTypeFilter', (value) => {
            try {
                const label = getOptionLabel(PayTypeOption, value)
                return label || value
            } catch (error) {
                return value
            }
        });

        /**
         * 订单状态过滤
         * @param {*} value - 订单状态值
         * @param {*} isObj - 是否返回对象
         * @returns {*} - 处理后的值
         */
        Vue.filter('OrderStatusFilter', (value, isObj = false) => {
            try {
                return getOption(OrderStatusOption, value, isObj);
            } catch (error) {
                return value
            }
        });
        /**
         * 支付状态过滤
         * @param {*} value - 支付状态值
         * @returns {*} - 处理后的值
         */
        Vue.filter('PayStatusOptionFilter', (value) => {
            try {
                return getOption(PayStatusOption, value);
            } catch (error) {
                return value
            }
        });

        /**
         * 退款状态过滤
         * @param {*} value - 退款状态值
         * @returns {*} - 处理后的值
         */
        Vue.filter('RefundStatusOptionFilter', (value) => {
            try {
                return getOption(RefundStatusOption, value);
            } catch (error) {
                return value
            }
        });


        /**
         * 补贴状态过滤
         * @param {*} value - 补贴状态值
         * @param {*} isObj - 是否返回对象
         * @returns {*} - 处理后的值
         */
        Vue.filter('SubsidyStatusOptionFilter', (value, isObj = false) => {
            try {
                return getOption(SubsidyStatusOption, value, isObj);
            } catch (error) {
                return value
            }
        });

        /**
         * 店铺类型过滤
         * @param {*} value - 店铺类型值
         * @returns {*} - 处理后的值
         */
        Vue.filter('ShopTypeOptionFilter', (value) => {
            try {
                return getOption(ShopTypeOption, value);
            } catch (error) {
                return value
            }
        });

        /**
         * 店铺状态过滤
         * @param {*} value - 店铺状态值
         * @param {*} isObj - 是否返回对象
         * @returns {*} - 处理后的值
         */
        Vue.filter('ShopStatusOptionFilter', (value, isObj = false) => {
            try {
                return getOption(ShopStatusOption, value, isObj);
            } catch (error) {
                return value
            }
        });


        /**
         * 审核状态过滤
         * @param {*} value - 审核状态值
         * @param {*} isObj - 是否返回对象
         * @returns {*} - 处理后的值
         */
        Vue.filter('AuditStatusOptionFilter', (value, isObj = false) => {
            try {
                return getOption(AuditStatusOption, value, isObj);
            } catch (error) {
                return value
            }
        });


        /**
         * 用途类型过滤
         * @param {*} value - 用途类型值
         * @returns {*} - 处理后的值
         */PurposeTypeOption
        Vue.filter('PurposeTypeOptionFilter', (value, isObj = false) => {
            try {
                return getOption(PurposeTypeOption, value, isObj);
            } catch (error) {
                return value
            }
        });
        /**
         * 提现状态过滤
         * @param {*} value - 提现状态值
         * @returns {*} - 处理后的值
         */
        Vue.filter('WithdrawalStatusOptionFilter', (value, isObj = false) => {
            try {
                return getOption(WithdrawalStatusOption, value, isObj);
            } catch (error) {
                return value
            }
        });
        /**
         * 提现方式过滤
         * @param {*} value - 提现方式值
         * @returns {*} - 处理后的值
         */
        Vue.filter('WithdrawalMethodOptionFilter', (value) => {
            try {
                return getOption(WithdrawalMethodOption, value);
            } catch (error) {
                return value
            }
        });


        /**
         * 提现来源过滤
         * @param {*} value - 提现来源值
         * @returns {*} - 处理后的值
         */
        Vue.filter('WithdrawalSourceOptionFilter', (value) => {
            try {
                return getOption(WithdrawalSourceOption, value);
            } catch (error) {
                return value
            }
        });


        /**
         * 代理级别过滤
         * @param {*} value - 代理级别值
         * @returns {*} - 处理后的值
         */
        Vue.filter('AgentLevelOptionFilter', (value) => {
            try {
                return getOption(AgentLevelOption, value);
            } catch (error) {
                return value
            }
        });

    }
}