package cn.ibizlab.businesscentral.core.extensions.service;

import cn.ibizlab.businesscentral.core.base.domain.Account;
import cn.ibizlab.businesscentral.core.base.domain.Contact;
import cn.ibizlab.businesscentral.core.runtime.domain.Connection;
import cn.ibizlab.businesscentral.core.runtime.domain.ConnectionRole;
import cn.ibizlab.businesscentral.core.runtime.filter.ConnectionRoleSearchContext;
import cn.ibizlab.businesscentral.core.runtime.filter.ConnectionSearchContext;
import cn.ibizlab.businesscentral.core.runtime.service.IConnectionRoleService;
import cn.ibizlab.businesscentral.core.runtime.service.IConnectionService;
import cn.ibizlab.businesscentral.core.runtime.service.impl.ConnectionServiceImpl;
import cn.ibizlab.businesscentral.core.sales.domain.LeadCompetitor;
import cn.ibizlab.businesscentral.core.sales.domain.Opportunity;
import cn.ibizlab.businesscentral.core.sales.domain.OpportunityCompetitor;
import cn.ibizlab.businesscentral.core.sales.service.IOpportunityCompetitorService;
import cn.ibizlab.businesscentral.core.sales.service.impl.LeadServiceImpl;
import lombok.extern.slf4j.Slf4j;
import cn.ibizlab.businesscentral.core.sales.domain.Lead;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Primary;
import java.util.*;

/**
 * 实体[潜在顾客] 自定义服务对象
 */
@Slf4j
@Primary
@Service("LeadExService")
public class LeadExService extends LeadServiceImpl {

    @Autowired
    IOpportunityCompetitorService opportunityCompetitorService ;

    @Autowired
    IConnectionRoleService connectionRoleService ;

    @Autowired
    IConnectionService connectionService ;

    @Override
    protected Class currentModelClass() {
        return com.baomidou.mybatisplus.core.toolkit.ReflectionKit.getSuperClassGenericType(this.getClass().getSuperclass(), 1);
    }

    /**
     * 自定义行为[Active]用户扩展
     * @param et
     * @return
     */
    @Override
    @Transactional
    public Lead active(Lead et) {
        return super.active(et);
    }
    /**
     * 自定义行为[AddList]用户扩展
     * @param et
     * @return
     */
    @Override
    @Transactional
    public Lead addList(Lead et) {
        return super.addList(et);
    }
    /**
     * 自定义行为[DisQualification]用户扩展
     * @param et
     * @return
     */
    @Override
    @Transactional
    public Lead disQualification(Lead et) {
        return super.disQualification(et);
    }
    /**
     * 自定义行为[Qualification]用户扩展
     * @param et
     * @return
     */
    @Override
    @Transactional
    public Lead qualification(Lead et) {
        et = this.get(et.getLeadid()) ;
        Contact contact = new Contact() ;
        Account account = new Account();
        if(StringUtils.isBlank(et.getParentcontactid()) && StringUtils.isNotBlank(et.getFullname())){
            contact.setFullname(et.getFullname());
            contact.setOriginatingleadid(et.getLeadid());
            contact.setFullname(et.getFullname());
            contactService.create(contact);
        }else{
            contact = contactService.get(et.getParentcontactid()) ;
        }
        if(StringUtils.isBlank(et.getParentaccountid()) && StringUtils.isNotBlank(et.getCompanyname())){
            account.setAccountname(et.getCompanyname());
            account.setOriginatingleadid(et.getLeadid());
            account.setOriginatingleadname(et.getCompanyname());
            account.setPrimarycontactid(contact.getContactid());
            account.setPrimarycontactname(contact.getFullname());
            account.setWebsiteurl(et.getWebsiteurl());
            accountService.create(account) ;
        }else{
            account = accountService.get(et.getParentaccountid()) ;
        }

        contact.setCustomerid(account.getAccountid());
        contact.setCusomername(account.getAccountname());
        contactService.update(contact);

        ConnectionRoleSearchContext rolecxt = new ConnectionRoleSearchContext() ;
        rolecxt.setN_category_eq("1000");
        rolecxt.setN_statecode_eq(0);
        List<ConnectionRole> connectionRoles = connectionRoleService.searchDefault(rolecxt).getContent() ;

        //潜在客户 利益干系人
        ConnectionSearchContext cxt = new ConnectionSearchContext() ;
        Map<String,Object> params = new HashMap<>() ;
        params.put("srfparentkey",et.getLeadid()) ;
        cxt.setParams(params);
        List<Connection> connections = connectionService.searchByParentKey(cxt).getContent() ;
        if(connections.size() == 0){
            connections = new ArrayList<>() ;
            Connection connection = new Connection() ;
            connection.setRecord1id(et.getLeadid());
            connection.setRecord1idobjecttypecode(et.getFullname());
            connection.setRecord1objecttypecode("LEAD");

            connection.setRecord2id(contact.getContactid());
            connection.setRecord2idobjecttypecode(contact.getFullname());
            connection.setRecord2objecttypecode("CONTACT");

            if(connectionRoles.size()>0){
                connection.setRecord1roleid(connectionRoles.get(0).getConnectionroleid());
                connection.setRecord1rolename(connectionRoles.get(0).getConnectionrolename());
            }

            connectionService.create(connection);
            connections.add(connection);
        }


        // 建立商机
        Opportunity opportunity = new Opportunity() ;
        opportunity.setOpportunityname(et.getSubject());
        opportunity.setParentcontactid(contact.getContactid());
        opportunity.setParentcontactname(contact.getFullname());
        opportunity.setParentaccountid(account.getAccountid());
        opportunity.setParentaccountname(account.getAccountname());
        opportunity.setOriginatingleadid(et.getLeadid());
        opportunity.setOriginatingleadname(et.getFullname());
        opportunity.setBudgetamount(et.getBudgetamount());
        opportunity.setDecisionmaker(et.getDecisionmaker());
        opportunity.setDescription(et.getDescription());
        opportunity.setPurchaseprocess(et.getPurchaseprocess());
        opportunity.setPurchasetimeframe(et.getPurchasetimeframe());
        opportunity.setStatecode(0);
        opportunity.setStatuscode(1);
        opportunityService.create(opportunity) ;
        //商机 利益干系人
        for (Connection connection:connections) {
            connection.setConnectionid(null);
            connection.setRecord1id(opportunity.getOpportunityid());
            connection.setRecord1idobjecttypecode(opportunity.getOpportunityname());
            connection.setRecord1objecttypecode("OPPORTUNITY");
            connectionService.create(connection);
        }



        //对手
        List<LeadCompetitor> leadCompetitors = leadcompetitorService.selectByEntityid(et.getLeadid()) ;
        for (LeadCompetitor ladCompetitor:leadCompetitors) {
            OpportunityCompetitor opportunityCompetitor = new OpportunityCompetitor() ;
            opportunityCompetitor.setEntityid(opportunity.getOpportunityid());
            opportunityCompetitor.setEntityname(opportunity.getOpportunityname());
            opportunityCompetitor.setEntity2id(ladCompetitor.getEntity2id());
            opportunityCompetitor.setEntity2name(ladCompetitor.getEntity2name());
            opportunityCompetitorService.create(opportunityCompetitor) ;
        }

        et.setStatecode(1);
        et.setStatuscode(3);
        this.update(et) ;
        return super.qualification(et);
    }
}

