package com.iformall.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iformall.common.IdWorker;
import com.iformall.domain.po.*;
import com.iformall.enums.EnumCouponPasswordStatus;
import com.iformall.enums.EnumMsgSendStatus;
import com.iformall.mapper.*;
import com.iformall.service.WxMsgCallbackService;
import com.iformall.utils.HMACSHA256;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class WxMsgCallbackServiceImpl implements WxMsgCallbackService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    WxMsgCallbackMapper wxMsgCallbackMapper;

    @Autowired
    WxMsgConfigMapper wxMsgConfigMapper;

    @Autowired
    WxMsgModelMapper wxMsgModelMapper;

    @Autowired
    WxMsgValidationcodeModelMapper wxMsgValidationcodeModelMapper;

    @Autowired
    WxMsgMapper wxMsgMapper;

    @Autowired
    WxCouponPasswordMapper wxCouponPasswordMapper;

    @Override
    public PageInfo<WxMsgCallback> listAsPage(WxMsgCallback record, Integer pageIndex, Integer pageSize) {
        return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> wxMsgCallbackMapper.findList(record));
    }

    @Override
    public WxMsgCallback getById(Long id) {
        return wxMsgCallbackMapper.selectById(id);
    }

    @Override
    public void saveOrUpdate(WxMsgCallback record) {
        if (record.getId() == null) {
            final IdWorker idWorker = IdWorker.get();
            record.setId(idWorker.nextId());
            wxMsgCallbackMapper.insert(record);
        } else {
            wxMsgCallbackMapper.updateById(record);
        }
    }

    @Override
    public void deleteById(Long id) {
        wxMsgCallbackMapper.deleteById(id);
    }

    @Override
    public void saveOrUpdate(String tenantId, Map<String, String> param) {

        if(checksign(tenantId,param)){
            logger.info("短信发送回调SIGN校验成功");
            WxMsgConfig wxMsgConfig = new WxMsgConfig();
            wxMsgConfig.setTenantId(tenantId);
            List<WxMsgConfig> list = wxMsgConfigMapper.findList(wxMsgConfig);
            List<WxMsgCallback> wxMsgCallbacks = JSONArray.parseArray(param.get("item"), WxMsgCallback.class);
            wxMsgConfig = list.get(0);
            wxMsgConfig.setRemains(wxMsgConfig.getRemains() - wxMsgCallbacks.size());
            //wxMsgConfigMapper.updateById(wxMsgConfig);
            final IdWorker idWorker = IdWorker.get();
            for (WxMsgCallback wxMsgCallback : wxMsgCallbacks) {
                WxMsgCallback callback=wxMsgCallbackMapper.queryCallbackByBatchNoAndPhone(wxMsgCallback);
                if(callback!=null){//有更新，无插入
                    callback.setSign(param.get("sign"));
                    callback.setTenantId(tenantId);
                    if (!wxMsgCallback.getStatus().equals(EnumMsgSendStatus.MSG_SEND_SUCCESS.getCode())) {
                        callback.setStatus(EnumMsgSendStatus.MSG_SEND_FAIL.getCode());
                    } else {
                        callback.setStatus(EnumMsgSendStatus.MSG_SEND_SUCCESS.getCode());
                    }
                    callback.setStatusMsg(wxMsgCallback.getStatusMsg());
                    callback.setBegintime(wxMsgCallback.getBegintime());
                    callback.setEndtime(wxMsgCallback.getEndtime());
                    callback.setCallbackId(wxMsgCallback.getId());
                    callback.setUpdatetime(new Date());
                    wxMsgCallbackMapper.updateById(callback);
                    //更新业务
                    if (!callback.getBusinessId().equals(0L)) {
                        WxCouponPassword couponPassword = new WxCouponPassword();
                        couponPassword.setId(callback.getBusinessId());
                        couponPassword.setStatus(EnumCouponPasswordStatus.MSG_SENDED.getCode());
                        couponPassword.setUpdateDate(new Date());
                        wxCouponPasswordMapper.updateById(couponPassword);
                    }
                }else{
                    Long callbackId = wxMsgCallback.getId();
                    wxMsgCallback.setId(idWorker.nextId());
                    wxMsgCallback.setCallbackId(callbackId);
                    wxMsgCallback.setTenantId(tenantId);
                    wxMsgCallback.setSign(param.get("sign"));
                    wxMsgCallback.setCreatetime(new Date());
                    wxMsgCallbackMapper.insert(wxMsgCallback);
                }
            }
        }else{
            logger.info("短信发送回调SIGN校验失败");
        }

    }

    @Override
    public void receivemodel(String tenantId, Map<String, String> param) {

        if (checksign(tenantId, param)) {
            logger.info("短信营销模板回调SIGN校验成功");
            WxMsgModel wxMsgModel = new WxMsgModel();
            wxMsgModel.setModelId(Integer.valueOf(param.get("id")));
            wxMsgModel.setTenantId(tenantId);
            wxMsgModel = wxMsgModelMapper.findList(wxMsgModel).get(0);
            wxMsgModel.setStatus(param.get("status").equals("1")?Integer.valueOf(param.get("status")):0);
            wxMsgModelMapper.updateById(wxMsgModel);
        } else {
            logger.info("短信营销模板回调SIGN校验失败");
        }

    }

    @Override
    public void receiveverifymodel(String tenantId, Map<String, String> param) {

        if(checksign(tenantId,param)) {
            logger.info("短信验证码回调SIGN校验成功");
            WxMsgValidationcodeModel wxMsgModel = new WxMsgValidationcodeModel();
            wxMsgModel.setModelId(Integer.valueOf(param.get("id")));
            wxMsgModel.setTenantId(tenantId);
            wxMsgModel = wxMsgValidationcodeModelMapper.findList(wxMsgModel).get(0);
            wxMsgModel.setStatus(param.get("status").equals("1")?Integer.valueOf(param.get("status")):0);
            wxMsgValidationcodeModelMapper.updateById(wxMsgModel);
        }else{
            logger.info("短信验证码回调SIGN校验失败");
        }



    }

    public boolean checksign(String tenantId,Map<String, String> param){

        WxMsgConfig wxMsgConfig = new WxMsgConfig();
        wxMsgConfig.setTenantId(tenantId);
        List<WxMsgConfig> list = wxMsgConfigMapper.findList(wxMsgConfig);
        wxMsgConfig = list.get(0);

        TreeMap<String, String> message = new TreeMap<>();
        message.putAll(param);
        message.remove("sign");

        StringBuilder sb = new StringBuilder();
        Set<Map.Entry<String, String>> entries = message.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            sb.append(entry.getKey()).append("=").append(entry.getValue());
        }
        sb.append("&secret=").append(wxMsgConfig.getSecret());
        logger.info("message:" + sb.toString() + ",secret:" + wxMsgConfig.getSecret());
        String sign_check = HMACSHA256.sha256_HMAC(sb.toString(), wxMsgConfig.getSecret());
        logger.info("sign_check:" + sign_check);
        return sign_check.equalsIgnoreCase(param.get("sign"));

    }


}
