package com.ruoyi.ibs.grid.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.ibs.grid.domain.dto.GridCustListDTO;
import com.ruoyi.ibs.grid.domain.dto.UnbindDTO;
import com.ruoyi.ibs.grid.domain.dto.virtual.VirtualGridListDTO;
import com.ruoyi.ibs.grid.domain.entity.VirtualCust;
import com.ruoyi.ibs.grid.domain.entity.VirtualCustUser;
import com.ruoyi.ibs.grid.domain.entity.VirtualCustUserUnbind;
import com.ruoyi.ibs.grid.domain.entity.VirtualUser;
import com.ruoyi.ibs.grid.domain.vo.VirtualGridCustVO;
import com.ruoyi.ibs.grid.domain.vo.VirtualGridListVO;
import com.ruoyi.ibs.grid.domain.vo.VirtualGridVO;
import com.ruoyi.ibs.grid.mapper.*;
import com.ruoyi.ibs.grid.service.VirtualGridListService;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @Author 吴凯程
 * @Date 2025/1/2
 **/
@Service
public class VirtualGridListServiceImpl implements VirtualGridListService {

    @Resource
    private VirtualCustUserMapper virtualCustUserMapper;

    @Resource
    private VirtualUserMapper virtualUserMapper;

    @Resource
    private VirtualCustMapper virtualCustMapper;

    @Resource
    private VirtualCustUserUnbindMapper virtualCustUserUnbindMapper;

    @Resource
    private VirtualGridMapper virtualGridMapper;

    @Resource
    private SysDeptMapper sysDeptMapper;

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private AnchorMapper anchorMapper;

    /**
     * @param gridCustListDTO
     * @return
     */
    @Override
    public List<VirtualGridCustVO> getCustList(GridCustListDTO gridCustListDTO) {
        gridCustListDTO.setUserName(SecurityUtils.getUsername());
        gridCustListDTO.setDeptId(SecurityUtils.getDeptId());
        List<VirtualGridCustVO> custList;
        if (!SecurityUtils.userRole().equals("manager")) {
            custList = virtualCustUserMapper.getCustList(gridCustListDTO);
        } else {
            custList = virtualCustUserMapper.getCustListByManager(gridCustListDTO);
        }
        if (custList.size() > 0) {
            String userName = custList.get(0).getUserName();
            SysUser sysUser = sysUserMapper.selectUserByUserName(userName);
            SysDept dept = sysDeptMapper.selectDeptById(sysUser.getDeptId());
            String branchName;
            String outletName;
            if (dept.getDeptType().equals("outlet")) {
                outletName = dept.getDeptName();
                branchName = dept.getParentName();
            } else {
                branchName = dept.getDeptName();
                outletName = null;
            }

            for (VirtualGridCustVO virtualGridCustVO : custList) {
                virtualGridCustVO.setAddress(anchorMapper.selectAddressByCustIdc(virtualGridCustVO.getCustIdn()));
                if (!virtualGridCustVO.getUserName().equals(userName)) {
                    userName = virtualGridCustVO.getUserName();
                    sysUser = sysUserMapper.selectUserByUserName(userName);
                    dept = sysDeptMapper.selectDeptById(sysUser.getDeptId());
                    if (dept.getDeptType().equals("outlet")) {
                        outletName = dept.getDeptName();
                        branchName = dept.getParentName();
                    } else {
                        branchName = dept.getDeptName();
                        outletName = null;
                    }
                }
                virtualGridCustVO.setBranchName(branchName);
                virtualGridCustVO.setOutletName(outletName);
            }
        }

        return custList;
    }

    /**
     * @param gridCustListDTO
     * @return
     */
    @Override
    public List<VirtualGridCustVO> getUnrelateCustList(GridCustListDTO gridCustListDTO) {
        return virtualCustUserMapper.getUnrelateCustList(gridCustListDTO);
    }


    /**
     * @param unbindDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String unbindCustUser(UnbindDTO unbindDTO) {
        LambdaQueryWrapper<VirtualCustUserUnbind> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(VirtualCustUserUnbind::getGridId, unbindDTO.getGridId())
                .eq(VirtualCustUserUnbind::getCustId, unbindDTO.getCustId())
                .eq(VirtualCustUserUnbind::getUserName, unbindDTO.getUserName());
        VirtualCustUserUnbind virtualCustUserUnbind = virtualCustUserUnbindMapper.selectOne(queryWrapper);
        if (Objects.nonNull(virtualCustUserUnbind)) {
            virtualCustUserUnbindMapper.deleteById(virtualCustUserUnbind);
            return "重新绑定管护关系";
        }
        virtualCustUserUnbind = new VirtualCustUserUnbind();
        BeanUtils.copyProperties(unbindDTO, virtualCustUserUnbind);
        virtualCustUserUnbindMapper.insert(virtualCustUserUnbind);
        return "解绑成功";
    }

    /**
     * @param unbindDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addCustUser(List<UnbindDTO> unbindDTOS) {
        for (UnbindDTO unbindDTO : unbindDTOS) {
            LambdaQueryWrapper<VirtualCustUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(VirtualCustUser::getGridId, unbindDTO.getGridId())
                    .eq(VirtualCustUser::getCustId, unbindDTO.getCustId())
                    .eq(VirtualCustUser::getUserName, unbindDTO.getUserName());
            if (virtualCustUserMapper.selectCount(queryWrapper) > 0) {
                throw new ServiceException("该管护关系已存在: " + unbindDTO.getCustId() + "-" + unbindDTO.getUserName());
            }
            SysUser sysUser = sysUserMapper.selectUserByUserName(unbindDTO.getUserName());
            SysDept dept = sysDeptMapper.selectDeptById(sysUser.getDeptId());

            VirtualCustUser virtualCustUser = new VirtualCustUser();
            BeanUtils.copyProperties(unbindDTO, virtualCustUser);
            virtualCustUser.setNickName(sysUser.getNickName());
            virtualCustUser.setRelateDeptId(dept.getDeptId());
            virtualCustUser.setRelateDeptName(dept.getDeptName());
            virtualCustUserMapper.insert(virtualCustUser);

            LambdaQueryWrapper<VirtualCust> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(VirtualCust::getGridId, unbindDTO.getGridId())
                    .eq(VirtualCust::getCustId, unbindDTO.getCustId());
            VirtualCust virtualCust = virtualCustMapper.selectOne(queryWrapper1);
            virtualCust.setLockFlag(Boolean.TRUE);
            virtualCustMapper.updateById(virtualCust);

            LambdaQueryWrapper<VirtualUser> queryWrapper2 = new LambdaQueryWrapper<>();
            queryWrapper2.eq(VirtualUser::getGridId, unbindDTO.getGridId())
                    .eq(VirtualUser::getUserName, unbindDTO.getUserName());
            if (virtualUserMapper.selectCount(queryWrapper2) < 1) {
                VirtualUser virtualUser = new VirtualUser();
                virtualUser.setGridId(unbindDTO.getGridId());
                virtualUser.setUserName(sysUser.getUserName());
                virtualUser.setNickName(sysUser.getNickName());
                virtualUser.setRelateType("1");
                virtualUser.setRelateDeptId(dept.getDeptId());
                virtualUser.setRelateDeptName(dept.getDeptName());
                virtualUser.setRelateDeptType(dept.getDeptType());
                virtualUserMapper.insert(virtualUser);
            }
            LambdaQueryWrapper<VirtualCustUser> queryWrapper3 = new LambdaQueryWrapper<>();
            queryWrapper3.eq(VirtualCustUser::getGridId, unbindDTO.getGridId())
                    .eq(VirtualCustUser::getCustId, unbindDTO.getCustId())
                    .isNull(VirtualCustUser::getUserName)
                    .isNull(VirtualCustUser::getRelateDeptId);
            virtualCustUserMapper.delete(queryWrapper3);
        }

        return "管护关系添加成功";
    }

    /**
     * @param virtualGridListDTO
     * @return
     */
    @Override
    public List<VirtualGridListVO> getGridList(VirtualGridListDTO virtualGridListDTO) {
        if (SecurityUtils.isHead()) {
            virtualGridListDTO.setOpsDept(SecurityUtils.getOpsDept());
        }

        List<VirtualGridListVO> gridListVOS = virtualGridMapper.getGridList(virtualGridListDTO);
        if (Objects.nonNull(gridListVOS) && !gridListVOS.isEmpty()) {
            for (VirtualGridListVO gridListVO : gridListVOS) {
                StringBuilder CustTypeBuilder = new StringBuilder();
                if (gridListVO.getDeptId().equals(SecurityUtils.getDeptId())) {
                    if (gridListVO.getOpsDept().equals("0")) {
                        gridListVO.setRetailCount(virtualCustMapper.getCustNumByGridId(gridListVO.getGridId(), "0"));
                        gridListVO.setMerchantCount(virtualCustMapper.getCustNumByGridId(gridListVO.getGridId(), "1"));
                        gridListVO.setBusinessCount(null);
                    } else if (gridListVO.getOpsDept().equals("1")) {
                        gridListVO.setRetailCount(null);
                        gridListVO.setMerchantCount(null);
                        gridListVO.setBusinessCount(virtualCustMapper.getCustNumByGridId(gridListVO.getGridId(), "2"));
                    } else {
                        gridListVO.setRetailCount(virtualCustMapper.getCustNumByGridId(gridListVO.getGridId(), "0"));
                        gridListVO.setMerchantCount(virtualCustMapper.getCustNumByGridId(gridListVO.getGridId(), "1"));
                        gridListVO.setBusinessCount(virtualCustMapper.getCustNumByGridId(gridListVO.getGridId(), "2"));
                    }

                } else {
                    if (gridListVO.getOpsDept().equals("0")) {
                        gridListVO.setRetailCount(virtualCustMapper.getCustNumByGridIdAndDept(gridListVO.getGridId(), SecurityUtils.getDeptId(), "0"));
                        gridListVO.setMerchantCount(virtualCustMapper.getCustNumByGridIdAndDept(gridListVO.getGridId(), SecurityUtils.getDeptId(), "1"));
                        gridListVO.setBusinessCount(null);
                    } else if (gridListVO.getOpsDept().equals("1")) {
                        gridListVO.setRetailCount(null);
                        gridListVO.setMerchantCount(null);
                        gridListVO.setBusinessCount(virtualCustMapper.getCustNumByGridIdAndDept(gridListVO.getGridId(), SecurityUtils.getDeptId(), "2"));
                    } else {
                        gridListVO.setRetailCount(virtualCustMapper.getCustNumByGridIdAndDept(gridListVO.getGridId(), SecurityUtils.getDeptId(), "0"));
                        gridListVO.setMerchantCount(virtualCustMapper.getCustNumByGridIdAndDept(gridListVO.getGridId(), SecurityUtils.getDeptId(), "1"));
                        gridListVO.setBusinessCount(virtualCustMapper.getCustNumByGridIdAndDept(gridListVO.getGridId(), SecurityUtils.getDeptId(), "2"));
                    }
                }

                if (Objects.nonNull(gridListVO.getRetailCount()) && gridListVO.getRetailCount() > 0) {
                    CustTypeBuilder.append("个人 ");
                }
                if (Objects.nonNull(gridListVO.getMerchantCount()) && gridListVO.getMerchantCount() > 0) {
                    CustTypeBuilder.append("商户 ");
                }
                if (Objects.nonNull(gridListVO.getBusinessCount()) && gridListVO.getBusinessCount() > 0) {
                    CustTypeBuilder.append("企业");
                }
                gridListVO.setCustTypes(CustTypeBuilder.toString());

                LambdaQueryWrapper<VirtualUser> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(VirtualUser::getGridId, gridListVO.getGridId());
                List<VirtualUser> virtualUsers = virtualUserMapper.selectList(queryWrapper);
                if (!virtualUsers.isEmpty()) {
                    List<String> userNames = virtualUsers.stream().map(virtualUser -> virtualUser.getNickName() + '-' + virtualUser.getUserName()).collect(Collectors.toList());
                    gridListVO.setUserNames(userNames.stream().collect(Collectors.joining(",")));

                    List<String> branches = new ArrayList<>();
                    List<String> outlets = new ArrayList<>();
                    for (VirtualUser virtualUser : virtualUsers) {
                        if (virtualUser.getRelateDeptType().equals("outlet") && !outlets.contains(virtualUser.getRelateDeptName())) {
                            outlets.add(virtualUser.getRelateDeptName());
                            SysDept sysDept = sysDeptMapper.selectDeptById(virtualUser.getRelateDeptId());
                            if (!branches.contains(sysDept.getParentName())) {
                                branches.add(sysDept.getParentName());
                            }
                        } else if (!virtualUser.getRelateDeptType().equals("outlet") && !branches.contains(virtualUser.getRelateDeptName())) {
                            branches.add(virtualUser.getRelateDeptName());
                        }
                    }
                    if (!branches.isEmpty()) {
                        gridListVO.setBranchNames(branches.stream().collect(Collectors.joining(",")));
                    }
                    if (!outlets.isEmpty()) {
                        gridListVO.setOutletNames(outlets.stream().collect(Collectors.joining(",")));
                    }
                }
                SysDept sysDept = sysDeptMapper.selectDeptById(gridListVO.getDeptId());
                if (sysDept.getDeptType().equals("head")) {
                    gridListVO.setIsEdit(gridListVO.getDeptId().equals(SecurityUtils.getDeptId())
                            && gridListVO.getOpsDept().equals(SecurityUtils.getOpsDept()));
                    gridListVO.setIsUnbind(gridListVO.getDeptId().equals(SecurityUtils.getDeptId())
                            && gridListVO.getOpsDept().equals(SecurityUtils.getOpsDept()));
                    gridListVO.setIsAddRelate(gridListVO.getDeptId().equals(SecurityUtils.getDeptId())
                            && gridListVO.getOpsDept().equals(SecurityUtils.getOpsDept())
                            && gridListVO.getGridAssignType().equals("2"));
                } else {
                    gridListVO.setIsEdit(gridListVO.getDeptId().equals(SecurityUtils.getDeptId()));
                    gridListVO.setIsUnbind(gridListVO.getDeptId().equals(SecurityUtils.getDeptId()));
                    gridListVO.setIsAddRelate(gridListVO.getDeptId().equals(SecurityUtils.getDeptId()) && gridListVO.getGridAssignType().equals("2"));
                }

            }
        }
        return gridListVOS;
    }

    /**
     * @param virtualGridListDTO
     * @return
     */
    @Override
    public List<VirtualGridListVO> getGridListByManager(VirtualGridListDTO virtualGridListDTO) {
        List<VirtualGridListVO> gridListVOS = virtualGridMapper.getGridListByManager(virtualGridListDTO);
        if (!gridListVOS.isEmpty()) {
            for (VirtualGridListVO gridListVO : gridListVOS) {
                StringBuilder CustTypeBuilder = new StringBuilder();
                gridListVO.setRetailCount(virtualCustUserMapper.getCountByGridIdAndUserName(gridListVO.getGridId(), "0", SecurityUtils.getUsername()));
                gridListVO.setMerchantCount(virtualCustUserMapper.getCountByGridIdAndUserName(gridListVO.getGridId(), "1", SecurityUtils.getUsername()));
                gridListVO.setBusinessCount(virtualCustUserMapper.getCountByGridIdAndUserName(gridListVO.getGridId(), "2", SecurityUtils.getUsername()));
                if (gridListVO.getRetailCount() > 0) {
                    CustTypeBuilder.append("个人 ");
                }
                if (gridListVO.getMerchantCount() > 0) {
                    CustTypeBuilder.append("商户 ");
                }
                if (gridListVO.getBusinessCount() > 0) {
                    CustTypeBuilder.append("企业");
                }
                gridListVO.setCustTypes(CustTypeBuilder.toString());

                gridListVO.setUserNames(SecurityUtils.getLoginUser().getUser().getNickName());
                SysDept sysDept = sysDeptMapper.selectDeptById(SecurityUtils.getDeptId());
                if (sysDept.getDeptType().equals("outlet")) {
                    gridListVO.setBranchNames(sysDept.getParentName());
                    gridListVO.setOutletNames(sysDept.getDeptName());
                } else {
                    gridListVO.setBranchNames(sysDept.getDeptName());
                }
                gridListVO.setIsEdit(Boolean.FALSE);
                gridListVO.setIsUnbind(Boolean.FALSE);
                gridListVO.setIsAddRelate(Boolean.FALSE);
            }
        }
        return gridListVOS;
    }

    /**
     * @param gridId
     * @param searchParam
     * @return
     */
    @Override
    public List<VirtualCust> selectCustFromGrid(Long gridId, String searchParam) {
        LambdaQueryWrapper<VirtualCust> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(VirtualCust::getGridId, gridId);
        if (Objects.nonNull(searchParam) && !searchParam.isEmpty()) {
            queryWrapper.and(qw -> qw.or().like(VirtualCust::getCustId, searchParam).or().like(VirtualCust::getCustName, searchParam));
        }
        return virtualCustMapper.selectList(queryWrapper);
    }

    /**
     * @param opsDept
     * @param gridName
     * @return
     */
    @Override
    public List<VirtualGridVO> searchVirtualGrid(String opsDept, String gridName) {
        return virtualGridMapper.searchVirtualGrid(SecurityUtils.getDeptId(), opsDept, gridName);
    }
}
