package com.ruoyi.ibs.cmpm.service;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.ibs.cmpm.domain.dto.*;
import com.ruoyi.ibs.cmpm.domain.entity.GridCmpm;
import com.ruoyi.ibs.cmpm.domain.entity.GridCmpmTransfer;
import com.ruoyi.ibs.cmpm.domain.vo.GridCmpmClaimVO;
import com.ruoyi.ibs.cmpm.domain.vo.GridCmpmTransferVO;
import com.ruoyi.ibs.cmpm.mapper.GridCmpmMapper;
import com.ruoyi.ibs.cmpm.mapper.GridCmpmTransferMapper;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author 吴凯程
 * @Date 2025/10/17
 **/
@Service
@Slf4j
@EnableAsync
public class GridCmpmTransferService {

    @Resource
    private GridCmpmTransferMapper gridCmpmTransferMapper;

    @Resource
    private ISysDeptService sysDeptService;

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private GridCmpmUpdateService gridCmpmUpdateService;


    @Resource
    private GridCmpmMapper gridCmpmMapper;

    @Transactional(rollbackFor = Exception.class)
    public String createGridCmpmTransfer(GridCmpmTransferDTO gridCmpmTransferDTO){
        if (gridCmpmTransferDTO.getPrevUserName().equals(gridCmpmTransferDTO.getNextUserName())){
            throw new ServiceException("流程前后不可选择相同的客户经理");
        }
        GridCmpmTransfer gridCmpmTransfer = new GridCmpmTransfer();
        gridCmpmTransfer.setTransferLabel("0");
        gridCmpmTransfer.setGridType(gridCmpmTransferDTO.getGridType());
        gridCmpmTransfer.setPrevUserName(gridCmpmTransferDTO.getPrevUserName());
        gridCmpmTransfer.setNextUserName(gridCmpmTransferDTO.getNextUserName());

        UserDeptDTO prevUserDeptDTO = getUserDeptDTO(gridCmpmTransferDTO.getPrevUserName());
        gridCmpmTransfer.setPrevBranchId(prevUserDeptDTO.getBranchId());
        gridCmpmTransfer.setPrevOutletId(prevUserDeptDTO.getOutletId());
        UserDeptDTO nextUserDeptDTO = getUserDeptDTO(gridCmpmTransferDTO.getNextUserName());
        gridCmpmTransfer.setNextBranchId(nextUserDeptDTO.getBranchId());
        gridCmpmTransfer.setNextOutletId(nextUserDeptDTO.getOutletId());
        gridCmpmTransfer.setHeadId(prevUserDeptDTO.getDeptId().toString().substring(0,3));

        GridCmpmTransfer statusAndType = setTransferStatusAndType(prevUserDeptDTO,nextUserDeptDTO);
        gridCmpmTransfer.setTransferType(statusAndType.getTransferType());
        gridCmpmTransfer.setTransferStatus(statusAndType.getTransferStatus());

        if (gridCmpmTransferDTO.getIsFullTransfer()){
            gridCmpmUpdateService.createFullTransferApprove(gridCmpmTransfer);
        }else{
            int i = 1;
            for (TransferCustDTO transferCustDTO : gridCmpmTransferDTO.getCustList()) {
                GridCmpmTransfer transfer = new GridCmpmTransfer();
                BeanUtils.copyProperties(gridCmpmTransfer, transfer);
                BeanUtils.copyProperties(transferCustDTO, transfer);
                gridCmpmTransferMapper.insert(transfer);
                log.info("开始插入第{}个审批，总共有{}个", i, gridCmpmTransferDTO.getCustList().size());
                i++;
            }
        }
        return "审批流程创建成功";
    }

    @Transactional(rollbackFor = Exception.class)
    public String createClaim(GridCmpmClaimDTO gridCmpmClaimDTO){
        int i = 1;
        UserDeptDTO nextUserDeptDTO = getUserDeptDTO(gridCmpmClaimDTO.getUserName());
        for (TransferCustDTO transferCustDTO : gridCmpmClaimDTO.getCustList()) {
            GridCmpm gridCmpm = gridCmpmMapper.getGridCmpmByCustKey(transferCustDTO.getCustId(),
                    transferCustDTO.getAccountNo(), transferCustDTO.getPrevUserName(),
                    gridCmpmClaimDTO.getGridType(), SecurityUtils.getHeadId());

            if (gridCmpmClaimDTO.getUserName().equals(gridCmpm.getUserName())){
                throw new ServiceException("流程前后不可选择相同的客户经理");
            }
            GridCmpmTransfer gridCmpmTransfer = new GridCmpmTransfer();
            BeanUtils.copyProperties(transferCustDTO, gridCmpmTransfer);

            gridCmpmTransfer.setTransferLabel("1");
            gridCmpmTransfer.setGridType(gridCmpmClaimDTO.getGridType());
            gridCmpmTransfer.setCustType(gridCmpm.getCustType());
            gridCmpmTransfer.setPrevUserName(gridCmpm.getUserName());
            gridCmpmTransfer.setNextUserName(gridCmpmClaimDTO.getUserName());

            UserDeptDTO prevUserDeptDTO = getUserDeptDTO(gridCmpm.getUserName());
            gridCmpmTransfer.setPrevBranchId(prevUserDeptDTO.getBranchId());
            gridCmpmTransfer.setPrevOutletId(prevUserDeptDTO.getOutletId());
            gridCmpmTransfer.setNextBranchId(nextUserDeptDTO.getBranchId());
            gridCmpmTransfer.setNextOutletId(nextUserDeptDTO.getOutletId());
            gridCmpmTransfer.setHeadId(prevUserDeptDTO.getDeptId().toString().substring(0,3));

            GridCmpmTransfer statusAndType = setTransferStatusAndType(prevUserDeptDTO,nextUserDeptDTO);
            gridCmpmTransfer.setTransferType(statusAndType.getTransferType());
            gridCmpmTransfer.setTransferStatus(statusAndType.getTransferStatus());

            gridCmpmTransferMapper.insert(gridCmpmTransfer);
            log.info("开始插入第{}个审批，总共有{}个", i, gridCmpmClaimDTO.getCustList().size());
            i++;
        }

        return "审批流程创建成功";
    }

    private GridCmpmTransfer setTransferStatusAndType (UserDeptDTO prevUserDeptDTO, UserDeptDTO nextUserDeptDTO){
        GridCmpmTransfer gridCmpmTransfer = new GridCmpmTransfer();
        if (prevUserDeptDTO.getDeptType().equals("outlet")){
            gridCmpmTransfer.setTransferStatus("0");
            // 网点相同 网点内移交
            if(Objects.nonNull(nextUserDeptDTO.getOutletId()) && prevUserDeptDTO.getOutletId().equals(nextUserDeptDTO.getOutletId())){
                gridCmpmTransfer.setTransferType(0);
            // 支行号相同 支行内移交
            }else if (Objects.nonNull(nextUserDeptDTO.getBranchId()) && prevUserDeptDTO.getBranchId().equals(nextUserDeptDTO.getBranchId())){
                gridCmpmTransfer.setTransferType(1);
            // 跨支行移交
            }else {
                gridCmpmTransfer.setTransferType(2);
            }
        }else if (prevUserDeptDTO.getDeptType().equals("branch")){
            gridCmpmTransfer.setTransferStatus("1");

            if (Objects.nonNull(nextUserDeptDTO.getBranchId()) && prevUserDeptDTO.getBranchId().equals(nextUserDeptDTO.getBranchId())){
                gridCmpmTransfer.setTransferType(1);
            }else{
                gridCmpmTransfer.setTransferType(2);
            }
        }else if (prevUserDeptDTO.getDeptType().equals("head")){
            gridCmpmTransfer.setTransferType(2);
            gridCmpmTransfer.setTransferStatus("2");
        }
        return gridCmpmTransfer;
    }

    @Transactional(rollbackFor = Exception.class)
    public String createCommonClaim(GridCmpmClaimDTO gridCmpmClaimDTO ){
        GridCmpmTransfer gridCmpmTransfer = new GridCmpmTransfer();
        gridCmpmTransfer.setTransferLabel("1");
        gridCmpmTransfer.setGridType(gridCmpmClaimDTO.getGridType());
        gridCmpmTransfer.setNextUserName(gridCmpmClaimDTO.getUserName());
        UserDeptDTO userDeptDTO = getUserDeptDTO(gridCmpmClaimDTO.getUserName());
        gridCmpmTransfer.setNextBranchId(userDeptDTO.getBranchId());
        gridCmpmTransfer.setNextOutletId(userDeptDTO.getOutletId());
        gridCmpmTransfer.setHeadId(userDeptDTO.getDeptId().toString().substring(0,3));

        int i = 1;
        for (TransferCustDTO transferCustDTO : gridCmpmClaimDTO.getCustList()) {
            GridCmpmTransfer transfer = new GridCmpmTransfer();
            BeanUtils.copyProperties(gridCmpmTransfer, transfer);
            BeanUtils.copyProperties(transferCustDTO, transfer);

            transfer.setPrevBranchId(userDeptDTO.getBranchId());
            transfer.setPrevOutletId(userDeptDTO.getOutletId());
            if (userDeptDTO.getDeptType().equals("outlet")){
                transfer.setTransferType(1);
                transfer.setTransferStatus("0");
            }else if (userDeptDTO.getDeptType().equals("branch")){
                transfer.setTransferType(1);
                transfer.setTransferStatus("1");
            } else if (userDeptDTO.getDeptType().equals("head")){
                transfer.setTransferType(2);
                transfer.setTransferStatus("2");
            }
            gridCmpmTransferMapper.insert(transfer);
            log.info("开始插入第{}个认领审批，总共有{}个:", i, gridCmpmClaimDTO.getCustList().size(), transfer);
            i++;
        }
        return "公共池认领审批流程创建成功";
    }

    @Transactional(rollbackFor = Exception.class)
    public String adjustGridCmpm(GridCmpmAdjustDTO gridCmpmAdjustDTO){
        if (!SecurityUtils.userRole().equals("branch") && !SecurityUtils.userRole().equals("head") &&!SecurityUtils.isHead()){
            throw new ServiceException("没有权限");
        }
        SysUser sysUser = sysUserService.selectUserByUserName(gridCmpmAdjustDTO.getUserName());
        UserDeptDTO userDeptDTO = getUserDeptDTO(gridCmpmAdjustDTO.getUserName());
        gridCmpmAdjustDTO.setDeptCode(SecurityUtils.getHeadId());
        for (TransferCustDTO transferCustDTO : gridCmpmAdjustDTO.getCustList()) {
            GridCmpm gridCmpm = gridCmpmMapper.getGridCmpmByCustKey(transferCustDTO.getCustId(),
                    transferCustDTO.getAccountNo(), transferCustDTO.getPrevUserName(),
                    gridCmpmAdjustDTO.getGridType(), gridCmpmAdjustDTO.getDeptCode());
            if (Objects.isNull(gridCmpm)){
                throw new ServiceException("客户不存在");
            }
            GridCmpmUpdateDTO gridCmpmUpdateDTO = new GridCmpmUpdateDTO();
            BeanUtils.copyProperties(gridCmpm, gridCmpmUpdateDTO);
            gridCmpmUpdateDTO.setDeptCode(gridCmpmAdjustDTO.getDeptCode());
            gridCmpmUpdateDTO.setPrevUserName(gridCmpm.getUserName());
            gridCmpmUpdateDTO.setUserName(sysUser.getUserName());
            gridCmpmUpdateDTO.setNickName(sysUser.getNickName());
            if (Objects.nonNull(userDeptDTO.getBranchId())){
                SysDept branch = sysDeptService.selectDeptById(userDeptDTO.getBranchId());
                gridCmpmUpdateDTO.setBranchId(userDeptDTO.getBranchId());
                gridCmpmUpdateDTO.setBranchName(branch.getDeptName());
            }else {
                gridCmpmUpdateDTO.setBranchId(null);
                gridCmpmUpdateDTO.setBranchName(null);
            }
            if (Objects.nonNull(userDeptDTO.getOutletId())){
                SysDept outlet = sysDeptService.selectDeptById(userDeptDTO.getOutletId());
                gridCmpmUpdateDTO.setOutletId(userDeptDTO.getOutletId());
                gridCmpmUpdateDTO.setOutletName(outlet.getDeptName());
            }else{
                gridCmpmUpdateDTO.setOutletId(null);
                gridCmpmUpdateDTO.setOutletName(null);
            }
            gridCmpmMapper.updateGridCmpm(gridCmpmUpdateDTO);
            log.info("调整绩效网格客户管护:" + gridCmpm);
        }
        return "调整成功";
    }

    public List<GridCmpmTransferVO> getGridCmpmTransferList(GridCmpmTransferListDTO gridCmpmTransferListDTO){
        if ("manager".equals(SecurityUtils.userRole())){
            throw new ServiceException("没有权限查控");
        }
        gridCmpmTransferListDTO.setUserRole(SecurityUtils.userRole());
        gridCmpmTransferListDTO.setDeptId(SecurityUtils.getDeptId());
        gridCmpmTransferListDTO.setUserName(SecurityUtils.getUsername());
        gridCmpmTransferListDTO.setHeadId(SecurityUtils.getHeadId());
        List<GridCmpmTransferVO> gridCmpmTransferList = gridCmpmTransferMapper.getGridCmpmTransferList(gridCmpmTransferListDTO);
        return gridCmpmTransferList;
    }

    public List<GridCmpmTransferVO> getGridCmpmTransferHistoryList(GridCmpmTransferListDTO gridCmpmTransferListDTO){
        gridCmpmTransferListDTO.setUserRole(SecurityUtils.userRole());
        gridCmpmTransferListDTO.setDeptId(SecurityUtils.getDeptId());
        gridCmpmTransferListDTO.setUserName(SecurityUtils.getUsername());
        gridCmpmTransferListDTO.setHeadId(SecurityUtils.getHeadId());
        List<GridCmpmTransferVO> gridCmpmTransferHistoryList = gridCmpmTransferMapper.getGridCmpmTransferHistoryList(gridCmpmTransferListDTO);
        return gridCmpmTransferHistoryList;
    }

    public Boolean checkExistTransferCust(String custKey, String userName){
        return gridCmpmTransferMapper.checkExistTransferCust(custKey, userName) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    public String approveTransfer(GridCmpmApproveDTO gridCmpmApproveDTO){
        for (Long id : gridCmpmApproveDTO.getIdList()) {
            GridCmpmTransfer gridCmpmTransfer = gridCmpmTransferMapper.selectById(id);
            if (gridCmpmTransfer.getTransferStatus().equals("0")){
                gridCmpmTransfer.setOutletApprover(SecurityUtils.getUsername());
                gridCmpmTransfer.setOutletApproveResult(gridCmpmApproveDTO.getApproveResult());
                gridCmpmTransfer.setOutletApproveTime(DateUtils.getNowDate());
            }else if (gridCmpmTransfer.getTransferStatus().equals("1")){
                gridCmpmTransfer.setBranchApprover(SecurityUtils.getUsername());
                gridCmpmTransfer.setBranchApproveResult(gridCmpmApproveDTO.getApproveResult());
                gridCmpmTransfer.setBranchApproveTime(DateUtils.getNowDate());
            }else if (gridCmpmTransfer.getTransferStatus().equals("2")){
                gridCmpmTransfer.setHeadApprover(SecurityUtils.getUsername());
                gridCmpmTransfer.setHeadApproveResult(gridCmpmApproveDTO.getApproveResult());
                gridCmpmTransfer.setHeadApproveTime(DateUtils.getNowDate());
            }
            if (gridCmpmApproveDTO.getApproveResult()){
                gridCmpmTransfer.setTransferStatus(getNextTransferStatus(gridCmpmTransfer.getTransferType(), gridCmpmTransfer.getTransferStatus()));
            }else{
                gridCmpmTransfer.setTransferStatus("-1");
            }
            if (gridCmpmTransferMapper.updateById(gridCmpmTransfer) > 0 && gridCmpmTransfer.getTransferStatus().equals("3")){
                gridCmpmUpdateService.updateGridCmpm(gridCmpmTransfer);
            }
        }
        return "审批成功";
    }

    private String getNextTransferStatus(Integer transferType, String transferStatus){
        if (transferType == 0){
            if (transferStatus.equals("0")){
                return "3";
            }
        }else if (transferType == 1){
            if (transferStatus.equals("0")){
                return "1";
            }else if (transferStatus.equals("1")){
                return "3";
            }
        }else if (transferType == 2){
            if (transferStatus.equals("0")){
                return "1";
            }else if (transferStatus.equals("1")){
                return "2";
            }else if (transferStatus.equals("2")){
                return "3";
            }
        }
        return "-1";
    }

    public UserDeptDTO getUserDeptDTO(String userName){
        UserDeptDTO userDeptDTO = new UserDeptDTO();
        SysUser sysUser = sysUserService.selectUserByUserName(userName);
        userDeptDTO.setDeptId(sysUser.getDeptId());
        SysDept sysDept = sysDeptService.selectDeptById(sysUser.getDeptId());
        userDeptDTO.setDeptType(sysDept.getDeptType());
        if (sysDept.getDeptType().equals("head")){
            userDeptDTO.setHeadId(sysDept.getDeptId());
        }else if (sysDept.getDeptType().equals("branch")){
            userDeptDTO.setBranchId(sysDept.getDeptId());
            userDeptDTO.setHeadId(sysDept.getParentId());
        }else if (sysDept.getDeptType().equals("outlet")){
            userDeptDTO.setOutletId(sysDept.getDeptId());
            userDeptDTO.setBranchId(sysDept.getParentId());
            SysDept branchDept = sysDeptService.selectDeptById(sysDept.getParentId());
            userDeptDTO.setHeadId(branchDept.getParentId());
        }
        return userDeptDTO;
    }

    public List<GridCmpmClaimVO> queryClaimList(String custKey, String gridType){
        List<GridCmpmClaimVO> gridCmpmClaimVOS = gridCmpmMapper.queryClaimList(SecurityUtils.getHeadId(), gridType, custKey);
        return gridCmpmClaimVOS.stream().map(gridCmpmClaimVO -> {
            gridCmpmClaimVO.setClaimFlag(Boolean.TRUE);
            if (gridType.equals("corproate_account")){
                if (gridCmpmTransferMapper.checkExistTransferCust(gridCmpmClaimVO.getAccountNo(), gridCmpmClaimVO.getUserName()) > 0){
                    gridCmpmClaimVO.setClaimFlag(Boolean.FALSE);
                    gridCmpmClaimVO.setClaimStatus("该客户存在正在审批的移交或者认领流程");
                }
            }else {
                if (gridCmpmTransferMapper.checkExistTransferCust(gridCmpmClaimVO.getCustId(), gridCmpmClaimVO.getUserName()) > 0){
                    gridCmpmClaimVO.setClaimFlag(Boolean.FALSE);
                    gridCmpmClaimVO.setClaimStatus("该客户存在正在审批的移交或者认领流程");
                }
            }
            if (Objects.nonNull(gridCmpmClaimVO.getUserName()) && gridCmpmClaimVO.getUserName().equals(SecurityUtils.getUsername())){
                gridCmpmClaimVO.setClaimFlag(Boolean.FALSE);
                gridCmpmClaimVO.setClaimStatus("该客户无须认领");
            }
            return gridCmpmClaimVO;
        }).collect(Collectors.toList());
    }


}
