// pages/withdraw/components/mode2/mode2.js — 自动打款纯提现
import request from '../../../../utils/request.js';
import PopupService from '../../../../services/popupService.js';

const app = getApp();

const ASSET_CONFIG = {
    dashou_yue:        { leixing: 1, label: '接单员佣金' },
    guanshi_fenyong:   { leixing: 2, label: '管事分红' },
    zuzhang_fenyong:   { leixing: 3, label: '组长分红' },
    kaoheguan_fenyong: { leixing: 4, label: '考核官分佣' },
    dashou_yajin:      { leixing: 5, label: '接单员保证金' },
    shangjia_yue:      { leixing: 6, label: '商家余额' },
};

/** 页面入参 from 与资产 type 映射 */
const FROM_ASSET_MAP = {
    dashou: 'dashou_yue',
    guanshi: 'guanshi_fenyong',
    zuzhang: 'zuzhang_fenyong',
    kaoheguan: 'kaoheguan_fenyong',
    kaohe: 'kaoheguan_fenyong',
    shangjia: 'shangjia_yue',
    yajin: 'dashou_yajin',
};

Component({
    properties: { options: { type: Object, value: {} } },
    data: {
        imgUrls: { iconWechat: '' },
        assetList: [],
        displayAssetList: [],
        totalAmount: '0.00',
        canWithdraw: false,
        selectedAsset: null,
        isLoadingAssets: false,
        tixianleixing: null,
        tixianjine: '',
        currentRate: '0.00',
        feeRateText: '--',
        showTixian: false,
        shouxufei: '0.00',
        shijidaozhang: '0.00',
        submitting: false,
    },
    lifetimes: {
        attached() {
            this.initImageUrls();
            this.loadAllAssets();
        },
    },
    pageLifetimes: {
        show() {
            this.registerNotificationComponent();
            this.loadAllAssets();
            PopupService.checkAndShow(this, 'tixian');
        },
        hide() {
            const popupComp = this.selectComponent('#popupNotice');
            if (popupComp && popupComp.cleanup) popupComp.cleanup();
        },
    },
    methods: {
        registerNotificationComponent() {
            const notificationComp = this.selectComponent('#global-notification');
            if (notificationComp && notificationComp.showNotification) {
                app.globalData.globalNotification = {
                    show: (data) => notificationComp.showNotification(data),
                    hide: () => notificationComp.hideNotification(),
                };
            }
        },

        gengxinYue(data, leixing) {
            if (!data) return;
            if (data.new_yongjin !== undefined && data.new_yongjin !== null) {
                app.globalData.yongjin = data.new_yongjin;
            }
            if (data.new_fenyong !== undefined && data.new_fenyong !== null) {
                app.globalData.guanshi.fenyongtixian = data.new_fenyong;
            }
            if (data.new_yajin !== undefined && data.new_yajin !== null) {
                app.globalData.yajin = data.new_yajin;
            }
            if (data.new_shangjia_yue !== undefined && data.new_shangjia_yue !== null) {
                if (app.globalData.shangjia) app.globalData.shangjia.sjyue = data.new_shangjia_yue;
            }
            if (data.current_rate !== undefined && leixing) {
                const rate = parseFloat(data.current_rate);
                const rateKeyMap = { 1: 'dashouRate', 5: 'dashou_yajin_rate', 6: 'shangjia_rate', 2: 'guanshi_rate', 3: 'zuzhang_rate', 4: 'kaoheguan_rate' };
                const key = rateKeyMap[leixing];
                if (key) wx.setStorageSync(key, rate);
            }
        },

        initImageUrls() {
            const ossBase = app.globalData.ossImageUrl || '';
            const imgDir = `${ossBase}beijing/tixian/`;
            this.setData({
                imgUrls: {
                    iconWechat: `${imgDir}icon_wechat.png`,
                },
            });
        },

        /** 顶部展示：不含保证金的可提现合计 */
        calcDisplayTotal(assets) {
            let total = 0;
            (assets || []).forEach((item) => {
                if (item.type === 'dashou_yajin') return;
                total += parseFloat(item.amount) || 0;
            });
            return total;
        },

        hasAnyWithdrawable(assets) {
            return (assets || []).some((item) => parseFloat(item.amount) > 0);
        },

        applyRouteOptions(assets) {
            const opts = this.properties.options || {};
            const fromKey = FROM_ASSET_MAP[opts.from];
            let selected = null;
            if (fromKey) {
                selected = assets.find((a) => a.type === fromKey) || null;
            } else if (assets.length === 1) {
                selected = assets[0];
            }
            const patch = {};
            if (selected) {
                patch.selectedAsset = selected;
                patch.tixianleixing = selected.leixing;
                patch.feeRateText = selected.rateText;
            }
            if (opts.amount && parseFloat(opts.amount) > 0) {
                const amt = parseFloat(opts.amount);
                const max = selected ? parseFloat(selected.amount) : amt;
                patch.tixianjine = Math.min(amt, max).toFixed(2);
            }
            if (Object.keys(patch).length) {
                this.setData(patch, () => {
                    this.recalcFee(this.data.tixianjine, this.data.selectedAsset);
                });
            }
        },

        onSelectAsset(e) {
            const index = e.currentTarget.dataset.index;
            const asset = this.data.displayAssetList[index];
            if (!asset || parseFloat(asset.amount) <= 0) {
                wx.showToast({ title: '该账户无可提余额', icon: 'none' });
                return;
            }
            let jine = this.data.tixianjine;
            const max = parseFloat(asset.amount);
            if (jine && parseFloat(jine) > max) {
                jine = asset.amount;
            }
            this.setData({
                selectedAsset: asset,
                tixianleixing: asset.leixing,
                tixianjine: jine,
            });
            this.recalcFee(jine, asset);
        },

        async loadAllAssets() {
            this.setData({ isLoadingAssets: true, totalAmount: '0.00', canWithdraw: false, assetList: [] });
            try {
                const res = await request({ url: '/yonghu/tixianzichan', method: 'POST' });
                if (res?.data?.code === 200 || res?.data?.code === 0) {
                    const data = res.data.data || {};
                    const assets = [];
                    const pushAsset = (type, amount, rate) => {
                        const cfg = ASSET_CONFIG[type];
                        if (!cfg || !amount || parseFloat(amount) <= 0) return;
                        assets.push({
                            type,
                            leixing: cfg.leixing,
                            label: cfg.label,
                            amount: parseFloat(amount).toFixed(2),
                            rate: rate || 0,
                            rateText: this.formatRatePercent(rate || 0),
                        });
                    };
                    pushAsset('dashou_yue', data.dashou_yue, data.dashou_rate);
                    pushAsset('dashou_yajin', data.dashou_yajin, data.dashou_yajin_rate);
                    pushAsset('shangjia_yue', data.shangjia_yue, data.shangjia_rate);
                    pushAsset('guanshi_fenyong', data.guanshi_fenyong, data.guanshi_rate);
                    pushAsset('zuzhang_fenyong', data.zuzhang_fenyong, data.zuzhang_rate);
                    pushAsset('kaoheguan_fenyong', data.kaoheguan_fenyong, data.kaoheguan_rate);

                    const displayTotal = this.calcDisplayTotal(assets);
                    const firstRate = assets.find((a) => a.type !== 'dashou_yajin')?.rate || 0;
                    this.setData({
                        assetList: assets,
                        displayAssetList: assets,
                        totalAmount: displayTotal.toFixed(2),
                        canWithdraw: this.hasAnyWithdrawable(assets),
                        isLoadingAssets: false,
                        feeRateText: displayTotal > 0 ? this.formatRatePercent(firstRate) : '--',
                    }, () => this.applyRouteOptions(assets));
                    if (!this.data.selectedAsset) {
                        this.recalcFee(this.data.tixianjine, null);
                    }
                } else {
                    throw new Error(res?.data?.msg || '获取资产失败');
                }
            } catch (err) {
                console.error('loadAllAssets', err);
                this.setData({ isLoadingAssets: false, totalAmount: '0.00', canWithdraw: false, assetList: [] });
            }
        },

        formatRatePercent(rate) {
            const r = parseFloat(rate) || 0;
            if (r <= 1 && r > 0) return `${(r * 100).toFixed(0)}%`;
            return `${r}%`;
        },

        recalcFee(amountStr, asset) {
            const amount = parseFloat(amountStr);
            if (!amountStr || isNaN(amount) || amount <= 0 || !asset) {
                this.setData({
                    shouxufei: '0.00',
                    shijidaozhang: '0.00',
                    feeRateText: asset ? this.formatRatePercent(asset.rate) : this.data.feeRateText,
                });
                return;
            }
            const rate = parseFloat(asset.rate) || 0;
            const fee = amount * rate;
            const actual = amount - fee;
            this.setData({
                shouxufei: fee.toFixed(2),
                shijidaozhang: actual.toFixed(2),
                feeRateText: this.formatRatePercent(rate),
                currentRate: this.formatRatePercent(rate),
            });
        },

        onJineInput(e) {
            const val = e.detail.value;
            this.setData({ tixianjine: val });
            this.recalcFee(val, this.data.selectedAsset);
        },

        onWithdrawAll() {
            const { selectedAsset } = this.data;
            if (!selectedAsset) {
                wx.showToast({ title: '请先选择提现账户', icon: 'none' });
                return;
            }
            const max = selectedAsset.amount;
            this.setData({ tixianjine: max });
            this.recalcFee(max, selectedAsset);
        },

        onTapWithdraw() {
            if (this.data.submitting) return;
            if (!this.hasAnyWithdrawable(this.data.assetList)) {
                wx.showToast({ title: '暂无可提现余额', icon: 'none' });
                return;
            }
            const { selectedAsset, tixianjine } = this.data;
            if (!selectedAsset) {
                wx.showToast({ title: '请先选择要提现的账户', icon: 'none' });
                return;
            }
            const jineValue = parseFloat(tixianjine);
            if (!tixianjine || isNaN(jineValue) || jineValue <= 0) {
                wx.showToast({ title: '请输入有效金额', icon: 'none' });
                return;
            }
            if (jineValue <= 0.1) {
                wx.showToast({ title: '提现金额须大于0.1元', icon: 'none' });
                return;
            }
            if (jineValue > parseFloat(selectedAsset.amount)) {
                wx.showToast({ title: `超过${selectedAsset.label}可提余额`, icon: 'none' });
                return;
            }
            this.applyIdentityAndConfirm(selectedAsset);
        },

        applyIdentityAndConfirm(asset) {
            this.recalcFee(this.data.tixianjine, asset);
            this.setData({
                selectedAsset: asset,
                tixianleixing: asset.leixing,
                currentRate: this.formatRatePercent(asset.rate),
                showTixian: true,
            });
        },

        async onConfirmTixian() {
            if (this.data.submitting) return;
            const { tixianleixing, tixianjine, selectedAsset } = this.data;
            if (!tixianleixing || !selectedAsset) {
                wx.showToast({ title: '请选择提现身份', icon: 'none' });
                return;
            }
            const jineValue = parseFloat(tixianjine);
            if (!tixianjine || isNaN(jineValue) || jineValue <= 0) {
                wx.showToast({ title: '请输入有效金额', icon: 'none' });
                return;
            }
            if (jineValue > parseFloat(selectedAsset.amount)) {
                wx.showToast({ title: `超过${selectedAsset.label}可提余额`, icon: 'none' });
                return;
            }

            this.setData({ submitting: true });
            try {
                const res = await request({
                    url: '/yonghu/zddksh',
                    method: 'POST',
                    data: { leixing: tixianleixing, jine: jineValue.toFixed(2) },
                });
                if (res.statusCode === 200 && res.data && res.data.code === 0) {
                    const data = res.data.data || {};
                    this.gengxinYue(data, tixianleixing);
                    this.setData({
                        showTixian: false,
                        submitting: false,
                        selectedAsset: null,
                        tixianjine: '',
                        shouxufei: '0.00',
                        shijidaozhang: '0.00',
                    });
                    await this.loadAllAssets();
                    wx.showModal({
                        title: '申请成功',
                        content: '提现申请已提交，请前往「提现记录」查看进度；审核通过后可在该页点击「收款」确认到账。',
                        confirmText: '查看提现记录',
                        cancelText: '知道了',
                        success: (res) => {
                            if (res.confirm) {
                                wx.navigateTo({ url: '/pages/withdraw/withdraw-records' });
                            }
                        },
                    });
                } else {
                    wx.showModal({ title: '提现申请失败', content: res.data?.msg || '未知错误', showCancel: false });
                    this.setData({ submitting: false });
                }
            } catch (err) {
                wx.showModal({ title: '网络错误', content: '网络连接失败，请稍后重试', showCancel: false });
                this.setData({ submitting: false });
            }
        },

        onCloseTixian() {
            if (this.data.submitting) {
                wx.showToast({ title: '正在处理中，请稍后', icon: 'none' });
                return;
            }
            this.setData({
                showTixian: false,
                selectedAsset: null,
                tixianleixing: null,
                shouxufei: '0.00',
                shijidaozhang: '0.00',
            });
        },

        stopPropagation() {},
    },
});
