package com.ssm.manage.service.impl;

import com.github.pagehelper.PageInfo;
import com.ssm.core.service.impl.BaseServiceImpl;
import com.ssm.core.utils.BigDecimalUtils;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.core.utils.StoreParaUtils;
import com.ssm.manage.dao.SsmProjectDao;
import com.ssm.manage.entity.*;
import com.ssm.manage.mapper.BaseProjectMapper;
import com.ssm.manage.query.CourseAccountRequest;
import com.ssm.manage.query.ProjectRequest;
import com.ssm.manage.query.StoreRequest;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.response.StaffResponse;
import com.ssm.manage.response.UserResponse;
import com.ssm.manage.service.*;
import com.ssm.manage.utils.Constant;
import com.ssm.util.RedisClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SsmProjectServiceImpl extends BaseServiceImpl<BaseProject> implements SsmProjectService {

    @Autowired
    private RedisClient<StaffResponse> redisClient;

    @Autowired
    private RedisClient<PageInfo<BaseProject>> projectRedisClient;

    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;

    @Autowired
    private SsmProjectTypeService ssmProjectTypeService;

    @Autowired
    private SsmStoreParaService ssmStoreParaService;

    @Autowired
    private SsmCourseAccountService ssmCourseAccountService;

    @Autowired
    private SsmProjectDao dao;

    @Autowired
    private BaseProjectMapper mapper;

    @Override
    public SsmProjectDao getDao() {
        return dao;
    }

    private static String staffKey = "staffKey";

    @Override
    public PageInfo<BaseProject> selectPage(ProjectRequest projectRequest) {
        PageInfo<BaseProject> pageInfo = new PageInfo<>();
//        if (projectRedisClient.hasKey(getKey(projectRequest.getStoreId(),key))){
//             pageInfo = projectRedisClient.get(getKey(projectRequest.getStoreId(),key));
//        }else {
            pageInfo = dao.selectPage(projectRequest);
//            projectRedisClient.set(getKey(projectRequest.getStoreId(),key),pageInfo,RedisClient.EXPIRE_TIME_ONE_DAY);
//        }
        return pageInfo;
    }

    @Override
    public PageInfo<BaseProject> repeatPage(ProjectRequest projectRequest) {
        PageInfo<BaseProject> pageInfo = new PageInfo<>();
//        if (projectRedisClient.hasKey(getKey(projectRequest.getStoreId(),key))){
//             pageInfo = projectRedisClient.get(getKey(projectRequest.getStoreId(),key));
//        }else {
        pageInfo = dao.repeatPage(projectRequest);
//            projectRedisClient.set(getKey(projectRequest.getStoreId(),key),pageInfo,RedisClient.EXPIRE_TIME_ONE_DAY);
//        }
        return pageInfo;
    }

    @Override
    public PageInfo<BaseProject> selectPageNew(ProjectRequest projectRequest)throws SmsException {
        PageInfo<BaseProject> pageInfo = new PageInfo<>();
//        if (projectRedisClient.hasKey(getKey(projectRequest.getStoreId(),key))){
//             pageInfo = projectRedisClient.get(getKey(projectRequest.getStoreId(),key));
//        }else {
            pageInfo = dao.selectPageNew1(projectRequest);
//            projectRedisClient.set(getKey(projectRequest.getStoreId(),key),pageInfo,RedisClient.EXPIRE_TIME_ONE_DAY);
//        }
        return pageInfo;
    }
    @Override
    public PageInfo<BaseProject> selectPageType(ProjectRequest projectRequest) {
        PageInfo<BaseProject> pageInfo = new PageInfo<>();
//        if (projectRedisClient.hasKey(getKey(projectRequest.getStoreId(),key))){
//             pageInfo = projectRedisClient.get(getKey(projectRequest.getStoreId(),key));
//        }else {
            pageInfo = dao.selectPageType(projectRequest);
//            projectRedisClient.set(getKey(projectRequest.getStoreId(),key),pageInfo,RedisClient.EXPIRE_TIME_ONE_DAY);
//        }
        return pageInfo;
    }

    @Override
    public int addProject(ProjectRequest projectRequest,String phone) throws SmsException {
        if(projectRequest.getValidTime()==null){
            projectRequest.setValidTime(0);
        }

        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(projectRequest.getStoreId());
        BaseProject baseProject = new BaseProject();
        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
        for (BaseStores pagesorganization : pagesorganizations) {
            if(null == pagesorganization.getParentId()){
                baseProject.setStoreId(pagesorganization.getId());
            }
        }
        baseProject.setProjectNum(projectRequest.getProjectNum());
        BaseProject baseProject1 = dao.selectOne(baseProject);
        if(null != baseProject1){
            throw new SmsException(ResponseCode.MSG,"该项目编码总店已经存在，不能使用");
        }
        this.checkNum(projectRequest.getProjectNum().toString(), projectRequest.getProjectName(), projectRequest.getStoreId(),Long.valueOf(1));
        BaseProject project = new BaseProject();
        project.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());//项目编码
        //project.setNewId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        project.setState(1);
        project.setProjectNum(projectRequest.getProjectNum());
        //project.setProjectNum(String.valueOf(projectRequest.getId()));
        project.setProjectName(projectRequest.getProjectName());
        project.setLabel(projectRequest.getLabel());
        project.setGoldInterval(projectRequest.getGoldInterval());
        project.setLongOperationTime(projectRequest.getLongOperationTime());
        project.setModerateOperationTime(projectRequest.getModerateOperationTime());
        project.setShortOperationTime(projectRequest.getShortOperationTime());
        project.setProjectTypeId(projectRequest.getProjectTypeId());
        project.setProjectTypeName(projectRequest.getProjectTypeName());
        project.setStoreId(projectRequest.getStoreId());
        project.setStoreName(projectRequest.getStoreName());
        project.setPrice(projectRequest.getPrice());
        project.setMinumumPrice(projectRequest.getMinumumPrice());
        project.setMinumumTimes(projectRequest.getMinumumTimes());
        project.setDirectConsumption(projectRequest.getDirectConsumption());
        project.setPriceMember(projectRequest.getPriceMember());
        project.setMinumumPriceMember(projectRequest.getMinumumPriceMember());
        project.setValidTime(projectRequest.getValidTime());
        project.setNoDiscount(projectRequest.getNoDiscount());
        project.setProjectTypeNum(projectRequest.getProjectTypeNum());
        project.setTopPrice(projectRequest.getTopPrice());
        project.setTopPriceMember(projectRequest.getTopPriceMember());
        if(null == projectRequest.getSalesDeadline()){
            project.setSalesDeadline("2099-01-01");
        }else{
            project.setSalesDeadline(projectRequest.getSalesDeadline());
        }

        //美发版小程序使用 添加时直接添加业绩提成
        project.setAchievementZhonggong(projectRequest.getAchievementZhonggong());
        project.setAchievementSmall(projectRequest.getAchievementSmall());
        project.setCommissionZhonggong(projectRequest.getCommissionZhonggong());
        project.setCommissionSmall(projectRequest.getCommissionSmall());
        project.setBrokerage(projectRequest.getBrokerage());
        project.setIsCooperation(projectRequest.getIsCooperation());
        project.setStoreType(projectRequest.getStoreType());
        project.setUnifiedDue(projectRequest.getUnifiedDue());
        project.setServicingTime(projectRequest.getServicingTime());

        project.setOvertime(projectRequest.getOvertime());
        project.setOvertimeMoney(projectRequest.getOvertimeMoney());
        project.setMarketComm(projectRequest.getCardMarketComm());
        project.setClockComm(projectRequest.getCardClockComm());
        project.setRoundClockComm(projectRequest.getCardRoundClockComm());
        project.setProjectNature(projectRequest.getProjectNature());
        project.setCardMarketComm(projectRequest.getCardMarketComm());
        project.setCardClockComm(projectRequest.getCardClockComm());
        project.setCardRoundClockComm(projectRequest.getCardRoundClockComm());
        project.setDeptName(projectRequest.getDeptName());
        project.setIsCardPay(projectRequest.getIsCardPay());
        project.setSmokeCommissionWay(projectRequest.getSmokeCommissionWay());
        if(projectRequest.getDirectConsumption()==1){
            project.setProjectNature(0);
        }

        StaffResponse staffResponse = new StaffResponse();
        if (redisClient.hasKey(getStaffKey(phone))){
            staffResponse = redisClient.get(getStaffKey(phone));
            project.setFounderStaff(staffResponse.getStaffName());
        }
        Set<String> keys = redisClient.keys(getStaffKey(phone) + "*");
        //从redis查询 设置录单人信息 app使用
        if (keys.size() > 0){
            String key =  new ArrayList<>(keys).get(0);
            staffResponse = redisClient.get(key);
            project.setFounderStaff(staffResponse.getStaffName());
        }
        project.setFounderDatetime(new Date());
        int i = dao.saveNotNull(project);

        return i;
    }

    @Override
    public int updateProject(ProjectRequest projectRequest, String phone) throws SmsException {
        if(projectRequest.getValidTime()==null){
            projectRequest.setValidTime(0);
        }

        this.checkNum(projectRequest.getProjectNum(), projectRequest.getProjectName(), projectRequest.getStoreId(),projectRequest.getId());
        BaseProject project = new BaseProject();
        project.setId(projectRequest.getId());
        BaseProject baseProject = dao.selectByPrimaryKey(project.getId());
        String projectNum = baseProject.getProjectNum();
        BeanUtils.copyProperties(projectRequest,project);
        //取反，为true修改项目名称
//        if(!projectName.equals(projectRequest.getProjectName())){
//
//
//        }
        project.setProjectNum(projectNum);
//        project.setProjectName(projectName);
//        project.setId(projectRequest.getId());
//        //project.setProjectNum(String.valueOf(projectRequest.getProjectNum()));
//        //project.setProjectName(projectRequest.getProjectName());
//        project.setLabel(projectRequest.getLabel());
//        project.setGoldInterval(projectRequest.getGoldInterval());
//        project.setLongOperationTime(projectRequest.getLongOperationTime());
//        project.setModerateOperationTime(projectRequest.getModerateOperationTime());
//        project.setShortOperationTime(projectRequest.getShortOperationTime());
//        project.setProjectTypeId(projectRequest.getProjectTypeId());
//        project.setProjectTypeName(projectRequest.getProjectTypeName());
//        project.setProjectTypeNum(projectRequest.getProjectTypeNum());
//        project.setState(projectRequest.getState());
//
//        project.setPrice(projectRequest.getPrice());
//        project.setMinumumPrice(projectRequest.getMinumumPrice());
//        project.setMinumumTimes(projectRequest.getMinumumTimes());
//        project.setDirectConsumption(projectRequest.getDirectConsumption());
//        project.setPriceMember(projectRequest.getPriceMember());
//        project.setMinumumPriceMember(projectRequest.getMinumumPriceMember());
//        project.setValidTime(projectRequest.getValidTime());
//        //美发版小程序使用 添加时直接添加业绩提成
//        project.setAchievementZhonggong(projectRequest.getAchievementZhonggong());
//        project.setAchievementSmall(projectRequest.getAchievementSmall());
//        project.setCommissionZhonggong(projectRequest.getCommissionZhonggong());
//        project.setCommissionSmall(projectRequest.getCommissionSmall());
//        project.setBrokerage(projectRequest.getBrokerage());
//        project.setNoDiscount(projectRequest.getNoDiscount());
//        project.setStoreType(projectRequest.getStoreType());
//        project.setTopPrice(projectRequest.getTopPrice());
//        project.setTopPriceMember(projectRequest.getTopPriceMember());
//        project.setSalesDeadline(projectRequest.getSalesDeadline());
//        project.setIsCooperation(projectRequest.getIsCooperation());
//        project.setUnifiedDue(projectRequest.getUnifiedDue());
//        project.setServicingTime(projectRequest.getServicingTime());
//        project.setOvertime(projectRequest.getOvertime());
//        project.setOvertimeMoney(projectRequest.getOvertimeMoney());
//        project.setMarketComm(projectRequest.getCardMarketComm());
//        project.setClockComm(projectRequest.getCardClockComm());
//        project.setRoundClockComm(projectRequest.getCardRoundClockComm());
//        project.setProjectNature(projectRequest.getProjectNature());
//        project.setCardMarketComm(projectRequest.getCardMarketComm());
//        project.setCardClockComm(projectRequest.getCardClockComm());
//        project.setCardRoundClockComm(projectRequest.getCardRoundClockComm());
//        project.setDeptName(projectRequest.getDeptName());
//        project.setIsCardPay(projectRequest.getIsCardPay());
        if(projectRequest.getDirectConsumption()==1){
            project.setProjectNature(0);
        }

        StaffResponse staffResponse = new StaffResponse();
        if (redisClient.hasKey(getStaffKey(phone))){
            staffResponse = redisClient.get(getStaffKey(phone));
            project.setModifyBy(staffResponse.getStaffName());
        }
        Set<String> keys = redisClient.keys(getStaffKey(phone) + "*");
        //从redis查询 设置录单人信息 app使用
        if (keys.size() > 0){
            String key =  new ArrayList<>(keys).get(0);
            staffResponse = redisClient.get(key);
            project.setModifyBy(staffResponse.getStaffName());
        }
        project.setModifyDatetime(new Date());
//        project.setProjectTypeName(project.getProjectTypeName().split("-")[1].trim());
        int i = dao.updateByPrimaryKey(project);
//        if (i > 0){
//            projectRedisClient.delete(getKey(projectRequest.getStoreId(),key));
//        }
        return i;
    }


    @Override
    public int deleteProject(ProjectRequest projectRequest) throws SmsException {
        int i = 0;
        //查询疗程账户 是否存在账户未使用完毕 否则不允许删除
        CourseAccountRequest courseAccountRequest = new CourseAccountRequest();
        courseAccountRequest.setStoreId(projectRequest.getStoreId());
        courseAccountRequest.setCourseProjectId(projectRequest.getId());
        List<CourseAccount> accountList = ssmCourseAccountService.selectList(courseAccountRequest);
        if (accountList.size() > 0){
            throw new SmsException(ResponseCode.MSG,"项目进行过交易，不能进行删除");
        }else {

            BaseProject project = new BaseProject();
            project.setId(projectRequest.getId());
            project.setOvertime("cash");
            List<BaseProject> select = dao.select(project);
            if(select.size()==0){
                project.setOvertime(null);
                i = dao.delete(project);
            }else{
                throw new SmsException(ResponseCode.MSG,"项目已经进行过收银,不能进行删除");
            }
            //取消redis存储
//            if (i > 0) {
//                projectRedisClient.delete(getKey(projectRequest.getStoreId(), key));
//            }
        }
        return i;
    }

    @Override
    public int updateStates(ProjectRequest projectRequest) throws SmsException {
        BaseProject project = dao.selectByPrimaryKey(projectRequest.getId());

        //启用时校验当前项目项目类别是否已启用
        if (projectRequest.getState() == 1){
            BaseProjectType projectType = ssmProjectTypeService.selectByPrimaryKey(project.getProjectTypeId());
            if (projectType==null || projectType.getState()==null || projectType.getState() != 1){
                throw new SmsException(ResponseCode.IS_ALREADY_STOP,"项目类别已停用");
            }
        }
        project.setState(projectRequest.getState());
        int i = dao.updateByPrimaryKeySelective(project);
//        if (i > 0){
//            projectRedisClient.delete(getKey(projectRequest.getStoreId(),key));
//        }
        return i;
    }

    public String getKey(String userNum){
        String key = "";
        if (StringUtils.isNotBlank(userNum)){
            key = Constant.userKey + userNum;
        }
        return key;
    }

    @Override
    @Transactional
    public int importProject(List<BaseProject> projectRequest,String userNum) throws SmsException {
        boolean status = true;

        for (BaseProject baseProject : projectRequest) {
//            BaseProject project = new BaseProject();
//            project.setProjectName(baseProject.getProjectName());
//            project.setLabel(baseProject.getLabel());
//            project.setGoldInterval(baseProject.getGoldInterval());
//            project.setLongOperationTime(baseProject.getLongOperationTime());
//            project.setModerateOperationTime(baseProject.getModerateOperationTime());
//            project.setShortOperationTime(baseProject.getShortOperationTime());
//            project.setProjectTypeId(baseProject.getProjectTypeId());
//            project.setProjectTypeName(baseProject.getProjectTypeName());
//            project.setId(baseProject.getId());
//
//            project.setPrice(baseProject.getPrice());
//            project.setMinumumPrice(baseProject.getMinumumPrice());
//            project.setMinumumTimes(baseProject.getMinumumTimes());
//            project.setDirectConsumption(baseProject.getDirectConsumption());
//            project.setPriceMember(baseProject.getPriceMember());
//            project.setMinumumPriceMember(baseProject.getMinumumPriceMember());
//            project.setValidTime(baseProject.getValidTime());
//            //美发版小程序使用 添加时直接添加业绩提成
//            project.setAchievementZhonggong(baseProject.getAchievementZhonggong());
//            project.setAchievementSmall(baseProject.getAchievementSmall());
//            project.setCommissionZhonggong(baseProject.getCommissionZhonggong());
//            project.setCommissionSmall(baseProject.getCommissionSmall());
//            project.setBrokerage(baseProject.getBrokerage());

            List<BaseProject> baseProjects1 = dao.selectOneimp(baseProject);
            if(null != baseProjects1){ //存在-修改
                if(baseProjects1.size()!=0){
                    if(baseProjects1.size()==1){
                        if (redisClient.hasKey(getKey(userNum))){
                            StaffResponse staffResponse = redisClient.get(getKey(userNum));
                            baseProject.setFounderStaff(staffResponse.getStaffName());
                            baseProject.setFounderDatetime(new Date());
                        }
                        baseProject.setId(baseProjects1.get(0).getId());
                        int insert = dao.updateByPrimaryKeySelective(baseProject);
                        if(insert>0){

                        }else{
                            status=false;
                        }
                    }else{
                        throw new SmsException(ResponseCode.DATABASE_EXCEPTION);
                    }
                }else{ //不存在-新增
                    if (redisClient.hasKey(getKey(userNum))){
                        StaffResponse staffResponse = redisClient.get(getKey(userNum));
                        baseProject.setModifyBy(staffResponse.getStaffName());
                        baseProject.setModifyDatetime(new Date());
                    }
                    baseProject.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                    int insert = dao.insert(baseProject);
                    if(insert>0){

                    }else{
                        status=false;
                    }
                }
            }else{ //不存在-新增
                if (redisClient.hasKey(getKey(userNum))){
                    StaffResponse staffResponse = redisClient.get(getKey(userNum));
                    baseProject.setModifyBy(staffResponse.getStaffName());
                    baseProject.setModifyDatetime(new Date());
                }
                baseProject.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                int insert = dao.insert(baseProject);
                if(insert>0){

                }else{
                    status=false;
                }
            }
        }
        if(status){
            return 1;
        }else{
            throw new SmsException(ResponseCode.DATABASE_EXCEPTION);
        }
    }

    @Override
    @Transactional
    public int assignProjectList(List< ProjectRequest>  projectRequests,String userNum) throws SmsException {
        boolean status = true;
        for (ProjectRequest projectRequest : projectRequests) {
            for (StoreRequest baseStore : projectRequest.getBaseStores()) {
                BaseProject baseProject1 = new BaseProject();
                baseProject1.setStoreId(baseStore.getId());
                baseProject1.setProjectNum(projectRequest.getProjectNum());

                List<BaseProject> baseProjects1 = dao.selectOneimp(baseProject1);
                if(baseProjects1.size()>0){
                    BaseProject baseProject = new BaseProject();
                    BeanUtils.copyProperties(projectRequest,baseProject);
                    if (redisClient.hasKey(getKey(userNum))){
                        StaffResponse staffResponse = redisClient.get(getKey(userNum));
                        baseProject.setFounderStaff(staffResponse.getStaffName());
                        baseProject.setFounderDatetime(new Date());
                    }
                    //设置录单人信息
                    if (redisClient.hasKey(getStaffKey(projectRequest.getUpdateCommPhone()))){
                        StaffResponse staffResponse = redisClient.get(getStaffKey(projectRequest.getUpdateCommPhone()));
                        baseProject.setModifyBy(staffResponse.getStaffName());
                        baseProject.setModifyDatetime(new Date());
                    }
                    baseProject.setStoreId(baseStore.getId());
                    baseProject.setStoreName(baseStore.getStoreName());
                    baseProject.setId(baseProjects1.get(0).getId());
                    int insert = dao.updateByPrimaryKeySelective(baseProject);
                    if(insert>0){

                    }else{
                        status=false;
                    }
                }else{ //不存在-新增
                    BaseProject baseProject = new BaseProject();
                    BeanUtils.copyProperties(projectRequest,baseProject);
                    if (redisClient.hasKey(getKey(userNum))){
                        StaffResponse staffResponse = redisClient.get(getKey(userNum));
                        baseProject.setModifyBy(staffResponse.getStaffName());
                        baseProject.setModifyDatetime(new Date());
                    }
                    //设置录单人信息
                    if (redisClient.hasKey(getStaffKey(projectRequest.getUpdateCommPhone()))){
                        StaffResponse staffResponse = redisClient.get(getStaffKey(projectRequest.getUpdateCommPhone()));
                        baseProject.setModifyBy(staffResponse.getStaffName());
                        baseProject.setModifyDatetime(new Date());
                    }
                    baseProject.setStoreId(baseStore.getId());
                    baseProject.setStoreName(baseStore.getStoreName());
                    baseProject.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                    int insert = dao.insert(baseProject);
                    if(insert>0){

                    }else{
                        status=false;
                    }
                }
            }
        }
        if(status){
            return 1;
        }else{
            throw new SmsException(ResponseCode.DATABASE_EXCEPTION);
        }
    }

    @Override
    @Transactional
    public int assignProject(ProjectRequest  projectRequest,String userNum) throws SmsException {
        boolean status = true;

            for (StoreRequest baseStore : projectRequest.getBaseStores()) {
                BaseProject baseProject1 = new BaseProject();
                baseProject1.setStoreId(baseStore.getId());
                baseProject1.setProjectNum(projectRequest.getProjectNum());

                List<BaseProject> baseProjects1 = dao.selectOneimp(baseProject1);
                if(baseProjects1.size()>0){
                    BaseProject baseProject = new BaseProject();
                    BeanUtils.copyProperties(projectRequest,baseProject);
                    if (redisClient.hasKey(getKey(userNum))){
                        StaffResponse staffResponse = redisClient.get(getKey(userNum));
                        baseProject.setFounderStaff(staffResponse.getStaffName());
                        baseProject.setFounderDatetime(new Date());
                    }

                    baseProject.setStoreId(baseStore.getId());
                    baseProject.setStoreName(baseStore.getStoreName());
                    baseProject.setId(baseProjects1.get(0).getId());
                    //设置录单人信息
                    if (redisClient.hasKey(getStaffKey(projectRequest.getUpdateCommPhone()))){
                        StaffResponse staffResponse = redisClient.get(getStaffKey(projectRequest.getUpdateCommPhone()));
                        baseProject.setModifyBy(staffResponse.getStaffName());
                        baseProject.setModifyDatetime(new Date());
                    }
                    int insert = dao.updateByPrimaryKeySelective(baseProject);
                    if(insert>0){

                    }else{
                        status=false;
                    }
                }else{ //不存在-新增
                    BaseProject baseProject = new BaseProject();
                    BeanUtils.copyProperties(projectRequest,baseProject);
                    if (redisClient.hasKey(getKey(userNum))){
                        StaffResponse staffResponse = redisClient.get(getKey(userNum));
                        baseProject.setModifyBy(staffResponse.getStaffName());
                        baseProject.setModifyDatetime(new Date());
                    }
                    //设置录单人信息
                    if (redisClient.hasKey(getStaffKey(projectRequest.getUpdateCommPhone()))){
                        StaffResponse staffResponse = redisClient.get(getStaffKey(projectRequest.getUpdateCommPhone()));
                        baseProject.setModifyBy(staffResponse.getStaffName());
                        baseProject.setModifyDatetime(new Date());
                    }
                    baseProject.setStoreId(baseStore.getId());
                    baseProject.setStoreName(baseStore.getStoreName());
                    baseProject.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                    int insert = dao.insert(baseProject);
                    if(insert>0){

                    }else{
                        status=false;
                    }
                }
            }
        if(status){
            return 1;
        }else{
            throw new SmsException(ResponseCode.DATABASE_EXCEPTION);
        }
    }

    @Override
    public int setAchiComm(ProjectRequest projectRequest) throws SmsException {

        StoreRequest storeRequest1 = new StoreRequest();
        storeRequest1.setId(projectRequest.getStoreId());
        BaseStores baseStores1 = ssmBaseStoreService.pagesorganizations(storeRequest1).stream().filter(baseStores -> null == baseStores.getParentId()).findAny().orElse(null);
        //查询门店项目设置业绩提成是否需要校验 0不校验 1校验
        StoreParament parament = StoreParaUtils.getStorePara(baseStores1.getId(), Constant.pro_achi_comm_verify);
        if ("1".equals(parament.getParamentValue())) {

            StoreParament commissionCheck = StoreParaUtils.getStorePara(baseStores1.getId(), Constant.commissionCheck);
            if(commissionCheck.getParamentValue().trim().equals("1")) {
                //对业绩和提成设置进行校验
                BaseProject baseProject = dao.selectByPrimaryKey(projectRequest.getId());

                //疗程最低销售价格
                BigDecimal saleTotalMoney = BigDecimalUtils.multiply(baseProject.getPriceMember(), BigDecimalUtils.bigDecimal(baseProject.getMinumumTimes().toString()));
                BigDecimal price = BigDecimalUtils.compareTo(baseProject.getPriceMember(), baseProject.getPrice()) == -1 ?  baseProject.getPrice():baseProject.getPriceMember() ;
                BigDecimal money = BigDecimalUtils.bigDecimal("0");
                BigDecimal ratio = BigDecimalUtils.bigDecimal("0", 3);

                //销售业绩提成标准校验
                if (null != projectRequest.getSalesAchievement()) {
                    if (BigDecimalUtils.compareTo(projectRequest.getSalesAchievement(), BigDecimalUtils.bigDecimal("1")) == 1) {
                        if (BigDecimalUtils.compareTo(projectRequest.getSalesAchievement(), baseProject.getPriceMember()) == 1) {
                            throw new SmsException(ResponseCode.NOT_MEET_REQUIREMENTS_S, "项目现付销售业绩");
                        }
                    }
                }
                if (null != projectRequest.getCardSalesAchievement()) {
                    if (BigDecimalUtils.compareTo(projectRequest.getCardSalesAchievement(), BigDecimalUtils.bigDecimal("1")) == 1) {
                        if (BigDecimalUtils.compareTo(projectRequest.getCardSalesAchievement(), baseProject.getPriceMember()) == 1) {
                            throw new SmsException(ResponseCode.NOT_MEET_REQUIREMENTS_S, "项目卡付销售业绩");
                        }
                    }
                }
                if (null != projectRequest.getSalesCommission()) {
                    if (BigDecimalUtils.compareTo(projectRequest.getSalesCommission(), BigDecimalUtils.bigDecimal("1")) == 1) {
                        if (BigDecimalUtils.compareTo(projectRequest.getSalesCommission(), baseProject.getPriceMember()) == 1) {
                            throw new SmsException(ResponseCode.NOT_MEET_REQUIREMENTS_S, "项目现付付销售提成");
                        }
                    }
                }
                if (null != projectRequest.getCardSalesCommission()) {
                    if (BigDecimalUtils.compareTo(projectRequest.getCardSalesCommission(), BigDecimalUtils.bigDecimal("1")) == 1) {
                        if (BigDecimalUtils.compareTo(projectRequest.getCardSalesCommission(), baseProject.getPriceMember()) == 1) {
                            throw new SmsException(ResponseCode.NOT_MEET_REQUIREMENTS_S, "项目卡付销售提成");
                        }
                    }
                }

                //固定金额
                if (BigDecimalUtils.compareTo(projectRequest.getAchievementLarge(), BigDecimalUtils.bigDecimal("1")) == 1) {
                    money = BigDecimalUtils.add(money, projectRequest.getAchievementLarge());
                } else {
                    //占比
                    ratio = BigDecimalUtils.add(ratio, projectRequest.getAchievementLarge());
                }
                //固定金额
                if (BigDecimalUtils.compareTo(projectRequest.getAchievementZhonggong(), BigDecimalUtils.bigDecimal("1")) == 1) {
                    money = BigDecimalUtils.add(money, projectRequest.getAchievementZhonggong());
                } else {
                    //占比
                    ratio = BigDecimalUtils.add(ratio, projectRequest.getAchievementZhonggong());
                }
                //固定金额
                if (BigDecimalUtils.compareTo(projectRequest.getAchievementTechnician(), BigDecimalUtils.bigDecimal("1")) == 1) {
                    money = BigDecimalUtils.add(money, projectRequest.getAchievementTechnician());
                } else {
                    //占比
                    ratio = BigDecimalUtils.add(ratio, projectRequest.getAchievementTechnician());
                }
                //固定金额
                if (BigDecimalUtils.compareTo(projectRequest.getAchievementSmall(), BigDecimalUtils.bigDecimal("1")) == 1) {
                    money = BigDecimalUtils.add(money, projectRequest.getAchievementSmall());
                } else {
                    //占比
                    ratio = BigDecimalUtils.add(ratio, projectRequest.getAchievementSmall());
                }
                //校验
//                if (BigDecimalUtils.compareTo(money, price) == 1 || BigDecimalUtils.compareTo(ratio, BigDecimalUtils.bigDecimal("1")) == 1) {
//                    throw new SmsException(ResponseCode.NOT_MEET_REQUIREMENTS_S, "项目现付美容师 美发师 技师 助理业绩");
//                }

                //置0
                money = BigDecimalUtils.bigDecimal("0");
                ratio = BigDecimalUtils.bigDecimal("0", 3);
                //固定金额
                if (BigDecimalUtils.compareTo(projectRequest.getCardAchievementLarge(), BigDecimalUtils.bigDecimal("1")) == 1) {
                    money = BigDecimalUtils.add(money, projectRequest.getCardAchievementLarge());
                } else {
                    //占比
                    ratio = BigDecimalUtils.add(ratio, projectRequest.getCardAchievementLarge());
                }
                //固定金额
                if (BigDecimalUtils.compareTo(projectRequest.getCardAchievementZhonggong(), BigDecimalUtils.bigDecimal("1")) == 1) {
                    money = BigDecimalUtils.add(money, projectRequest.getCardAchievementZhonggong());
                } else {
                    //占比
                    ratio = BigDecimalUtils.add(ratio, projectRequest.getCardAchievementZhonggong());
                }
                //固定金额
                if (BigDecimalUtils.compareTo(projectRequest.getCardAchievementTechnician(), BigDecimalUtils.bigDecimal("1")) == 1) {
                    money = BigDecimalUtils.add(money, projectRequest.getCardAchievementTechnician());
                } else {
                    //占比
                    ratio = BigDecimalUtils.add(ratio, projectRequest.getCardAchievementTechnician());
                }
                //固定金额
                if (BigDecimalUtils.compareTo(projectRequest.getCardAchievementSmall(), BigDecimalUtils.bigDecimal("1")) == 1) {
                    money = BigDecimalUtils.add(money, projectRequest.getCardAchievementSmall());
                } else {
                    //占比
                    ratio = BigDecimalUtils.add(ratio, projectRequest.getCardAchievementSmall());
                }
                //校验
//                if (BigDecimalUtils.compareTo(money, price) == 1 || BigDecimalUtils.compareTo(ratio, BigDecimalUtils.bigDecimal("1")) == 1) {
//                    throw new SmsException(ResponseCode.NOT_MEET_REQUIREMENTS_S, "项目卡付美容师 美发师 技师 助理业绩");
//                }

                //置0
                money = BigDecimalUtils.bigDecimal("0");
                ratio = BigDecimalUtils.bigDecimal("0", 3);
                //固定金额
                if (BigDecimalUtils.compareTo(projectRequest.getCommissionLarge(), BigDecimalUtils.bigDecimal("1")) == 1) {
                    money = BigDecimalUtils.add(money, projectRequest.getCommissionLarge());
                } else {
                    //占比
                    ratio = BigDecimalUtils.add(ratio, projectRequest.getCommissionLarge());
                }
                //固定金额
                if (BigDecimalUtils.compareTo(projectRequest.getCommissionZhonggong(), BigDecimalUtils.bigDecimal("1")) == 1) {
                    money = BigDecimalUtils.add(money, projectRequest.getCommissionZhonggong());
                } else {
                    //占比
                    ratio = BigDecimalUtils.add(ratio, projectRequest.getCommissionZhonggong());
                }
                //固定金额
                if (BigDecimalUtils.compareTo(projectRequest.getCommissionTechnician(), BigDecimalUtils.bigDecimal("1")) == 1) {
                    money = BigDecimalUtils.add(money, projectRequest.getCommissionTechnician());
                } else {
                    //占比
                    ratio = BigDecimalUtils.add(ratio, projectRequest.getCommissionTechnician());
                }
                //固定金额
                if (BigDecimalUtils.compareTo(projectRequest.getCommissionSmall(), BigDecimalUtils.bigDecimal("1")) == 1) {
                    money = BigDecimalUtils.add(money, projectRequest.getCommissionSmall());
                } else {
                    //占比
                    ratio = BigDecimalUtils.add(ratio, projectRequest.getCommissionSmall());
                }
                //校验
                if (BigDecimalUtils.compareTo(money, price) == 1 || BigDecimalUtils.compareTo(ratio, BigDecimalUtils.bigDecimal("1")) == 1) {
                    throw new SmsException(ResponseCode.NOT_MEET_REQUIREMENTS_S, "项目卡付美容师 美发师 技师 助理提成");
                }

                //置0
                money = BigDecimalUtils.bigDecimal("0");
                ratio = BigDecimalUtils.bigDecimal("0", 3);
                //固定金额
                if (BigDecimalUtils.compareTo(projectRequest.getCardCommissionLarge(), BigDecimalUtils.bigDecimal("1")) == 1) {
                    money = BigDecimalUtils.add(money, projectRequest.getCardCommissionLarge());
                } else {
                    //占比
                    ratio = BigDecimalUtils.add(ratio, projectRequest.getCardCommissionLarge());
                }
                //固定金额
                if (BigDecimalUtils.compareTo(projectRequest.getCardCommissionZhonggong(), BigDecimalUtils.bigDecimal("1")) == 1) {
                    money = BigDecimalUtils.add(money, projectRequest.getCardCommissionZhonggong());
                } else {
                    //占比
                    ratio = BigDecimalUtils.add(ratio, projectRequest.getCardCommissionZhonggong());
                }
                //固定金额
                if (BigDecimalUtils.compareTo(projectRequest.getCardCommissionTechnician(), BigDecimalUtils.bigDecimal("1")) == 1) {
                    money = BigDecimalUtils.add(money, projectRequest.getCardCommissionTechnician());
                } else {
                    //占比
                    ratio = BigDecimalUtils.add(ratio, projectRequest.getCardCommissionTechnician());
                }
                //固定金额
                if (BigDecimalUtils.compareTo(projectRequest.getCardCommissionSmall(), BigDecimalUtils.bigDecimal("1")) == 1) {
                    money = BigDecimalUtils.add(money, projectRequest.getCardCommissionSmall());
                } else {
                    //占比
                    ratio = BigDecimalUtils.add(ratio, projectRequest.getCardCommissionSmall());
                }
                //校验
                if (BigDecimalUtils.compareTo(money, price) == 1 || BigDecimalUtils.compareTo(ratio, BigDecimalUtils.bigDecimal("1")) == 1) {
                    throw new SmsException(ResponseCode.NOT_MEET_REQUIREMENTS_S, "项目卡付美容师 美发师 技师 助理提成");
                }
            }

        }

        BaseProject project = new BaseProject();
        project.setId(projectRequest.getId());
        project.setSalesAchievement(projectRequest.getSalesAchievement());
        project.setSalesCommission(projectRequest.getSalesCommission());
        project.setCardSalesAchievement(projectRequest.getCardSalesAchievement());
        project.setCardSalesCommission(projectRequest.getCardSalesCommission());
        project.setAchievementLarge(projectRequest.getAchievementLarge());
        project.setAchievementZhonggong(projectRequest.getAchievementZhonggong());
        project.setAchievementTechnician(projectRequest.getAchievementTechnician());
        project.setAchievementSmall(projectRequest.getAchievementSmall());
        project.setCardAchievementLarge(projectRequest.getCardAchievementLarge());
        project.setCardAchievementZhonggong(projectRequest.getCardAchievementZhonggong());
        project.setCardAchievementTechnician(projectRequest.getCardAchievementTechnician());
        project.setCardAchievementSmall(projectRequest.getCardAchievementSmall());
        project.setCommissionLarge(projectRequest.getCommissionLarge());
        project.setCommissionZhonggong(projectRequest.getCommissionZhonggong());
        project.setCommissionTechnician(projectRequest.getCommissionTechnician());
        project.setCommissionSmall(projectRequest.getCommissionSmall());
        project.setCardCommissionLarge(projectRequest.getCardCommissionLarge());
        project.setCardCommissionZhonggong(projectRequest.getCardCommissionZhonggong());
        project.setCardCommissionTechnician(projectRequest.getCardCommissionTechnician());
        project.setCardCommissionSmall(projectRequest.getCardCommissionSmall());
        //设置录单人信息
        if (redisClient.hasKey(getStaffKey(projectRequest.getUpdateCommPhone()))){
            StaffResponse staffResponse = redisClient.get(getStaffKey(projectRequest.getUpdateCommPhone()));
            project.setModifyBy(staffResponse.getStaffName());
            project.setModifyDatetime(new Date());
        }
        int i = dao.updateByPrimaryKeySelective(project);
//        if (i > 0){
//            projectRedisClient.delete(getKey(projectRequest.getStoreId(),key));
//        }
        return i;
    }

    @Override
    public int setAchiComms(ProjectRequest projectRequest) throws SmsException {
        List<Long> projectRequests = projectRequest.getProjectRequests();
        boolean status = true;
        for (Long requests : projectRequests) {
            ProjectRequest request = new ProjectRequest();
            request.setStoreId(projectRequest.getStoreId());
            request.setId(requests);
            //设置业绩提成
            request.setSalesAchievement(projectRequest.getSalesAchievement());
            request.setSalesCommission(projectRequest.getSalesCommission());
            request.setCardSalesAchievement(projectRequest.getCardSalesAchievement());
            request.setCardSalesCommission(projectRequest.getCardSalesCommission());
            request.setAchievementLarge(projectRequest.getAchievementLarge());
            request.setAchievementZhonggong(projectRequest.getAchievementZhonggong());
            request.setAchievementTechnician(projectRequest.getAchievementTechnician());
            request.setAchievementSmall(projectRequest.getAchievementSmall());
            request.setCommissionLarge(projectRequest.getCommissionLarge());
            request.setCommissionZhonggong(projectRequest.getCommissionZhonggong());
            request.setCommissionTechnician(projectRequest.getCommissionTechnician());

            request.setCommissionSmall(projectRequest.getCommissionSmall());
            request.setCardAchievementLarge(projectRequest.getCardAchievementLarge());
            request.setCardAchievementZhonggong(projectRequest.getCardAchievementZhonggong());
            request.setCardAchievementTechnician(projectRequest.getCardAchievementTechnician());
            request.setCardAchievementSmall(projectRequest.getCardAchievementSmall());
            request.setCardCommissionLarge(projectRequest.getCardCommissionLarge());
            request.setCardCommissionZhonggong(projectRequest.getCardCommissionZhonggong());
            request.setCardCommissionTechnician(projectRequest.getCardCommissionTechnician());
            request.setCardCommissionSmall(projectRequest.getCardCommissionSmall());

            BaseProject project = new BaseProject();
            project.setId(request.getId());
            project.setSalesAchievement(request.getSalesAchievement());
            project.setSalesCommission(request.getSalesCommission());
            project.setCardSalesAchievement(request.getCardSalesAchievement());
            project.setCardSalesCommission(request.getCardSalesCommission());
            project.setAchievementLarge(request.getAchievementLarge());
            project.setAchievementZhonggong(request.getAchievementZhonggong());
            project.setAchievementTechnician(request.getAchievementTechnician());
            project.setAchievementSmall(request.getAchievementSmall());
            project.setCardAchievementLarge(request.getCardAchievementLarge());
            project.setCardAchievementZhonggong(request.getCardAchievementZhonggong());
            project.setCardAchievementTechnician(request.getCardAchievementTechnician());
            project.setCardAchievementSmall(request.getCardAchievementSmall());
            project.setCommissionLarge(request.getCommissionLarge());
            project.setCommissionZhonggong(request.getCommissionZhonggong());
            project.setCommissionTechnician(request.getCommissionTechnician());
            project.setCommissionSmall(request.getCommissionSmall());
            project.setCardCommissionLarge(request.getCardCommissionLarge());
            project.setCardCommissionZhonggong(request.getCardCommissionZhonggong());
            project.setCardCommissionTechnician(request.getCardCommissionTechnician());
            project.setCardCommissionSmall(request.getCardCommissionSmall());
            int i = dao.updateByPrimaryKeySelective(project);
            if (i > 0){

            }else{
                status=false;
            }
        }
        if(status){
            return 1;
        }else{
            return 0;
        }
    }

    @Override
    public BaseProject one(ProjectRequest projectRequest) {
        return dao.selectByPrimaryKey(projectRequest.getId());
    }


    @Override
    public List<BaseProject> insertBatch(List<BaseProject> list, Long storeId, String storeName, String phone) throws SmsException {
        long start=System.currentTimeMillis();
        List<BaseProject> unusualList = this.check(list);
        if (!unusualList.isEmpty()){
            return unusualList;
        }
        StaffResponse staffResponse = new StaffResponse();
        if (redisClient.hasKey(getStaffKey(phone))){
            staffResponse = redisClient.get(getStaffKey(phone));
        }
        Long ZStoreId= null;
        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(storeId);
        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
        for (BaseStores pagesorganization : pagesorganizations) {
            if(null == pagesorganization.getParentId()){
                ZStoreId= pagesorganization.getId();
            }
        }
        List<BaseProject> lists = new ArrayList<>();
        for (BaseProject project : list) {
            if(null != project.getProjectNum()){
                Example example = new Example(BaseProject.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andIn("storeId", Arrays.asList(storeId));
                criteria.andEqualTo("projectNum", project.getProjectNum());

                List<BaseProject> projects = dao.selectByExample(example);
                if(null != projects && projects.size()>0){
                    BaseProject baseProject = projects.get(0);
                    if(null != baseProject){
                        project.setStoreId(baseProject.getStoreId());
                        project.setId(baseProject.getId());
                        project.setStoreName(baseProject.getStoreName());
                        project.setProjectName(baseProject.getProjectName());
                        BeanUtils.copyProperties(project,baseProject);
                        baseProject.setModifyBy(staffResponse.getStaffName());
                        baseProject.setModifyDatetime(new Date());

                        int update = dao.updateByPrimaryKeySelective(baseProject);
                        if(update ==0){
                            throw new SmsException(ResponseCode.MSG,"导入的项目编码为：{ "+baseProject.getProjectNum()+"  }的项目重复更新覆盖失败");
                        }
                    }
                }else{
                    project.setId(SnowflakeUtil.getId());
                    project.setStoreId(storeId);
                    project.setStoreName(storeName);
                    project.setFounderStaff(staffResponse.getStaffName());
                    project.setFounderDatetime(new Date());
                    lists.add(project);
                }
            }else{
                throw new SmsException(ResponseCode.MSG,"导入的项目名称{ "+project.getProjectName()+"  }编码不存在");

            }
            if(null != project.getProjectTypeNum()){
                BaseProjectType projectRequest = new BaseProjectType();
                projectRequest.setStoreId(ZStoreId);
                projectRequest.setProjectTypeNum(project.getProjectTypeNum());
                BaseProjectType baseProjectType = ssmProjectTypeService.selectOne(projectRequest);
                if(null != baseProjectType){
                    project.setProjectTypeId(baseProjectType.getId());
                }else{
                    throw new SmsException(ResponseCode.DATA_NOT_ALLOW_UPDATESSSS,"导入的项目关联的项目类别{  "+project.getProjectTypeNum()+"  }在门店中不存在，请先检查关联的类别编码是否全部存在");
                }
            }
//            project.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
            //批量上传避免数据量过大时new Random()重复导致生成的ID重复

        }
        int i = 0;
        try {
            if(lists.size()>0){
                i = dao.insertBatch(lists);
            }else{
                i=1;
            }
            long end=System.currentTimeMillis();
            System.out.println("*******-----*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- \n 耗时："+(end-start)+"ms \n");
        }catch (Exception e){
            log.error("SsmProjectServiceImpl.insertBatch:", e);
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        if (i == 0){
            throw new SmsException(ResponseCode.ENCRYPT_ERROR);
        }else {
            throw new SmsException(ResponseCode.OK);
        }
    }

    @Override
    public List<BaseProject> insertBatch1(List<BaseProject> list, Long storeId, String storeName, String phone) throws SmsException {
        long start=System.currentTimeMillis();
        List<BaseProject> unusualList = this.check(list);
        if (!unusualList.isEmpty()){
            return unusualList;
        }
        StaffResponse staffResponse = new StaffResponse();
        if (redisClient.hasKey(getStaffKey(phone))){
            staffResponse = redisClient.get(getStaffKey(phone));
        }
        Long ZStoreId= null;
        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(storeId);
        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
        for (BaseStores pagesorganization : pagesorganizations) {
            if(null == pagesorganization.getParentId()){
                ZStoreId= pagesorganization.getId();
            }
        }
        List<BaseProject> lists = new ArrayList<>();
        List<BaseProject> updateList=new ArrayList<>();
        List<BaseProject> nullList=new ArrayList<>();
        for (BaseProject project : list) {
            if(null != project.getProjectNum()){
                Example example = new Example(BaseProject.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andIn("storeId", Arrays.asList(storeId));
                criteria.andEqualTo("projectNum", project.getProjectNum());
                List<BaseProject> projects = dao.selectByExample(example);
                if(null != projects && projects.size()>0){
                    BaseProject baseProject = projects.get(0);
                        project.setStoreId(baseProject.getStoreId());
                        project.setId(baseProject.getId());
                        project.setStoreName(baseProject.getStoreName());
                        project.setProjectName(baseProject.getProjectName());
                        BeanUtils.copyProperties(project,baseProject);
                        baseProject.setModifyBy(staffResponse.getStaffName());
                        baseProject.setModifyDatetime(new Date());
                        updateList.add(baseProject);
                }else{
                    project.setId(SnowflakeUtil.getId());
                    project.setStoreId(storeId);
                    project.setStoreName(storeName);
                    project.setFounderStaff(staffResponse.getStaffName());
                    project.setFounderDatetime(new Date());
                    lists.add(project);
                }

            }else{
                throw new SmsException(ResponseCode.MSG,"导入的项目名称{ "+project.getProjectName()+"  }编码不存在");
            }
            if(null != project.getProjectTypeNum()){
                BaseProjectType projectRequest = new BaseProjectType();
                projectRequest.setStoreId(ZStoreId);
                projectRequest.setProjectTypeNum(project.getProjectTypeNum());
                BaseProjectType baseProjectType = ssmProjectTypeService.selectOne(projectRequest);
                if(null == baseProjectType){
                    //project.setProjectTypeId(baseProjectType.getId());
                    nullList.add(project);
                }
            }
        }
        //修改
        if(updateList.size()>0){
            for(BaseProject baseProject:updateList){
                int update = dao.updateByPrimaryKeySelective(baseProject);
                if(update ==0){
                    throw new SmsException(ResponseCode.MSG,"导入的项目编码为：{ "+baseProject.getProjectNum()+"  }的项目重复更新覆盖失败");
                }
            }

        }

        if(nullList.size()>0){
            String ProjectTypeNum="";
            for(BaseProject baseProject:nullList){
                ProjectTypeNum=ProjectTypeNum+baseProject.getProjectTypeNum()+"\n";
            }
            throw new SmsException(ResponseCode.DATA_NOT_ALLOW_UPDATESSSS,"导入的项目关联的项目类别{  "+ProjectTypeNum+"  }在门店中不存在，请先检查关联的类别编码是否全部存在");
        }

        int i = 0;
        try {
            if(lists.size()>0){
                i = dao.insertBatch(lists);
            }else{
                i=1;
            }
            long end=System.currentTimeMillis();
            System.out.println("*******-----*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- \n 耗时："+(end-start)+"ms \n");
        }catch (Exception e){
            log.error("SsmProjectServiceImpl.insertBatch:", e);
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        if (i == 0){
            throw new SmsException(ResponseCode.ENCRYPT_ERROR);
        }else {
            throw new SmsException(ResponseCode.OK);
        }
    }

    @Override
    public List<BaseProject> insertBatch2(List<BaseProject> list, Long storeId, String storeName, String phone) throws SmsException {
        long start=System.currentTimeMillis();
        List<BaseProject> unusualList = this.check(list);
        if (!unusualList.isEmpty()){
            return unusualList;
        }
        StaffResponse staffResponse = new StaffResponse();
        if (redisClient.hasKey(getStaffKey(phone))){
            staffResponse = redisClient.get(getStaffKey(phone));
        }
        Long ZStoreId= null;
        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(storeId);
        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
        for (BaseStores pagesorganization : pagesorganizations) {
            if(null == pagesorganization.getParentId()){
                ZStoreId= pagesorganization.getId();
            }
        }
        List<BaseProject> addLists = new ArrayList<>();
        addLists.addAll(list);

        List<BaseProject> updateList=new ArrayList<>();
        List<BaseProject> nullList=new ArrayList<>();
        List<BaseProject> selectList=new ArrayList<>();
        for (BaseProject project : list) {
            if(null != project.getProjectNum()){
                project.setStoreId(storeId);
                selectList.add(project);
            }else{
                throw new SmsException(ResponseCode.MSG,"导入的项目名称{ "+project.getProjectName()+"  }编码不存在");
            }
            if(null != project.getProjectTypeNum()){
                BaseProjectType projectRequest = new BaseProjectType();
                projectRequest.setStoreId(ZStoreId);
                projectRequest.setProjectTypeNum(project.getProjectTypeNum());
                BaseProjectType baseProjectType = ssmProjectTypeService.selectOne(projectRequest);
                if(null == baseProjectType){
                    nullList.add(project);
                }
            }
        }
        if(nullList.size()>0){
            String ProjectTypeNum="";
            for(BaseProject baseProject:nullList){
                ProjectTypeNum=ProjectTypeNum+baseProject.getProjectTypeNum()+"\n";
            }
            throw new SmsException(ResponseCode.DATA_NOT_ALLOW_UPDATESSSS,"导入的项目关联的项目类别{  "+ProjectTypeNum+"  }在门店中不存在，请先检查关联的类别编码是否全部存在");
        }

        List<BaseProject> aa=dao.selectUpdate(selectList);
        if(aa.size()>0){
            for(BaseProject project:aa){

                for(BaseProject baseProject:list){
                    if(baseProject.getProjectNum().hashCode()==project.getProjectNum().hashCode()){
                        //去掉修改的剩下就是添加的了
                        addLists.remove(baseProject);

                        baseProject.setStoreId(project.getStoreId());
                        baseProject.setId(project.getId());
                        baseProject.setStoreName(project.getStoreName());
                        baseProject.setProjectName(project.getProjectName());

                        BeanUtils.copyProperties(baseProject,project);
                        project.setModifyBy(staffResponse.getStaffName());
                        project.setModifyDatetime(new Date());
                        updateList.add(project);
                    }
                }
            }
        }
        //修改
        if(updateList.size()>0){
            for(BaseProject baseProject:updateList){
                if(baseProject.getSalesAchievement()==null){
                    baseProject.setSalesAchievement(BigDecimal.ZERO);
                }
                if(baseProject.getSalesCommission()==null){
                    baseProject.setSalesCommission(BigDecimal.ZERO);
                }
                if(baseProject.getCardSalesCommission()==null){
                    baseProject.setCardSalesCommission(BigDecimal.ZERO);
                }
                if(baseProject.getCardSalesAchievement()==null){
                    baseProject.setCardSalesAchievement(BigDecimal.ZERO);
                }
                if(baseProject.getAchievementLarge()==null){
                    baseProject.setAchievementLarge(BigDecimal.ZERO);
                }
                if(baseProject.getAchievementZhonggong()==null){
                    baseProject.setAchievementZhonggong(BigDecimal.ZERO);
                }
                if(baseProject.getAchievementTechnician()==null){
                    baseProject.setAchievementTechnician(BigDecimal.ZERO);
                }
                if(baseProject.getAchievementSmall()==null){
                    baseProject.setAchievementSmall(BigDecimal.ZERO);
                }
                if(baseProject.getCommissionSmall()==null){
                    baseProject.setCommissionSmall(BigDecimal.ZERO);
                }
                if(baseProject.getCommissionLarge()==null){
                    baseProject.setCommissionLarge(BigDecimal.ZERO);
                }
                if(baseProject.getCommissionZhonggong()==null){
                    baseProject.setCommissionZhonggong(BigDecimal.ZERO);
                }
                if(baseProject.getCommissionTechnician()==null){
                    baseProject.setCommissionTechnician(BigDecimal.ZERO);
                }

                if(baseProject.getCardAchievementLarge()==null){
                    baseProject.setCardAchievementLarge(BigDecimal.ZERO);
                }
                if(baseProject.getCardAchievementZhonggong()==null){
                    baseProject.setCardAchievementZhonggong(BigDecimal.ZERO);
                }
                if(baseProject.getCardAchievementTechnician()==null){
                    baseProject.setCardAchievementTechnician(BigDecimal.ZERO);
                }
                if(baseProject.getCardAchievementSmall()==null){
                    baseProject.setCardAchievementSmall(BigDecimal.ZERO);
                }
                if(baseProject.getCardCommissionLarge()==null){
                    baseProject.setCardCommissionLarge(BigDecimal.ZERO);
                }
                if(baseProject.getCardCommissionZhonggong()==null){
                    baseProject.setCardCommissionZhonggong(BigDecimal.ZERO);
                }
                if(baseProject.getCardCommissionTechnician()==null){
                    baseProject.setCardCommissionTechnician(BigDecimal.ZERO);
                }
                if(baseProject.getCardCommissionSmall()==null){
                    baseProject.setCardCommissionSmall(BigDecimal.ZERO);
                }

                int update = dao.updateByPrimaryKeySelective(baseProject);
                if(update ==0){
                    throw new SmsException(ResponseCode.MSG,"导入的项目编码为：{ "+baseProject.getProjectNum()+"  }的项目重复更新覆盖失败");
                }
            }

        }

        int i = 0;
        try {
            if(addLists.size()>0){
                for(BaseProject baseProject:addLists){
                    baseProject.setId(SnowflakeUtil.getId());
                    baseProject.setStoreId(storeId);
                    baseProject.setStoreName(storeName);
                    baseProject.setFounderStaff(staffResponse.getStaffName());
                    baseProject.setFounderDatetime(new Date());
                }
//                for (BaseProject addList : addLists) {
//                  i +=  dao.saveNotNull(addList);
//                }
//                dao.saveNotNull()
                for (BaseProject addList : addLists) {
                    if(addList.getProjectTypeId()==null){
                        BaseProjectType baseProjectType = new BaseProjectType();
                        baseProjectType.setProjectTypeNum(addList.getProjectTypeNum());
                        baseProjectType = ssmProjectTypeService.selectOne(baseProjectType);
                        addList.setProjectTypeId(baseProjectType.getId());
                    }
                }
                for (BaseProject baseProject : addLists) {
                    if(baseProject.getSalesAchievement()==null){
                        baseProject.setSalesAchievement(BigDecimal.ZERO);
                    }
                    if(baseProject.getSalesCommission()==null){
                        baseProject.setSalesCommission(BigDecimal.ZERO);
                    }
                    if(baseProject.getCardSalesCommission()==null){
                        baseProject.setCardSalesCommission(BigDecimal.ZERO);
                    }
                    if(baseProject.getCardSalesAchievement()==null){
                        baseProject.setCardSalesAchievement(BigDecimal.ZERO);
                    }
                    if(baseProject.getAchievementLarge()==null){
                        baseProject.setAchievementLarge(BigDecimal.ZERO);
                    }
                    if(baseProject.getAchievementZhonggong()==null){
                        baseProject.setAchievementZhonggong(BigDecimal.ZERO);
                    }
                    if(baseProject.getAchievementTechnician()==null){
                        baseProject.setAchievementTechnician(BigDecimal.ZERO);
                    }
                    if(baseProject.getAchievementSmall()==null){
                        baseProject.setAchievementSmall(BigDecimal.ZERO);
                    }
                    if(baseProject.getCommissionSmall()==null){
                        baseProject.setCommissionSmall(BigDecimal.ZERO);
                    }
                    if(baseProject.getCommissionLarge()==null){
                        baseProject.setCommissionLarge(BigDecimal.ZERO);
                    }
                    if(baseProject.getCommissionZhonggong()==null){
                        baseProject.setCommissionZhonggong(BigDecimal.ZERO);
                    }
                    if(baseProject.getCommissionTechnician()==null){
                        baseProject.setCommissionTechnician(BigDecimal.ZERO);
                    }

                    if(baseProject.getCardAchievementLarge()==null){
                        baseProject.setCardAchievementLarge(BigDecimal.ZERO);
                    }
                    if(baseProject.getCardAchievementZhonggong()==null){
                        baseProject.setCardAchievementZhonggong(BigDecimal.ZERO);
                    }
                    if(baseProject.getCardAchievementTechnician()==null){
                        baseProject.setCardAchievementTechnician(BigDecimal.ZERO);
                    }
                    if(baseProject.getCardAchievementSmall()==null){
                        baseProject.setCardAchievementSmall(BigDecimal.ZERO);
                    }
                    if(baseProject.getCardCommissionLarge()==null){
                        baseProject.setCardCommissionLarge(BigDecimal.ZERO);
                    }
                    if(baseProject.getCardCommissionZhonggong()==null){
                        baseProject.setCardCommissionZhonggong(BigDecimal.ZERO);
                    }
                    if(baseProject.getCardCommissionTechnician()==null){
                        baseProject.setCardCommissionTechnician(BigDecimal.ZERO);
                    }
                    if(baseProject.getCardCommissionSmall()==null){
                        baseProject.setCardCommissionSmall(BigDecimal.ZERO);
                    }
                }
                i = dao.insertBatch(addLists);
            }else{
                i=1;
            }
            long end=System.currentTimeMillis();
            System.out.println("*******-----*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- \n 耗时："+(end-start)+"ms \n");
        }catch (Exception e){
            log.error("SsmProjectServiceImpl.insertBatch:", e);
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        if (i == 0){
            throw new SmsException(ResponseCode.ENCRYPT_ERROR);
        }else {
            throw new SmsException(ResponseCode.OK);
        }
    }

    @Override
    public BaseProject copyProject(ProjectRequest projectRequest) throws SmsException {
        if(projectRequest.getId()==null){
            throw new SmsException(ResponseCode.MSG,"请选择一个项目");
        }
        return dao.selectByPrimaryKey(projectRequest);
    }

    @Override
    public List<BaseProject> selectList(List<Long> collect) {
        return mapper.selectList(collect);
    }

    public String getStaffKey(String phone){
        return staffKey + phone;
    }

    public String getKey(Long storeId, String key){
        BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(storeId);
        key = baseStore.getStoreNum() + key;
        return key;
    }

    public StoreParament getStorePara(Long storeId,String key){
        StoreParament storeParament = new StoreParament();
        storeParament.setStoreId(storeId);
        storeParament.setParamentName(key);
        storeParament = ssmStoreParaService.selectOne(storeParament);
        return storeParament;
    }

    public List<BaseProject> check(List<BaseProject> list){
        List<BaseProject> unusualList = new ArrayList<>();
        Map<String,List<BaseProject>> map = list.stream().collect(Collectors.groupingBy(baseProject -> baseProject.getProjectNum() + "-" + baseProject.getState()));
        for (String s : map.keySet()) {
            if (map.get(s).size() > 1){
                unusualList.addAll(map.get(s));
                list.removeAll(map.get(s));
            }
        }

        Map<String,List<BaseProject>> map1 = list.stream().collect(Collectors.groupingBy(baseProject -> baseProject.getProjectName() + "-" + baseProject.getState()));
        for (String s : map1.keySet()) {
            if (map1.get(s).size() > 1){
                unusualList.addAll(map1.get(s));
            }
        }
        return unusualList;
    }

    public void checkNum(String projectNum, String projectName, Long storeIds,Long id) throws SmsException {
        if (StringUtils.isNotBlank(projectNum) || null != projectNum) {
            Example example = new Example(BaseProject.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andIn("storeId", Arrays.asList(storeIds));
            criteria.andEqualTo("state", 1);
            criteria.andEqualTo("projectNum", projectNum);
            if(!id.equals("1")){
                criteria.andNotEqualTo("id",id);
            }
            List<BaseProject> projects = dao.selectByExample(example);
//            BaseProject project = new BaseProject();
//            project.setProjectNum(projectNum);
//            project.setStoreId(storeId);
//            project.setState(1);
//            List<BaseProject> projects = dao.select(project);
            if (projects.size() > 0) {
                throw new SmsException(ResponseCode.DATA_ALREADY_EXISTS_S, "项目编码");
            }
        }
        if (StringUtils.isNotBlank(projectName) || null != projectName) {
            Example example = new Example(BaseProject.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andIn("storeId", Arrays.asList(storeIds));
            criteria.andEqualTo("state", 1);
            criteria.andEqualTo("projectName", projectName);
            if(!id.equals("1")){
                criteria.andNotEqualTo("id",id);
            }
            List<BaseProject> projects = dao.selectByExample(example);
//            BaseProject project = new BaseProject();
//            project.setProjectName(projectName);
//            project.setStoreId(storeId);
//            project.setState(1);
//            List<BaseProject> projects = dao.select(project);
            if (projects.size() > 0) {
                throw new SmsException(ResponseCode.DATA_ALREADY_EXISTS_S, "项目名称");
            }
        }
    }
}
