package com.goafanti.customer.service.impl;

import com.goafanti.Interview.bo.selectByUidAidBo;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.dao.*;
import com.goafanti.common.model.*;
import com.goafanti.common.utils.DateUtils;
import com.goafanti.common.utils.excel.NewExcelUtil;
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.InputSelectUserArchives;
import com.goafanti.customer.bo.OutSelectUserArchives;
import com.goafanti.customer.bo.OutSelectUserChannelArchives;
import com.goafanti.customer.bo.UserArchivesDetails;
import com.goafanti.customer.service.CustomerService;
import com.goafanti.customer.service.UserArchivesService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 客户档案表(UserArchives)表服务实现类
 *
 * @author makejava
 * @since 2024-07-12 11:52:01
 */
@Service("userArchivesService")
public class UserArchivesServiceImpl extends BaseMybatisDao< UserArchivesMapper> implements UserArchivesService {
    @Resource
    private UserArchivesMapper userArchivesMapper;
    @Resource
    private UserArchivesInterviewMapper userArchivesInterviewMapper;
    @Resource
    private CustomerService customerService;
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserMidMapper userMidMapper;
    @Resource
    private UserLimitCheckMapper userLimitCheckMapper;
    @Resource
    private AdminMapper adminMapper;
    @Resource
    private UserDataLogMapper userDataLogMapper;
    @Resource
    private UserFirstInterviewMapper userFirstInterviewMapper;
    @Resource
    private OrganizationIdentityMapper organizationIdentityMapper;
    @Resource
    private DistrictGlossoryMapper districtGlossoryMapper;
    @Resource
    private UserInterviewProjectMapper userInterviewProjectMapper;




    @Value(value = "${upload.path}")
    private final String	uploadPath			= null;



    @Override
    public Pagination<UserArchives> list(UserArchives userArchives, Integer pageNo, Integer pageSize) {
		Map<String, Object> params = new HashMap<>();
        params.put("in",userArchives); 
		return (Pagination<UserArchives>) findPage("findUserArchivesList",
				"findUserArchivesCount", params, pageNo, pageSize);
	}

    @Override
    public UserArchives queryByUid(String id) {
        UserArchives userArchives =userArchivesMapper.queryByUid(id);
        if (userArchives==null)userArchives =new UserArchives();
        return userArchives;
    }

    @Override
    public Object queryByUidAll(String id) {
        //查询等级 0=自己 1=全部
        int type=0;
        if (TokenManager.hasRole(AFTConstants.SUPERADMIN)){
            type=1;
        }
        UserArchivesDetails user = customerService.selectUserByUid(id);
        User u = userMapper.queryById(id);
        OrganizationIdentity ori = organizationIdentityMapper.selectOrgIdentityByUserId(id);
        pushProvincePlus(ori, user);

        if (u.getAid().equals(TokenManager.getAdminId())){
            user.setMyUser(1);
        }else {
            user.setMyUser(0);
        }
        user.setSignBills(u.getSignBills());
        UserArchives userArchives = queryByUid(id);
        List<OrganizationContactBook> customerContacts = userMapper.findCustomerContacts(id, TokenManager.getAdminId());
        List<OrganizationContactBook> collect = customerContacts.stream()
                .filter(e -> e.getMajor() == 1).collect(Collectors.toList());
        if (user.getMyUser()==0){
            for (OrganizationContactBook ob : collect) {
                ob.setName("***");
                ob.setMobile("***");
            }
        }
        if (!customerContacts.isEmpty()){
            user.setContactList(collect);
        }
        BeanUtils.copyProperties(userArchives, user);
        user.setUid(id);
        //设置面谈列表
        user.setInterviewList(userArchivesInterviewMapper.selectByUidAid(id, TokenManager.getAdminId()));
        //获取首次面谈时间
        List<UserFirstInterview> firstList;
        if (type == 0){
            firstList = userFirstInterviewMapper.selectByUidAid(id, TokenManager.getAdminId());
        }else {
            firstList = userFirstInterviewMapper.selectByUidAid(id, null);
        }
        if (!firstList.isEmpty()){
            UserFirstInterview userFirstInterview = firstList.get(0);
            user.setFirstInterviewDate(userFirstInterview.getFirstTime());
        }
        List<UserInterviewProjectBo> userInterviewProjects ;
        if (type==0){
            userInterviewProjects =userInterviewProjectMapper.selectByAid(TokenManager.getAdminId(), id);
        } else {
            userInterviewProjects =userInterviewProjectMapper.selectByAid(null, id);
        }
        user.setProjectList(userInterviewProjects);
        return user;
    }

    private void pushProvincePlus(OrganizationIdentity ori, UserArchivesDetails user) {
        user.setLocationProvince(ori.getLocationProvince());
        user.setLocationCity(ori.getLocationCity());
        user.setLocationArea(ori.getLocationArea());
        user.setIndustryName(ori.getIndustryName());
        List<DistrictGlossory> all = districtGlossoryMapper.getAll();
        if (ori.getLocationProvince()!=null){
            all.stream().filter(e -> e.getLevel()==1).collect(Collectors.toList()).forEach(e -> {
                if (ori.getLocationProvince().equals(e.getId())){
                        user.setLocationProvinceName(e.getName());
                }
            });
        }
        if (ori.getLocationCity()!=null){
            all.stream().filter(e -> e.getLevel()==2).collect(Collectors.toList()).forEach(e -> {
                if (ori.getLocationCity().equals(e.getId())){
                    user.setLocationCityName(e.getName());
                }
            });
        }
        if (ori.getLocationArea()!=null){
            all.stream().filter(e -> e.getLevel()==3).collect(Collectors.toList()).forEach(e -> {
                if (ori.getLocationArea().equals(e.getId())){
                    user.setLocationAreaName(e.getName());
                }
            });
        }
    }

    @Override
    public boolean checkPermission(String id) {
        User user = userMapper.queryById(id);
        if (user.getAid().equals(TokenManager.getAdminId())){
            return false;
        }
        UserLimitCheck userLimitCheck = userLimitCheckMapper.selectByUid(id);
        //如果没有和大于时间则不能查看
        return userLimitCheck == null || System.currentTimeMillis() > userLimitCheck.getCheckTime().getTime();
    }

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public UserArchives queryById(Integer id) {
        return this.userArchivesMapper.queryById(id);
    }

    /**
     * 新增数据
     *
     * @param userArchives 实例对象
     * @return 实例对象
     */
    @Override
    public UserArchives insert(UserArchives userArchives) {
        UserArchives query = userArchivesMapper.queryByUid(userArchives.getUid());
        if (query != null){
            userArchives.setId(query.getId());
            return update(userArchives,null);
        }else {
            if (userArchives.getAppearancePatentCount()!=null||
                    userArchives.getInventionPatentCount()!=null||
                    userArchives.getUtilityModelCount() !=null||
                    userArchives.getSoftwareWorksCount()!=null||
                    userArchives.getOtherCount()!=null
            ){
                int count = getCount(userArchives);
                userArchives.setPatentCount(count);
            }
            if(userArchives.getPatentCount()==null)userArchives.setPatentCount(0);
            userArchives.setCreateTime(new Date());
            this.userArchivesMapper.insert(userArchives);
        }
        return userArchives;
    }

    /**
     * 修改数据
     *
     * @param userArchives 实例对象
     * @return 实例对象
     */
    @Override
    public UserArchives update(UserArchives userArchives,Integer channelType) {
        if (userArchives.getAppearancePatentCount()!=null||
            userArchives.getInventionPatentCount()!=null||
                userArchives.getUtilityModelCount() !=null||
                userArchives.getSoftwareWorksCount()!=null||
                userArchives.getOtherCount()!=null
        ){
            int count = getCount(userArchives);
            userArchives.setPatentCount(count);
        }
        if (channelType!=null){
            String uid=null;
            if (userArchives.getUid()==null){
                UserArchives useData = this.queryById(userArchives.getId());
                uid=useData.getUid();
            }else {
                uid=userArchives.getUid();
            }
            userMidMapper.updateByUid(new UserMid(uid,channelType));
        }
        if(userArchives.getId()==null){
            return insert(userArchives);
        }else {
            addUserLog( userArchives);
            userArchives.setUpdateTime(new Date());
            this.userArchivesMapper.update(userArchives);
            return this.queryById(userArchives.getId());
        }

    }

    private void addUserLog(UserArchives userArchives) {
        UserArchives use = userArchivesMapper.queryById(userArchives.getId());
        Admin admin = adminMapper.selectById(TokenManager.getAdminId());
        List<UserDataLog> list =new ArrayList<>();
        if(userArchives.getFinancialData()!=null&&!Objects.equals(use.getFinancialData(),userArchives.getFinancialData())){
            String builder = admin.getName() + "修改了财务数据: " + use.getFinancialData() + "=>" + userArchives.getFinancialData();
            UserDataLog userDataLog = new UserDataLog(userArchives.getUid(), builder,1);
            list.add(userDataLog);
        }
        if (userArchives.getEarlyCommunication()!=null&&!Objects.equals(use.getEarlyCommunication(),userArchives.getEarlyCommunication())){
            String builder = admin.getName() + "修改了前期沟通: " + use.getEarlyCommunication() + "=>" + userArchives.getEarlyCommunication();
            UserDataLog userDataLog = new UserDataLog(userArchives.getUid(), builder,2);
            list.add(userDataLog);
        }
        if (userArchives.getInterviewIdeas()!=null&&!Objects.equals(use.getInterviewIdeas(),userArchives.getInterviewIdeas())){
            String builder = admin.getName() + "修改了面谈思路: " + use.getInterviewIdeas() + "=>" + userArchives.getInterviewIdeas();
            UserDataLog userDataLog = new UserDataLog(userArchives.getUid(), builder,3);
            list.add(userDataLog);
        }
        if (!list.isEmpty())userDataLogMapper.insertBatch(list);
    }

    /**
     * 计算专利总数,必须5个都传，不然会导致计算漏掉
     * @param userArchives 用户档案参数
     * @return count
     */
    private int getCount(UserArchives userArchives) {
        int count = 0;
        if (userArchives.getAppearancePatentCount()!=null){
            count+= userArchives.getAppearancePatentCount();
        }
        if (userArchives.getInventionPatentCount()!=null){
            count+= userArchives.getInventionPatentCount();
        }
        if (userArchives.getUtilityModelCount() !=null){
            count+= userArchives.getUtilityModelCount();
        }
        if (userArchives.getSoftwareWorksCount() !=null){
            count+= userArchives.getSoftwareWorksCount();
        }
        if (userArchives.getOtherCount()!=null){
            count+= userArchives.getOtherCount();
        }
        return count;
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.userArchivesMapper.deleteById(id) > 0;
    }


    @Override
    public Object selectUserArchives(InputSelectUserArchives in) {
        Map<String, Object> params = getParams(in);
        Pagination<?> page = findPage("selectUserArchivesList",
                "selectUserArchivesCount", params, in.getPageNo(), in.getPageSize());
//        List<OutSelectUserArchives> list = (List<OutSelectUserArchives>) page.getList();
//                 list.stream().forEach(e ->{
//                     List<selectByUidAidBo> userArchivesInterviews = userArchivesInterviewMapper.selectByUidAid(e.getId(), null);
//                     e.setPublicContent(pushContent(userArchivesInterviews));
//                 });
        return page;
    }

    private String pushContent(List<selectByUidAidBo> list) {
        if (!list.isEmpty()){
            StringBuilder builder = new StringBuilder();
            list.stream().forEach(e ->{
                builder.append(e.getAdminName()).append( "[").append(DateUtils.formatDateChineseYYYYMMddHH(e.getCreateTime())).append("]:\n");
                builder.append("前期沟通-客户的难处:").append(e.getEarlyCommunication()).append("\n");
                builder.append("客户的需求:").append(e.getCustomerDemand()).append("\n");
                builder.append("面谈思路:").append(e.getInterviewIdeas()).append("\n");
                builder.append("面谈达成的目的:").append(e.getInterviewPurpose()).append("\n");
                builder.append("经理/上级面谈建议:").append(e.getInterviewRecommend()).append("\n");
                if (e.getInterviewFeedback()!=null)builder.append("面谈的反馈:").append(e.getInterviewFeedback()).append("\n");
                if (e.getFollowUpPlan()!=null)builder.append("后续计划:").append(e.getFollowUpPlan()).append("\n");
                builder.append("\n");
            });
            return builder.toString();
        }
        return null;
    }

    private Map<String, Object> getParams(InputSelectUserArchives in) {
        Map<String, Object> params = new HashMap<>();
        if (in.getNewChannel() != null)params.put("newChannel", in.getNewChannel());
        if (in.getShareType() != null)params.put("shareType", in.getShareType());
        if (in.getChannelType() != null){
            String[] split = in.getChannelType().split(",");
            params.put("channelType", split);
        }
        if (in.getName() != null)params.put("name", in.getName());
        if (in.getAid() != null)params.put("aid", in.getAid());
        if (in.getBusinessScope() != null)params.put("businessScope", in.getBusinessScope());
        if (in.getIndustry() != null){
            String[] split = in.getIndustry().split(",");
            params.put("industry", split);
        }
        if (in.getSignBills()!=null)params.put("signBills", in.getSignBills());
        if (in.getStartTime() != null&&in.getEndTime() != null){
            params.put("startTime", in.getStartTime());
            params.put("endTime", in.getEndTime()+" 23:59:59");
        }
        return params;

    }

    @Override
    public Object addAwards(String uid,Integer status) {
        return updateAwards(uid,status);
    }

    @Override
    public Object updateAwards(String uid, Integer status) {
        UserArchives use = userArchivesMapper.queryByUid(uid);
        UserArchives userArchives = new UserArchives();
        userArchives.setId(use.getId());
        userArchives.setAwardsStatus(status);
        if (status==2)userArchives.setAwardsTime(new Date());
        userArchivesMapper.update(userArchives);
        if (status==2){
            userArchivesMapper.updateStatus();
        }
        return 1;
    }

    @Override
    public Object selectUserArchivesExport(InputSelectUserArchives in) {
        Map<String, Object> params = getParams(in);
        List<OutSelectUserArchives> list= (List<OutSelectUserArchives>) findList("selectUserArchivesList",
                params, 1, 999999);
        list.stream().forEach(e ->{
            List<selectByUidAidBo> userArchivesInterviews = userArchivesInterviewMapper.selectByUidAid(e.getId(), null);
            e.setPublicContent(pushContent(userArchivesInterviews));
        });
        String sheetName = "用户档案";
        if (in.getNewChannel()==1){
            sheetName="渠道档案";
            NewExcelUtil<OutSelectUserChannelArchives> newExcelUtil = new NewExcelUtil<>(OutSelectUserChannelArchives.class);
            List<OutSelectUserChannelArchives> newList = new ArrayList<>();
            //将类型转换
            list.stream().forEach(e ->{
                OutSelectUserChannelArchives outSelectUserChannelArchives = new OutSelectUserChannelArchives();
                BeanUtils.copyProperties(e,outSelectUserChannelArchives);
                newList.add(outSelectUserChannelArchives);
            });
            return newExcelUtil.exportExcel( newList,sheetName,uploadPath);
        }else {
            NewExcelUtil<OutSelectUserArchives> newExcelUtil = new NewExcelUtil<>(OutSelectUserArchives.class);
            return newExcelUtil.exportExcel( list,sheetName,uploadPath);
        }
    }


}
