package com.goafanti.order.service.impl;

import com.goafanti.business.bo.InputRestrictProject;
import com.goafanti.common.dao.*;
import com.goafanti.common.enums.ChannelStatus;
import com.goafanti.common.enums.NoticeStatus;
import com.goafanti.common.model.*;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.order.bo.TOrderNewBo;
import com.goafanti.order.bo.TOrderTaskBo;
import com.goafanti.order.enums.NewProjectStatus;
import com.goafanti.order.enums.OrderChangeProcess;
import com.goafanti.order.enums.ProcessStatus;
import com.goafanti.order.service.OrderNewService;
import com.goafanti.techproject.enums.TaskState;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
@Async
@Service
public class ProjectDistributionAsyncService {

    @Resource
    private TOrderTaskMapper tOrderTaskMapper;
    @Resource
    private OrderNewService orderNewService;
    @Resource
    private TOrderLogMapper tOrderLogMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserLockReleaseMapper userLockReleaseMapper;
    @Resource
    private BusinessProjectMapper businessProjectMapper;
    @Resource
    private RestrictProjectMapper restrictProjectMapper;
    @Resource
    private UserTransferLogMapper userTransferLogMapper;
    @Resource
    private TTaskMidMapper tTaskMidMapper;
    @Resource
    private TOrderNewMapper tOrderNewMapper;
    @Resource
    private TOrderMidMapper tOrderMidMapper;
    @Resource
    private OrderExamineMapper orderExamineMapper;
    @Resource
    private AdminProjectStatisticsMapper adminProjectStatisticsMapper;
    @Resource
    private NewOrderChangeMapper newOrderChangeMapper;
    @Resource
    private UserBusinessMapper userBusinessMapper;
    @Resource
    private PublicReleaseMapper publicReleaseMapper;
    @Resource
    private UserChannelMapper userChannelMapper;
    @Resource
    private UserMidMapper userMidMapper;




    @Transactional
    public void pushProjectDistribution(Integer taskId, String taskReceiverId,  Integer type, TOrderTask t, TOrderNew tn, Date date, Admin a) {
        List<String> aids = new ArrayList<>();
        aids.add(taskReceiverId);
        TOrderNewBo order = tOrderNewMapper.getSaleIdByOno(t.getOrderNo());
        orderNewService.pushGeneralSendNoticeAndEmail(aids, NoticeStatus.ORDER_TASK_TO.getCode(),order, TokenManager.getAdminId(),0, taskId);
        //处理项目统计表
        TTaskMid details = tTaskMidMapper.getDtails(taskId);
        if (type ==0){
            //设置催款触发
            orderNewService.pushOrderDun(tn);
            //未锁定客户就锁定客户
            pushUser(t, tn, date);
            //处理客户已派项目
            projectDistributionPushUserMid(tn);
            //处理限定项目状态
            BusinessProject businessProject = businessProjectMapper.selectById(t.getCommodityId());
            if (businessProject.getRestrictStatus()==1){
                RestrictProject use = restrictProjectMapper.selectByParam(new InputRestrictProject(tn.getBuyerId(), null, t.getCommodityId()));
                if (use!=null){
                    RestrictProject newRP=new RestrictProject();
                    newRP.setId(use.getId());
                    newRP.setLockTime(date);
                    newRP.setType(2);
                    if (!use.getAid().equals(tn.getSalesmanId())){
                        newRP.setAid(tn.getSalesmanId());
                    }
                    restrictProjectMapper.updateByPrimaryKeySelective(newRP);
                    UserTransferLog log=new UserTransferLog();
                    log.setAid(use.getAid());
                    log.setUid(use.getUid());
                    log.setPid(use.getPid());
                    log.setType(20);
                    log.setRemarks("签单触发锁定限时项目");
                    userTransferLogMapper.insertSelective(log);
                } else {
                    RestrictProject newRP=new RestrictProject();
                    newRP.setUid(tn.getBuyerId());
                    newRP.setAid(tn.getSalesmanId());
                    newRP.setPid(t.getCommodityId());
                    newRP.setLockTime(date);
                    newRP.setType(2);
                    restrictProjectMapper.insertSelective(newRP);
                }
            }
            details.setDispatchCount(t.getCommodityQuantity());
            details.setStockCount(t.getCommodityQuantity());
        }
        //如果不相等就切换
        if (!details.getDutyDep().equals(a.getDepartmentId())){
            details.setDutyDep(a.getDepartmentId());
        }
        tTaskMidMapper.updateByTid(details);
        //处理订单信息
        checkProjiectAllocation(t.getOrderNo());
        pushTaskChange(TokenManager.getAdminId(), taskReceiverId, type, t.getOrderNo());
        //派单后设置用户客户统计
        if (type ==0){
            updateAdminByAid(taskReceiverId);
        }else {
            updateAdminByAid(TokenManager.getAdminId(), taskReceiverId);
        }
    }

    public void updateAdminByAid(String aid,String aid2) {
        updateAdminByAid(aid);
        updateAdminByAid(aid2);
    }

    public void updateAdminByAid(String aid) {
        List<TOrderTaskBo> tOrderTaskBos = tOrderTaskMapper.selectAdminTaskByAid(aid);

        int htSatCount = 0,htSatScoreCount = 0,htSatNotScoreCount = 0,
                memberCount=0,memberScoreCount = 0,memberNotScoreCount = 0;
        BigDecimal ht_satSum=new BigDecimal(0);
        BigDecimal hySum=new BigDecimal(0);
        for (TOrderTaskBo tOrderTaskBo : tOrderTaskBos) {
            if (aid ==null) aid =tOrderTaskBo.getTaskReceiver();
            if (tOrderTaskBo.getcSort()==3||tOrderTaskBo.getcSort()==9){
                htSatCount++;
                if (tOrderTaskBo.getScoreStatus()==1){
                    htSatNotScoreCount++;
                }else if (tOrderTaskBo.getScoreStatus()==2){
                    htSatScoreCount++;
                    ht_satSum=ht_satSum.add(new BigDecimal(tOrderTaskBo.getScoreNumber()));
                }

            }else  if (tOrderTaskBo.getcSort()==6) {
                memberCount++;
                if (tOrderTaskBo.getScoreStatus()==1){
                    memberNotScoreCount++;
                }else if (tOrderTaskBo.getScoreStatus()==2){
                    memberScoreCount++;
                    hySum=hySum.add(new BigDecimal(tOrderTaskBo.getScoreNumber()));
                }

            }
        }
        BigDecimal htSatScoreAverage = BigDecimal.ZERO;
        BigDecimal memberScoreAverage = BigDecimal.ZERO;
        if (htSatScoreCount>0)htSatScoreAverage=ht_satSum.divide(new BigDecimal(htSatScoreCount),2, RoundingMode.HALF_UP);
        if (memberScoreCount>0)memberScoreAverage=hySum.divide(new BigDecimal(memberScoreCount),2, RoundingMode.HALF_UP);
        AdminProjectStatistics adminProjectStatistics = adminProjectStatisticsMapper.queryByAid(aid);
        AdminProjectStatistics aps=new AdminProjectStatistics();
        aps.setAid(aid);
        aps.setHtSatCount(htSatCount);
        aps.setHtSatScoreAverage(htSatScoreAverage.doubleValue());
        aps.setHtSatNotScoreCount(htSatNotScoreCount);
        aps.setHtSatScoreCount(htSatScoreCount);
        aps.setMemberScoreAverage(memberScoreAverage.doubleValue());
        aps.setMemberScoreCount(memberScoreCount);
        aps.setMemberNotScoreCount(memberNotScoreCount);
        aps.setMemberCount(memberCount);
        if (adminProjectStatistics==null){
            adminProjectStatisticsMapper.insert(aps);
        }else {
            aps.setId(adminProjectStatistics.getId());
            adminProjectStatisticsMapper.update(aps);
        }
    }

    /**
     *
     * @param aid 操作者
     * @param taskReceiverId 接收方
     * @param type type – 0管理员派单 1经理转交 2经理派单 3咨询师转交 4回退
     */
    private void pushTaskChange(String aid, String taskReceiverId,Integer type,String orderNo) {
        if (type==1||type==3){
            orderExamineMapper.updateDimissionTransfer(aid,taskReceiverId,null,orderNo);
        }else if (type==2){
            OrderExamine o=new OrderExamine();
            o.setAid(taskReceiverId);
            o.setOrderNo(orderNo);
            o.setCreateTime(new Date());
            o.setType(0);//咨询师经理
            o.setStatus(0);//正常
            orderExamineMapper.insertSelective(o);
        }else if (type==4){
            orderExamineMapper.updateBack(aid,taskReceiverId,orderNo);
        }
        newOrderChangeMapper.updateTaskExamineName(aid,taskReceiverId, OrderChangeProcess.JSY.getCode());
        newOrderChangeMapper.updateTaskExamineName(aid,taskReceiverId,OrderChangeProcess.JSJL.getCode());
    }

    public void addOrderLog(String orderNo, Integer code,String remarks) {
        TOrderLog tl=new TOrderLog();
        tl.setOrderNo(orderNo);
        tl.setProcess(code);
        tl.setAid(TokenManager.getAdminId());
        if(null!=remarks)tl.setRemarks(remarks);
        tOrderLogMapper.insertSelective(tl);

    }

    public void checkProjiectAllocation(String  orderNo) {
        TOrderNew tNew=new TOrderNew();
        tNew.setOrderNo(orderNo);
        tNew.setProcessStatus(getOrderProcessStatus(orderNo));
        tNew.setExamineName("");
        tOrderNewMapper.update(tNew);
        updateMidServiceProject(orderNo);
    }

    public Integer getOrderProcessStatus(String  orderNo) {
        Integer processStatus=ProcessStatus.YPZXSGLY.getCode();
        List<TOrderTaskBo> taskBos=tOrderTaskMapper.selectOrderTaskAll(orderNo,4);
        int i=0;
        for (TOrderTaskBo to : taskBos) {
            if (to.getTaskStatus()> TaskState.UN_DISTRIBUTION.getCode()&&to.getTaskStatus()<TaskState.INVALID.getCode()) {
                i++;
            }
        }
        if (i==taskBos.size()) {
            processStatus=ProcessStatus.YQBFPZXSGLY.getCode();
        }else if(i>0&&i<taskBos.size()){
            processStatus=ProcessStatus.YBFPZXSGLY.getCode();
        }else if(i==0){
            processStatus=ProcessStatus.YPZXSGLY.getCode();
        }
        return processStatus;
    }

    public void updateMidServiceProject(String orderNo) {
        List<TOrderTaskBo> taskBos = tOrderTaskMapper.selectOrderTaskAll(orderNo, 4);
        if (!taskBos.isEmpty()){
            List<String > cp=new ArrayList<>();
            List<String > cc=new ArrayList<>();
            StringBuilder ps=new StringBuilder();
            StringBuilder cs=new StringBuilder();
            for (TOrderTaskBo taskBo : taskBos) {
                if (!cp.contains(taskBo.getCommodityName())){
                    cp.add(taskBo.getCommodityName());
                    ps.append(taskBo.getCommodityName());
                    String str= NewProjectStatus.getValueByCode(taskBo.getProjectStatus());
                    String contacts=taskBo.getContacts()!=null?taskBo.getContacts():"暂无";
                    ps.append("-").append(str).append("-").append(contacts).append(",");
                }
                if (!cc.contains(taskBo.getCname())){
                    cc.add(taskBo.getCname());
                    cs.append(taskBo.getCname()).append(",");
                }
            }
            TOrderMid tOrderMid = new TOrderMid();
            tOrderMid.setOrderNo(orderNo);
            if (ps.length()>1)tOrderMid.setServiceProject(ps.substring(0,ps.length()-1));
            if (ps.length()>1)tOrderMid.setServiceType(cs.substring(0,cs.length()-1));
            tOrderMidMapper.updateByOrderNo(tOrderMid);
        }
    }

    /**
     * 	推动客户、业务渠道的锁定
     */
    private void pushUser(TOrderTask t, TOrderNew tn, Date date) {
        if (userMapper.checkLock(tn.getBuyerId())<1) {
            User user = userMapper.queryById(tn.getBuyerId());
            //新增如果不是渠道才转换时间和改成签单
            if (user!=null&&user.getNewChannel()!=1){
                //签单改成刷新客户跟进时间
                userLockReleaseMapper.updateByAidAndUid(tn.getBuyerId());
                userMapper.updateShareType(tn.getBuyerId(),tn.getSalesmanId());
            }
        }
        //判定用户最后签单时间
        pushSignTime(tn);
        //未锁定业务就锁定业务
        if (userLockReleaseMapper.checkLock(tn.getSalesmanId(),tn.getBuyerId(),t.getCommodityId())<1) {
            UserLockRelease ulr=new UserLockRelease();
            ulr.setId(UUID.randomUUID().toString());
            ulr.setBusinessProjectId(t.getCommodityId());
            ulr.setType(1);
            ulr.setUid(tn.getBuyerId());
            ulr.setAid(tn.getSalesmanId());
            ulr.setStatus(0);
            ulr.setLockTime(date);
            userLockReleaseMapper.insertSelective(ulr);
        }
        int i = userBusinessMapper.judgeBusiness(tn.getBuyerId(), t.getCommodityId(), tn.getSalesmanId());
        UserBusiness ub=new UserBusiness();
        ub.setId(UUID.randomUUID().toString());
        ub.setUid(tn.getBuyerId());
        ub.setAid(tn.getSalesmanId());
        ub.setFollowSituation(5);
        ub.setCustomerStatus(4);
        ub.setUpdateTime(date);
        ub.setRemarks("派单自动锁定客户");
        ub.setBusinessProjectId(t.getCommodityId());
        if (i>0){
            userBusinessMapper.updateByPrimaryKeySelective(ub);
        }else {
            ub.setCreateTime(date);
            userBusinessMapper.insertSelective(ub);
        }
        //如果是渠道客户更新渠道表
        UserChannel uc=new UserChannel();
        uc.setUid(tn.getBuyerId());
        uc.setStatus(ChannelStatus.YQD.getCode());
        uc.setSignTime(date);
        userChannelMapper.updateByUid(uc);
        //标记最新的打卡
        publicReleaseMapper.updateSignByAidAndUid(tn.getBuyerId(),tn.getSalesmanId());
    }
    private void pushSignTime(TOrderNew tn) {
        List<TOrderNewBo> tOrderNewBos = tOrderNewMapper.selectByuidandAid(tn.getBuyerId(), tn.getSalesmanId());
        Date lastSigningTime= tn.getSignTime();
        if (!tOrderNewBos.isEmpty()){
            for (TOrderNewBo e : tOrderNewBos) {
                if(e.getSignTime()!=null){
                    if (e.getSignTime().getTime()>lastSigningTime.getTime()){
                        lastSigningTime = e.getSignTime();
                    }
                }
            }
        }
        User u=new User();
        u.setId(tn.getBuyerId());
        u.setSignTime(lastSigningTime);
        userMapper.update(u);
    }

    private void projectDistributionPushUserMid(TOrderNew tn) {
        if (Objects.equals(tn.getProcessStatus(), ProcessStatus.YPZXSGLY.getCode())){
            UserMid um=new UserMid();
            String taskNames=userMidMapper.getUserTaskNames(tn.getBuyerId());
            UserMid use=userMidMapper.getUserDtails(tn.getBuyerId());
            um.setUid(tn.getBuyerId());
            um.setTaskNames(taskNames);
            um.setLastSigningTime(tn.getCreateTime());
            if(tn.getSalesType()!=null){
                um.setLastSalesType(tn.getSalesType());
            }
            BigDecimal signAmount;
            int signNumber;
            if (use!=null){
                if (use.getFirstSigningTime() != null) {
                    um.setFirstSigningTime(use.getFirstSigningTime()); }
                if (use.getSignAmount() != null) {
                    signAmount=use.getSignAmount().add(tn.getTotalAmount());
                }else{
                    signAmount=new BigDecimal(0).add(tn.getTotalAmount());

                }
                if (use.getSignNumber()!=null){
                    signNumber=use.getSignNumber()+1;
                }else {
                    signNumber=1;
                }
            }else {
                signAmount=new BigDecimal(0).add(tn.getTotalAmount());
                signNumber=1;
            }
            um.setSignAmount(signAmount);
            um.setSignNumber(signNumber);
            userMidMapper.updateByUid(um);
        }
    }
}
