package com.sifang.modules.customer.dao;

import com.google.common.collect.Lists;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.constant.PartnerConstants;
import com.sifang.modules.customer.entity.CrmCustomerIncomingApplication;
import com.sifang.modules.customer.entity.CustomerEntry;
import com.sifang.modules.customer.utils.CustomerEntryUtil;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.persistence.BaseDao;
import com.sifang.modules.sys.common.persistence.Parameter;
import org.hibernate.SQLQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;


@Repository
public class CrmCustomerIncomingApplicationDao extends BaseDao<CrmCustomerIncomingApplication> {
    Logger logger= LoggerFactory.getLogger(getClass());

    public CrmCustomerIncomingApplication getByEntryId(String entryId){

        return getByHql(" from CrmCustomerIncomingApplication where entryId =:p1 and status != 'a' and ifDelete = '0' ", new Parameter(entryId));
    }
    public CrmCustomerIncomingApplication getByEntryId2(String entryId){
        return getByHql(" from CrmCustomerIncomingApplication where entryId =:p1  and ifDelete = '0' ", new Parameter(entryId));
    }

    public CrmCustomerIncomingApplication getByPartnersContractNumber(String partnersContractNumber){
        return getByHql(" from CrmCustomerIncomingApplication where partnersContractNumber =:p1 and status != 'a' and ifDelete = '0' ",new Parameter(partnersContractNumber));
    }

    public boolean updateToDelete(String entryId) {
        SQLQuery sqlQuery = getSession()
                .createSQLQuery("UPDATE crm_customer_incoming_application SET if_delete='1' WHERE entry_id=:entryId and if_delete = '0'");
        sqlQuery.setParameter("entryId", entryId);
        int count = sqlQuery.executeUpdate();
        if (count > 0)
            return true;
        return false;
    }

    /**
     * 校验是否可以删除进件记录
     */
    public boolean checkCanDelete(String entryId){
        // 可删除的状态有：0.待预审 1.预审中 2.预审成功 3.预审驳回 4.待进件 7.进件审核驳回 a.取消进件
        StringBuilder sb = new StringBuilder();
        sb.append("select count(1) from crm_customer_incoming_application ");
        sb.append("where status not in ('0','1','2','3','4','7','a') and entry_id=? and if_delete = '0' ");
        return Db.queryLong(sb.toString(), entryId) <= 0;
    }

    public List<CrmCustomerIncomingApplication> getInputPieceInProgress(String partnerId){
        List<Record> records = Db.find("select * from crm_customer_incoming_application where partner_id = ? and if_delete = 0 and status in ('5')", partnerId);
        return Optional.ofNullable(records)
                .map(l -> l.stream().map(r -> {
                    CrmCustomerIncomingApplication application = new CrmCustomerIncomingApplication();
                    application.setEntryId(r.get("entry_id"));
                    application.setPartnersContractNumber(r.get("partners_contract_number"));
                    application.setInputPieceId(r.get("input_piece_id"));
                    application.setStatus(r.get("status"));
                    return application;
                }).collect(Collectors.toList()))
                .orElse(Lists.newArrayList());
    }

    public CrmCustomerIncomingApplication getIncomingByEntryId(String entryId){

        Record rd = Db.findFirst("select * from crm_customer_incoming_application where entry_id=? and status<>'a' and if_delete = '0' ",entryId);
        if (rd!= null){
            CrmCustomerIncomingApplication app = new CrmCustomerIncomingApplication();
            app.setId(rd.getStr("id"));
            app.setEntryId(entryId);
            app.setImgUpload(rd.getStr("img_upload"));
            return app;
        }
        return null;
    }

    public List<Record> findProductParaList(String type,String projectCode) {
        return Db.find("select * from crm_customer_incoming_product_para where type=? and project_code =?",type,projectCode);
    }


    public Long getMaxVersion(String partnerId){
        return Db.queryColumn("SELECT IFNULL(max(version),0) from crm_customer_incoming_application WHERE partner_id = ?", partnerId);
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateIncomingIfDelete(String entryId){
        SQLQuery sqlQuery = getSession().createSQLQuery("UPDATE `crm_customer_incoming_application` SET if_delete='1' WHERE if_delete='0' AND status='a' AND entry_id=:entryId ");
        sqlQuery.setParameter("entryId", entryId);
        sqlQuery.executeUpdate();
    }


    //创建进件信息 或者修改进件的预审状态
    @Transactional(rollbackFor = Exception.class)
    public CrmCustomerIncomingApplication saveIncomingApplication(CustomerEntry entry){
        String partnerId = entry.getPartnerId();
        logger.info(">>>>>>>>saveIncomingApplication  credit:{}",entry.getCredit());
        CrmCustomerIncomingApplication incomingApplication=getByEntryId(entry.getId());
        if(incomingApplication==null && entry.getCredit()!=null && Integer.valueOf(entry.getCredit())>1){ //预审后的创建进件表
            incomingApplication=new CrmCustomerIncomingApplication();
            incomingApplication.setEntryId(entry.getId());
            String tenantStatus=getTenantStatus(entry.getCredit());
            incomingApplication.setTenantStatus(tenantStatus);
            incomingApplication.setApplyTime(new Date());
            incomingApplication.setPartnerId(partnerId);
            if(StringUtil.isNotBlank(entry.getApplyStatus())){
                incomingApplication.setStatus(entry.getApplyStatus());
            }
            Long maxVersion=getMaxVersion(partnerId);
            logger.info(">>>>>>saveIncomingApplication  maxVersion:{}",maxVersion);
            String partnersContractNumber= CustomerEntryUtil.addZero(CustomerEntryUtil.getJJPrefix(partnerId),maxVersion+1);
            logger.info(">>>>>>saveIncomingApplication  partnersContractNumber:{}",partnersContractNumber);
            incomingApplication.setPartnersContractNumber(partnersContractNumber);
            incomingApplication.setVersion(maxVersion+1);
            incomingApplication.setPartnerId(entry.getPartnerId());
            save(incomingApplication);
        }else {
            if(entry.getCredit()!=null && incomingApplication != null && !entry.getCredit().equals(incomingApplication.getTenantStatus())){
                String tenantStatus=getTenantStatus(entry.getCredit());
                 incomingApplication.setTenantStatus(tenantStatus);
                if(StringUtil.isNotBlank(entry.getApplyStatus())){
                    incomingApplication.setStatus(entry.getApplyStatus());
                }
                 save(incomingApplication);
            }
        }
        return incomingApplication;
    }


    //第一次进件时获取进件信息
    @Transactional(rollbackFor = Exception.class)
    public CrmCustomerIncomingApplication getIncomingApplication(CustomerEntry entry){
        String partnerId = entry.getPartnerId();
        CrmCustomerIncomingApplication incomingApplication=getByEntryId(entry.getId());
        if(incomingApplication==null){ //有可能是进件取消后重新进件
            incomingApplication=new CrmCustomerIncomingApplication();
            incomingApplication.setEntryId(entry.getId());
            String tenantStatus=getTenantStatus(entry.getCredit());
            incomingApplication.setTenantStatus(tenantStatus);
            if(StringUtil.isNotBlank(entry.getApplyStatus())){
                incomingApplication.setStatus(entry.getApplyStatus());
            }
            incomingApplication.setPartnerId(partnerId);
            incomingApplication.setApplyTime(new Date());
            Long maxVersion=getMaxVersion(partnerId);
            String numberQZ = CustomerEntryUtil.getJJPrefix(partnerId);
            logger.info(">>>>>>getIncomingApplication  maxVersion:{}",maxVersion);
            //当资方为广发时，进件序号加上NHGF
            String partnersContractNumber = "";
            partnersContractNumber = CustomerEntryUtil.addZero(numberQZ, maxVersion+1);
            logger.info(">>>>>>getIncomingApplication  partnersContractNumber:{}",partnersContractNumber);
            incomingApplication.setPartnersContractNumber(partnersContractNumber);
            incomingApplication.setVersion(maxVersion+1);
            return incomingApplication;
        }else {
          return incomingApplication;
        }
    }


    public String getTenantStatus(String credit){
        String tenantStatus="";
        if(StringUtil.isNotBlank(credit)){
            if("2".equals(credit)){
                tenantStatus="NEW";
            }else  if("3".equals(credit)){
                tenantStatus="APPROVING";
            }else  if("4".equals(credit)){
                tenantStatus="APPROVED";
            }else if("5".equals(credit)){
                tenantStatus="REJECTED";
            }
        }
        return tenantStatus;
    }


    public CrmCustomerIncomingApplication getNoDeleteApplication(String entryId){

        return getByHql(" from CrmCustomerIncomingApplication where entryId =:p1 and ifDelete = '0' ", new Parameter(entryId));
    }

}
