package com.goafanti.business.service.impl;

import com.goafanti.business.bo.InputRestrictProject;
import com.goafanti.business.bo.OutRestrictProject;
import com.goafanti.business.bo.RestrictProjectPageList;
import com.goafanti.business.bo.UserRestrictProjectBo;
import com.goafanti.business.service.RestrictProjectService;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.dao.*;
import com.goafanti.common.enums.NoticeStatus;
import com.goafanti.common.error.BusinessException;
import com.goafanti.common.model.*;
import com.goafanti.common.utils.AsyncUtils;
import com.goafanti.core.mybatis.BaseMybatisDao;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.customer.bo.BusinessListBo;
import com.goafanti.customer.bo.FollowBusinessBo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class RestrictProjectServiceImpl extends BaseMybatisDao<RestrictProjectMapper> implements RestrictProjectService {
    @Resource
    private RestrictProjectMapper restrictProjectMapper;
    @Resource
    private UserTransferLogMapper userTransferLogMapper;
    @Resource
    private UserBusinessMapper userBusinessMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private AdminMapper adminMapper;
    @Resource
    private AsyncUtils asyncUtils;
    @Resource
    private BusinessProjectMapper businessProjectMapper;

    @Value(value = "${yxzj_max}")
    private Integer YXZJ_MAX = null;
    @Value(value = "${yxy_max}")
    private Integer YXY_MAX = null;
    @Value(value = "${yxjl_max}")
    private Integer YXJL_MAX = null;










    @Override
    public int add(InputRestrictProject in) {
        String aid = TokenManager.getAdminId();
        in.setAid(aid);
        in.setType(1);
        in.setLockTime(new Date());
        RestrictProject use = restrictProjectMapper.selectByParam(in);
        if (use != null && use.getType() != 0){
            throw new BusinessException("该项目已存在");
        }
        if(use ==null){
            restrictProjectMapper.insertSelective(in);
        }else if (use.getType() == 0){
            in.setId(use.getId());
            restrictProjectMapper.updateByPrimaryKeySelective(in);
        }
        int i = userBusinessMapper.judgeBusiness(in.getUid(), in.getPid(),null);
        if (i==0){
            UserBusiness ub=new UserBusiness();
            ub.setId(UUID.randomUUID().toString());
            ub.setAid(aid);
            ub.setUid(in.getUid());
            ub.setBusinessProjectId(in.getPid());
            ub.setCustomerStatus(in.getCustomerStatus());
            ub.setFollowSituation(in.getFollowSituation());
            ub.setCreateTime(new Date());
            ub.setRemarks("领取限定项目触发");
            userBusinessMapper.insertSelective(ub);
        }else {
            userBusinessMapper.updateAidByUidAndPid(aid,in.getUid(),in.getPid());
        }
        addUserLog(in,0);
        User user = userMapper.queryById(in.getUid());
        BusinessProject businessProject = businessProjectMapper.selectById(in.getPid());
        String str =String.format("客户：%s，已被营销员%s领取了【限定项目：%s】",user.getNickname(),TokenManager.getAdminToken().getName(),businessProject.getBname());
        //如果客户是当事人的不提示消息
        if (user.getAid()!=null&&!user.getAid().equals(aid)){
            asyncUtils.addNoticAndEmail(new Notice(user.getAid(), NoticeStatus.RECEIVE_RESTRICT_PROJECT.getCode(),str));
        }
        return 1;
    }

    /**
     *
     * @param i 0=新增 1=移除
     */
    private void addUserLog(RestrictProject in, int i) {
        addUserLog(in,i,null);
    }

    @Override
    public Object list(InputRestrictProject in) {
        in.setAid(TokenManager.getAdminId());
        String aname=null;
        List<OutRestrictProject> list = restrictProjectMapper.selectByUidAndAid(in);
        User u = userMapper.queryById(in.getUid());
        for (OutRestrictProject e : list) {
            if (e.getType()==null){
                e.setType(0);
            }
            if (e.getType()==0&&u.getAid()!=null&&u.getAid().equals(AFTConstants.CAOJIN_AID)){
                e.setType(1);
                if (aname==null){
                    Admin admin = adminMapper.selectById(AFTConstants.CAOJIN_AID);
                    aname  =admin.getName();
                }
                e.setAdminName(aname);
            }
        }

        return list;
    }

    @Override
    public Object update(String ids,Integer type,String takeAid) {
        String[] split = ids.split(",");
        Date date = new Date();
        for (String s : split) {
            Integer id = Integer.parseInt(s);
            RestrictProject in = new RestrictProject();
            RestrictProject use = restrictProjectMapper.selectByPrimaryKey(id);
            in.setId(id);
            if (type==0){
                in.setReleaseTime(date);
                in.setType(0);
                addUserLog(use,1);
            }else if (type==1){
                in.setLockTime(date);
                in.setAid(takeAid);
                in.setPid(use.getPid());
                in.setUid(use.getUid());
                addUserLog(use,2,takeAid);
            }
            restrictProjectMapper.updateByPrimaryKeySelective(in);
        }

        return 1;
    }

    @Override
    public Object pageList(InputRestrictProject in) {
        Map<String,Object> param = new HashMap<>();
        if (in.getUserName()!=null)param.put("userName",in.getUserName());
        if (in.getType()!=null)param.put("type",in.getType());
        if (in.getStartTime()!=null)param.put("startTime",in.getStartTime());
        if (in.getEndTime()!=null)param.put("endTime",in.getEndTime()+" 23:59:59");
        if (in.getProjectName()!=null)param.put("projectName",in.getProjectName());
        if (!TokenManager.hasRole(AFTConstants.SUPERADMIN)){
            param.put("aid",TokenManager.getAdminId());
        }
        Pagination<RestrictProjectPageList> page =
                (Pagination<RestrictProjectPageList>) findPage("RestrictProjectList", "RestrictProjectCount",
                        param, in.getPageNo(), in.getPageSize());
        pushPageList((List<RestrictProjectPageList>)page.getList());
        return page;
    }

    @Override
    public Object getFollowDetails(String uid) {
        User user = userMapper.findUserAccountDetail(uid);
        FollowBusinessBo fbb = new FollowBusinessBo();
        SimpleDateFormat format = new SimpleDateFormat(AFTConstants.YYYYMMDDHHMMSS);
        fbb.setFollowTime(format.format(new Date()));
        fbb.setIdentifyName(user.getIdentifyName());
        fbb.setUid(uid);
        List<BusinessListBo> businessListBos = userBusinessMapper.selectBusinessByUAid(uid, TokenManager.getAdminId());
        fbb.setUserBusinessList(businessListBos);
        return fbb;
    }



    private void pushPageList(List<RestrictProjectPageList> list) {
//        LocalDateTime now = LocalDateTime.now();
//        now=now.withHour(0).withMinute(0).withSecond(0).withNano(0);
        for (RestrictProjectPageList e : list) {
//            LocalDateTime lockTime = e.getLockTime().toInstant().atZone(java.time.ZoneId.systemDefault()).toLocalDateTime();
//            lockTime=lockTime.withHour(0).withMinute(0).withSecond(0).withNano(0);
            if (e.getType()==1){
//                LocalDateTime endTime = lockTime.plusDays(30);
//                long between = ChronoUnit.DAYS.between(now, endTime);
//                e.setPrivateDays(between>0?(int)between:0);
                //保持与旧版开发29-0一致，所以减去一天与私有客户同步
                e.setPrivateDays(e.getDays());
            }else if (e.getType()==2){
//                LocalDateTime endTime = lockTime.plusDays(270);
//                long between = ChronoUnit.DAYS.between(now, endTime);
//                e.setSignDays(between>0?(int)between:0);
                e.setSignDays(e.getDays());
            }
        }
    }

    private void addUserLog(RestrictProject in, int i, String takeAid) {
        UserTransferLog log = new UserTransferLog();
        log.setUid(in.getUid());

        log.setPid(in.getPid());
        if (i == 0){
            log.setAid(in.getAid());
            log.setType(21);
        } else if (i == 1) {
            log.setAid(in.getAid());
            log.setType(16);
        }else if (i == 2) {
            log.setAid(TokenManager.getAdminId());
            log.setTakeAid(takeAid);
            log.setType(17);
        }
        userTransferLogMapper.insertSelective(log);
    }

    @Override
    public Object getRestrictProjectUser(String ids) {
        List<UserRestrictProjectBo> list = new ArrayList<>();
        String aid=TokenManager.getAdminId();
        Admin my = adminMapper.selectById(aid);
        boolean flag= my.getPublicPurview() == 1;
        if (ids!=null&& !ids.isEmpty()){
            String[] split = ids.split(",");
            for (String s : split) {
                UserRestrictProjectBo bo = new UserRestrictProjectBo();
                bo.setUid(s);
                bo.setAdminSalesman(0);
                User user = userMapper.queryById(s);
                bo.setUserName(user.getNickname());
                if (!flag){
                    if (user.getShareType()==0||user.getShareType()==2){
                        //0私有 2签单 查询当前是否有签订限定项目
                        if (user.getAid().equals(aid)){
                            //是自己的
                            bo.setType(0);
                        }else{
                            //不是自己的
                            List<RestrictProject> restrictProjects = restrictProjectMapper.selectListByParam(new InputRestrictProject(s, aid));
                            if (!restrictProjects.isEmpty()){
                                // 有限定项目
                                if(TokenManager.hasRole(AFTConstants.SALESMAN)){
                                    bo.setType(1);
                                }else {
                                    bo.setType(5);
                                }
                            }else{
                                //没有限定
                                bo.setType(2);
                                Admin admin = adminMapper.selectById(user.getAid());
                                bo.setAdminName(admin.getName());
                            }
                        }
                    }else if(user.getShareType()==1){
                        //公共客户
                        bo.setType(3);
                    }
                }else {
                    bo.setType(4);
                }
            list.add(bo);
            }
        }
        return list;
    }

    @Override
    public boolean checkMax(String uid) {
        int i = userMapper.checkUserMax(TokenManager.getAdminId());
        int limitMax=101;
        //加入限定项目的数量  不算自己的签单只算非自己的客户
        Integer rpCount =restrictProjectMapper.selectPrivateByAid(TokenManager.getAdminId());
        rpCount=rpCount==null?0:rpCount;
        i=i+rpCount;
        User user = userMapper.queryById(uid);
        if (user.getShareType()==0||user.getShareType()==2){
            //0私有 2签单
            if (!user.getAid().equals(TokenManager.getAdminId())){
                //是自己的
                i++;
            }
       }else if(user.getShareType()==1) {
            //公共客户
            i++;
       }
        //张芬芳修改为200   0c92fbd3-873a-4907-b09e-83d0e8953d99
        if (TokenManager.getAdminId().equals("0c92fbd3-873a-4907-b09e-83d0e8953d99")){
            limitMax = 200;
        }else if (TokenManager.hasRole(AFTConstants.SALESMAN_DIRECTOR)){
            if(limitMax<YXZJ_MAX)limitMax = YXZJ_MAX;
        } else if (TokenManager.hasRole(AFTConstants.SALESMAN_MANAGER)){
            if(limitMax<YXJL_MAX)limitMax = YXJL_MAX;
        } else if (TokenManager.hasRole(AFTConstants.SALESMAN)){
            if(limitMax<YXY_MAX)limitMax = YXY_MAX;

        }
        System.out.println(String.format("已经领取【%s】,最大领取【%s】",i,limitMax));
        return i >= limitMax;
    }
}
