package com.kiisoo.ic.job.behavior;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kiisoo.ic.config.WxCpConfiguration;
import com.kiisoo.ic.employee.entity.PrivilageCpUserDO;
import com.kiisoo.ic.employee.mapper.PrivilageCpUserDOMapper;
import com.kiisoo.ic.generalize.entity.PoiCustomerContactDataStat;
import com.kiisoo.ic.generalize.mapper.PoiCustomerContactDataStatMapper;
import com.kiisoo.ic.store.constant.Constants;
import com.kiisoo.ic.store.entity.WxCusInfoReqDO;
import com.kiisoo.ic.store.entity.WxCusInfoRespDO;
import com.kiisoo.ic.store.mapper.PrivilageCpUserStoreDOMapper;
import com.kiisoo.ic.store.mapper.StorePromotionDataDOMapper;
import com.kiisoo.ic.utils.DateUtils;
import com.lmax.disruptor.WorkHandler;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpExternalContactService;
import me.chanjar.weixin.cp.api.WxCpService;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import static com.kiisoo.ic.config.WxCpConfiguration.APPLICATIONID;

@Slf4j
public class BehaviorDTOMessageGroupConsumer implements WorkHandler<BehaviorDTOMessage> {

    private WxCpService wxCpService;
    int i = 0;
    /**
     * 处理事件， 如入库操作
     *
     * @param behaviorDtoMessage
     * @throws Exception
     */
    @Override
    public void onEvent(BehaviorDTOMessage behaviorDtoMessage) throws Exception {
        behaviorDtoMessage.setId(UUID.randomUUID().toString());
        String cpUserId = behaviorDtoMessage.getCpUserId();
        Date statDate = behaviorDtoMessage.getStatDate();
        PrivilageCpUserStoreDOMapper privilageCpUserStoreDOMapper = behaviorDtoMessage.getPrivilageCpUserStoreDOMapper();
        PoiCustomerContactDataStatMapper poiCustomerContactDataStatMapper = behaviorDtoMessage.getPoiCustomerContactDataStatMapper();
        StorePromotionDataDOMapper storePromotionDataDOMapper = behaviorDtoMessage.getStorePromotionDataDOMapper();
        PrivilageCpUserDOMapper privilageCpUserDOMapper = behaviorDtoMessage.getPrivilageCpUserDOMapper();

        wxCpService = WxCpConfiguration.getCpService(APPLICATIONID);
        WxCpExternalContactService externalContactService = wxCpService.getExternalContactService();

        try {
            Long storeId = privilageCpUserStoreDOMapper.selectOneByCpUserId(cpUserId);
            Long regionId = null;

            if (storeId == null){
                QueryWrapper<PrivilageCpUserDO> qw = new QueryWrapper<>();
                qw.eq("cp_user_id",cpUserId).last("limit 1");
                PrivilageCpUserDO privilageCpUserDO = privilageCpUserDOMapper.selectOne(qw);
                if (privilageCpUserDO != null){
                    regionId = privilageCpUserDOMapper.selectOne(qw).getId();
                }
            }

            WxCusInfoReqDO wxCusInfoReqDO = new WxCusInfoReqDO();
            wxCusInfoReqDO.setAccess_token(wxCpService.getAccessToken());
            wxCusInfoReqDO.setUserid(cpUserId);
            wxCusInfoReqDO.setStart_time(statDate.getTime() / 1000);
            wxCusInfoReqDO.setEnd_time(statDate.getTime() / 1000);
            WxCusInfoRespDO wxCusInfoRespDO = getWxCusInfo(wxCusInfoReqDO);
            if (wxCusInfoRespDO == null) {
                return;
            }
            wxCusInfoRespDO.setStoreId(storeId);
            wxCusInfoRespDO.setRegionId(regionId);
            wxCusInfoRespDO.setStatTime(statDate);

            QueryWrapper<PoiCustomerContactDataStat> qw = new QueryWrapper();
            if (storeId == null && regionId !=null){
                qw.eq("region_id", regionId).eq("stat_time", statDate).last("limit 1");
            }else if (regionId  == null && storeId !=null){
                qw.eq("store_id",storeId).eq("stat_time", statDate).last("limit 1");
            }else{
                return;
            }
            PoiCustomerContactDataStat poiCustomerContactDataStat = poiCustomerContactDataStatMapper.selectOne(qw);
            int syncRes = 0;
            if (poiCustomerContactDataStat == null) {
                syncRes = storePromotionDataDOMapper.insertStorePromotionData(wxCusInfoRespDO);
            } else {
                Long newApplyCnt = 0L;
                if (wxCusInfoRespDO.getNew_apply_cnt() != null) {
                    newApplyCnt = new Long(wxCusInfoRespDO.getNew_apply_cnt());
                }
                poiCustomerContactDataStat.setNewApplyCnt(newApplyCnt);

                Long avgReplyTime = 0L;
                if (wxCusInfoRespDO.getAvg_reply_time() != null) {
                    avgReplyTime = new Long(wxCusInfoRespDO.getAvg_reply_time());
                }
                poiCustomerContactDataStat.setAvgReplyTime(avgReplyTime);

                Long chatCny = 0L;
                if (wxCusInfoRespDO.getChat_cnt() != null) {
                    chatCny = new Long(wxCusInfoRespDO.getChat_cnt());
                }
                poiCustomerContactDataStat.setChatCnt(chatCny);

                Long messageCnt = 0L;
                if (wxCusInfoRespDO.getMessage_cnt() != null) {
                    messageCnt = new Long(wxCusInfoRespDO.getMessage_cnt());
                }
                poiCustomerContactDataStat.setMessageCnt(messageCnt);

                Float replyPercentage = 0F;
                if (wxCusInfoRespDO.getReply_percentage() != null) {
                    replyPercentage = wxCusInfoRespDO.getReply_percentage();
                }
                poiCustomerContactDataStat.setReplyPercentage(replyPercentage);

                Long newContactCnt = 0L;
                if (wxCusInfoRespDO.getNew_contact_cnt() != null) {
                    newContactCnt = new Long(wxCusInfoRespDO.getNew_contact_cnt());
                }
                poiCustomerContactDataStat.setNewContactCnt(newContactCnt);

                Long negativeFeedbackCnt = 0L;
                if (wxCusInfoRespDO.getNegative_feedback_cnt() != null) {
                    negativeFeedbackCnt = new Long(wxCusInfoRespDO.getNegative_feedback_cnt());
                }
                poiCustomerContactDataStat.setNegativeFeedbackCnt(negativeFeedbackCnt);

                syncRes = poiCustomerContactDataStatMapper.updateById(poiCustomerContactDataStat);
            }

            if (syncRes == Constants.INSERT_FAIL) {
                throw new RuntimeException("向数据库导入客户统计数据时出错");
            }
        } catch (Exception e) {
            log.error("请求企业微信api获取客户统计数据或日期转换出错！", e);
        }
    }


    /**
     * 获取联系客户统计数据
     *
     * @param wxCusInfoReqDO
     * @return
     * @throws WxErrorException
     */
    public WxCusInfoRespDO getWxCusInfo(WxCusInfoReqDO wxCusInfoReqDO) throws WxErrorException {
        String url = wxCpService.getWxCpConfigStorage().getApiUrl("/cgi-bin/externalcontact/get_user_behavior_data");
        String result = wxCpService.post(url, wxCusInfoReqDO.toJson());
        JSONObject parseObject = JSON.parseObject(result);
        String[] behavior_data = JSONObject.parseObject(parseObject.getString("behavior_data"), String[].class);
        return JSONObject.parseObject(behavior_data[0], WxCusInfoRespDO.class);
    }
}
