import request from '../../../../utils/request.js';

const app = getApp();
const MEIYE = 5;

Component({
  properties: {
    status: { type: Number, value: 1, observer: 'reload' },
    searchDingdan: { type: String, value: '', observer: 'reload' },
    trigger: { type: Number, value: 0, observer: 'reload' }
  },

  data: {
    list: [],
    page: 1,
    hasMore: true,
    loading: false,
    loadingMore: false,
    ossImageUrl: app.globalData.ossImageUrl || '',

    showDetail: false,
    detailItem: null,

    showModify: false,
    modifyLiyou: '',
    modifyJine: '',

    showCancel: false,
    cancelLiyou: '',

    showResubmit: false,
    resubmitLiyou: '',
    resubmitJine: '',

    uploading: false,
    uploadProgressWidth: '0%'
  },

  lifetimes: {
    attached() { this.reload(); }
  },

  methods: {
    reload() {
      this.setData({ page: 1, list: [], hasMore: true });
      this.loadData();
    },

    mapItem(item) {
      const z = Number(item.zhuangtai);
      let display_status = '未知', status_class = 'zhuangtai-weizhi';
      if (z === 1) { display_status = '待缴纳'; status_class = 'zhuangtai-daijiaona'; }
      else if (z === 2) { display_status = '已缴纳'; status_class = 'zhuangtai-yijiaona'; }
      else if (z === 3) { display_status = '申诉中'; status_class = 'zhuangtai-shensuzhong'; }
      else if (z === 4) { display_status = '已驳回'; status_class = 'zhuangtai-yibohui'; }

      const zhengju = (item.zhengju_tupian || []).map(img => ({
        id: img.id,
        url: img.url,
        fullUrl: this.getFullUrl(img.url)
      }));
      const shensu = (item.shensu_tupian || []).map(img => ({
        id: img.id,
        url: img.url,
        fullUrl: this.getFullUrl(img.url)
      }));

      return {
        ...item,
        display_status,
        status_class,
        create_time: item.CreateTime || '',
        zhengju_list: zhengju,
        shensu_list: shensu,
        staff_label: item.staff_display_name ? `客服：${item.staff_display_name}` : ''
      };
    },

    async loadData(isLoadMore = false) {
      if (this.data.loading || this.data.loadingMore) return;
      if (isLoadMore && !this.data.hasMore) return;

      if (isLoadMore) this.setData({ loadingMore: true });
      else this.setData({ loading: true });

      try {
        const res = await request({
          url: '/yonghu/sjfklbhq',
          method: 'POST',
          data: {
            page: this.data.page,
            page_size: MEIYE,
            zhuangtai: this.data.status,
            sousuo_dingdan_id: this.data.searchDingdan
          }
        });
        if (res.statusCode === 200 && res.data.code === 0) {
          const data = res.data.data;
          const rows = (data.list || []).map(item => this.mapItem(item));
          const newList = isLoadMore ? this.data.list.concat(rows) : rows;
          this.setData({
            list: newList,
            hasMore: data.has_more || false,
            page: isLoadMore ? this.data.page + 1 : 2,
            loading: false,
            loadingMore: false
          });
        } else {
          wx.showToast({ title: res.data?.msg || '加载失败', icon: 'none' });
          this.setData({ loading: false, loadingMore: false });
        }
      } catch (e) {
        wx.showToast({ title: '网络请求失败', icon: 'none' });
        this.setData({ loading: false, loadingMore: false });
      }
    },

    loadMore() {
      if (this.data.list.length === 0 || !this.data.hasMore) return;
      this.loadData(true);
    },

    openDetail(e) {
      const item = e.currentTarget.dataset.item;
      this.setData({ showDetail: true, detailItem: item });
    },

    closeDetail() {
      this.setData({ showDetail: false, detailItem: null });
    },

    goOrder(e) {
      const id = e.currentTarget.dataset.id || this.data.detailItem?.guanliandingdan_id;
      if (!id) return;
      wx.navigateTo({ url: `/pages/merchant-order-detail/merchant-order-detail?dingdan_id=${id}` });
    },

    openModify() {
      const item = this.data.detailItem;
      this.setData({
        showModify: true,
        modifyLiyou: item.chufaliyou || '',
        modifyJine: item.fakuanjine || ''
      });
    },

    closeModify() { this.setData({ showModify: false }); },

    onModifyLiyou(e) { this.setData({ modifyLiyou: e.detail.value.slice(0, 500) }); },
    onModifyJine(e) { this.setData({ modifyJine: e.detail.value }); },

    async submitModify() {
      const item = this.data.detailItem;
      const liyou = this.data.modifyLiyou.trim();
      const jine = parseFloat(this.data.modifyJine);
      if (!liyou) { wx.showToast({ title: '请输入罚款原因', icon: 'none' }); return; }
      if (!jine || jine <= 0) { wx.showToast({ title: '金额无效', icon: 'none' }); return; }

      wx.showLoading({ title: '提交中' });
      try {
        const res = await request({
          url: '/dingdan/sjfkxgycx',
          method: 'POST',
          data: {
            operation: 'modify_penalty',
            dingdan_id: item.guanliandingdan_id,
            fadan_id: item.id,
            liyou: liyou,
            jine: jine.toFixed(2)
          }
        });
        if (res.statusCode === 200 && res.data.code === 0) {
          wx.showToast({ title: '修改成功', icon: 'success' });
          this.setData({ showModify: false });
          this.closeDetail();
          this.reload();
          this.triggerEvent('changed');
        } else {
          wx.showToast({ title: res.data?.msg || '修改失败', icon: 'none' });
        }
      } finally {
        wx.hideLoading();
      }
    },

    openCancel() { this.setData({ showCancel: true, cancelLiyou: '' }); },
    closeCancel() { this.setData({ showCancel: false }); },
    onCancelLiyou(e) { this.setData({ cancelLiyou: e.detail.value.slice(0, 500) }); },

    async submitCancel() {
      const item = this.data.detailItem;
      const liyou = this.data.cancelLiyou.trim();
      if (!liyou) { wx.showToast({ title: '请输入驳回理由', icon: 'none' }); return; }
      wx.showLoading({ title: '提交中' });
      try {
        const res = await request({
          url: '/dingdan/sjfkxgycx',
          method: 'POST',
          data: {
            operation: 'cancel_penalty',
            dingdan_id: item.guanliandingdan_id,
            fadan_id: item.id,
            liyou: liyou
          }
        });
        if (res.statusCode === 200 && res.data.code === 0) {
          wx.showToast({ title: '已撤销', icon: 'success' });
          this.setData({ showCancel: false });
          this.closeDetail();
          this.reload();
          this.triggerEvent('changed');
        } else {
          wx.showToast({ title: res.data?.msg || '操作失败', icon: 'none' });
        }
      } finally {
        wx.hideLoading();
      }
    },

    openResubmit() {
      const item = this.data.detailItem;
      this.setData({
        showResubmit: true,
        resubmitLiyou: item.chufaliyou || '',
        resubmitJine: item.fakuanjine || ''
      });
    },

    closeResubmit() { this.setData({ showResubmit: false }); },
    onResubmitLiyou(e) { this.setData({ resubmitLiyou: e.detail.value.slice(0, 500) }); },
    onResubmitJine(e) { this.setData({ resubmitJine: e.detail.value }); },

    async submitResubmit() {
      const item = this.data.detailItem;
      const liyou = this.data.resubmitLiyou.trim();
      const jine = parseFloat(this.data.resubmitJine);
      if (!liyou || !jine || jine <= 0) {
        wx.showToast({ title: '请填写完整信息', icon: 'none' });
        return;
      }
      wx.showLoading({ title: '提交中' });
      try {
        const res = await request({
          url: '/dingdan/sjfkxgycx',
          method: 'POST',
          data: {
            operation: 'resubmit_penalty',
            dingdan_id: item.guanliandingdan_id,
            fadan_id: item.id,
            liyou: liyou,
            jine: jine.toFixed(2)
          }
        });
        if (res.statusCode === 200 && res.data.code === 0) {
          wx.showToast({ title: '已重新申请', icon: 'success' });
          this.setData({ showResubmit: false });
          this.closeDetail();
          this.reload();
          this.triggerEvent('changed');
        } else {
          wx.showToast({ title: res.data?.msg || '操作失败', icon: 'none' });
        }
      } finally {
        wx.hideLoading();
      }
    },

    chooseEvidence() {
      const item = this.data.detailItem;
      const remain = 9 - (item.zhengju_list || []).length;
      if (remain <= 0) return;
      wx.chooseMedia({
        count: remain,
        mediaType: ['image'],
        sourceType: ['album', 'camera'],
        success: async (res) => {
          const paths = res.tempFiles.map(f => f.tempFilePath);
          await this.uploadAndAddEvidence(paths);
        }
      });
    },

    async uploadAndAddEvidence(localPaths) {
      const item = this.data.detailItem;
      if (!localPaths.length) return;
      this.setData({ uploading: true, uploadProgressWidth: '0%' });

      try {
        const keys = await this.uploadToCos(localPaths, item);
        if (!keys) return;
        const res = await request({
          url: '/dingdan/sjfkxgycx',
          method: 'POST',
          data: {
            operation: 'manage_penalty_evidence',
            dingdan_id: item.guanliandingdan_id,
            fadan_id: item.id,
            add_urls: keys,
            remove_ids: []
          }
        });
        if (res.statusCode === 200 && res.data.code === 0) {
          wx.showToast({ title: '图片已更新', icon: 'success' });
          this.reload();
          this.triggerEvent('changed');
          this.setData({ showDetail: false, detailItem: null });
        } else {
          wx.showToast({ title: res.data?.msg || '保存失败', icon: 'none' });
        }
      } finally {
        this.setData({ uploading: false });
      }
    },

    async deleteEvidence(e) {
      const imgId = e.currentTarget.dataset.id;
      const item = this.data.detailItem;
      wx.showLoading({ title: '删除中' });
      try {
        const res = await request({
          url: '/dingdan/sjfkxgycx',
          method: 'POST',
          data: {
            operation: 'manage_penalty_evidence',
            dingdan_id: item.guanliandingdan_id,
            fadan_id: item.id,
            add_urls: [],
            remove_ids: [imgId]
          }
        });
        if (res.statusCode === 200 && res.data.code === 0) {
          const zhengju = item.zhengju_list.filter(img => img.id !== imgId);
          this.setData({ detailItem: { ...item, zhengju_list: zhengju } });
          this.reload();
          this.triggerEvent('changed');
        } else {
          wx.showToast({ title: res.data?.msg || '删除失败', icon: 'none' });
        }
      } finally {
        wx.hideLoading();
      }
    },

    async uploadToCos(localPaths, item) {
      const credRes = await request({
        url: '/dingdan/dsscpz',
        method: 'POST',
        data: {
          dingdan_id: item.guanliandingdan_id,
          fadan_id: item.id,
          yongtu: 'fakuan_evidence'
        }
      });
      if (credRes.data.code !== 0) {
        wx.showToast({ title: credRes.data.msg || '凭证失败', icon: 'none' });
        return null;
      }
      const tokenData = credRes.data.data;
      const credentials = tokenData.credentials || tokenData;
      const COS = require('../../../../utils/cos-wx-sdk-v5.min.js');
      const cos = new COS({
        SimpleUploadMethod: 'putObject',
        getAuthorization: (_, callback) => {
          callback({
            TmpSecretId: credentials.tmpSecretId,
            TmpSecretKey: credentials.tmpSecretKey,
            SecurityToken: credentials.sessionToken || '',
            StartTime: tokenData.startTime,
            ExpiredTime: tokenData.expiredTime
          });
        }
      });
      const bucket = tokenData.bucket || 'julebu-1361527063';
      const region = tokenData.region || 'ap-shanghai';
      const uid = app.globalData.userInfo?.yonghuid || wx.getStorageSync('uid') || '0000000';
      const keys = [];
      const total = localPaths.length;

      for (let i = 0; i < total; i++) {
        const key = `fakuan/shangjiafakuan/zhengju/${uid}_${item.id}_${Date.now() + i}.jpg`;
        await new Promise((resolve, reject) => {
          cos.uploadFile({
            Bucket: bucket,
            Region: region,
            Key: key,
            FilePath: localPaths[i]
          }, (err) => err ? reject(err) : resolve());
        });
        keys.push(key);
        this.setData({ uploadProgressWidth: `${((i + 1) / total * 100).toFixed(0)}%` });
      }
      return keys;
    },

    previewImage(e) {
      const url = e.currentTarget.dataset.url;
      wx.previewImage({ current: url, urls: [url] });
    },

    getFullUrl(url) {
      if (!url) return '';
      if (url.startsWith('http')) return url;
      return this.data.ossImageUrl + url;
    }
  }
});
