package com.ruoyi.ibs.customerselect.service.Impl;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.ibs.customerselect.domain.*;
import com.ruoyi.ibs.customerselect.mapper.CustInfoBusinessMapper;
import com.ruoyi.ibs.customerselect.service.IListSelectService;
import com.ruoyi.ibs.list.mapper.*;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.ruoyi.common.utils.SecurityUtils.*;
import static com.ruoyi.ibs.list.domain.Constans.*;

/**
 * 清单查询 服务实现
 *
 * @author ruoyi
 */
@Service
public class ListSelectServiceImpl implements IListSelectService {

    private static Logger logger= LoggerFactory.getLogger(ListSelectServiceImpl.class);

    @Autowired
    CustInfoMerchantMapper custInfoMerchantMapper;

    @Autowired
    CustInfoBusinessMapper custInfoBusinessMapper;

    @Autowired
    SysCampaignMapper sysCampaignMapper;

    @Autowired
    SysCampaignGroupCustomerMapper sysCampaignGroupCustomerMapper;

    @Autowired
    SysListMapper sysListMapper;

    @Autowired
    SysGroupCustomerMapper sysGroupCustomerMapper;

    @Autowired
    SysGroupMapper sysGroupMapper;

    @Autowired
    SysDeptMapper sysDeptMapper;

    @Autowired
    SysUserMapper sysUserMapper;

    /**
     * 查询清单列表信息
     *
     * @param listSelectByUser 客户信息
     * @return 客户信息集合
     */
    @Override
    public List<ListSelectByUser> getListInfoByUser(ListSelectByUser listSelectByUser){
        List<ListSelectByUser> listSelectByUserList = new ArrayList<>();
        logger.info("操作员为"+userRole());
        String roleName = userRole();
        if(ROLE_HEAD.equals(roleName)||ROLE_HeadPublic.equals(roleName)||ROLE_HeadPrivate.equals(roleName)||ROLE_HeadOps.equals(roleName)
        ||ROLE_BRANCH.equals(roleName)||ROLE_Outlet.equals(roleName)){//根据机构号查询清单
            listSelectByUser.setUserDept(getDeptId());
            if(listSelectByUser.getGroupType() != null){
                if((ROLE_BRANCH.equals(roleName)||ROLE_Outlet.equals(roleName)) && listSelectByUser.getGroupType().equals("0")){//支行视角里我的清单与总行码值相反
                    listSelectByUser.setGroupType("1");
                }else if((ROLE_BRANCH.equals(roleName)||ROLE_Outlet.equals(roleName)) && listSelectByUser.getGroupType().equals("1")){
                    listSelectByUser.setGroupType("0");
                }else if((ROLE_HEAD.equals(roleName)||ROLE_HeadPublic.equals(roleName)||ROLE_HeadPrivate.equals(roleName)||ROLE_HeadOps.equals(roleName)) && listSelectByUser.getGroupType().equals("2")){
                    listSelectByUser.setGroupType("1");
                }
                if (ROLE_Outlet.equals(roleName)){
                    listSelectByUser.setUserDept(null);
                    listSelectByUser.setBelongOutlet(getDeptId().toString());
                }
            }
        }else if(userRole().equals("manager")){//根据客户经理查询清单
            listSelectByUser.setUserId(getUserId());
            listSelectByUser.setGroupType(listSelectByUser.getCreateRole());
        }else{
            logger.info("操作员为其他人员");
            throw new ServiceException("该操作员无法查看清单列表！");
        }
        Date now = new Date();
        listSelectByUser.setNowTime(now);
        if (ROLE_Outlet.equals(roleName)){
            listSelectByUserList = sysListMapper.selectMarketingListByOutlet(listSelectByUser);
        }else {
            listSelectByUserList = sysListMapper.selectMarketingListByBank(listSelectByUser);
        }

        for(int i = 0; i < listSelectByUserList.size(); i++) {
            listSelectByUserList.get(i).setCustPattern(listSelectByUser.getCustPattern());
            if((ROLE_HEAD.equals(roleName)||ROLE_HeadPublic.equals(roleName)||ROLE_HeadPrivate.equals(roleName)||ROLE_HeadOps.equals(roleName))&&"1".equals(listSelectByUserList.get(i).getCreateRole())){//总行视角里支行创建的为其他营销清单
                listSelectByUserList.get(i).setGroupType("2");
            }else if(userRole().equals("manager")){//客户经理视角只有推荐营销清单
                listSelectByUserList.get(i).setGroupType("1");
            }else if((ROLE_BRANCH.equals(roleName)||ROLE_Outlet.equals(roleName))&&"1".equals(listSelectByUserList.get(i).getCreateRole())){//支行视角里我的清单与总行码值相反
                listSelectByUserList.get(i).setGroupType("0");
            }else if((ROLE_BRANCH.equals(roleName)||ROLE_Outlet.equals(roleName))&&"0".equals(listSelectByUserList.get(i).getCreateRole())){
                listSelectByUserList.get(i).setGroupType("1");
            }else{
                listSelectByUserList.get(i).setGroupType(listSelectByUserList.get(i).getCreateRole());
            }
            Date startTime = listSelectByUserList.get(i).getStartTime();
            Date endTime = listSelectByUserList.get(i).getEndTime();
            if (startTime != null && endTime != null) {//根据时间关系判断当前活动状态
                if (now.getTime() < startTime.getTime()) {
                    listSelectByUserList.get(i).setActionStatus("待开始");
                } else if (now.getTime() > startTime.getTime() && now.getTime() < endTime.getTime()) {
                    listSelectByUserList.get(i).setActionStatus("进行中");
                } else if (now.getTime() > endTime.getTime()) {
                    listSelectByUserList.get(i).setActionStatus("已结束");
                }
            }
            if("0".equals(listSelectByUserList.get(i).getClaimType())&& listSelectByUserList.get(i).getDeptId() != null){//如果该活动分配给机构并为强制认领时，认领状态默认为已认领
                listSelectByUserList.get(i).setOrgClaimStatus("1");
            }
            if(ROLE_HEAD.equals(roleName)||ROLE_HeadPublic.equals(roleName)||ROLE_HeadPrivate.equals(roleName)||ROLE_HeadOps.equals(roleName)
                    ||ROLE_BRANCH.equals(roleName)||ROLE_Outlet.equals(roleName)) {//总行支行视角需要查询客户经理及认领率
                if(ROLE_Outlet.equals(roleName)){
                    List<String> receiveUser = sysCampaignGroupCustomerMapper.getReceiveUserNumOutlet(listSelectByUserList.get(i).getGroupId(),listSelectByUserList.get(i).getCampaignId(),getDeptId());
                    List<String> allUser = sysCampaignGroupCustomerMapper.getAllUserNumOutlet(listSelectByUserList.get(i).getGroupId(),listSelectByUserList.get(i).getCampaignId(),getDeptId());
                    Long Receivesitustion = Long.parseLong(String.valueOf(receiveUser.size() * 100 / allUser.size()));
                    listSelectByUserList.get(i).setReceiveSitustion(Receivesitustion.toString() + '%');
                    if("0".equals(listSelectByUserList.get(i).getClaimType()) &&listSelectByUserList.get(i).getDeptId() == null){//如果该活动为强制认领并且活动为分配客户经理时，认领率为100%
                        listSelectByUserList.get(i).setReceiveSitustion("100%");
                    }
                }else{
                    List<String> receiveUser = sysCampaignGroupCustomerMapper.getReceiveUserNum(listSelectByUserList.get(i).getGroupId(),listSelectByUserList.get(i).getCampaignId(),listSelectByUserList.get(i).getDeptId(),getDeptId());
                    List<String> allUser = sysCampaignGroupCustomerMapper.getAllUserNum(listSelectByUserList.get(i).getGroupId(),listSelectByUserList.get(i).getCampaignId(),listSelectByUserList.get(i).getDeptId(),getDeptId());
                    Long Receivesitustion = Long.parseLong(String.valueOf(receiveUser.size() * 100 / allUser.size()));
                    listSelectByUserList.get(i).setReceiveSitustion(Receivesitustion.toString() + '%');
                    if("0".equals(listSelectByUserList.get(i).getClaimType()) &&listSelectByUserList.get(i).getDeptId() == null){//如果该活动为强制认领并且活动为分配客户经理时，认领率为100%
                        listSelectByUserList.get(i).setReceiveSitustion("100%");
                    }
                }
            }
        }

        return listSelectByUserList;
    }



    /**
     * 查询客户清单列表信息
     *
     * @param listSelectForUser 客户信息
     * @return 客户信息集合
     */
    @Override
    public List<ListSelectForUser> getCustListInfoByUser(ListSelectForUser listSelectForUser){
        List<ListSelectForUser> ListSelectForUserList = new ArrayList<>();
        logger.info("操作员id为" + getUserId());
        logger.info("操作员机构id为" + getDeptId());
        int deptstatus = 0;
        logger.info("操作员为"+userRole());
        String roleName = userRole();
        if(ROLE_HEAD.equals(roleName)||ROLE_HeadPublic.equals(roleName)||ROLE_HeadPrivate.equals(roleName)||ROLE_HeadOps.equals(roleName)
                ||ROLE_BRANCH.equals(roleName)||ROLE_Outlet.equals(roleName)){//根据机构号查询清单
            listSelectForUser.setUserDept(getDeptId());
        }else if(userRole().equals("manager")){//根据客户经理查询清单
            logger.info("操作员为客户经理,经理id为" + getUserId());
            listSelectForUser.setUserId(getUserId());
        }else{
            logger.info("操作员为其他人员");
            throw new ServiceException("该操作员无法查看清单列表！");
        }
        if (ROLE_Outlet.equals(roleName)){
            listSelectForUser.setIsOutlet("1");
        }else{
            listSelectForUser.setIsOutlet("0");
        }
        if (retail.equals(listSelectForUser.getCustPattern())){
            ListSelectForUserList = sysListMapper.selectCustListByBankRetail(listSelectForUser);
        }
        else if (merchant.equals(listSelectForUser.getCustPattern())){
            ListSelectForUserList = sysListMapper.selectCustListByBankMerchant(listSelectForUser);
        } else if (business.equals(listSelectForUser.getCustPattern())){
            ListSelectForUserList = sysListMapper.selectCustListByBankBusiness(listSelectForUser);
        }

        for(int i = 0; i < ListSelectForUserList.size(); i++) {
            ListSelectForUserList.get(i).setCustPattern(listSelectForUser.getCustPattern());
            if("1".equals(ListSelectForUserList.get(i).getOrgDistributeStatus())){//清单中只要有一个客户是已分配的，其余的都改成是已分配
                deptstatus = 1;
            }
        }
        if(deptstatus == 1) {//将其余客户改为改成已分配
            for (int i = 0; i < ListSelectForUserList.size(); i++) {
                ListSelectForUserList.get(i).setOrgDistributeStatus("1");
            }
        }
        return ListSelectForUserList;
    }


    /**
     * 批量导出客群列表
     *
     * @param groupId groupId
     * @return 客户信息集合
     */
    @Override
    public void  selectListExportByGroupId (HttpServletResponse response, String custPattern, String groupId, String campaignId, Long deptId, List<String> custIds) {
        logger.info("开始导出查询");
        ListSelectForUser listSelectForUser = new ListSelectForUser();
        listSelectForUser.setCampaignId(campaignId);
        listSelectForUser.setCustPattern(custPattern);
        listSelectForUser.setGroupId(groupId);
        listSelectForUser.setDeptId(deptId);
        List<ListSelectForUser>  listSelectForUserList = getCustListInfoByUser(listSelectForUser);
        listSelectForUserList = listSelectForUserList.stream().filter(l->custIds.contains(l.getCustId())).collect(Collectors.toList());
        if (custPattern.equals(retail)){
            List<ListSelectForUserExportRetail> list  = listSelectForUserList.stream().map(s->{
                ListSelectForUserExportRetail listSelectForUserExport =   new ListSelectForUserExportRetail();
                BeanUtils.copyProperties(s,listSelectForUserExport);
                return listSelectForUserExport;}).collect(Collectors.toList());
            ExcelUtil<ListSelectForUserExportRetail> util = new ExcelUtil<ListSelectForUserExportRetail>(ListSelectForUserExportRetail.class);
            util.exportExcel(response, list, "批量导出分群客户");
        }else if (custPattern.equals(merchant)){
            List<ListSelectForUserExportMerchant> list  = listSelectForUserList.stream().map(s->{
                ListSelectForUserExportMerchant listSelectForUserExport =   new ListSelectForUserExportMerchant();
                BeanUtils.copyProperties(s,listSelectForUserExport);
                return listSelectForUserExport;}).collect(Collectors.toList());
            ExcelUtil<ListSelectForUserExportMerchant> util = new ExcelUtil<ListSelectForUserExportMerchant>(ListSelectForUserExportMerchant.class);
            util.exportExcel(response, list, "批量导出分群客户");
        }else if (custPattern.equals(business)){
            List<ListSelectForUserExportBusiness> list  = listSelectForUserList.stream().map(s->{
                ListSelectForUserExportBusiness listSelectForUserExport =   new ListSelectForUserExportBusiness();
                BeanUtils.copyProperties(s,listSelectForUserExport);
                return listSelectForUserExport;}).collect(Collectors.toList());
            ExcelUtil<ListSelectForUserExportBusiness> util = new ExcelUtil<ListSelectForUserExportBusiness>(ListSelectForUserExportBusiness.class);
            util.exportExcel(response, list, "批量导出分群客户");
        }
    }
}
