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

Page({
  data: {
    mode: 'add', // add 或 edit
    productId: null,
    loading: false,
    formData: {
      productName: '',
      productCode: '',
      productType: 'personal',
      minLoanAmount: '',
      maxLoanAmount: '',
      minLoanTerm: '',
      maxLoanTerm: '',
      interestRate: '',
      productDescription: '',
      serviceArea: '',
      servicePhone: '',
      riskLevel: 'LOW',
      requiredDocuments: '',
      onSaleStatus: true
    },
    typeOptions: [
      { value: 'personal', label: '个人贷款' },
      { value: 'mortgage', label: '住房贷款' },
      { value: 'business', label: '企业贷款' },
      { value: 'agricultural', label: '农业贷款' },
      { value: 'livestock_collateral', label: '养殖抵押贷款' }
    ],
    riskLevelOptions: [
      { value: 'LOW', label: '低风险' },
      { value: 'MEDIUM', label: '中风险' },
      { value: 'HIGH', label: '高风险' }
    ],
    // 计算属性
    productTypeIndex: 0,
    riskLevelIndex: 0,
    currentProductTypeLabel: '请选择产品类型',
    currentRiskLevelLabel: '请选择风险等级'
  },

  onLoad(options) {
    console.log('表单页面加载', options);
    
    // 检查认证状态
    if (!auth.isAuthenticated()) {
      console.log('用户未登录，跳转到登录页面');
      wx.reLaunch({
        url: '/pages/login/login'
      });
      return;
    }

    const { mode, productId } = options;
    console.log('表单模式:', mode, '商品ID:', productId);
    
    this.setData({
      mode: mode || 'add',
      productId: productId || null
    });

    // 初始化计算属性
    this.updatePickerIndexes();

    if (mode === 'edit' && productId) {
      this.loadProductDetail(productId);
    }
  },

  // 更新选择器的索引和标签
  updatePickerIndexes() {
    const { formData, typeOptions, riskLevelOptions } = this.data;
    
    // 更新产品类型索引
    const productTypeIndex = typeOptions.findIndex(item => item.value === formData.productType);
    const currentProductTypeLabel = productTypeIndex >= 0 ? typeOptions[productTypeIndex].label : '请选择产品类型';
    
    // 更新风险等级索引
    const riskLevelIndex = riskLevelOptions.findIndex(item => item.value === formData.riskLevel);
    const currentRiskLevelLabel = riskLevelIndex >= 0 ? riskLevelOptions[riskLevelIndex].label : '请选择风险等级';
    
    this.setData({
      productTypeIndex: productTypeIndex >= 0 ? productTypeIndex : 0,
      riskLevelIndex: riskLevelIndex >= 0 ? riskLevelIndex : 0,
      currentProductTypeLabel,
      currentRiskLevelLabel
    });
  },

  // 加载商品详情（编辑模式）
  async loadProductDetail(productId) {
    try {
      this.setData({ loading: true });
      
      const response = await apiService.loanProducts.getDetail(productId);
      
      if (response.success) {
        const product = response.data;
        this.setData({
          formData: {
            productName: product.productName || '',
            productCode: product.productCode || '',
            productType: product.productType || 'personal',
            minLoanAmount: product.minLoanAmount || '',
            maxLoanAmount: product.maxLoanAmount || '',
            minLoanTerm: product.minLoanTerm || '',
            maxLoanTerm: product.maxLoanTerm || '',
            interestRate: product.interestRate || '',
            productDescription: product.productDescription || '',
            serviceArea: product.serviceArea || '',
            servicePhone: product.servicePhone || '',
            riskLevel: product.riskLevel || 'LOW',
            requiredDocuments: product.requiredDocuments || '',
            onSaleStatus: product.onSaleStatus !== false
          }
        });
        
        // 更新选择器索引
        this.updatePickerIndexes();
      } else {
        throw new Error(response.message || '获取商品详情失败');
      }
    } catch (error) {
      console.error('加载商品详情失败:', error);
      wx.showToast({
        title: error.message || '加载失败',
        icon: 'error'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  // 输入处理
  onInputChange(e) {
    const { field } = e.currentTarget.dataset;
    const { value } = e.detail;
    
    this.setData({
      [`formData.${field}`]: value
    });
  },

  // 选择器处理
  onPickerChange(e) {
    const { field } = e.currentTarget.dataset;
    const { value } = e.detail;
    
    let selectedValue = '';
    let selectedLabel = '';
    
    if (field === 'productType') {
      selectedValue = this.data.typeOptions[value].value;
      selectedLabel = this.data.typeOptions[value].label;
      this.setData({
        [`formData.${field}`]: selectedValue,
        productTypeIndex: value,
        currentProductTypeLabel: selectedLabel
      });
    } else if (field === 'riskLevel') {
      selectedValue = this.data.riskLevelOptions[value].value;
      selectedLabel = this.data.riskLevelOptions[value].label;
      this.setData({
        [`formData.${field}`]: selectedValue,
        riskLevelIndex: value,
        currentRiskLevelLabel: selectedLabel
      });
    }
  },

  // 开关处理
  onSwitchChange(e) {
    const { field } = e.currentTarget.dataset;
    const { value } = e.detail;
    
    this.setData({
      [`formData.${field}`]: value
    });
  },

  // 表单验证
  validateForm() {
    const { formData } = this.data;
    
    if (!formData.productName.trim()) {
      wx.showToast({
        title: '请输入产品名称',
        icon: 'none'
      });
      return false;
    }
    
    if (!formData.productType) {
      wx.showToast({
        title: '请选择产品类型',
        icon: 'none'
      });
      return false;
    }
    
    if (!formData.minLoanAmount || !formData.maxLoanAmount) {
      wx.showToast({
        title: '请输入贷款额度范围',
        icon: 'none'
      });
      return false;
    }
    
    if (parseFloat(formData.minLoanAmount) >= parseFloat(formData.maxLoanAmount)) {
      wx.showToast({
        title: '最小额度应小于最大额度',
        icon: 'none'
      });
      return false;
    }
    
    if (!formData.interestRate) {
      wx.showToast({
        title: '请输入利率',
        icon: 'none'
      });
      return false;
    }
    
    if (!formData.riskLevel) {
      wx.showToast({
        title: '请选择风险等级',
        icon: 'none'
      });
      return false;
    }
    
    return true;
  },

  // 提交表单
  async submitForm() {
    if (!this.validateForm()) {
      return;
    }

    try {
      this.setData({ loading: true });
      
      const { mode, productId, formData } = this.data;
      
      // 转换字段名为后端期望的格式
      const submitData = {
        productName: formData.productName,
        productCode: formData.productCode,
        productType: formData.productType,
        // 后端期望的字段名
        loanAmount: formData.maxLoanAmount || formData.minLoanAmount, // 使用最大贷款额度作为贷款金额
        loanTerm: formData.maxLoanTerm || formData.minLoanTerm, // 使用最大贷款期限作为贷款期限
        minLoanAmount: formData.minLoanAmount,
        maxLoanAmount: formData.maxLoanAmount,
        minLoanTerm: formData.minLoanTerm,
        maxLoanTerm: formData.maxLoanTerm,
        interestRate: formData.interestRate,
        productDescription: formData.productDescription,
        serviceArea: formData.serviceArea,
        servicePhone: formData.servicePhone,
        riskLevel: formData.riskLevel,
        requiredDocuments: formData.requiredDocuments,
        onSaleStatus: formData.onSaleStatus
      };
      
      // 调试信息：打印发送的数据
      console.log('发送的数据:', submitData);
      console.log('必填字段检查:');
      console.log('productName:', submitData.productName, '是否为空:', !submitData.productName);
      console.log('loanAmount:', submitData.loanAmount, '是否为空:', !submitData.loanAmount);
      console.log('loanTerm:', submitData.loanTerm, '是否为空:', !submitData.loanTerm);
      console.log('interestRate:', submitData.interestRate, '是否为空:', !submitData.interestRate);
      console.log('serviceArea:', submitData.serviceArea, '是否为空:', !submitData.serviceArea);
      console.log('servicePhone:', submitData.servicePhone, '是否为空:', !submitData.servicePhone);
      
      let response;
      
      if (mode === 'add') {
        response = await apiService.loanProducts.create(submitData);
      } else {
        response = await apiService.loanProducts.update(productId, submitData);
      }
      
      if (response.success) {
        wx.showToast({
          title: mode === 'add' ? '新增成功' : '修改成功',
          icon: 'success'
        });
        
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      } else {
        throw new Error(response.message || '操作失败');
      }
    } catch (error) {
      console.error('提交失败:', error);
      wx.showToast({
        title: error.message || '操作失败',
        icon: 'error'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  // 取消
  cancel() {
    wx.navigateBack();
  }
});
