package com.huiju.estateagents.reportCustomerAop;

import com.huiju.estateagents.base.BaseController;
import com.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.common.CommConstant;
import com.huiju.estateagents.common.StringUtils;
import com.huiju.estateagents.entity.TaBuilding;
import com.huiju.estateagents.entity.TaCustomerFrom;
import com.huiju.estateagents.entity.TaPerson;
import com.huiju.estateagents.mapper.TaBuildingMapper;
import com.huiju.estateagents.mapper.TaPersonMapper;
import com.huiju.estateagents.service.ITaRecommendCustomerService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Aspect
@Component
public class ReportCustomerAspect extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(ReportCustomerAspect.class);

    @Autowired
    private ITaRecommendCustomerService iTaRecommendCustomerService;

    @Autowired
    TaPersonMapper taPersonMapper;

    @Autowired
    TaBuildingMapper taBuildingMapper;

    @Autowired
    ReportCustomerImpl reportCustomerImpl;


    /**
     * 以自定义 @ReportCustomer 注解为切点
     */
    @Pointcut("@annotation(com.huiju.estateagents.reportCustomerAop.ReportCustomer)")
    public void reportCustomer() {

    }

    @After("reportCustomer()")
    public ResponseBean doAround(JoinPoint proceedingJoinPoint) {
        logger.info("ReportCustomerAspect 开始");
        ResponseBean responseBean = new ResponseBean();
        try {
            ReportCustomer reportCustomer = ((MethodSignature) proceedingJoinPoint.getSignature()).getMethod().getAnnotation(ReportCustomer.class);
            //获取请求参数
            Object[] args = proceedingJoinPoint.getArgs();
            String targetType = reportCustomer.type();
            String targetId = String.valueOf(args[0]);
            String qrCodeId = String.valueOf(args[1]);
            String channelId = String.valueOf(args[2]);
            String sceneId = String.valueOf(args[3]);
            HttpServletRequest request = (HttpServletRequest) args[4];

            Map<String, Object> stringObjectMap = getBuildingByIdAndType(targetId, targetType);
            if (!CommConstant.INDEX.equals(targetType) && request == null) {
                responseBean.addError("未授权，不进行操作");
                return responseBean;
            }

            String consultantPersonId = request.getHeader("x-consultant");
            String recommend = request.getHeader("x-recommender");

            logger.info("ReportCustomerAspect 获取header信息，consultantPersonId：{}，recommend：{}", consultantPersonId, recommend);

            List<TaPerson> persons = getPersonsByOpenId(getOpenId(request));
            TaPerson taPerson = persons.get(0);
            Integer orgId = getOrgId(request);

            TaCustomerFrom taCustomerFrom = assembleVO(taPerson, targetType,StringUtils.ifNull(targetId,null), null == stringObjectMap ? null : stringObjectMap.get("targetName").toString(), orgId, StringUtils.ifNull(sceneId,null), channelId, qrCodeId);
            // 推广人
            TaPerson recPerson = StringUtils.isEmpty(recommend) ? null : taPersonMapper.getById(recommend);
            // 是否置业顾问
            boolean isConsultant = null != recPerson && CommConstant.PERSON_REALTY_CONSULTANT.equals(recPerson.getPersonType());
            TaPerson consultantInfo = null != consultantPersonId ? reportCustomerImpl.getPerson(consultantPersonId) : (isConsultant ? recPerson : null);
            // 推荐楼盘
            TaBuilding taBuilding = null == stringObjectMap ? null : (TaBuilding) stringObjectMap.get("taBuilding");
            TaBuilding building = taBuilding == null ? null : taBuildingMapper.selectById(taBuilding.getBuildingId());

            if (StringUtils.isEmpty(taPerson.getPhone())) {
                responseBean.addError("未授权，不进行操作");
                return responseBean;
            }
            iTaRecommendCustomerService.newCustomer(orgId, taPerson, recPerson, consultantInfo, building, taCustomerFrom);
            responseBean.addSuccess("绑定成功");

        } catch (Exception e) {
            logger.error("绑定失败",e);
            responseBean.addError("失败");
        }
        logger.info("ReportCustomerAspect 结束");
        return responseBean;
    }

    public TaCustomerFrom assembleVO(TaPerson person, String targetType, String targetId, String targetName, Integer orgId, String sceneId, String channelId, String qrCodeId) {
        // 客户来源
        TaCustomerFrom customerFrom = new TaCustomerFrom();
        customerFrom.setPersonId(person.getPersonId());
        customerFrom.setPersonName(StringUtils.ifNull(person.getName(), person.getNickname()));
        customerFrom.setTargetType(targetType);
        customerFrom.setTargetId(targetId);
        customerFrom.setTargetName(targetName);
        customerFrom.setOrgId(orgId);
        customerFrom.setSceneId(sceneId);
        if (!StringUtils.isEmpty(channelId)) {
            customerFrom.setChannelId(Integer.valueOf(channelId));
        }
        if (!StringUtils.isEmpty(qrCodeId)) {
            customerFrom.setQrCodeId(Integer.valueOf(qrCodeId));
        }
        customerFrom.setCreateDate(LocalDateTime.now());

        return customerFrom;
    }

    public List<TaPerson> getPersonsByOpenId(String openId) {
        return taPersonMapper.getPersonByOpenId(openId);
    }

    public Map<String, Object> getBuildingByIdAndType(String targetId, String targetType) {
        Map<String, Object> buildingAndNameInfo = null;

        switch (targetType) {
            case CommConstant.FAVOR_ACTIVITY:
                buildingAndNameInfo = reportCustomerImpl.selectActivityBuildingInfo(targetId);
                break;
            case CommConstant.POINTS_CHANGE_HELP:
                buildingAndNameInfo = reportCustomerImpl.selectHelpBuildingInfo(targetId);
                break;
            case CommConstant.POINTS_CHANGE_GROUP:
                buildingAndNameInfo = reportCustomerImpl.selectGroupBuildingInfo(targetId);
                break;
            case CommConstant.LIVE:
                buildingAndNameInfo = reportCustomerImpl.selectLiveBuildingInfo(targetId);
                break;
            case CommConstant.EVENT_H5:
                buildingAndNameInfo = reportCustomerImpl.selectH5BuildingInfo(targetId);
                break;
            case CommConstant.FAVOR_NEWS:
                buildingAndNameInfo = reportCustomerImpl.selectNewsBuildingInfo(targetId);
                break;
            case CommConstant.HOUSE:
                buildingAndNameInfo = reportCustomerImpl.selectHouseBuildingInfo(targetId);
                break;
            case CommConstant.INDEX:
                break;
            default:
                buildingAndNameInfo = reportCustomerImpl.selectBuildingInfo(targetId);
                break;
        }

        return buildingAndNameInfo;
    }


}
