// pages/tixian/components/mode2/mode2.js
// UI 与 mode1 完全一致，业务逻辑为自动打款审核收款
import request from '../../../../utils/request.js';
import PopupService from '../../../../services/popupService.js';

const app = getApp();
const yemianshuju = 5;
let lastPullDownTime = 0;
const PULL_DOWN_INTERVAL = 2000;

const TX_STATUS = {
    SHENHEZHONG: 1,
    TIXIAN_CHENGGONG: 2,
    TIXIAN_SHIBAI: 3,
    SHENHE_CHENGGONG: 4,
    SHENHE_SHIBAI: 5,
    DAI_SHOUKUAN: 6,
};

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: '商家余额' },
};

const LEIXING_LABEL = {
    1: '打手佣金', 2: '管事分红', 3: '组长分红',
    4: '考核官分佣', 5: '打手保证金', 6: '商家余额',
};

Component({
    properties: { options: { type: Object, value: {} } },
    data: {
        imgUrls: {
            pageBg: '', cardBg: '', assetTileBg: '',
        },
        assetList: [],
        totalAmount: '0.00',
        selectedAsset: null,
        isLoadingAssets: false,
        tixianleixing: null,
        tixianjine: '',
        currentRate: '0.00',
        showTixian: false,
        recordList: [],
        page: 1,
        loading: false,
        nomore: false,
        canloadmore: true,
        isRefreshing: false,
        shouxufei: '0.00',
        shijidaozhang: '0.00',
        currentTixianId: null,
        submitting: false,
        mchId: '',
        currentStatusFilter: 0,
        statusTabs: [
            { value: 0, label: '全部' },
            { value: 1, label: '审核中' },
            { value: 6, label: '待收款' },
            { value: 4, label: '审核成功' },
            { value: 5, label: '审核失败' },
            { value: 2, label: '提现成功' },
            { value: 3, label: '提现失败' },
        ],
        hasPendingCollect: false,
        showCollectConfirm: false,
        collectConfirmRecord: null,
        showDetailModal: false,
        detailTitle: '',
        detailContent: '',
    },
    lifetimes: {
        attached() {
            this.initImageUrls();
            this.chushihuashuju();
        }
    },
    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()
                };
            }
        },

        initImageUrls() {
            const ossBase = app.globalData.ossImageUrl || '';
            const imgDir = `${ossBase}beijing/tixian/`;
            this.setData({
                imgUrls: {
                    pageBg: `${imgDir}page_bg.png`,
                    cardBg: `${imgDir}card_bg.png`,
                    assetTileBg: `${imgDir}asset_tile_bg.png`,
                }
            });
        },

        parseZhuangtai(item) {
            const raw = item.zhuangtai ?? item.status ?? item.state;
            const n = parseInt(raw, 10);
            return Number.isNaN(n) ? -1 : n;
        },

        /** 规范化列表字段（兼容后端多种命名 / 嵌套 audit） */
        normalizeRecordFields(item) {
            const audit = item.audit || item.shenhe || item.shenhe_info || {};
            const shenheJiluId = item.shenhe_jilu_id ?? item.shenheJiluId
                ?? item.audit_id ?? item.shenheid ?? audit.id ?? audit.shenhe_jilu_id ?? null;
            const shenheDanhao = String(
                item.shenhe_danhao || item.shenheDanhao || item.audit_shenhe_danhao
                || audit.shenhe_danhao || audit.danhao || ''
            ).trim();
            const tixianjiluId = item.tixianjilu_id ?? item.tixianjiluId ?? item.id ?? null;
            const zhuangtai = this.parseZhuangtai(item);
            return {
                ...item,
                zhuangtai: zhuangtai >= 0 ? zhuangtai : item.zhuangtai,
                shenhe_jilu_id: shenheJiluId,
                shenhe_danhao: shenheDanhao,
                tixianjilu_id: tixianjiluId,
            };
        },

        hasAuditJiluId(item) {
            const id = item.shenhe_jilu_id;
            return id !== null && id !== undefined && id !== '' && id !== 0 && id !== '0';
        },

        hasShenheDanhao(item) {
            return !!(item.shenhe_danhao && String(item.shenhe_danhao).trim());
        },

        isNewAuditRecord(item) {
            return this.hasAuditJiluId(item) && this.hasShenheDanhao(item);
        },

        /** 待收款是否可点击：状态6 + 审核记录ID + 审核单号 缺一不可 */
        canCollectRecord(item) {
            return this.parseZhuangtai(item) === TX_STATUS.DAI_SHOUKUAN
                && this.hasAuditJiluId(item)
                && this.hasShenheDanhao(item);
        },

        getLeixingLabel(leixing) {
            return LEIXING_LABEL[parseInt(leixing)] || '提现';
        },

        getStatusBadgeClass(status) {
            switch (parseInt(status)) {
                case TX_STATUS.SHENHEZHONG: return 'status-wait';
                case TX_STATUS.TIXIAN_CHENGGONG:
                case TX_STATUS.SHENHE_CHENGGONG: return 'status-done';
                case TX_STATUS.DAI_SHOUKUAN: return 'status-pending';
                case TX_STATUS.TIXIAN_SHIBAI:
                case TX_STATUS.SHENHE_SHIBAI: return 'status-fail';
                default: return 'status-wait';
            }
        },

        processRecordItem(item) {
            item = this.normalizeRecordFields(item);
            const isNew = this.isNewAuditRecord(item);
            const status = this.parseZhuangtai(item);
            let statusText = '未知';
            let canCollect = false;
            let canShowDetail = false;
            let detailReason = '';

            switch (status) {
                case TX_STATUS.SHENHEZHONG: statusText = '审核中'; break;
                case TX_STATUS.TIXIAN_CHENGGONG: statusText = '提现成功'; break;
                case TX_STATUS.TIXIAN_SHIBAI:
                    statusText = '提现失败';
                    if (item.fail_reason || item.bhliyou) {
                        canShowDetail = true;
                        detailReason = item.fail_reason || item.bhliyou;
                    }
                    break;
                case TX_STATUS.SHENHE_CHENGGONG: statusText = '审核成功'; break;
                case TX_STATUS.SHENHE_SHIBAI:
                    statusText = '审核失败';
                    if (item.bhliyou) { canShowDetail = true; detailReason = item.bhliyou; }
                    break;
                case TX_STATUS.DAI_SHOUKUAN:
                    statusText = '待收款';
                    canCollect = this.canCollectRecord(item);
                    break;
            }

            return {
                ...item,
                isNewAudit: isNew,
                leixingLabel: this.getLeixingLabel(item.leixing),
                statusText,
                statusBadgeClass: this.getStatusBadgeClass(status),
                canCollect,
                canShowDetail,
                detailReason,
            };
        },

        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);
            }
        },

        updatePendingCollectFlag(list) {
            const hasPending = (list || []).some(item => item.canCollect);
            if (hasPending !== this.data.hasPendingCollect) {
                this.setData({ hasPendingCollect: hasPending });
            }
        },

        async loadAllAssets() {
            this.setData({ isLoadingAssets: true });
            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,
                        });
                    };
                    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);

                    let total = 0;
                    assets.forEach(item => { total += parseFloat(item.amount); });
                    this.setData({ assetList: assets, totalAmount: total.toFixed(2), isLoadingAssets: false });
                } else {
                    throw new Error(res?.data?.msg || '获取资产失败');
                }
            } catch (err) {
                console.error('loadAllAssets', err);
                this.setData({ isLoadingAssets: false });
            }
        },

        chushihuashuju() {
            this.loadAllAssets();
            this.huoquJilu(true);
        },

        /** 点击资产卡片（与 mode1 一致） */
        onSelectAsset(e) {
            const index = e.currentTarget.dataset.index;
            const asset = this.data.assetList[index];
            if (!asset || parseFloat(asset.amount) <= 0) {
                wx.showToast({ title: '无可提现金额', icon: 'none' });
                return;
            }
            this.setData({
                selectedAsset: asset,
                tixianleixing: asset.leixing,
                currentRate: asset.rate,
                tixianjine: '',
                shouxufei: '0.00',
                shijidaozhang: '0.00',
                showTixian: true,
            });
        },

        onJineInput(e) {
            this.setData({ tixianjine: e.detail.value, shouxufei: '0.00', shijidaozhang: '0.00' });
        },

        onQuickAmountTap(e) {
            const value = e.currentTarget.dataset.value;
            this.setData({ tixianjine: value.toString(), shouxufei: '0.00', shijidaozhang: '0.00' });
        },

        onStatusFilterTap(e) {
            const value = parseInt(e.currentTarget.dataset.value);
            if (value === this.data.currentStatusFilter) return;
            this.setData({ currentStatusFilter: value });
            this.huoquJilu(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);
                    if (data.shouxufei !== undefined) {
                        this.setData({
                            shouxufei: parseFloat(data.shouxufei || 0).toFixed(2),
                            shijidaozhang: parseFloat(data.shijidaozhang || 0).toFixed(2),
                        });
                    }
                    this.setData({ showTixian: false, submitting: false, selectedAsset: null });
                    await this.loadAllAssets();
                    this.huoquJilu(true);
                    wx.showModal({
                        title: '申请已提交',
                        content: '您的提现申请已提交，请等待后台审核。审核通过后，请在本页「提现记录」中点击「收款」按钮，主动确认后才能到账微信零钱。',
                        showCancel: false,
                    });
                } 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 });
            }
        },

        onCollectTap(e) {
            const index = e.currentTarget.dataset.index;
            const record = this.data.recordList[index];
            if (!record) return;
            if (this.parseZhuangtai(record) !== TX_STATUS.DAI_SHOUKUAN) {
                wx.showToast({ title: '当前状态不可收款', icon: 'none' });
                return;
            }
            if (!this.hasShenheDanhao(record) || !this.hasAuditJiluId(record)) {
                wx.showToast({ title: '审核信息不完整，请刷新后重试', icon: 'none' });
                return;
            }
            if (this.data.submitting) {
                wx.showToast({ title: '正在处理中，请稍后', icon: 'none' });
                return;
            }
            this.setData({ showCollectConfirm: true, collectConfirmRecord: record });
        },

        onCloseCollectConfirm() {
            if (this.data.submitting) return;
            this.setData({ showCollectConfirm: false, collectConfirmRecord: null });
        },

        async onConfirmCollect() {
            if (this.data.submitting) return;
            let record = this.data.collectConfirmRecord;
            if (!record) return;

            if (!this.canCollectRecord(record)) {
                await this.huoquJilu(true, true);
                const refreshed = (this.data.recordList || []).find(
                    r => String(r.id) === String(record.id)
                        || String(r.tixianjilu_id) === String(record.tixianjilu_id)
                );
                if (refreshed) record = refreshed;
            }
            if (!this.canCollectRecord(record)) {
                wx.showModal({
                    title: '暂时无法收款',
                    content: '缺少审核单号或审核记录ID，请下拉刷新后重试。仍不行请联系客服。',
                    showCancel: false,
                });
                return;
            }

            this.setData({ showCollectConfirm: false, submitting: true, collectConfirmRecord: record });
            try {
                const res = await request({
                    url: '/yonghu/tixiansq',
                    method: 'POST',
                    data: {
                        shenhe_danhao: record.shenhe_danhao,
                        shenhe_jilu_id: record.shenhe_jilu_id || '',
                        tixianjilu_id: record.tixianjilu_id || record.id || '',
                        leixing: record.leixing,
                    }
                });
                if (res.statusCode === 200 && res.data && res.data.code === 0) {
                    const data = res.data.data;
                    this.setData({
                        currentTixianId: data.tixian_id,
                        mchId: data.mch_id || '',
                        collectConfirmRecord: record,
                    });
                    this.tiaoqiWeixinQueRen(data.package_info);
                } else {
                    wx.showModal({ title: '收款失败', content: res.data?.msg || '无法发起收款，请稍后重试', showCancel: false });
                    this.setData({ submitting: false, collectConfirmRecord: null });
                }
            } catch (err) {
                wx.showModal({ title: '网络错误', content: '网络连接失败，请稍后重试', showCancel: false });
                this.setData({ submitting: false, collectConfirmRecord: null });
            }
        },

        tiaoqiWeixinQueRen(packageInfo) {
            const appId = app.globalData.appId;
            const mchId = this.data.mchId;
            if (!appId || !mchId) {
                wx.showModal({ title: '配置错误', content: '无法调起收款，请联系客服', showCancel: false });
                this.setData({ submitting: false, collectConfirmRecord: null });
                return;
            }
            wx.requestMerchantTransfer({
                appId, mchId, package: packageInfo,
                success: () => { this.tongzhiHouduanQueRen(1); },
                fail: () => {
                    this.tongzhiHouduanQueRen(0);
                    wx.showModal({
                        title: '确认收款失败',
                        content: '微信收款确认失败，您可在记录中再次点击「收款」重试。',
                        showCancel: false,
                    });
                }
            });
        },

        async tongzhiHouduanQueRen(result) {
            if (!this.data.currentTixianId) {
                this.setData({ submitting: false, collectConfirmRecord: null });
                return;
            }
            const record = this.data.collectConfirmRecord;
            try {
                const res = await request({
                    url: '/yonghu/tixianqr',
                    method: 'POST',
                    data: {
                        tixian_id: this.data.currentTixianId,
                        result: result,
                        shenhe_danhao: record ? record.shenhe_danhao : '',
                        shenhe_jilu_id: record ? (record.shenhe_jilu_id || '') : '',
                        tixianjilu_id: record ? (record.tixianjilu_id || record.id || '') : '',
                        leixing: record ? record.leixing : '',
                    }
                });
                if (res.statusCode === 200 && res.data && res.data.code === 0) {
                    const data = res.data.data || {};
                    this.gengxinYue(data, record ? record.leixing : null);
                    await this.loadAllAssets();
                    this.huoquJilu(true);
                    if (result === 1) PopupService.checkAndShow(this, 'tixianchenggong');
                    wx.showToast({
                        title: result === 1 ? '提现成功' : '收款已取消',
                        icon: result === 1 ? 'success' : 'none',
                        duration: 3000,
                    });
                } else {
                    wx.showModal({ title: '确认状态失败', content: res.data?.msg || '操作失败', showCancel: false });
                }
            } catch (err) {
                wx.showModal({ title: '网络错误', content: '网络连接失败', showCancel: false });
            } finally {
                this.setData({ submitting: false, currentTixianId: null, collectConfirmRecord: null });
            }
        },

        onViewDetail(e) {
            const index = e.currentTarget.dataset.index;
            const record = this.data.recordList[index];
            if (!record || !record.canShowDetail) return;
            const status = parseInt(record.zhuangtai);
            let detailTitle = '失败原因';
            if (status === TX_STATUS.SHENHE_SHIBAI) detailTitle = '审核失败原因';
            else if (status === TX_STATUS.TIXIAN_SHIBAI) detailTitle = '提现失败原因';
            this.setData({
                showDetailModal: true,
                detailTitle,
                detailContent: record.detailReason || '暂无详细信息',
            });
        },

        onCloseDetailModal() {
            this.setData({ showDetailModal: false, detailTitle: '', detailContent: '' });
        },

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

        async huoquJilu(fresh = false, force = false) {
            const now = Date.now();
            if (!force && now - lastPullDownTime < 2000 && !fresh) return;
            if (!force && (this.data.loading || this.data.isRefreshing)) return;
            const page = fresh ? 1 : this.data.page;
            if (fresh) this.setData({ nomore: false, canloadmore: true, isRefreshing: true });
            if (this.data.nomore && !fresh) return;
            this.setData({ loading: true });
            lastPullDownTime = now;
            try {
                const res = await request({
                    url: '/yonghu/tixianjiluhq',
                    method: 'POST',
                    data: { page, limit: yemianshuju, mode: 2, zhuangtai: this.data.currentStatusFilter }
                });
                if (res.statusCode === 200 && res.data && res.data.code === 0) {
                    const data = res.data.data;
                    const processedList = (data.list || []).map(item => this.processRecordItem(item));
                    const newList = fresh ? processedList : [...this.data.recordList, ...processedList];
                    this.setData({
                        recordList: newList,
                        page: page + 1,
                        nomore: !(data.has_more === true),
                        canloadmore: data.has_more === true,
                        loading: false,
                        isRefreshing: false,
                    });
                    this.updatePendingCollectFlag(newList);
                } else {
                    this.setData({ loading: false, isRefreshing: false });
                }
            } catch (err) {
                this.setData({ loading: false, isRefreshing: false });
            }
        },

        onReachBottom() {
            if (this.data.canloadmore && !this.data.nomore && !this.data.loading && !this.data.isRefreshing) {
                const now = Date.now();
                if (now - lastPullDownTime >= PULL_DOWN_INTERVAL) this.huoquJilu();
            }
        },

        stopPropagation() {}
    }
});
