// pages/tixian/tixian.js
// 子组件版本 - 完整代码，仅适配生命周期，业务逻辑不动

import request from '../../../../utils/request.js';
import upload from '../../../../utils/upload.js';
import PopupService from '../../../../services/popupService.js';

const app = getApp();
const PAGE_SIZE = 10;
let lastPullDownTime = 0;
const PULL_DOWN_INTERVAL = 2000;

Component({
  data: {
    imgUrls: {
      pageBg: '',
      cardBg: '',
      iconWechat: '',
      iconAlipay: '',
      iconRecord: '',
      iconRefresh: '',
    },
    assetList: [],
    totalAmount: '0.00',
    selectedAsset: null,
    txfangshi: null,
    txdianhua: '',
    txzh: '',
    txtupian: '',
    ossImageUrl: '',
    showTixianModal: false,
    tixianAmount: '',
    shouxufei: '0.00',
    shijidaozhang: '0.00',
    currentRate: '0.00',
    recordList: [],
    page: 1,
    nomore: false,
    loading: false,
    isRefreshing: false,
    canloadmore: true,
    showSkfsModal: false,
    tempTxfangshi: null,
    tempTxPhone: '',
    tempTxAccount: '',
    tempTxImage: '',
    choosingImage: false,
    showModifyModal: false,
    modifyingRecord: null,
    modifyTxfangshi: null,
    modifyTxPhone: '',
    modifyTxAccount: '',
    modifyTxImage: '',
    modifyImageUrl: '',
    showFailModal: false,
    currentFailReason: '',
    isLoading: false,
  },

  attached() {
    this.initImageUrls();
    this.loadAllAssets();
    this.loadWithdrawMethod();
    this.loadWithdrawRecords(true);
  },

  pageLifetimes: {
    show() {
      this.registerNotification();
      PopupService.checkAndShow(this, 'tixian');
    },
    hide() {
      const popup = this.selectComponent('#popupNotice');
      popup?.cleanup?.();
    }
  },

  methods: {
    // 下拉刷新
    onPullDownRefresh() {
      if (this.data.isRefreshing) {
        wx.stopPullDownRefresh();
        return;
      }
      this.setData({ isRefreshing: true });
      this.loadWithdrawRecords(true).then(() => {
        wx.stopPullDownRefresh();
        this.setData({ isRefreshing: false });
      }).catch(() => {
        wx.stopPullDownRefresh();
        this.setData({ isRefreshing: false });
      });
    },

    // 底部按钮加载更多
    loadMoreRecords() {
      if (this.data.nomore) {
        wx.showToast({ title: '没有更多记录了', icon: 'none' });
        return;
      }
      if (this.data.loading) return;
      this.loadWithdrawRecords();
    },

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

    async loadAllAssets() {
      this.setData({ isLoading: true });
      try {
        const res = await request({ url: '/yonghu/tixianzichan', method: 'POST' });
        if (res?.data?.code === 200) {
          const data = res.data.data;
          const assets = [];
          if (data.dashou_yue && parseFloat(data.dashou_yue) > 0) {
            assets.push({ type: 'dashou_yue', label: '打手佣金', amount: data.dashou_yue, rate: data.dashou_rate || 0 });
          }
          if (data.dashou_yajin && parseFloat(data.dashou_yajin) > 0) {
            assets.push({ type: 'dashou_yajin', label: '打手保证金', amount: data.dashou_yajin, rate: data.dashou_yajin_rate || 0 });
          }
          if (data.shangjia_yue && parseFloat(data.shangjia_yue) > 0) {
            assets.push({ type: 'shangjia_yue', label: '商家余额', amount: data.shangjia_yue, rate: data.shangjia_rate || 0 });
          }
          if (data.guanshi_fenyong && parseFloat(data.guanshi_fenyong) > 0) {
            assets.push({ type: 'guanshi_fenyong', label: '管事分红', amount: data.guanshi_fenyong, rate: data.guanshi_rate || 0 });
          }
          if (data.zuzhang_fenyong && parseFloat(data.zuzhang_fenyong) > 0) {
            assets.push({ type: 'zuzhang_fenyong', label: '组长分红', amount: data.zuzhang_fenyong, rate: data.zuzhang_rate || 0 });
          }
          if (data.kaoheguan_fenyong && parseFloat(data.kaoheguan_fenyong) > 0) {
            assets.push({ type: 'kaoheguan_fenyong', label: '考核官分佣', amount: data.kaoheguan_fenyong, rate: data.kaoheguan_rate || 0 });
          }
          let total = 0;
          assets.forEach(item => { total += parseFloat(item.amount); });
          this.setData({ assetList: assets, totalAmount: total.toFixed(2), isLoading: false });
          // 缓存费率
          wx.setStorageSync('dashouRate', data.dashou_rate || 0);
          wx.setStorageSync('dashou_yajin_rate', data.dashou_yajin_rate || 0);
          wx.setStorageSync('shangjia_rate', data.shangjia_rate || 0);
          wx.setStorageSync('guanshi_rate', data.guanshi_rate || 0);
          wx.setStorageSync('zuzhang_rate', data.zuzhang_rate || 0);
          wx.setStorageSync('kaoheguan_rate', data.kaoheguan_rate || 0);
        } else {
          throw new Error(res?.data?.msg || '获取资产失败');
        }
      } catch (err) {
        console.error(err);
        wx.showToast({ title: '加载失败', icon: 'none' });
        this.setData({ isLoading: false });
      }
    },

    async loadWithdrawMethod() {
      const txzh = wx.getStorageSync('txzh') || '';
      const txtupian = wx.getStorageSync('txtupian') || '';
      const txfangshi = wx.getStorageSync('txfangshi') || null;
      const txdianhua = wx.getStorageSync('txdianhua') || '';
      if (txzh || txtupian) {
        this.setData({ txzh, txtupian, txfangshi, txdianhua, ossImageUrl: app.globalData.ossImageUrl || '' });
      } else {
        try {
          const res = await request({ url: '/yonghu/tixianhq', method: 'POST' });
          if (res?.data?.code === 0) {
            const data = res.data.data;
            this.setData({
              txzh: data.txzh || '',
              txtupian: data.txtupian || '',
              txfangshi: data.txfangshi || null,
              txdianhua: data.txdianhua || '',
            });
            wx.setStorageSync('txzh', data.txzh || '');
            wx.setStorageSync('txtupian', data.txtupian || '');
            wx.setStorageSync('txfangshi', data.txfangshi || null);
            wx.setStorageSync('txdianhua', data.txdianhua || '');
          }
        } catch (err) {}
      }
    },

    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,
        showTixianModal: true,
        tixianAmount: '',
        shouxufei: '0.00',
        shijidaozhang: '0.00',
        currentRate: asset.rate
      });
    },

    onAmountInput(e) {
      let val = e.detail.value;
      if (val && !/^\d*\.?\d{0,2}$/.test(val)) return;
      this.setData({ tixianAmount: val });
      if (val && parseFloat(val) > 0) {
        const amount = parseFloat(val);
        const rate = parseFloat(this.data.selectedAsset.rate) || 0;
        const fee = amount * rate;
        const actual = amount - fee;
        this.setData({ shouxufei: fee.toFixed(2), shijidaozhang: actual.toFixed(2) });
      } else {
        this.setData({ shouxufei: '0.00', shijidaozhang: '0.00' });
      }
    },

    onQuickAmount(e) {
      const val = e.currentTarget.dataset.value;
      this.setData({ tixianAmount: val.toString() });
      this.onAmountInput({ detail: { value: val.toString() } });
    },

    async onConfirmWithdraw() {
      const { selectedAsset, tixianAmount, txfangshi, txzh, txtupian, txdianhua } = this.data;
      if (!selectedAsset) { wx.showToast({ title: '请选择提现项目', icon: 'none' }); return; }
      const amount = parseFloat(tixianAmount);
      if (isNaN(amount) || amount <= 0) { wx.showToast({ title: '请输入有效金额', icon: 'none' }); return; }
      if (amount > parseFloat(selectedAsset.amount)) { wx.showToast({ title: '超过可提现金额', icon: 'none' }); return; }
      if (!txfangshi || (!txzh && !txtupian)) {
        wx.showToast({ title: '请先设置收款方式', icon: 'none' });
        this.setData({ showTixianModal: false });
        this.onSetSkfs();
        return;
      }
      let leixing = 1;
      switch (selectedAsset.type) {
        case 'dashou_yue': leixing = 1; break;
        case 'dashou_yajin': leixing = 5; break;
        case 'shangjia_yue': leixing = 6; break;
        case 'guanshi_fenyong': leixing = 2; break;
        case 'zuzhang_fenyong': leixing = 3; break;
        case 'kaoheguan_fenyong': leixing = 4; break;
      }
      let txskfs = 0;
      if (txzh && txtupian) txskfs = 3;
      else if (txzh) txskfs = 1;
      else if (txtupian) txskfs = 2;
      try {
        const res = await request({
          url: '/yonghu/tixian',
          method: 'POST',
          data: { leixing, jine: amount.toFixed(2), fangshi: txfangshi, txskfs }
        });
        if (res?.data?.code === 0) {
          const newAssetList = this.data.assetList.map(item => {
            if (item.type === selectedAsset.type) {
              const newAmount = (parseFloat(item.amount) - amount).toFixed(2);
              return { ...item, amount: newAmount };
            }
            return item;
          });
          let newTotal = 0;
          newAssetList.forEach(item => { newTotal += parseFloat(item.amount); });
          this.setData({ assetList: newAssetList, totalAmount: newTotal.toFixed(2), showTixianModal: false, selectedAsset: null });
          this.loadWithdrawRecords(true);
          wx.showToast({ title: '提现申请已提交', icon: 'success' });
        } else {
          wx.showToast({ title: res?.data?.msg || '提现失败', icon: 'none' });
        }
      } catch (err) {
        wx.showToast({ title: '网络错误', icon: 'none' });
      }
    },

    onCloseTixianModal() {
      this.setData({ showTixianModal: false, selectedAsset: null, tixianAmount: '' });
    },

    onSetSkfs() {
      this.setData({
        showSkfsModal: true,
        tempTxfangshi: this.data.txfangshi,
        tempTxPhone: this.data.txdianhua,
        tempTxAccount: this.data.txzh,
        tempTxImage: ''
      });
    },

    onSelectFangshi(e) {
      this.setData({ tempTxfangshi: e.currentTarget.dataset.fangshi });
    },

    onPhoneInput(e) { this.setData({ tempTxPhone: e.detail.value }); },
    onAccountInput(e) { this.setData({ tempTxAccount: e.detail.value }); },

    onChooseImage() {
      if (this.data.choosingImage) return;
      this.setData({ choosingImage: true });
      wx.chooseMedia({
        count: 1, mediaType: ['image'],
        success: (res) => { this.setData({ tempTxImage: res.tempFiles[0].tempFilePath }); },
        complete: () => { this.setData({ choosingImage: false }); }
      });
    },

    onPreviewImage() {
      if (this.data.tempTxImage) wx.previewImage({ urls: [this.data.tempTxImage] });
    },

    onDeleteImage() { this.setData({ tempTxImage: '' }); },

    async onConfirmSkfs() {
      const { tempTxfangshi, tempTxPhone, tempTxAccount, tempTxImage } = this.data;
      if (!tempTxfangshi) { wx.showToast({ title: '请选择提现方式', icon: 'none' }); return; }
      if (!tempTxPhone) { wx.showToast({ title: '请输入收款人电话', icon: 'none' }); return; }
      if (tempTxfangshi == 1 && !tempTxImage) { wx.showToast({ title: '请上传微信收款码', icon: 'none' }); return; }
      if (tempTxfangshi == 2 && !tempTxAccount && !tempTxImage) {
        wx.showToast({ title: '请填写支付宝账号或上传收款码', icon: 'none' }); return;
      }
      const formData = { txdianhua: tempTxPhone, txzh: tempTxAccount || '' };
      try {
        const res = await upload({ url: '/yonghu/sksc', formData, filePath: tempTxImage || null, fileName: 'file' });
        if (res?.data?.code === 0) {
          const data = res.data.data;
          this.setData({
            txfangshi: tempTxfangshi, txdianhua: tempTxPhone, txzh: data.txzh || '', txtupian: data.txtupian || '', showSkfsModal: false
          });
          wx.setStorageSync('txfangshi', tempTxfangshi);
          wx.setStorageSync('txdianhua', tempTxPhone);
          wx.setStorageSync('txzh', data.txzh || '');
          wx.setStorageSync('txtupian', data.txtupian || '');
          wx.showToast({ title: '设置成功', icon: 'success' });
        } else {
          wx.showToast({ title: res?.data?.msg || '保存失败', icon: 'none' });
        }
      } catch (err) {
        wx.showToast({ title: '网络错误', icon: 'none' });
      }
    },

    onCloseSkfsModal() { this.setData({ showSkfsModal: false }); },

    async loadWithdrawRecords(refresh = false) {
      const now = Date.now();
      if (now - lastPullDownTime < PULL_DOWN_INTERVAL && !refresh) return;
      if (this.data.loading || this.data.isRefreshing) return;
      const page = refresh ? 1 : this.data.page;
      if (this.data.nomore && !refresh) return;
      this.setData({ loading: true, isRefreshing: refresh });
      lastPullDownTime = now;
      try {
        const res = await request({ url: '/yonghu/tixianjiluhq', method: 'POST', data: { page, limit: PAGE_SIZE } });
        if (res?.data?.code === 0) {
          const list = (res.data.data.list || []).map(item => ({
            ...item,
            statusText: this.getStatusText(item.zhuangtai),
            statusColor: this.getStatusColor(item.zhuangtai)
          }));
          const newList = refresh ? list : [...this.data.recordList, ...list];
          const hasMore = res.data.data.has_more === true;
          this.setData({
            recordList: newList, page: page + 1, nomore: !hasMore, canloadmore: hasMore,
            loading: false, isRefreshing: false
          });
        } else {
          this.setData({ loading: false, isRefreshing: false });
        }
      } catch (err) {
        this.setData({ loading: false, isRefreshing: false });
      }
    },

    onModifyRecord(e) {
      const record = e.currentTarget.dataset.record;
      if (parseInt(record.zhuangtai) !== 1) {
        wx.showToast({ title: '只有审核中的记录可修改', icon: 'none' });
        return;
      }
      this.setData({
        modifyingRecord: record,
        modifyTxfangshi: record.fangshi,
        modifyTxPhone: record.txdianhua || '',
        modifyTxAccount: record.txzh || '',
        modifyTxImage: '',
        modifyImageUrl: record.txtupian ? (app.globalData.ossImageUrl + record.txtupian) : '',
        showModifyModal: true
      });
    },

    onSelectModifyFangshi(e) { this.setData({ modifyTxfangshi: e.currentTarget.dataset.fangshi }); },
    onModifyPhoneInput(e) { this.setData({ modifyTxPhone: e.detail.value }); },
    onModifyAccountInput(e) { this.setData({ modifyTxAccount: e.detail.value }); },

    onChooseModifyImage() {
      if (this.data.choosingImage) return;
      this.setData({ choosingImage: true });
      wx.chooseMedia({
        count: 1, mediaType: ['image'],
        success: (res) => { this.setData({ modifyTxImage: res.tempFiles[0].tempFilePath }); },
        complete: () => { this.setData({ choosingImage: false }); }
      });
    },

    onPreviewModifyImage() {
      if (this.data.modifyTxImage) wx.previewImage({ urls: [this.data.modifyTxImage] });
      else if (this.data.modifyImageUrl) wx.previewImage({ urls: [this.data.modifyImageUrl] });
    },

    onDeleteModifyImage() { this.setData({ modifyTxImage: '' }); },

    async onConfirmModify() {
      const { modifyTxfangshi, modifyTxPhone, modifyTxAccount, modifyTxImage, modifyingRecord } = this.data;
      if (!modifyTxfangshi) { wx.showToast({ title: '请选择提现方式', icon: 'none' }); return; }
      if (!modifyTxPhone) { wx.showToast({ title: '请输入收款人电话', icon: 'none' }); return; }
      if (modifyTxfangshi == 1 && !modifyTxImage) { wx.showToast({ title: '请上传微信收款码', icon: 'none' }); return; }
      if (modifyTxfangshi == 2 && !modifyTxAccount && !modifyTxImage) {
        wx.showToast({ title: '请填写支付宝账号或上传收款码', icon: 'none' }); return;
      }
      const formData = { tixian_id: modifyingRecord.id, fangshi: modifyTxfangshi, txdianhua: modifyTxPhone, txzh: modifyTxAccount || '' };
      try {
        const res = await upload({ url: '/yonghu/yonghutxshxg', formData, filePath: modifyTxImage || null, fileName: 'file' });
        if (res?.data?.code === 0) {
          const data = res.data.data;
          const newList = this.data.recordList.map(item => {
            if (item.id === modifyingRecord.id) {
              return { ...item, fangshi: modifyTxfangshi, txdianhua: modifyTxPhone, txzh: modifyTxAccount || '', txtupian: data.txtupian || modifyingRecord.txtupian };
            }
            return item;
          });
          this.setData({ recordList: newList, showModifyModal: false, modifyingRecord: null });
          wx.showToast({ title: '修改成功', icon: 'success' });
        } else {
          wx.showToast({ title: res?.data?.msg || '修改失败', icon: 'none' });
        }
      } catch (err) {
        wx.showToast({ title: '网络错误', icon: 'none' });
      }
    },

    onCloseModifyModal() { this.setData({ showModifyModal: false, modifyingRecord: null }); },

    onViewFailReason(e) {
      const record = e.currentTarget.dataset.record;
      const reason = record.fail_reason || record.shibaiyuanyin || '暂无详细信息';
      this.setData({ currentFailReason: reason, showFailModal: true });
    },

    onCloseFailModal() { this.setData({ showFailModal: false }); },

    getStatusText(zhuangtai) {
      const s = parseInt(zhuangtai);
      if (s === 1) return '审核中';
      if (s === 2) return '成功';
      if (s === 3) return '失败';
      return '未知';
    },
    getStatusColor(zhuangtai) {
      const s = parseInt(zhuangtai);
      if (s === 1) return '#F5A623';
      if (s === 2) return '#2ED158';
      if (s === 3) return '#FF4D4F';
      return '#999';
    },

    registerNotification() {
      const comp = this.selectComponent('#global-notification');
      if (comp?.showNotification) {
        app.globalData.globalNotification = {
          show: (data) => comp.showNotification(data),
          hide: () => comp.hideNotification()
        };
      }
    },
    stopPropagation() {}
  }
});