package com.sifang.modules.customer.Service;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.constant.CombinerBoxGroupConstants;
import com.sifang.modules.customer.constant.CustomerEntryConstants;
import com.sifang.modules.customer.dao.CrmEntryCombinerBoxGroupDao;
import com.sifang.modules.customer.dao.CrmEntryCombinerBoxGroupDetailDao;
import com.sifang.modules.customer.dao.CustomerEntryDao;
import com.sifang.modules.customer.entity.CrmEntryCombinerBoxGroup;
import com.sifang.modules.customer.entity.CrmEntryCombinerBoxGroupDetail;
import com.sifang.modules.customer.entity.CustomerEntry;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.entity.Operator;
import org.hibernate.SQLQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class CrmEntryCombinerBoxGroupService extends BaseService {

    @Autowired
    private CrmEntryCombinerBoxGroupDao combinerBoxGroupDao;

    @Autowired
    private CrmEntryCombinerBoxGroupDetailDao combinerBoxGroupDetailDao;

    @Autowired
    private CustomerEntryDao entryDao;

    /**新增一个新的汇流组   type 并网方式 1一户多站 2整村汇流
     * 一户多站汇流组名称生成方式=客户名称+几汇一+年月日
     * 汇流组编号生成方式=一户多站首字母+几汇一+年月日
     * 示例：黄振-3汇一-20240808          YHDZ-3汇一-20240808
     *
     * 整村汇流汇流组名称生成方式=最小安装地址+几汇一+年月日
     * 汇流组编号生成方式=整村汇流首字母+几汇一+年月日
     * 示例：XX县-10汇一-20240808 ZCHL-10汇一-20240808
     *
     *
     * ifSubmit true 提交()  false 暂存
     */

    @Transactional(rollbackFor = Exception.class)
    public void addNewCombinerBoxGroup(CustomerEntry entry, Integer totalCount, String type,boolean ifSubmit, Operator operator,String boxGroupId){
        logger.info("....addNewCombinerBoxGroup  entryId:{},totalCount:{},type:{},ifSubmit:{},boxGroupId:{}",entry.getId(),totalCount,type,ifSubmit,boxGroupId);
        if(StringUtil.isBlank(type)){
            return;
        }
        CrmEntryCombinerBoxGroupDetail boxGroupDetail=combinerBoxGroupDetailDao.getByEntryId(entry.getId());
        //信息提交了之后，就不可以在次修改
        if(boxGroupDetail!=null && CombinerBoxGroupConstants.STATUS_BOX_USE.equals(boxGroupDetail.getStatus())){
            return;
        }
        if(CombinerBoxGroupConstants.MERGE_TYPE_DHBW.equals(type)){
            boxGroupId="";
        }
        if(boxGroupDetail!=null){
            //判断现在的和原来的是否一样
            if(StringUtil.isNotBlank(boxGroupDetail.getBoxGroupId()) && !boxGroupDetail.getBoxGroupId().equals(boxGroupId) && CombinerBoxGroupConstants.STATUS_BOX_LOCAL_SUBMIT.equals(boxGroupDetail.getStatus())){ //原来的组，和现在的组不一样
                CrmEntryCombinerBoxGroup combinerBoxGroup= combinerBoxGroupDao.get(boxGroupDetail.getBoxGroupId());
                if(combinerBoxGroup!=null){
                    if(combinerBoxGroup.getAlreadyIntoCount()>1){
                        combinerBoxGroup.setAlreadyIntoCount(combinerBoxGroup.getAlreadyIntoCount()-1);
                        combinerBoxGroupDao.save(combinerBoxGroup);
                    }else{
                      SQLQuery sqlQuery=combinerBoxGroupDao.getSession().createSQLQuery(" DELETE FROM crm_entry_combiner_box_group WHERE id='"+combinerBoxGroup.getId()+"' ");
                        int deleteCount=sqlQuery.executeUpdate();
                        logger.info(">>>>>>>>>>>>>>addNewCombinerBoxGroup  deleteCount:{}",deleteCount);
                    }
                }
            }
        }

        if("0".equals(type)){ //一户一站
            if(boxGroupDetail==null){
                boxGroupDetail=new CrmEntryCombinerBoxGroupDetail();
                boxGroupDetail.setEntryId(entry.getId());
            }
            boxGroupDetail.setType(type);
            boxGroupDetail.setBoxGroupId(null);
            boxGroupDetail.setTotalCount(1);
            boxGroupDetail.setCreateTime(new Date());
            boxGroupDetail.setCreateName(operator.getUserName());
            boxGroupDetail.setStatus(ifSubmit?CombinerBoxGroupConstants.STATUS_BOX_LOCAL_SUBMIT:CombinerBoxGroupConstants.STATUS_BOX_TEMP);
            combinerBoxGroupDetailDao.save(boxGroupDetail);
            return;
        }
        if(boxGroupDetail==null){
            boxGroupDetail=new CrmEntryCombinerBoxGroupDetail();
        }
        Date date=new Date();
        if(StringUtil.isBlank(boxGroupId)){
            if(totalCount==null || totalCount<=1){
                throw new BusinessException("本组电站个数至少大于1！");
            }
            if(ifSubmit){
                CrmEntryCombinerBoxGroup combinerBoxGroup=new CrmEntryCombinerBoxGroup();
                combinerBoxGroup.setType(type);
                String groupName="";
                String dataStr= DateUtils.getDate("yyyyMMddHHmm");
                String groupNumber="";
                if(CombinerBoxGroupConstants.MERGE_TYPE_YHDZ.equals(type)){ //一户多站
                    if(CustomerEntryConstants.TENANT_TYPE_PERSON.equals(entry.getTenantType())){  //租户分类: 1.个人 2.单位
                        combinerBoxGroup.setIdCode(entry.getIdCode());
                    }else{
                        combinerBoxGroup.setRegnoCode(entry.getRegno());
                    }
                    groupNumber="YHDZ-"+totalCount+"汇一-"+ dataStr;
                    groupName=entry.getTenantName()+"-"+totalCount+"汇一-"+dataStr;
                }else{
                    groupNumber="ZCHL-"+totalCount+"汇一-"+ dataStr;
                    groupName=entry.getArea()+"-"+totalCount+"汇一-"+dataStr;
                }
                //判断一下汇流组编码 是否已存在
                Long count= combinerBoxGroupDao.getSamBoxGroupNumber(groupNumber);
                if(count>0){
                    throw new BusinessException("汇流组编号:"+groupNumber+" 已存在，请勿重复添加！");
                }

                combinerBoxGroup.setTotalCount(totalCount);
                combinerBoxGroup.setGroupNumber(groupNumber);
                combinerBoxGroup.setGroupName(groupName);
                combinerBoxGroup.setAlreadyIntoCount(1);
                combinerBoxGroup.setAlreadyIncomingCount(0);

                combinerBoxGroup.setProvince(entry.getProvince());
                combinerBoxGroup.setCity(entry.getCity());
                combinerBoxGroup.setArea(entry.getArea());
                combinerBoxGroup.setAddress(entry.getAddress());
                combinerBoxGroup.setTraderId(entry.getCreateTraderId());
                combinerBoxGroup.setCreateTime(date);
                combinerBoxGroup.setCreateName(operator.getUserName());
                combinerBoxGroupDao.save(combinerBoxGroup);

                boxGroupDetail.setBoxGroupId(combinerBoxGroup.getId());
                boxGroupDetail.setStatus(CombinerBoxGroupConstants.STATUS_BOX_LOCAL_SUBMIT);
            }else{
                boxGroupDetail.setBoxGroupId("");
                boxGroupDetail.setStatus(CombinerBoxGroupConstants.STATUS_BOX_TEMP);
            }
        }else{
            CrmEntryCombinerBoxGroup combinerBoxGroup= combinerBoxGroupDao.get(boxGroupId);
            if(combinerBoxGroup==null){
                throw new BusinessException("未找到该编码的汇流组！");
            }

            if(ifSubmit){
                if(CombinerBoxGroupConstants.STATUS_BOX_LOCAL_SUBMIT.equals(boxGroupDetail.getStatus()) && boxGroupDetail.getBoxGroupId().equals(boxGroupId)){  //之前已经提交过了

                }else{

                    if(combinerBoxGroup.getAlreadyIntoCount()>=combinerBoxGroup.getTotalCount()){
                        throw new BusinessException(combinerBoxGroup.getGroupName()+"，该汇流组电站已满！");
                    }

                    SQLQuery sqlQuery=combinerBoxGroupDao.getSession().createSQLQuery(" UPDATE `crm_entry_combiner_box_group` SET already_into_count=already_into_count+1 WHERE id=:id and already_into_count=:alreadyIntoCount ");
                    sqlQuery.setParameter("id", combinerBoxGroup.getId());
                    sqlQuery.setParameter("alreadyIntoCount",combinerBoxGroup.getAlreadyIntoCount());
                    int cou = sqlQuery.executeUpdate();
                    if(cou==0){
                        throw new BusinessException("保存汇流箱信息失败！");
                    }
                }

                boxGroupDetail.setStatus(CombinerBoxGroupConstants.STATUS_BOX_LOCAL_SUBMIT);
            }else{
                boxGroupDetail.setStatus(CombinerBoxGroupConstants.STATUS_BOX_TEMP);
            }

            boxGroupDetail.setBoxGroupId(combinerBoxGroup.getId());
        }
        boxGroupDetail.setType(type);
        boxGroupDetail.setTotalCount(totalCount);
        boxGroupDetail.setEntryId(entry.getId());
        boxGroupDetail.setCreateTime(date);
        boxGroupDetail.setCreateName(operator.getUserName());
        combinerBoxGroupDetailDao.save(boxGroupDetail);
    }



    public List<Record> choiceBoxGroupList(String entryId){
        StringBuilder sb=new StringBuilder();
        sb.append(" SELECT g.id, g.group_number,g.group_name,g.total_count,g.already_into_count,g.province,g.city,g.area,g.address ");
        sb.append(" FROM `crm_entry_combiner_box_group` g ");
        sb.append(" JOIN  `crm_customer_entry` e ON e.`province`=g.province AND e.city=g.city AND e.area=g.area AND e.`create_trader_id`=g.`trader_id` ");
        sb.append(" WHERE e.id=? AND g.type='2' and g.total_count>g.already_into_count ORDER BY g.create_time DESC ");
        return Db.find(sb.toString(),entryId);
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveOneOwner(String entryId,Integer totalCount,String boxGroupId,Operator operator){
        CrmEntryCombinerBoxGroupDetail boxGroupDetail=combinerBoxGroupDetailDao.getByEntryId(entryId);
        //判断现在的和原来的是否一样
        if(boxGroupDetail!=null && StringUtil.isNotBlank(boxGroupDetail.getBoxGroupId()) && !boxGroupDetail.getBoxGroupId().equals(boxGroupId) && CombinerBoxGroupConstants.STATUS_BOX_LOCAL_SUBMIT.equals(boxGroupDetail.getStatus())){ //原来的组，和现在的组不一样
            CrmEntryCombinerBoxGroup combinerBoxGroup= combinerBoxGroupDao.get(boxGroupDetail.getBoxGroupId());
            if(combinerBoxGroup!=null){
                if(combinerBoxGroup.getAlreadyIntoCount()>1){
                    combinerBoxGroup.setAlreadyIntoCount(combinerBoxGroup.getAlreadyIntoCount()-1);
                    combinerBoxGroupDao.save(combinerBoxGroup);
                }else{
                    SQLQuery sqlQuery=combinerBoxGroupDao.getSession().createSQLQuery(" DELETE FROM crm_entry_combiner_box_group WHERE id='"+combinerBoxGroup.getId()+"' ");
                    int deleteCount=sqlQuery.executeUpdate();
                    logger.info(">>>>>>>>>>>>>>addNewCombinerBoxGroup  deleteCount:{}",deleteCount);
                }
            }
        }else if(boxGroupDetail!=null && StringUtil.isNotBlank(boxGroupDetail.getBoxGroupId()) && boxGroupDetail.getBoxGroupId().equals(boxGroupId)){
            return;
        }
        if(boxGroupDetail==null){
            boxGroupDetail=new CrmEntryCombinerBoxGroupDetail();
            boxGroupDetail.setEntryId(entryId);
        }
        boxGroupDetail.setType(CombinerBoxGroupConstants.MERGE_TYPE_ZCHL);
        if(StringUtil.isNotBlank(boxGroupId)){
            boxGroupDetail.setBoxGroupId(boxGroupId);
        }else{
            if(totalCount<=1){
                throw new BusinessException("本组电站个数至少大于1!");
            }
            boxGroupDetail.setTotalCount(totalCount);
            boxGroupDetail.setBoxGroupId(null);
        }
        boxGroupDetail.setCreateTime(new Date());
        boxGroupDetail.setStatus(CombinerBoxGroupConstants.STATUS_BOX_TEMP);
        boxGroupDetail.setCreateName(operator.getUserName());
        combinerBoxGroupDetailDao.save(boxGroupDetail);
    }

    //电站推送并网资料的时候，判断发电户号
    @Transactional(rollbackFor = Exception.class)
    public void saveSameBoxGroupGeneratorNo(String entryId,String generatorNo){
        String sql=" SELECT g.id FROM `crm_entry_combiner_box_group` g  " +
                " WHERE g.id=(SELECT box_group_id FROM `crm_entry_combiner_box_group_detail` d WHERE d.entry_id=? AND d.status='1') AND g.generator_no IS NULL ";

        String boxGroupId=Db.queryStr(sql,entryId);
        if(StringUtil.isNotBlank(boxGroupId)){
          SQLQuery sqlQuery= combinerBoxGroupDetailDao.getSession().createSQLQuery(" UPDATE `crm_entry_combiner_box_group`  SET generator_no=:generatorNo  WHERE id=:id ");
          sqlQuery.setParameter("generatorNo",generatorNo);
          sqlQuery.setParameter("id",boxGroupId);
          int i=sqlQuery.executeUpdate();
          logger.info("....saveSameBoxGroupGeneratorNo i :{}",i);
          //修改同一个汇流组里面电站的发电户号
          SQLQuery sqlQuery1=entryDao.getSession().createSQLQuery(" UPDATE crm_customer_entry e SET generator_no=:generatorNo " +
                  " WHERE e.id IN (SELECT entry_id  FROM `crm_entry_combiner_box_group_detail` d WHERE d.`box_group_id`=:id AND d.`status`='1' AND d.entry_id!=:entryId ) AND generator_no IS NULL ");
          sqlQuery1.setParameter("generatorNo",generatorNo);
          sqlQuery1.setParameter("id",boxGroupId);
          sqlQuery1.setParameter("entryId",entryId);
          int count=sqlQuery1.executeUpdate();
          logger.info(">>>>>saveSameBoxGroupGeneratorNo count:{} ",count);
        }
    }

}
