package com.rj.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rj.common.DataEnrichmentUtil;
import com.rj.common.PasswordUtil;
import com.rj.entity.Dealership;
import com.rj.entity.ProjectManagement;
import com.rj.entity.SalesManagement;
import com.rj.entity.sys.User;
import com.rj.service.IDealershipService;
import com.rj.service.IProjectManagementService;
import com.rj.service.ISalesManagementService;
import com.rj.service.sys.IUserService;
import com.rj.controller.sys.UserController;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 销售管理表 前端控制器
 * </p>
 *
 * @author 李中华 ,spllzh
 * @since 2025-08-07
 */
@RestController
@RequestMapping("/api/salesManagement")
@Tag(name = "销售管理", description = "销售管理相关接口")
public class SalesManagementController {

    @Autowired
    private ISalesManagementService salesManagementService;

    @Autowired
    private IUserService userService;

    @Autowired
    private UserController userController;

    /**
     * 新增销售
     */
    @PostMapping("/add")
    @Operation(summary = "新增销售", description = "添加新的销售信息")
    public ResponseEntity<Map<String, Object>> addSales(
            @Parameter(description = "销售信息", required = true)
            @RequestBody SalesManagement salesManagement) {
        Map<String, Object> result = new HashMap<>();
        try {
            salesManagement.setCreateTime(LocalDateTime.now());
            salesManagement.setUpdateTime(LocalDateTime.now());
            boolean success = salesManagementService.save(salesManagement);
            if (success) {
                // 原有逻辑处理完成后，创建用户管理模块的用户
                try {
                    createUserForSales(salesManagement);
                } catch (Exception userException) {
                    // 用户创建失败不影响销售人员创建成功，只记录日志
                    System.err.println("创建用户失败：" + userException.getMessage());
                }
                
                result.put("success", true);
                result.put("message", "销售添加成功");
                result.put("data", salesManagement);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "销售添加失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "销售添加异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 为销售人员创建用户管理模块的用户
     */
    private void createUserForSales(SalesManagement salesManagement) {
        // 检查销售人员是否有联系方式（登录账号）
        if (salesManagement.getLoginAccount() == null || salesManagement.getLoginAccount().trim().isEmpty()) {
            throw new RuntimeException("销售人员联系方式不能为空");
        }
        
        String phone = salesManagement.getLoginAccount();

        User oldUser = userService.getUserByUserName(phone);
        // 创建用户对象
        User newUser = new User();
        ResponseEntity<Map<String, Object>> response = ResponseEntity.ok(new HashMap<>());
        if (oldUser == null){

//        user.setUserId(salesManagement.getId().hashCode());
            newUser.setUserName(phone); // 用户名 = 销售人员电话
            newUser.setPhone(phone);    // 电话号码 = 销售人员电话
            newUser.setOriginalPassword(salesManagement.getPassword());
            newUser.setPassword(salesManagement.getPassword()); // 设置密码（UserController会自动加密）
            newUser.setEmail(phone+"@YiDuoWang.com");
            newUser.setTenantId(salesManagement.getTenantId());
            // 调用UserController的addUser方法保存用户
              response = userController.addUser(newUser);
        }else {
            oldUser.setPhone(phone);    // 电话号码 = 销售人员电话
            oldUser.setOriginalPassword(salesManagement.getPassword());
//        encryptPassword(inputPassword,DEFAULT_SALT);
            oldUser.setPassword(salesManagement.getPassword()); // 设置密码（UserController会自动加密）
            oldUser.setTenantId(salesManagement.getTenantId());
            userController.updateUser(oldUser);
        }


        
        // 检查响应结果
        if (response.getBody() != null) {
            Map<String, Object> result = response.getBody();
            Boolean success = (Boolean) result.get("success");
            if (success == null || !success) {
                String message = (String) result.get("message");
                throw new RuntimeException("用户创建失败：" + (message != null ? message : "未知错误"));
            }
        } else {
            throw new RuntimeException("用户创建失败：响应为空");
        }
    }
    
    /**
     * 生成销售人员密码：当前日期 + 联系方式后4位
     */
    private String generatePasswordForSales(String phone) {
        // 获取当前日期，格式：yyyyMMdd
        String currentDate = LocalDate.now().format(DateTimeFormatter.ofPattern("MMdd"));
        
        // 获取联系方式后4位
        String lastFourDigits = "";
        if (phone != null && phone.length() >= 4) {
            lastFourDigits = phone.substring(phone.length() - 4);
        } else {
            lastFourDigits = phone; // 如果长度不足4位，使用全部
        }
        
        return currentDate + lastFourDigits;
    }

    /**
     * 根据ID查询销售
     */
    @GetMapping("/get/{id}")
    @Operation(summary = "根据ID查询销售", description = "根据销售ID获取销售详细信息")
    public ResponseEntity<Map<String, Object>> getSalesById(
            @Parameter(description = "销售ID", required = true)
            @PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            SalesManagement sales = salesManagementService.getById(id);
            if (sales != null) {
                result.put("success", true);
                result.put("message", "查询成功");
                result.put("data", sales);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "销售不存在");
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据登录账号查询销售
     */
    @GetMapping("/getByAccount")
    @Operation(summary = "根据登录账号查询销售", description = "根据销售登录账号查询销售信息")
    public ResponseEntity<Map<String, Object>> getSalesByAccount(
            @Parameter(description = "登录账号", required = true)
            @RequestParam String loginAccount) {
        Map<String, Object> result = new HashMap<>();
        try {
            LambdaQueryWrapper<SalesManagement> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.like(SalesManagement::getLoginAccount, loginAccount);
            List<SalesManagement> salesList = salesManagementService.list(queryWrapper);
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", salesList);
            result.put("count", salesList.size());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @Autowired
    private DataEnrichmentUtil dataEnrichmentUtil;

    /**
     * 分页查询销售列表
     */
    @GetMapping("/list")
    @Operation(summary = "分页查询销售列表", description = "分页查询销售信息列表")
    public ResponseEntity<Map<String, Object>> getSalesList(
            @Parameter(description = "页码", example = "1")
            @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小", example = "10")
            @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "销售名称（模糊查询）")
            @RequestParam(required = false) String salesName,
            @Parameter(description = "登录账号（模糊查询）")
            @RequestParam(required = false) String salesPhone,
            @Parameter(description = "所属门店ID")
            @RequestParam(required = false) String dealershipId,
            @Parameter(description = "销售状态")
            @RequestParam(required = false) Boolean status,
            @Parameter(description = "角色")
            @RequestParam(required = false) String role) {
        Map<String, Object> result = new HashMap<>();
        try {
            Page<SalesManagement> page = new Page<>(current, size);
            LambdaQueryWrapper<SalesManagement> queryWrapper = new LambdaQueryWrapper<>();
            
            // 添加查询条件
            if (salesName != null && !salesName.trim().isEmpty()) {
                queryWrapper.like(SalesManagement::getSalesName, salesName);
            }
            if (salesPhone != null && !salesPhone.trim().isEmpty()) {
                queryWrapper.like(SalesManagement::getLoginAccount, salesPhone);
            }
            if (dealershipId != null && !dealershipId.trim().isEmpty()) {
                queryWrapper.eq(SalesManagement::getDealershipId, dealershipId);
            }
            if (status != null) {
                queryWrapper.eq(SalesManagement::getStatus, status);
            }
            if (role != null && !role.trim().isEmpty()) {
                queryWrapper.eq(SalesManagement::getRole, role);
            }
            
            // 按创建时间倒序排列
            queryWrapper.orderByDesc(SalesManagement::getCreateTime);
            
            Page<SalesManagement> salesPage = salesManagementService.page(page, queryWrapper);

            //  4S店 提取ID列表 ， 项目ID列表
            List<String> dealershipIds = DataEnrichmentUtil.extractIds(salesPage.getRecords(), SalesManagement::getDealershipId);
            List<String> projectIds = DataEnrichmentUtil.extractIds(salesPage.getRecords(), SalesManagement::getProjectId);

            // 使用工具类批量获取关联数据
            Map<String, String> dealershipNameMap = dataEnrichmentUtil.getDealershipIdNameMap(dealershipIds);
            Map<String, String> projectNameMap = dataEnrichmentUtil.getProjectIdNameMap(projectIds);

            // 填充关联数据
            salesPage.getRecords().forEach(sales -> {
                sales.setDealershipName(dealershipNameMap.get(sales.getDealershipId()));
                sales.setProjectName(projectNameMap.get(sales.getProjectId()));
            });

            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", salesPage.getRecords());
            result.put("total", salesPage.getTotal());
            result.put("current", salesPage.getCurrent());
            result.put("size", salesPage.getSize());
            result.put("pages", salesPage.getPages());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 更新销售信息
     */
    @PutMapping("/update")
    @Operation(summary = "更新销售信息", description = "更新销售详细信息")
    public ResponseEntity<Map<String, Object>> updateSales(
            @Parameter(description = "销售信息", required = true)
            @RequestBody SalesManagement salesManagement) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (salesManagement.getId() == null || salesManagement.getId().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "销售ID不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            salesManagement.setUpdateTime(LocalDateTime.now());
            boolean success = salesManagementService.updateById(salesManagement);
            createUserForSales(salesManagement);
            if (success) {
                result.put("success", true);
                result.put("message", "销售信息更新成功");
                result.put("data", salesManagement);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "销售信息更新失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据ID删除销售
     */
    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除销售", description = "根据销售ID删除销售信息")
    public ResponseEntity<Map<String, Object>> deleteSales(
            @Parameter(description = "销售ID", required = true)
            @PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = salesManagementService.removeById(id);
            if (success) {
                result.put("success", true);
                result.put("message", "销售删除成功");
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "销售删除失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 批量删除销售
     */
    @DeleteMapping("/batchDelete")
    @Operation(summary = "批量删除销售", description = "根据销售ID列表批量删除销售信息")
    public ResponseEntity<Map<String, Object>> batchDeleteSales(
            @Parameter(description = "销售ID列表", required = true)
            @RequestBody List<String> ids) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (ids == null || ids.isEmpty()) {
                result.put("success", false);
                result.put("message", "销售ID列表不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            boolean success = salesManagementService.removeByIds(ids);
            result.put("data", "删除");
            if (success) {
                result.put("success", true);
                result.put("message", "批量删除成功，共删除 " + ids.size() + " 条记录");
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "批量删除失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "批量删除异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 获取销售统计信息
     */
    @GetMapping("/statistics")
    @Operation(summary = "获取销售统计信息", description = "获取销售总数等统计信息")
    public ResponseEntity<Map<String, Object>> getSalesStatistics() {
        Map<String, Object> result = new HashMap<>();
        try {
            long totalCount = salesManagementService.count();
            
            Map<String, Object> statistics = new HashMap<>();
            statistics.put("totalSales", totalCount);
            
            result.put("success", true);
            result.put("message", "统计信息获取成功");
            result.put("data", statistics);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "统计信息获取异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
}
