// pages/business/loan-products/loan-products.js
const { apiService } = require('../../../services/apiService');
const auth = require('../../../utils/auth.js');

Page({
  data: {
    products: [],
    loading: false,
    searchKeyword: '',
    filterStatus: 'all',
    typeMap: {
      'personal': '个人贷款',
      'mortgage': '住房贷款',
      'business': '企业贷款',
      'agricultural': '农业贷款'
    }
  },

  onLoad() {
    // 检查认证状态
    if (!auth.isAuthenticated()) {
      wx.reLaunch({
        url: '/pages/login/login'
      });
      return;
    }
    
    this.loadProducts();
  },

  onShow() {
    // 检查认证状态
    if (!auth.isAuthenticated()) {
      wx.reLaunch({
        url: '/pages/login/login'
      });
      return;
    }
    
    this.loadProducts();
  },

  // 加载商品数据
  async loadProducts() {
    this.setData({ loading: true });
    
    try {
      const params = {
        page: 1,
        limit: 20,
        search: this.data.searchKeyword,
        status: this.data.filterStatus === 'all' ? '' : this.data.filterStatus
      };
      
      const response = await apiService.loanProducts.getList(params);
      
      if (response.success) {
        const products = response.data.products.map(product => ({
          ...product,
          // 字段映射 - 根据接口返回数据调整
          name: product.productName || product.name,
          code: product.productCode || product.code,
          type: product.productType || product.type,
          status: product.onSaleStatus ? 'active' : 'inactive',
          statusText: product.onSaleStatus ? '在售' : '停售',
          typeText: this.data.typeMap[product.productType || product.type] || (product.productType || product.type),
          minAmount: product.minLoanAmount || product.minAmount,
          maxAmount: product.maxLoanAmount || product.maxAmount,
          minTerm: product.minLoanTerm || product.minTerm,
          maxTerm: product.maxLoanTerm || product.maxTerm,
          interestRate: product.interestRate || product.minInterestRate,
          maxInterestRate: product.maxInterestRate || product.interestRate,
          description: product.productDescription || product.description,
          // 新增字段
          serviceArea: product.serviceArea,
          servicePhone: product.servicePhone,
          riskLevel: product.riskLevel,
          requiredDocuments: product.requiredDocuments,
          supervisionCustomers: product.supervisionCustomers,
          totalCustomers: product.totalCustomers
        }));
        
        this.setData({
          products,
          loading: false
        });
      } else {
        throw new Error(response.message || '获取商品列表失败');
      }
    } catch (error) {
      console.error('加载商品失败:', error);
      
      // 使用模拟数据作为降级处理
      const mockProducts = [
        {
          id: 1,
          name: '个人住房贷款',
          code: 'LOAN-001',
          type: 'mortgage',
          typeText: '住房贷款',
          status: 'active',
          statusText: '在售',
          minAmount: 100000,
          maxAmount: 5000000,
          minTerm: 12,
          maxTerm: 360,
          interestRate: 4.5,
          maxInterestRate: 6.5,
          description: '专为个人购房提供的住房抵押贷款产品'
        },
        {
          id: 2,
          name: '个人消费贷款',
          code: 'LOAN-002',
          type: 'personal',
          typeText: '个人贷款',
          status: 'active',
          statusText: '在售',
          minAmount: 10000,
          maxAmount: 500000,
          minTerm: 6,
          maxTerm: 60,
          interestRate: 6.8,
          maxInterestRate: 12.5,
          description: '用于个人消费支出的信用贷款产品'
        }
      ];
      
      this.setData({
        products: mockProducts,
        loading: false
      });
      
      wx.showToast({
        title: '使用模拟数据',
        icon: 'none'
      });
    }
  },

  // 搜索输入
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
    this.loadProducts();
  },

  // 筛选状态
  onFilterChange(e) {
    const status = e.detail.value;
    this.setData({
      filterStatus: status
    });
    this.loadProducts();
  },

  // 查看商品详情
  viewProductDetail(e) {
    const productId = e.currentTarget.dataset.productId;
    wx.navigateTo({
      url: `/pages/business/loan-products/detail?productId=${productId}`
    });
  },

  // 新增商品
  addProduct() {
    console.log('点击新增商品按钮');
    
    // 使用绝对路径跳转到表单页面
    wx.navigateTo({
      url: '/pages/business/loan-products/form/form?mode=add',
      success: (res) => {
        console.log('跳转到表单页面成功', res);
      },
      fail: (err) => {
        console.error('跳转到表单页面失败', err);
        console.error('错误详情:', JSON.stringify(err));
        
        // 如果失败，尝试跳转到测试页面
        wx.navigateTo({
          url: '/pages/business/loan-products/test-form?mode=add',
          success: (res) => {
            console.log('跳转到测试页面成功', res);
          },
          fail: (err2) => {
            console.error('跳转到测试页面也失败', err2);
            wx.showModal({
              title: '跳转失败',
              content: `表单页面错误: ${err.errMsg}\n测试页面错误: ${err2.errMsg}`,
              showCancel: false
            });
          }
        });
      }
    });
  },

  // 编辑商品
  editProduct(e) {
    console.log('点击编辑商品按钮', e);
    const productId = e.currentTarget.dataset.productId;
    console.log('商品ID:', productId);
    
    // 使用绝对路径跳转到表单页面
    wx.navigateTo({
      url: `/pages/business/loan-products/form/form?mode=edit&productId=${productId}`,
      success: (res) => {
        console.log('跳转到编辑页面成功', res);
      },
      fail: (err) => {
        console.error('跳转到编辑页面失败', err);
        console.error('错误详情:', JSON.stringify(err));
        
        // 如果失败，尝试跳转到测试页面
        wx.navigateTo({
          url: `/pages/business/loan-products/test-form?mode=edit&productId=${productId}`,
          success: (res) => {
            console.log('跳转到测试页面成功', res);
          },
          fail: (err2) => {
            console.error('跳转到测试页面也失败', err2);
            wx.showModal({
              title: '跳转失败',
              content: `表单页面错误: ${err.errMsg}\n测试页面错误: ${err2.errMsg}`,
              showCancel: false
            });
          }
        });
      }
    });
  },

  // 删除商品（下架）
  deleteProduct(e) {
    console.log('点击删除商品按钮', e);
    const productId = e.currentTarget.dataset.productId;
    console.log('商品ID:', productId);
    const product = this.data.products.find(p => p.id == productId);
    
    wx.showModal({
      title: '确认下架',
      content: `确定要下架商品"${product?.name || '该商品'}"吗？`,
      success: (res) => {
        if (res.confirm) {
          this.handleDeleteProduct(productId);
        }
      }
    });
  },

  // 处理删除商品
  async handleDeleteProduct(productId) {
    try {
      wx.showLoading({
        title: '下架中...'
      });

      const response = await apiService.loanProducts.delete(productId);
      
      if (response.success) {
        wx.hideLoading();
        wx.showToast({
          title: '下架成功',
          icon: 'success'
        });
        
        // 重新加载商品列表
        this.loadProducts();
      } else {
        throw new Error(response.message || '下架失败');
      }
    } catch (error) {
      console.error('下架商品失败:', error);
      wx.hideLoading();
      wx.showToast({
        title: error.message || '下架失败',
        icon: 'error'
      });
    }
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadProducts().finally(() => {
      wx.stopPullDownRefresh();
    });
  }
});
