import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'expense_apply_model.dart';

final expenseApplyStatusFilterProvider = StateProvider<String>((ref) => '');
final expenseApplyPageProvider = StateProvider<int>((ref) => 1);
final expenseApplyScopeProvider = StateProvider<String>((ref) => 'mine');
final expenseApplyDateStartProvider = StateProvider<DateTime?>((ref) => null);
final expenseApplyDateEndProvider = StateProvider<DateTime?>((ref) => null);
final expenseApplyKeywordProvider = StateProvider<String>((ref) => '');
final expenseApplyTypeFilterProvider = StateProvider<String?>((ref) => null);
final expenseApplyUrgencyFilterProvider = StateProvider<String?>((ref) => null);
final expenseApplyRefreshProvider = StateProvider<int>((ref) => 0);
final expenseApplySortDirProvider = StateProvider<String>((ref) => 'DESC');

final now = DateTime.now();
final mockExpenseApplies = <ExpenseApplyModel>[
  ExpenseApplyModel(
    id: 'EA001', expenseApplyNo: 'BXSQ-20240501-001', applicantId: 'U001',
    applicantName: '张三', deptId: 'D001', deptName: '销售部', estimatedAmount: 3500.0,
    purpose: '上海出差拜访客户', status: 'pending', urgency: 'normal', version: 1,
    validUntil: DateTime(2024, 6, 30), usageStatus: 'unused',
    createTime: DateTime(2024, 5, 1, 14, 30), updateTime: DateTime(2024, 5, 1, 14, 30),
    details: [
      ExpenseApplyDetailModel(id: 'd1-1', expenseCategory: 'transport', purpose: '往返机票',
          projectId: 'P001', projectName: '华东销售项目', costDeptId: 'D001', costDeptName: '销售部',
          acctSubjectId: '550201', acctSubjectName: '差旅费-交通', estimatedAmount: 2000.0,
          estimatedStartDate: DateTime(2024, 5, 10), estimatedEndDate: DateTime(2024, 5, 12),
          remark: '经济舱往返', createTime: now, updateTime: now),
      ExpenseApplyDetailModel(id: 'd1-2', expenseCategory: 'hotel', purpose: '酒店住宿',
          projectId: 'P001', projectName: '华东销售项目', costDeptId: 'D001', costDeptName: '销售部',
          acctSubjectId: '550202', acctSubjectName: '差旅费-住宿', estimatedAmount: 1500.0,
          estimatedStartDate: DateTime(2024, 5, 10), estimatedEndDate: DateTime(2024, 5, 12),
          remark: '3晚', createTime: now, updateTime: now),
    ],
    attachments: ['发票_机票.pdf', '发票_酒店.pdf'],
  ),
  ExpenseApplyModel(
    id: 'EA002', expenseApplyNo: 'BXSQ-20240428-002', applicantId: 'U002',
    applicantName: '李四', deptId: 'D002', deptName: '技术部', estimatedAmount: 1560.0,
    purpose: '采购开发板及配件', status: 'approved', urgency: 'urgent', version: 1,
    validUntil: DateTime(2024, 5, 31), usageStatus: 'partially_used',
    createTime: DateTime(2024, 4, 28, 9, 15), updateTime: DateTime(2024, 4, 29, 10, 0),
    details: [
      ExpenseApplyDetailModel(id: 'd2-1', expenseCategory: 'equipment', purpose: 'ARM开发板×2',
          projectId: 'P002', projectName: '智能硬件研发', costDeptId: 'D002', costDeptName: '技术部',
          acctSubjectId: '550301', acctSubjectName: '研发费用-设备', estimatedAmount: 1200.0,
          remark: '树莓派替代方案', createTime: now, updateTime: now),
      ExpenseApplyDetailModel(id: 'd2-2', expenseCategory: 'equipment', purpose: '传感器模块',
          projectId: 'P002', projectName: '智能硬件研发', costDeptId: 'D002', costDeptName: '技术部',
          acctSubjectId: '550301', acctSubjectName: '研发费用-设备', estimatedAmount: 360.0,
          createTime: now, updateTime: now),
    ],
    attachments: ['采购清单.pdf'],
  ),
  ExpenseApplyModel(
    id: 'EA003', expenseApplyNo: 'BXSQ-20240425-003', applicantId: 'U003',
    applicantName: '王五', deptId: 'D003', deptName: '市场部', estimatedAmount: 5000.0,
    purpose: '客户答谢晚宴', status: 'rejected', urgency: 'normal', version: 1,
    referenceNo: 'HT-20240420-001', usageStatus: 'unused',
    createTime: DateTime(2024, 4, 25, 16, 0), updateTime: DateTime(2024, 4, 26, 11, 0),
    details: [
      ExpenseApplyDetailModel(id: 'd3-1', expenseCategory: 'meals', purpose: '晚宴餐费',
          projectId: 'P003', projectName: '品牌推广', costDeptId: 'D003', costDeptName: '市场部',
          acctSubjectId: '550401', acctSubjectName: '业务招待费', estimatedAmount: 4000.0,
          estimatedStartDate: DateTime(2024, 4, 30), estimatedEndDate: DateTime(2024, 4, 30),
          createTime: now, updateTime: now),
      ExpenseApplyDetailModel(id: 'd3-2', expenseCategory: 'gift', purpose: '伴手礼',
          projectId: 'P003', projectName: '品牌推广', costDeptId: 'D003', costDeptName: '市场部',
          acctSubjectId: '550401', acctSubjectName: '业务招待费', estimatedAmount: 1000.0,
          createTime: now, updateTime: now),
    ],
    attachments: ['餐厅预订确认.png', '礼品清单.xlsx'],
  ),
  ExpenseApplyModel(
    id: 'EA004', expenseApplyNo: 'BXSQ-20240601-004', applicantId: 'U001',
    applicantName: '张三', deptId: 'D001', deptName: '销售部', estimatedAmount: 12000.0,
    purpose: '年度销售总结大会', status: 'draft', urgency: 'normal', version: 1,
    validUntil: DateTime(2024, 7, 31), remark: '需要提前一周预订场地',
    createTime: DateTime(2024, 6, 1, 9, 0), updateTime: DateTime(2024, 6, 1, 9, 0),
    details: [
      ExpenseApplyDetailModel(id: 'd4-1', expenseCategory: 'service', purpose: '场地租赁',
          projectId: 'P001', projectName: '华东销售项目', costDeptId: 'D001', costDeptName: '销售部',
          acctSubjectId: '550501', acctSubjectName: '会务费', estimatedAmount: 5000.0,
          estimatedStartDate: DateTime(2024, 7, 15), estimatedEndDate: DateTime(2024, 7, 16),
          createTime: now, updateTime: now),
      ExpenseApplyDetailModel(id: 'd4-2', expenseCategory: 'meals', purpose: '茶歇及午餐',
          projectId: 'P001', projectName: '华东销售项目', costDeptId: 'D001', costDeptName: '销售部',
          acctSubjectId: '550501', acctSubjectName: '会务费', estimatedAmount: 3000.0,
          createTime: now, updateTime: now),
      ExpenseApplyDetailModel(id: 'd4-3', expenseCategory: 'office', purpose: '打印物料',
          projectId: 'P001', projectName: '华东销售项目', costDeptId: 'D001', costDeptName: '销售部',
          acctSubjectId: '550601', acctSubjectName: '办公费', estimatedAmount: 4000.0,
          remark: '会议手册+展架', createTime: now, updateTime: now),
    ],
    attachments: ['场地合同.pdf', '报价单.xlsx', '设计稿.png'],
  ),
  ExpenseApplyModel(
    id: 'EA005', expenseApplyNo: 'BXSQ-20240602-005', applicantId: 'U001',
    applicantName: '张三', deptId: 'D001', deptName: '销售部', estimatedAmount: 8000.0,
    purpose: '广州出差并拜访重要客户', status: 'pending', urgency: 'urgent', version: 1,
    validUntil: DateTime(2024, 7, 15), usageStatus: 'unused',
    createTime: DateTime(2024, 6, 2, 11, 0), updateTime: DateTime(2024, 6, 2, 11, 0),
    currentApproverId: 'M001',
    details: [
      ExpenseApplyDetailModel(id: 'd5-1', expenseCategory: 'transport', purpose: '往返高铁',
          projectId: 'P004', projectName: '华南市场拓展', costDeptId: 'D001', costDeptName: '销售部',
          acctSubjectId: '550201', acctSubjectName: '差旅费-交通', estimatedAmount: 1800.0,
          estimatedStartDate: DateTime(2024, 6, 15), estimatedEndDate: DateTime(2024, 6, 18),
          createTime: now, updateTime: now),
      ExpenseApplyDetailModel(id: 'd5-2', expenseCategory: 'hotel', purpose: '酒店住宿',
          projectId: 'P004', projectName: '华南市场拓展', costDeptId: 'D001', costDeptName: '销售部',
          acctSubjectId: '550202', acctSubjectName: '差旅费-住宿', estimatedAmount: 2400.0,
          estimatedStartDate: DateTime(2024, 6, 15), estimatedEndDate: DateTime(2024, 6, 18),
          createTime: now, updateTime: now),
      ExpenseApplyDetailModel(id: 'd5-3', expenseCategory: 'meals', purpose: '客户商务宴请',
          projectId: 'P004', projectName: '华南市场拓展', costDeptId: 'D001', costDeptName: '销售部',
          acctSubjectId: '550401', acctSubjectName: '业务招待费', estimatedAmount: 3800.0,
          estimatedStartDate: DateTime(2024, 6, 16), estimatedEndDate: DateTime(2024, 6, 16),
          remark: '预计6人', createTime: now, updateTime: now),
    ],
    attachments: ['行程单.pdf'],
  ),
  ExpenseApplyModel(
    id: 'EA006', expenseApplyNo: 'BXSQ-20240610-006', applicantId: 'U001',
    applicantName: '张三', deptId: 'D001', deptName: '销售部', estimatedAmount: 1500.0,
    purpose: '部门办公设备采购（已撤回）', status: 'withdrawn', urgency: 'normal', version: 1,
    createTime: DateTime(2024, 6, 10, 9, 0), updateTime: DateTime(2024, 6, 11, 10, 0),
  ),
];

final expenseApplyListProvider = FutureProvider
    .family<List<ExpenseApplyModel>, String>((ref, status) async {
  ref.watch(expenseApplyPageProvider);
  ref.watch(expenseApplyRefreshProvider);
  ref.watch(expenseApplyDateStartProvider);
  ref.watch(expenseApplyDateEndProvider);
  ref.watch(expenseApplyTypeFilterProvider);
  ref.watch(expenseApplyUrgencyFilterProvider);
  ref.watch(expenseApplyKeywordProvider);
  await Future.delayed(const Duration(milliseconds: 1000));

  var list = status.isEmpty
      ? mockExpenseApplies
      : mockExpenseApplies.where((e) => e.status == status).toList();

  final dateStart = ref.read(expenseApplyDateStartProvider);
  final dateEnd = ref.read(expenseApplyDateEndProvider);
  if (dateStart != null) {
    list = list.where((e) => e.createTime.isAfter(dateStart.subtract(const Duration(days: 1)))).toList();
  }
  if (dateEnd != null) {
    list = list.where((e) => e.createTime.isBefore(dateEnd.add(const Duration(days: 1)))).toList();
  }

  final urgencyFilter = ref.read(expenseApplyUrgencyFilterProvider);
  if (urgencyFilter != null && urgencyFilter.isNotEmpty) {
    list = list.where((e) => e.urgency == urgencyFilter).toList();
  }

  final keyword = ref.read(expenseApplyKeywordProvider);
  if (keyword.isNotEmpty) {
    final kw = keyword.toLowerCase();
    list = list.where((e) =>
      e.expenseApplyNo.toLowerCase().contains(kw) ||
      e.purpose.toLowerCase().contains(kw) ||
      e.applicantName.toLowerCase().contains(kw)
    ).toList();
  }

  return list;
});
