// pages/withdraw/components/record-mode1/record-mode1.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.loadWithdrawRecords(true);
  },

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

  methods: {
    onPullDownRefresh() {
      return this.loadWithdrawRecords(true);
    },

    onLoadMoreFromScroll() {
      this.loadMoreRecords();
    },

    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 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() {}
  }
});