package com.cool.store.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cool.store.dao.EnterpriseUserDAO;
import com.cool.store.dao.HyPartnerBaseInfoDAO;
import com.cool.store.dao.HyPartnerLineInfoDAO;
import com.cool.store.dao.HyPartnerUserInfoDAO;
import com.cool.store.entity.*;
import com.cool.store.enums.LineStatusEnum;
import com.cool.store.enums.WorkflowStageEnum;
import com.cool.store.enums.WorkflowStatusEnum;
import com.cool.store.exception.ApiException;
import com.cool.store.http.UserSourceResponse;
import com.cool.store.mapper.HyPartnerUserChannelMapper;
import com.cool.store.request.CustomerInfoRequest;
import com.cool.store.sdk.ec.EcClient;
import com.cool.store.sdk.ec.bo.ChangeFollowUserBo;
import com.cool.store.sdk.ec.bo.UpdateCustomerBo;
import com.cool.store.sdk.ec.request.ChangeFollowUserRequest;
import com.cool.store.sdk.ec.request.UpdateCustomerRequest;
import com.cool.store.sdk.ec.response.ChangeFollowUserResponse;
import com.cool.store.sdk.ec.response.UpdateCustomerResponse;
import com.cool.store.service.EcSyncService;
import com.cool.store.utils.Post;
import com.cool.store.utils.StringUtil;
import com.cool.store.utils.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Service
public class EcSyncServiceImpl implements EcSyncService {



    @Value("${ec.baseUrl:null}")
    private String baseUrl;

    @Resource
    private HyPartnerLineInfoDAO hyPartnerLineInfoDAO;

    @Resource
    private HyPartnerBaseInfoDAO hyPartnerBaseInfoDAO;

    @Resource
    private HyPartnerUserInfoDAO hyPartnerUserInfoDAO;

    @Resource
    private EnterpriseUserDAO enterpriseUserDAO;


    @Resource
    private HyPartnerUserChannelMapper hyPartnerUserChannelMapper;


    @Override
    public boolean ecToApplet(List<CustomerInfoRequest> queryListData) {
        for (CustomerInfoRequest customerInfoItem : queryListData) {
            try {
                insertSelectiveSync(customerInfoItem);
            } catch (Exception e) {
                e.printStackTrace();
                sendFeiShuRobotMessage("推送："+JSONObject.toJSONString(e),"27243d49-97ca-4981-8aec-7c3bf84eb660");
            }
        }
        return false;
    }

    @Override
    public void getChannelSource() {
        String s = HttpUtil.get(baseUrl+"/ec/getChannelSource");
        UserSourceResponse userSourceResponse = JSONObject.parseObject(s, UserSourceResponse.class);
        for (UserSourceResponse.ChannelSource channelSource : userSourceResponse.getData()) {
            Long id = channelSource.getId();
            HyPartnerUserChannelDO selectByChannel = hyPartnerUserChannelMapper.selectByChannelId(id);
            HyPartnerUserChannelDO hyPartnerUserChannel = new HyPartnerUserChannelDO();
            hyPartnerUserChannel.setChannelId(channelSource.getId()).setChannelName(channelSource.getName());
            //有就更新 没有插入
            if (ObjectUtil.isNotNull(selectByChannel)) {
                hyPartnerUserChannel.setUpdateTime(new Date()).setId(selectByChannel.getId());
                hyPartnerUserChannelMapper.updateByPrimaryKeySelective(hyPartnerUserChannel);
            }else {
                hyPartnerUserChannel.setCreateTime(new Date());
                hyPartnerUserChannelMapper.insertSelective(hyPartnerUserChannel);
            }
        }
    }

    /**
     * 同步ec数据到表中 同时将部分数据同步到ec
     *
     * @param customerInfoItem
     */
    @Transactional(rollbackFor = Exception.class)
    public void insertSelectiveSync(CustomerInfoRequest customerInfoItem) throws ApiException {
        if (StringUtil.isNotEmpty(customerInfoItem.getMobile())) {
            customerInfoItem.setMobile(customerInfoItem.getMobile().split(" ")[1]);
        }
        //获取客户来源id
        String channel = customerInfoItem.getChannel();
        HyPartnerUserChannelDO hyPartnerUserChannelDO = hyPartnerUserChannelMapper.selectByChannelName(channel);
        Long channelId =null;
        if (StringUtil.isNotEmpty(channel)) {
            if (ObjectUtil.isNull(hyPartnerUserChannelDO)||ObjectUtil.isNull(hyPartnerUserChannelDO.getChannelId())) {
                getChannelSource();
            }
            HyPartnerUserChannelDO channelDO = hyPartnerUserChannelMapper.selectByChannelName(channel);
            channelId=channelDO.getChannelId();
        }
        String newPartnerId = UUIDUtils.get32UUID();
        HyPartnerUserInfoDO resultUser = new HyPartnerUserInfoDO();
        resultUser.setUsername(customerInfoItem.getName()).setMobile(customerInfoItem.getMobile()).setUserChannelId(Convert.toInt(channelId));

        HyPartnerLineInfoDO resultLine = new HyPartnerLineInfoDO();
        String followUserName = customerInfoItem.getFollowUserName();
        String followUserMobile = customerInfoItem.getFollowUserMobile();
        //传递过来有跟进人的情况下查询跟进人是否存在
        if (StringUtil.isNotEmpty(followUserMobile)&&StringUtil.isNotEmpty(followUserName)) {
            String userId = enterpriseUserDAO.selectByMobile(followUserMobile);
            if (StringUtil.isEmpty(userId)) {
                // 给飞书群发送消息 跟进人找不到
                sendFeiShuRobotMessage("推送：飞书架构中找不到该用户：【" + followUserName + "】，该用户电话号码为：" + followUserMobile,"27243d49-97ca-4981-8aec-7c3bf84eb660");
                throw new ApiException("飞书架构中找不到该用户：【" + followUserName + "】，该用户电话号码为：" + followUserMobile);
            }
            resultLine.setInvestmentManager(userId);
        }
        resultLine.setWorkflowStage(WorkflowStageEnum.INTENT.getCode())
                .setLineStatus(StringUtil.isEmpty(customerInfoItem.getFollowUserName()) ? LineStatusEnum.PUBLIC_SEAS.getCode() : LineStatusEnum.PRIVATE_SEAS.getCode());

        HyPartnerBaseInfoDO resultBase = new HyPartnerBaseInfoDO();
        resultBase.setUsername(customerInfoItem.getName()).setMobile(customerInfoItem.getMobile());

        HyPartnerUserInfoDO newUserInfo = hyPartnerUserInfoDAO.selectByMobile(resultUser.getMobile());
        EcClient ecClient=new EcClient();
        //有就更新ec没有就插入
        if (newUserInfo != null) {
            // EC与沪姨合伙人同时存在的线索用户，但用户姓名不同，将沪姨合伙人线索姓名同步至EC覆盖原EC线索姓名
            if (!newUserInfo.getUsername().equals(resultUser.getUsername())) {
                UpdateCustomerRequest updateUserRequest=new UpdateCustomerRequest();
                UpdateCustomerBo updateCustomerBo = new UpdateCustomerBo();
                updateCustomerBo.setUsername(newUserInfo.getUsername()).setMobile(newUserInfo.getMobile()).setCrmId(customerInfoItem.getCrmId());
                updateUserRequest.setParameter(updateCustomerBo);
                UpdateCustomerResponse updateUserExec = ecClient.exec(baseUrl,updateUserRequest);
            }
            String oldPartnerId = newUserInfo.getPartnerId();
            //线索表
            HyPartnerLineInfoDO partnerLine = hyPartnerLineInfoDAO.getByPartnerId(oldPartnerId);
            if (partnerLine != null) {
                //  EC与沪姨合伙人同时存在的线索用户，但存在不同的跟进人，将沪姨合伙人跟进人信息同步至EC覆盖原EC跟进人信息
                if (StringUtil.isEmpty(partnerLine.getInvestmentManager())) {
                    if (StringUtil.isNotEmpty(resultLine.getInvestmentManager())) {
                        resultLine.setId(partnerLine.getId()).setUpdateTime(new Date());
                        //沪姨合伙人线索存在黑名单，EC该线索分配跟进人同步到沪姨合伙人但线索状态不变，还存在黑名单中
                        resultLine.setLineStatus(partnerLine.getLineStatus().intValue()==LineStatusEnum.BLACKLIST.getCode().intValue()
                                ?LineStatusEnum.BLACKLIST.getCode():resultLine.getLineStatus());
                        hyPartnerLineInfoDAO.updateByPrimaryKeySelective(resultLine);
                    }
                }else {
                    EnterpriseUserDO enterpriseUser = enterpriseUserDAO.getUserInfoById(partnerLine.getInvestmentManager());
                    enterpriseUser.setMobile(getNoWith86Number(enterpriseUser.getMobile()));
                    //电话相同但是名字不同
                    if (enterpriseUser.getMobile().equals(followUserMobile) && !enterpriseUser.getName().equals(followUserName)) {
                        ChangeFollowUserRequest changeFollowUserRequest = new ChangeFollowUserRequest();
                        ChangeFollowUserBo changeFollowUserBo = new ChangeFollowUserBo();
                        changeFollowUserBo.setFollowUserId(customerInfoItem.getLastFollowUserId()).setCrmId(customerInfoItem.getCrmId())
                                .setType(1).setUsername(enterpriseUser.getName()).setMobile(enterpriseUser.getMobile());
                        changeFollowUserRequest.setParameter(changeFollowUserBo);
                        ChangeFollowUserResponse changeFollowUserExec = ecClient.exec(baseUrl,changeFollowUserRequest);
                    }
                    //电话不同
                    if (!enterpriseUser.getMobile().equals(followUserMobile)) {
                        ChangeFollowUserRequest changeFollowUserRequest = new ChangeFollowUserRequest();
                        ChangeFollowUserBo changeFollowUserBo = new ChangeFollowUserBo();
                        changeFollowUserBo.setFollowUserId(customerInfoItem.getLastFollowUserId()).setCrmId(customerInfoItem.getCrmId())
                                .setType(2).setUsername(enterpriseUser.getName()).setMobile(enterpriseUser.getMobile());
                        changeFollowUserRequest.setParameter(changeFollowUserBo);
                        ChangeFollowUserResponse changeFollowUserExec = ecClient.exec(baseUrl,changeFollowUserRequest);
                    }
                }
                //base表
                HyPartnerBaseInfoDO partnerIdAndLine = hyPartnerBaseInfoDAO.getByPartnerIdAndLineId(partnerLine.getPartnerId(), partnerLine.getId());
                if (partnerIdAndLine == null) {
                    resultBase.setPartnerId(newPartnerId).setPartnerLineId(partnerLine.getId()).setStatus(Integer.valueOf(WorkflowStatusEnum.INTENT_0.getCode())).
                            setCreateTime(new Date());
                    hyPartnerBaseInfoDAO.insertSelective(resultBase);
                }
            } else {
                resultLine.setPartnerId(newPartnerId).setCreateTime(new Date());
                hyPartnerLineInfoDAO.insertSelective(resultLine);

                resultBase.setPartnerId(newPartnerId).setPartnerLineId(resultLine.getId()).setStatus(Integer.valueOf(WorkflowStatusEnum.INTENT_0.getCode())).
                        setCreateTime(new Date());
                hyPartnerBaseInfoDAO.insertSelective(resultBase);
            }
        } else {
            resultUser.setPartnerId(newPartnerId).setCreateTime(new Date());
            hyPartnerUserInfoDAO.insertSelective(resultUser);

            resultLine.setPartnerId(newPartnerId).setCreateTime(new Date());
            hyPartnerLineInfoDAO.insertSelective(resultLine);

            resultBase.setPartnerId(newPartnerId).setPartnerLineId(resultLine.getId()).setStatus(Integer.valueOf(WorkflowStatusEnum.INTENT_0.getCode())).
                    setCreateTime(new Date());
            hyPartnerBaseInfoDAO.insertSelective(resultBase);
        }
    }

    /**
     * 得到不带86开头的号码
     *
     * @param number
     * @return
     */
    public static String getNoWith86Number(String number) {
        String regular = number;
        if (StringUtils.isNotBlank(regular)) {
            // 去掉+号
            while (regular.startsWith("+")) {
                regular = regular.substring(1);
            }
            // 号码以0开始,去掉前缀
            while (regular.startsWith("0")) {
                regular = regular.substring(1);
            }
            // 号码以86开始,去掉前缀
            while (regular.startsWith("86")) {
                regular = regular.substring(2);
            }
            // 号码以0开始，去掉前缀
            while (regular.startsWith("0")) {
                regular = regular.substring(1);
            }
        }
        return regular;
    }


    /**
     * 发送飞书机器人
     *
     * @param text
     * @param token
     * @return
     */
    public String sendFeiShuRobotMessage(String text, String token) {
        HashMap<String, Object> map = new HashMap<>(4);
        HashMap<String, String> textMap = new HashMap<String, String>(4);
        textMap.put("text", text);
        map.put("content", textMap);
        map.put("msg_type", "text");
        String body = JSON.toJSONString(map);
        String send = "";
        try {
            send = Post.send("https://open.feishu.cn/open-apis/bot/v2/hook/" + token, body, new HashMap<String, String>(4) {{
                put("Content-Type", "application/json");
            }});
        } catch (IOException e) {
            e.printStackTrace();
        }
        return send;
    }


}
