package com.gxwebsoft.sdy.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.sdy.param.SdyDealerOrderImportParam;
import com.gxwebsoft.shop.entity.*;
import com.gxwebsoft.shop.service.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 售电云分销订单控制器
 *
 * @author 科技小王子
 * @since 2025-08-12 11:55:18
 */
@Tag(name = "售电云分销订单管理")
@RestController
@RequestMapping("/api/sdy/sdy-dealer-order")
public class SdyDealerOrderController extends BaseController {
    @Resource
    private ShopDealerOrderService shopDealerOrderService;
    @Resource
    private ShopDealerApplyService shopDealerApplyService;
    @Resource
    private ShopDealerRefereeService shopDealerRefereeService;
    @Resource
    private ShopDealerCapitalService shopDealerCapitalService;
    @Resource
    private ShopDealerUserService shopDealerUserService;

    /**
     * excel批量导入售电云分销订单
     */
    @PreAuthorize("hasAuthority('shop:shopDealerOrder:save')")
    @OperationLog
    @Operation(summary = "批量导入售电云分销订单")
    @Transactional(rollbackFor = {Exception.class})
    @PostMapping("/import")
    public ApiResult<List<String>> importBatch(MultipartFile file) {
        ImportParams importParams = new ImportParams();
        try {
            System.out.println("开始导入数据...");
            System.out.println("文件大小: " + (file != null ? file.getSize() : "null"));

            // 导入XLS文件的内容
            List<SdyDealerOrderImportParam> list = ExcelImportUtil.importExcel(file.getInputStream(), SdyDealerOrderImportParam.class, importParams);

            // 打印导入的数据条数用于调试
            System.out.println("导入数据条数: " + (list != null ? list.size() : 0));

            // 打印第一条数据用于调试
            if (list != null && !list.isEmpty()) {
                SdyDealerOrderImportParam first = list.get(0);
                System.out.println("第一条数据: " + first);
                System.out.println("title: " + first.getTitle());
                System.out.println("userId: " + first.getUserId());
            }

            if (list == null || list.isEmpty()) {
                return fail("未读取到任何数据，请检查Excel文件格式和数据行位置", null);
            }

            int importedCount = 0;

            for (SdyDealerOrderImportParam d : list) {
                // 检查是否已存在相同的记录（根据comments字段和未结算状态）
                com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ShopDealerOrder> queryWrapper = new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
                queryWrapper.eq(ShopDealerOrder::getTitle, d.getTitle()); // 使用comments字段
                queryWrapper.eq(ShopDealerOrder::getIsSettled, 0); // 未结算状态

                if (shopDealerOrderService.count(queryWrapper) == 0) {
                    // 不存在相同记录，可以导入
                    ShopDealerOrder item = new ShopDealerOrder();

                    // 生成订单号
                    String orderNo = Long.toString(IdUtil.getSnowflakeNextId());

                    // 手动映射字段
                    item.setUserId(d.getUserId());
                    item.setOrderNo(orderNo);
                    item.setOrderPrice(d.getOrderPrice());
                    item.setDegreePrice(d.getOrderPrice().multiply(new BigDecimal(1000)));
                    item.setFirstUserId(d.getFirstUserId());
                    item.setSecondUserId(d.getSecondUserId());
                    item.setThirdUserId(d.getThirdUserId());
                    item.setFirstMoney(d.getFirstMoney());
                    item.setSecondMoney(d.getSecondMoney());
                    item.setThirdMoney(d.getThirdMoney());
                    item.setTenantId(d.getTenantId());
                    item.setTitle(d.getTitle());
                    item.setComments(d.getComments());
                    // 假设d.getPrice()返回的BigDecimal未设置精度
                    item.setPrice(d.getPrice());
                    item.setSettledPrice(d.getSettledPrice());
                    item.setPayPrice(d.getPayPrice());
                    item.setRate(d.getRate());
                    item.setMonth(d.getMonth());
                    item.setIsInvalid(0);
                    item.setIsSettled(0); // 新导入的数据设为未结算

                    System.out.println("准备导入数据: " + item);
                    if (ObjectUtil.isNotEmpty(item)) {
                        shopDealerOrderService.save(item);
                        importedCount++;
                    }
                } else {
                    System.out.println("跳过重复数据: " + d.getComments());
                }
            }
            return success("成功导入" + importedCount + "条，重复或已存在" + (list.size() - importedCount) + "条", null);
        } catch (Exception e) {
            e.printStackTrace();
            return fail("导入失败: " + e.getMessage(), null);
        }
    }

    @PreAuthorize("hasAuthority('shop:shopDealerOrder:update')")
    @Operation(summary = "结算订单")
    @PutMapping()
    public ApiResult<?> saveSettled(@RequestBody ShopDealerOrder shopDealerOrder) {
      shopDealerOrder.setSettleTime(LocalDateTime.now());
      shopDealerOrder.setIsSettled(1);
      if (shopDealerOrderService.updateById(shopDealerOrder)) {

        // 一级分成
        ShopDealerUser dealerUser = shopDealerUserService.getByUserIdRel(shopDealerOrder.getFirstUserId());
        dealerUser.setMoney(dealerUser.getMoney().add(shopDealerOrder.getFirstMoney()));
        if(shopDealerUserService.updateById(dealerUser)){
          System.out.println("一级分成 = 1");
          ShopDealerCapital shopDealerCapital = new ShopDealerCapital();
          shopDealerCapital.setUserId(shopDealerOrder.getFirstUserId());
          shopDealerCapital.setOrderNo(shopDealerOrder.getOrderNo());
          shopDealerCapital.setMoney(shopDealerOrder.getFirstMoney());
          shopDealerCapital.setMonth(shopDealerOrder.getMonth());
          shopDealerCapital.setComments("分销订单结算");
          shopDealerCapital.setToUserId(shopDealerOrder.getUserId());
          shopDealerCapitalService.save(shopDealerCapital);
        }

        // 二级分成
        ShopDealerUser dealerUser2 = shopDealerUserService.getByUserIdRel(shopDealerOrder.getSecondUserId());
        if(ObjectUtil.isNotEmpty(dealerUser2)){
          dealerUser2.setMoney(dealerUser2.getMoney().add(shopDealerOrder.getSecondMoney()));
          if (shopDealerUserService.updateById(dealerUser2)) {
            System.out.println("二级分成 = 2");
            ShopDealerCapital shopDealerCapital2 = new ShopDealerCapital();
            shopDealerCapital2.setUserId(shopDealerOrder.getSecondUserId());
            shopDealerCapital2.setOrderNo(shopDealerOrder.getOrderNo());
            shopDealerCapital2.setMoney(shopDealerOrder.getSecondMoney());
            shopDealerCapital2.setMonth(shopDealerOrder.getMonth());
            shopDealerCapital2.setComments("分销订单结算");
            shopDealerCapital2.setToUserId(shopDealerOrder.getUserId());
            shopDealerCapitalService.save(shopDealerCapital2);
          }
        }

        // 三级分成
        ShopDealerUser dealerUser3 = shopDealerUserService.getByUserIdRel(shopDealerOrder.getThirdUserId());
        if(ObjectUtil.isNotEmpty(dealerUser3)){
          dealerUser3.setMoney(dealerUser3.getMoney().add(shopDealerOrder.getThirdMoney()));
          if (shopDealerUserService.updateById(dealerUser3)) {
            System.out.println("三级分成 = 3");
            ShopDealerCapital shopDealerCapital3 = new ShopDealerCapital();
            shopDealerCapital3.setUserId(shopDealerOrder.getThirdUserId());
            shopDealerCapital3.setOrderNo(shopDealerOrder.getOrderNo());
            shopDealerCapital3.setMoney(shopDealerOrder.getThirdMoney());
            shopDealerCapital3.setMonth(shopDealerOrder.getMonth());
            shopDealerCapital3.setComments("分销订单结算");
            shopDealerCapital3.setToUserId(shopDealerOrder.getUserId());
            shopDealerCapitalService.save(shopDealerCapital3);
          }
        }

        return success("结算成功");
      }
      return fail("结算失败");
    }
}
