import { Component, OnInit, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { MatCardModule } from '@angular/material/card';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatExpansionModule } from '@angular/material/expansion';
import { MatSelectModule } from '@angular/material/select';
import { MatInputModule } from '@angular/material/input';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatDialogModule, MatDialog } from '@angular/material/dialog';
import { AutoSettlementService, AutoSettlementRule, SettlementCondition, SettlementAction } from '../../../services/auto-settlement.service';

@Component({
  selector: 'app-auto-settlement-config',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    MatCardModule,
    MatButtonModule,
    MatIconModule,
    MatExpansionModule,
    MatSelectModule,
    MatInputModule,
    MatCheckboxModule,
    MatSlideToggleModule,
    MatDialogModule
  ],
  templateUrl: './auto-settlement-config.html',
  styleUrls: ['./auto-settlement-config.scss']
})
export class AutoSettlementConfigComponent implements OnInit {
  rules = signal<AutoSettlementRule[]>([]);
  expandedPanels = signal<Set<string>>(new Set());
  isAddingNew = signal(false);
  
  // 条件类型选项
  conditionTypes = [
    { value: 'amountRange', label: '金额范围' },
    { value: 'overdueDays', label: '逾期天数' },
    { value: 'customerTier', label: '客户层级' },
    { value: 'projectType', label: '项目类型' },
    { value: 'paymentMethod', label: '支付方式' }
  ];

  // 操作符选项
  operators = [
    { value: 'equals', label: '等于' },
    { value: 'greaterThan', label: '大于' },
    { value: 'lessThan', label: '小于' },
    { value: 'between', label: '介于' },
    { value: 'contains', label: '包含' }
  ];

  // 动作类型选项
  actionTypes = [
    { value: 'sendReminder', label: '发送提醒' },
    { value: 'applyDiscount', label: '应用折扣' },
    { value: 'extendDueDate', label: '延长期限' },
    { value: 'autoConfirm', label: '自动确认' },
    { value: 'notifyManager', label: '通知经理' }
  ];

  // 新规则模板
  newRule: AutoSettlementRule = {
    id: '',
    name: '',
    enabled: true,
    priority: 5,
    conditions: [],
    actions: [],
    description: ''
  };

  constructor(private autoSettlementService: AutoSettlementService) {}

  ngOnInit() {
    this.loadRules();
  }

  // 加载规则
  loadRules() {
    this.autoSettlementService.getRules().subscribe(rules => {
      this.rules.set(rules);
    });
  }

  // 切换面板展开状态
  togglePanel(ruleId: string) {
    const panels = new Set(this.expandedPanels());
    if (panels.has(ruleId)) {
      panels.delete(ruleId);
    } else {
      panels.add(ruleId);
    }
    this.expandedPanels.set(panels);
  }

  // 添加新条件
  addCondition(rule: AutoSettlementRule) {
    const newCondition: SettlementCondition = {
      type: 'amountRange',
      operator: 'greaterThan',
      value: 0
    };
    rule.conditions.push(newCondition);
  }

  // 删除条件
  removeCondition(rule: AutoSettlementRule, index: number) {
    rule.conditions.splice(index, 1);
  }

  // 添加新动作
  addAction(rule: AutoSettlementRule) {
    const newAction: SettlementAction = {
      type: 'sendReminder',
      params: {}
    };
    rule.actions.push(newAction);
  }

  // 删除动作
  removeAction(rule: AutoSettlementRule, index: number) {
    rule.actions.splice(index, 1);
  }

  // 保存规则
  saveRule(rule: AutoSettlementRule) {
    if (rule.id) {
      this.autoSettlementService.updateRule(rule.id, rule);
    } else {
      rule.id = `rule-${Date.now()}`;
      this.autoSettlementService.addRule(rule);
    }
    this.cancelAddNew();
  }

  // 删除规则
  deleteRule(ruleId: string) {
    if (confirm('确定要删除这条规则吗？')) {
      this.autoSettlementService.deleteRule(ruleId);
      this.loadRules();
    }
  }

  // 启用/禁用规则
  toggleRule(rule: AutoSettlementRule) {
    rule.enabled = !rule.enabled;
    this.autoSettlementService.updateRule(rule.id, { enabled: rule.enabled });
  }

  // 开始添加新规则
  startAddNew() {
    this.isAddingNew.set(true);
    this.newRule = {
      id: '',
      name: '',
      enabled: true,
      priority: 5,
      conditions: [],
      actions: [],
      description: ''
    };
  }

  // 取消添加新规则
  cancelAddNew() {
    this.isAddingNew.set(false);
  }

  // 获取条件操作符选项
  getOperatorOptions(conditionType: string) {
    switch (conditionType) {
      case 'amountRange':
      case 'overdueDays':
        return this.operators.filter(op => 
          ['equals', 'greaterThan', 'lessThan', 'between'].includes(op.value)
        );
      case 'customerTier':
      case 'projectType':
      case 'paymentMethod':
        return this.operators.filter(op => 
          ['equals', 'contains'].includes(op.value)
        );
      default:
        return this.operators;
    }
  }

  // 获取动作参数配置
  getActionParamsConfig(actionType: string) {
    switch (actionType) {
      case 'sendReminder':
        return {
          channels: ['wechat', 'sms', 'email', 'system'],
          frequency: ['immediate', 'daily', 'weekly']
        };
      case 'applyDiscount':
        return {
          type: ['percentage', 'fixed'],
          maxAmount: 1000
        };
      case 'extendDueDate':
        return {
          days: 7
        };
      case 'autoConfirm':
        return {
          immediate: true
        };
      case 'notifyManager':
        return {
          threshold: 10000
        };
      default:
        return {};
    }
  }

  // 格式化条件显示
  formatCondition(condition: SettlementCondition): string {
    switch (condition.type) {
      case 'amountRange':
        return `金额 ${this.getOperatorLabel(condition.operator)} ${condition.value}`;
      case 'overdueDays':
        return `逾期天数 ${this.getOperatorLabel(condition.operator)} ${condition.value}`;
      case 'customerTier':
        return `客户层级 ${this.getOperatorLabel(condition.operator)} ${condition.value}`;
      default:
        return `${condition.type} ${condition.operator} ${condition.value}`;
    }
  }

  // 格式化动作显示
  formatAction(action: SettlementAction): string {
    switch (action.type) {
      case 'sendReminder':
        return '发送提醒';
      case 'applyDiscount':
        return '应用折扣';
      case 'extendDueDate':
        return '延长期限';
      case 'autoConfirm':
        return '自动确认';
      case 'notifyManager':
        return '通知经理';
      default:
        return action.type;
    }
  }

  // 获取操作符标签
  private getOperatorLabel(operator: string): string {
    const op = this.operators.find(o => o.value === operator);
    return op ? op.label : operator;
  }
}