package com.ycwl.basic.profitsharing.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ycwl.basic.integration.scenic.dto.scenic.ScenicV2DTO;
import com.ycwl.basic.profitsharing.dto.ProfitSharingConfigReqQuery;
import com.ycwl.basic.profitsharing.dto.ProfitSharingConfigVO;
import com.ycwl.basic.profitsharing.entity.ProfitSharingConfig;
import com.ycwl.basic.profitsharing.entity.ProfitSharingUser;
import com.ycwl.basic.profitsharing.mapper.ProfitSharingConfigMapper;
import com.ycwl.basic.profitsharing.mapper.ProfitSharingUserMapper;
import com.ycwl.basic.repository.ScenicRepository;
import com.ycwl.basic.utils.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/profitSharingConfig/v1")
public class ProfitSharingConfigController {

    @Autowired
    private ProfitSharingConfigMapper configMapper;
    @Autowired
    private ProfitSharingUserMapper userMapper;
    @Autowired
    private ScenicRepository scenicRepository;

    // 新增: 分页查询接口
    @PostMapping("/page")
    public ApiResponse<PageInfo<ProfitSharingConfigVO>> pageQuery(@RequestBody ProfitSharingConfigReqQuery req) {
        PageHelper.startPage(req.getPageNum(), req.getPageSize());
        List<ProfitSharingConfigVO> list = configMapper.list(req);
        list.forEach(item -> {
            try {
                ScenicV2DTO scenicBasic = scenicRepository.getScenicBasic(item.getScenicId());
                item.setScenicName(scenicBasic.getName());
            } catch (Exception e) {
                item.setScenicName("");
            }
        });
        PageInfo<ProfitSharingConfigVO> pageInfo = new PageInfo<>(list);
        return ApiResponse.success(pageInfo);
    }
    // 增加: 插入新的ProfitSharingConfig记录
    @PostMapping("/add")
    public ApiResponse addConfig(@RequestBody ProfitSharingConfig config) {
        // 检查是否存在相同 scenicId 的配置
        ProfitSharingConfig existingConfig = configMapper.findByScenicId(config.getScenicId());
        if (existingConfig != null) {
            return ApiResponse.fail("该景区已存在配置");
        }
        config.setCreateTime(new Date());
        config.setUpdateTime(new Date());
        configMapper.insert(config);
        // 获取生成的 configId
        Long configId = config.getId();
        // 插入 users 列表
        if (config.getUsers() != null) {
            // 提前检查，避免realRate总和超过100
            BigDecimal totalPercentage = BigDecimal.ZERO;
            for (ProfitSharingUser user : config.getUsers()) {
                totalPercentage = totalPercentage.add(user.getRealRate());
            }
            if (totalPercentage.compareTo(BigDecimal.valueOf(100)) > 0) {
                return ApiResponse.fail("分账比例总和超过100%");
            }
            for (ProfitSharingUser user : config.getUsers()) {
                user.setConfigId(configId);
                userMapper.insert(user);
            }
        }
        return ApiResponse.success("配置添加成功");
    }

    @DeleteMapping("/delete/{id}")
    public ApiResponse deleteConfig(@PathVariable Long id) {
        configMapper.deleteById(id);
        return ApiResponse.success("配置删除成功");
    }

    // 更新: 更新指定ID的ProfitSharingConfig记录
    @PutMapping("/update")
    public ApiResponse updateConfig(@RequestBody ProfitSharingConfig config) {
        // 更新 ProfitSharingConfig 记录
        configMapper.update(config);
        // 获取 configId
        Long configId = config.getId();
        if (configId == null) {
            return ApiResponse.fail("configId不能为空");
        }
        // 插入新的 users 列表
        if (config.getUsers() != null) {
            // 提前检查，避免realRate总和超过100
            BigDecimal totalPercentage = BigDecimal.ZERO;
            for (ProfitSharingUser user : config.getUsers()) {
                totalPercentage = totalPercentage.add(user.getRealRate());
            }
            if (totalPercentage.compareTo(BigDecimal.valueOf(100)) > 0) {
                return ApiResponse.fail("分账比例总和超过100%");
            }
            // 删除原有 users 列表
            userMapper.deleteByConfigId(configId);
            for (ProfitSharingUser user : config.getUsers()) {
                user.setConfigId(configId);
                userMapper.insert(user);
            }
        }
        return ApiResponse.success("配置更新成功");
    }

    @GetMapping("/{id}")
    public ApiResponse findById(@PathVariable Long id) {
        ProfitSharingConfig config = configMapper.findById(id);
        config.setUsers(userMapper.findByConfigId(id));
        return ApiResponse.success(config);
    }

    // 查询: 查询所有记录
    @GetMapping("/findAll")
    public ApiResponse findAllConfigs() {
        List<ProfitSharingConfig> configs = configMapper.findAll();
        return ApiResponse.success(configs);
    }

    // 查询: 根据scenicId查询单个记录
    @GetMapping("/scenicId/{scenicId}")
    public ApiResponse findByScenicId(@PathVariable Long scenicId) {
        ProfitSharingConfig config = configMapper.findByScenicId(scenicId);
        if (config == null) {
            config = new ProfitSharingConfig();
            config.setScenicId(scenicId);
            config.setName("默认配置");
            config.setCreateTime(new Date());
            config.setUpdateTime(new Date());
            configMapper.insert(config);
        }
        config.setUsers(userMapper.findByConfigId(config.getId()));
        return ApiResponse.success(config);
    }
}
