package com.iformall.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iformall.common.ErrorCode;
import com.iformall.common.IdWorker;
import com.iformall.common.Result;
import com.iformall.common.ResultData;
import com.iformall.domain.po.WxMsgConfig;
import com.iformall.domain.po.WxMsgValidationcodeModel;
import com.iformall.enums.EnumMsgModelStatus;
import com.iformall.enums.EnumVerifyCode;
import com.iformall.mapper.WxMsgConfigMapper;
import com.iformall.mapper.WxMsgValidationcodeModelMapper;
import com.iformall.service.WxMsgValidationcodeModelService;
import com.iformall.utils.*;
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 WxMsgValidationcodeModelServiceImpl implements WxMsgValidationcodeModelService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
    WxMsgValidationcodeModelMapper wxMsgValidationcodeModelMapper;

    @Autowired
    WxMsgConfigMapper wxMsgConfigMapper;

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

    @Override
    public WxMsgValidationcodeModel getById(String id) {
        return wxMsgValidationcodeModelMapper.selectById(id);
    }

    @Override
    public ResultData saveOrUpdate(WxMsgValidationcodeModel wxMsgModel) {


        //从短信配置中查询密钥 bid 等信息
        WxMsgConfig wxMsgConfig = new WxMsgConfig();
        wxMsgConfig.setTenantId(wxMsgModel.getTenantId());
        List<WxMsgConfig> wxMsgConfigs = wxMsgConfigMapper.findList(wxMsgConfig);
        if(wxMsgConfigs.size()==0)return new ResultData(Result.SUCCESS, "您还未接入短信运营商，请联系平台管理员");
        wxMsgConfig = wxMsgConfigs.get(0);

        String secret = wxMsgConfig.getSecret();
        String bid = wxMsgConfig.getBid();

        String signature = wxMsgModel.getSignature();
        String content = wxMsgModel.getContent();
        //查看用户最新数据是否存在
        List<WxMsgValidationcodeModel> wxMsgModels = wxMsgValidationcodeModelMapper.findList(wxMsgModel);
        if (wxMsgModel.getId() == null && wxMsgModels.size() == 1) {
            return new ResultData(ErrorCode.MSG_TEMPLATE_REPEAT.getCode(), "您添加的短信模板已存在");
        }

        if (wxMsgModel.getId() != null && wxMsgModels.size() == 1) {
            //ID相同 内容相同 不发送短信 不做修改
            WxMsgValidationcodeModel wxmsgmodel = wxMsgModels.get(0);
            if(wxmsgmodel.getContent().equals(wxMsgModel.getContent()) && wxmsgmodel.getSignature().equals(wxMsgModel.getSignature())) {
                return new ResultData(Result.SUCCESS, "修改成功");
            }

        }
        String result = WiwideUtil.addTemplate(secret, bid, wxMsgConfig.getPublickey(), signature, content, wxMsgConfig.getVerifynotifyurl(),EnumVerifyCode.YES.getCode().toString());

        JSONObject jsonObjectResult = JSONObject.parseObject(result);
        String ret = jsonObjectResult.get("ret").toString();
        if (ret.equals(EnumMsgModelStatus.SUCCESS.getCode().toString())) {
            if (wxMsgModel.getId() == null) {
                final IdWorker idWorker = IdWorker.get();
                wxMsgModel.setId(idWorker.nextId());
                wxMsgModel.setTenantId(wxMsgModel.getTenantId());
                String data = jsonObjectResult.get("data").toString();
                wxMsgModel.setModelId(Integer.valueOf(data));
                wxMsgModel.setCreatetime(new Date());
                wxMsgModel.setStatus(2);//审核中
                wxMsgValidationcodeModelMapper.insert(wxMsgModel);
            } else {
                String data = jsonObjectResult.get("data").toString();
                wxMsgModel.setModelId(Integer.valueOf(data));
                wxMsgModel.setStatus(2);//审核中
                wxMsgValidationcodeModelMapper.updateById(wxMsgModel);
            }
            return new ResultData(Result.SUCCESS, "创建模板成功");
        } else if (ret.equals(EnumMsgModelStatus.REPEAT.getCode().toString())) {
            if (wxMsgModel.getId() == null) {
                final IdWorker idWorker = IdWorker.get();
                wxMsgModel.setId(idWorker.nextId());
                wxMsgModel.setTenantId(wxMsgModel.getTenantId());
                wxMsgModel.setCreatetime(new Date());
                wxMsgModel.setStatus(1);
                wxMsgValidationcodeModelMapper.insert(wxMsgModel);
            } else {
                wxMsgValidationcodeModelMapper.updateById(wxMsgModel);
            }
        } else if (ret.equals(EnumMsgModelStatus.SINATURE_CONTENT_ERROR.getCode().toString())) {
            return new ResultData(ErrorCode.MSG_SIGNATURE_CONTENT_ERROR.getCode(), "短信签名或内容错误");
        } else if (ret.equals(EnumMsgModelStatus.NOT_FOUND.getCode().toString())) {
            return new ResultData(ErrorCode.MSG_TEMPLATE_NOT_FOUND.getCode(), "短信模板不存在");
        } else if (ret.equals(EnumMsgModelStatus.PARAMETERS_ERROR.getCode().toString())) {
            return new ResultData(ErrorCode.MSG_REQUEST_PARAMS_ERROR.getCode(), "参数错误");
        } else if (ret.equals(EnumMsgModelStatus.MSG_SEND_FAIL.getCode().toString())) {
            return new ResultData(ErrorCode.MSG_SEND_ERROR.getCode(), "发送短信失败");
        } else if (ret.equals(EnumMsgModelStatus.INTERFACE_ERROR.getCode().toString())) {
            return new ResultData(ErrorCode.MSG_METHOD_REQUEST_ERROR.getCode(), "接口请求错误");
        }
        return new ResultData(ErrorCode.MSG_TEMPLATE_CREATE_ERROR.getCode(), "创建模板失败");

    }

    @Override
    public void deleteById(String id) {
        wxMsgValidationcodeModelMapper.deleteById(id);
    }

    @Override
    public void update(WxMsgValidationcodeModel record) {
        wxMsgValidationcodeModelMapper.updateById(record);
    }
}
