package com.dk.mdm.service.xxl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.dk.common.infrastructure.constant.Constant;
import com.dk.common.infrastructure.xxl.XxlJobUtils;
import com.dk.common.mapper.BaseMapper;
import com.dk.common.model.response.mst.StaffResponse;
import com.dk.common.response.ResponseCodeEnum;
import com.dk.common.response.ResponseResultVO;
import com.dk.common.service.BaseService;
import com.dk.common.util.HttpUtils;
import com.dk.mdm.feign.UserFeign;
import com.dk.mdm.infrastructure.config.Config;
import com.dk.mdm.mapper.mst.CusFollowMapper;
import com.dk.mdm.mapper.mst.CustomerMapper;
import com.dk.mdm.mapper.mst.FollowPlanMapper;
import com.dk.mdm.mapper.mst.StaffMapper;
import com.dk.mdm.model.pojo.mst.CusFollow;
import com.dk.mdm.model.pojo.mst.Customer;
import com.dk.mdm.model.pojo.mst.FollowPlan;
import com.dk.mdm.model.query.mst.CustomerQuery;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Service
public class XxlService extends BaseService<CusFollow> {
    @Override
    public BaseMapper<CusFollow> getRepository() {
        return cusFollowMapper;
    }

    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private StaffMapper staffMapper;
    @Autowired
    private CusFollowMapper cusFollowMapper;
    @Autowired
    private FollowPlanMapper followPlanMapper;
    @Autowired
    private XxlJobUtils xxlJobUtils;
    @Autowired
    private Config config;
    @Resource
    private UserFeign userFeign;

    /**
     * @desc : 客户跟进提醒回调
     * @author : 姜永辉
     * @date : 2022-06-29 14:22
     */
    @Transactional(rollbackFor = {Exception.class})
    @XxlJob("customer-reminder")
    public ResponseResultVO customerReminder() {
        log.info("@XxlJob(\"customer-reminder\")");
        log.info("followPlan id: {}", XxlJobHelper.getJobParam());
//        String planid = "10112024-0715-0000-0000-0004a8b4d1e6";
        FollowPlan followPlan = followPlanMapper.selectById(XxlJobHelper.getJobParam());
        if (followPlan != null) {
            CusFollow follow = cusFollowMapper.selectById(followPlan.getFollowId());
            if (follow != null) {
                FollowPlan plan = new FollowPlan().setPlanId(followPlan.getPlanId());
                try {
                    //发消息
                    String msg = sendFollowMessage(follow, followPlan);
                    if (msg == null) {
                        plan.setCallStatus(Constant.CallStatus.CALL_STATUS_DONE.getName() + "");
                    } else {
                        plan.setCallStatus(Constant.CallStatus.CALL_STATUS_ERROR.getName() + "").setRemarks(msg);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("客户跟进发送消息异常：{}", e.getMessage());
                    plan.setCallStatus(Constant.CallStatus.CALL_STATUS_ERROR.getName() + "").setRemarks(e.getMessage());
                }

                //修改状态
                followPlanMapper.update(plan,
                        new UpdateWrapper<FollowPlan>().lambda()
                                .eq(FollowPlan::getPlanId, UUID.fromString(plan.getPlanId())));

                //删除任务
                xxlJobUtils.delete(followPlan.getXxlJobId());
            }

        }
        return null;
    }

    /**
     * @desc : 客户计划任务提醒回调
     * @author : jyh
     * @date : 2022-06-29 14:22
     */
    @Transactional(rollbackFor = {Exception.class})
    @XxlJob("plan-reminder")
    public void planReminder() {
        log.info("@XxlJob(\"plan-reminder\")");
        log.info("followPlan id: {}", XxlJobHelper.getJobParam());
//        String planid = "10112024-0715-0000-0000-0004a8b4d1e6";
        FollowPlan followPlan = followPlanMapper.selectById(XxlJobHelper.getJobParam());
        if (followPlan != null && followPlan.getFlgValid()) {
            FollowPlan plan = new FollowPlan().setPlanId(followPlan.getPlanId());
            try {
                //发消息
                String msg = sendFollowPlanMessage(followPlan);
                if (msg == null) {
                    plan.setCallStatus(Constant.CallStatus.CALL_STATUS_DONE.getName() + "");
                } else {
                    plan.setCallStatus(Constant.CallStatus.CALL_STATUS_ERROR.getName() + "").setRemarks(msg);
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("跟进任务发送消息异常：{}", e.getMessage());
                plan.setCallStatus(Constant.CallStatus.CALL_STATUS_ERROR.getName() + "").setRemarks(e.getMessage());
            }
            //修改状态
            followPlanMapper.updateById(plan);
            //删除任务
            xxlJobUtils.delete(followPlan.getXxlJobId());

        }
    }

    /**
     * @desc : 发送跟进任务消息
     * @author : 姜永辉
     * @date : 2022-06-30 19:24
     */
    public String sendFollowPlanMessage(FollowPlan followPlan) {
        log.info("sendFollowMessage:{}", JSONObject.toJSONString(followPlan));
        // 跟进人
        StaffResponse followStaff = staffMapper.selectById(followPlan.getFollowUser());

        Customer customer = customerMapper.selectById(new CustomerQuery().setCusId(followPlan.getCusId()));

        if (customer != null) {
            // 小程序消息


            return null;
        } else {
            return ResponseCodeEnum.SELECT_NULL.getMessage();
        }
    }

    /**
     * @desc : 发送跟进消息
     * @author : 姜永辉
     * @date : 2022-05-27 09:34
     */
    public String sendFollowMessage(CusFollow follow, FollowPlan followPlan) {
        log.info("sendFollowMessage:{}", JSONObject.toJSONString(follow));
        // 跟进人
        StaffResponse followStaff = null;
        // 当跟进计划状态为跟尺时 获取设计师信息
        if (follow.getFollowStatus().equals("跟进状态-约尺")) {
            followStaff = staffMapper.selectById(follow.getDesignStaff());
        } else {
            followStaff = staffMapper.selectById(followPlan.getFollowUser());
        }
        //查到跟进人
        if (followStaff != null) {
            log.info("sendFollowMessage:{}", JSONObject.toJSONString(followStaff));
            Customer customer = customerMapper.selectById(follow.getCusId());
            log.info("customer:{}", JSONObject.toJSONString(customer));
            Map<String, Object> otherParamMap = new HashMap<>();
            if (customer != null) {
                if (follow.getFollowStatus().equals("跟进状态-约尺")) {
//                    customer.setStaffName(followStaff.getStaffName());
//                    // 暂时用最后一次 跟进id传过去
//                    customer.setLastFollowId(follow.getFollowId());
                    otherParamMap.put("staffName", followStaff.getStaffName());
                    otherParamMap.put("staffId", followStaff.getStaffId());
                    otherParamMap.put("followId", follow.getFollowId());
                }
                String loginType = "4";
//                List<String> list = new ArrayList<>();
                Map<String, String> keywordMap = new HashMap<>();
                if (Constant.BasicDataConstant.FOLLOW_STATUS_4.getValue().equals(follow.getFollowStatus()) ||
                        Constant.BasicDataConstant.FOLLOW_STATUS_1.getValue().equals(follow.getFollowStatus()) ||
                        Constant.BasicDataConstant.FOLLOW_STATUS_5.getValue().equals(follow.getFollowStatus())) {
//                    list.add("您有客户需要跟进");
                    keywordMap.put("remark", "您有客户需要跟进");
                    loginType = "4";

                } else if (Constant.BasicDataConstant.FOLLOW_STATUS_6.getValue().equals(follow.getFollowStatus())) {
//                    list.add("您有客户需要量尺服务");
                    keywordMap.put("remark", "您有客户需要量尺服务");
                    loginType = "6";

                } else if (Constant.BasicDataConstant.FOLLOW_STATUS_2.getValue().equals(follow.getFollowStatus())) {
//                    list.add("您有客户邀约进店");
                    keywordMap.put("remark", "您有客户邀约进店");
                    loginType = "2";

                } else if (Constant.BasicDataConstant.FOLLOW_STATUS_3.getValue().equals(follow.getFollowStatus())) {
//                    list.add("您有客户需要约尺服务");
                    keywordMap.put("remark", "您有客户需要约尺服务");
                    loginType = "3";
                }
//                list.add(customer.getCusName());
//                list.add(customer.getCusPhone());
                LocalDateTime followTime = follow.getFollowTime();
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

                keywordMap.put("cusName", customer.getCusName());
                keywordMap.put("cusPhone", customer.getCusPhone());
                keywordMap.put("followTime", followTime.format(formatter));
                // 查询跟进人的openid和publicOpenId   7.19 加了userWxId 刘尧
                ResponseResultVO<?> resultVO = userFeign.getUser(followStaff.getWxUserId());
                // 如果没有成功返回，状态设置为待审
                if (resultVO.getCode() != ResponseCodeEnum.SUCCESS.getCode()) {
                    log.error("客户查询异常：为空{}", follow.getCusId());
                    return ResponseCodeEnum.SELECT_NULL.getMessage();
                } else {
                    Map<String, Object> user = (Map<String, Object>) resultVO.getData();
                    if (user != null) {
                        // 发送消息
                        Map<String, Object> mapMessage = new HashMap<>();
                        mapMessage.put("loginType", loginType);
                        otherParamMap.put("cusId", customer.getCusId());
                        mapMessage.put("otherParam", JSONObject.toJSONString(otherParamMap));
//                        mapMessage.put("publicOpenId", user.get("publicOpenId"));
                        mapMessage.put("userWxId", user.get("userWxId"));
                        mapMessage.put("first", "客户跟进提醒");
//                      mapMessage.put("keywordList", list);
//                      mapMessage.put("keywordMap", keywordMap);
                        mapMessage.put("remark", "客户跟进备注");
//                      sendUniformMessage(mapMessage);
                        List<String> miniMessageModelIds = config.getMiniMessageModelIds();
                        // 构造对应的显示信息 和模板数据结构对应
                        JSONObject data = new JSONObject();
                        data.put("time4", createDataItem("value", String.valueOf(keywordMap.get("followTime"))));
                        data.put("thing1", createDataItem("value", String.valueOf(keywordMap.get("cusName"))));
                        data.put("phone_number2", createDataItem("value", String.valueOf(keywordMap.get("cusPhone"))));
                        data.put("thing6", createDataItem("value", String.valueOf(keywordMap.get("remark"))));
                        data.put("thing5", createDataItem("value", String.valueOf(mapMessage.get("remark"))));
                        wxMessagePush(miniMessageModelIds.get(0), data, mapMessage);
                    }
                }

                return null;
            } else {
                log.error("客户查询异常：为空{}", follow.getCusId());
                return ResponseCodeEnum.SELECT_NULL.getMessage();
            }
        } else {
            log.error("跟进人异常：为空{}", followPlan.getFollowUser());
            return ResponseCodeEnum.SELECT_NULL.getMessage();
        }

    }

    /**
     * @desc : 构造消息推送模板中data值
     * @author : 刘尧
     * @date : 2024-07-19 08:56
     */
    private static Map<String, Object> createDataItem(String name, String value) {
        Map<String, Object> item = new HashMap<>();
        item.put(name, value);
        return item;
    }


    /**
     * @desc : 向用户推送小程序订阅消息方法
     * @author : 刘尧
     * @date : 2024-07-19 08:56
     */
    public ResponseResultVO<?> wxMessagePush(String messId, JSONObject data, Map<String, Object> map) {
        // 获取微信Token
        String wxToken = getWxToken();
        Map<String, Object> params = new HashMap<>();
        // 接口调用凭证
        params.put("access_token", wxToken);
        // 所需下发的订阅模板id
        params.put("template_id", messId);
        // 点击模板卡片后的跳转页面
        if (map.containsKey("otherParam")) {
            params.put("page", "pages/welcome/welcome?loginType=" + map.get("loginType").toString() + "&otherParam=" + map.get("otherParam").toString());
        } else {
            params.put("page", "pages/welcome/welcome?loginType=" + map.get("loginType").toString());
        }
        // 接收者（用户）的 openid
        params.put("touser", map.get("userWxId"));
        // 跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；
        params.put("miniprogram_state", "trial");
        // 配置模板中明细值
        params.put("data", data);

        ResponseResultVO<JSONObject> post = HttpUtils.post("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + wxToken, params);
        return post;
    }

    /**
     * @desc : 获取微信小程序后台Token
     * @author : 刘尧
     * @date : 2024-07-19 08:56
     */
    private String getWxToken() {
        String appId = config.getAppId();
        String appSecret = config.getAppSecret();
        ResponseResultVO<JSONObject> tokenRes = HttpUtils.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret);
        JSONObject data = tokenRes.getData();
        return String.valueOf(data.get("access_token"));
    }

    /**
     * @desc : 将字节转化为十六进制字符串
     * @author : 刘尧
     * @date : 2024-07-19 08:56
     */
    private static String byteToStr(byte[] byteArray) {
        String strDigest = "";
        for (int i = 0; i < byteArray.length; i++) {
            strDigest += byteToHexStr(byteArray[i]);
        }
        return strDigest;
    }

    /**
     * @desc : 将字节转换成对应的两位十六进制字符串
     * @author : 刘尧
     * @date : 2024-07-19 08:56
     */
    private static String byteToHexStr(byte mByte) {
        char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
                'B', 'C', 'D', 'E', 'F'};
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
        tempArr[1] = Digit[mByte & 0X0F];
        String s = new String(tempArr);
        return s;
    }

}
