package com.zjrs.ggfw.portal.blo.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import org.apache.commons.lang.StringUtils;
import org.mohrss.leaf.core.framework.persistens.PageResult;
import org.mohrss.leaf.core.framework.persistens.PageUtil;
import org.mohrss.leaf.core.framework.util.CurrentUser;
import org.mohrss.leaf.core.framework.web.controller.AjaxResponse;
import org.mohrss.leaf.core.framework.web.exception.AppException;
import com.zjrs.ggfw.portal.blo.CommBLO;
import com.zjrs.ggfw.portal.blo.EMSBLO;
import com.zjrs.ggfw.portal.dto.*;
import com.zjrs.ggfw.portal.entity.*;
import com.zjrs.ggfw.portal.po.*;
import com.zjrs.ggfw.portal.utils.EncryptionUtil;
import com.zjrs.ggfw.portal.utils.HttpUtil;
import com.zjrs.ggfw.portal.utils.WXPayUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import static org.mohrss.leaf.core.framework.util.SecurityUtils.getCurrentUser;

@Service
public class EMSBLOImpl implements EMSBLO {
    private static final Logger LOG = LoggerFactory.getLogger(EMSBLOImpl.class);
    @Value("${ems.mrkey:a7cc6c5acf497f8cec13fd9004fcbadf}")
    private String key;//默认key

    @Value("${ems.xdurl:http://14.29.115.226:9222/mgr/o2oapi/order/add}")
    private String xdurl;

    @Value("${ems.zfurl:http://14.29.115.226:9222/mgr/o2oapi/v1/pay/askPayment}")
    private String zfurl;

    @Value("${ems.wlurl:http://14.29.115.226:9222/mgr/o2oapi/common/getMailTrackByExpressNbr?params=}")
    private String wlurl;

    @Value("${ems.xcxzfurl:https://wx.emspost.com.cn/weixin/pay/order/createAndPay}")
    private String xcxzfurl;

    @Value("${ems.notifyUrl:https://rsj.zhanjiang.gov.cn/wxtest/ggfw/api/portal/ems/wxxcxZftz}")
    private String notifyUrl;

    @Value("${ems.serviceId:D1XB77jx2MKr}")
    private String serviceId;

    @Value("${ems.areaCode:440000}")
    private String areaCode;

    @Value("${ems.customCode:SSJSB}")
    private String customCode;

    @Value("${ems.orderRule:ZJRCZ}")
    private String orderRule;

    @Value("${ems.productCode:ZJRCZD1XB77jx2MKr}")
    private String productCode;

    @Value("${ems.postCode:POSTD1XB77jx2MKr}")
    private String postCode;

    @Value("${ems.xcxkey:2Ob828OiuwY5ljJ1KKJTgOTdrQMpx4SD}")
    private String xcxkey;

    @Value("${ems.protocolNum:PTC000000}")
    private String protocolNum;


    @Resource
    private EMSMapper emsMapper;

    @Resource
    private VRsGgfwUserMapper rsGgfwUserMapper;

    @Resource
    private RsSlxxEMSLogMapper emsLogMapper;

    @Resource
    CommBLO commBLO;

    @Resource
    private VRsWbBjListMapper vRsWbBjListMapper;

    @Resource
    VRsGgfwUserMapper vRsGgfwUserMapper;

    @Resource
    RsSlxxJglqMapper rsSlxxJglqMapper;


    @Override
    public void order() {
          List<EMSOrderDTO> list = this.emsMapper.queryNeedOrder();
            for (EMSOrderDTO dto1 : list) {
                JSONObject object1 = new JSONObject();
                JSONObject addressInfo = new JSONObject();
                try{
                object1.put("protocolNum",protocolNum);// "PTC000000" protocolNum
                object1.put("printKind", dto1.getPrintKind());
                object1.put("expressNbr", "");
                object1.put("custOrderId", dto1.getCustOrderId());
                addressInfo.put("tcustMobile", dto1.getTcustMobile());
                addressInfo.put("tcustAddress", dto1.getTcustAddress());
                object1.put("addressInfo", addressInfo);
                RsSlxxEMSLog rsSlxxEMSLog = new RsSlxxEMSLog();
                String params = EncryptionUtil.encodeContent(object1.toString(),key);
                rsSlxxEMSLog.setCs(object1.toString());
                rsSlxxEMSLog.setCjsj(getDateTime());
                rsSlxxEMSLog.setCustOrderId(dto1.getCustOrderId());
                rsSlxxEMSLog.setJklx("01");
                rsSlxxEMSLog.setUrl(xdurl);
                String result = HttpUtil.restTemplate(xdurl, params, HttpMethod.POST); //http://10.201.27.146
                if (StringUtils.isNotBlank(result)) {
                    LOG.info(result);
                    result = EncryptionUtil.decodeContent(result,key);
                    LOG.info("保存o2o返回:{}", result);
                    JSONObject jsonTemp = JSON.parseObject(result);
                    String code = jsonTemp.getString("code");
                    UpdateWrapper<SlxxEMSOrderPO> updateWrapper = new UpdateWrapper();
                    SlxxEMSOrderPO slxxEMSOrderPO = new SlxxEMSOrderPO();
                    rsSlxxEMSLog.setJg("1");
                    rsSlxxEMSLog.setRtn(result);
                    slxxEMSOrderPO.setXdsj(getDateTime());
                    slxxEMSOrderPO.setOrderStatus("1");
                    updateWrapper.eq("custOrderId",dto1.getCustOrderId());
                    
                    this.emsMapper.update(slxxEMSOrderPO,updateWrapper);
                    this.emsLogMapper.insert(rsSlxxEMSLog);
                    }
                }catch (Exception e) {
                    LOG.error("下单异常:" + e.getMessage());
                    RsSlxxEMSLog rsSlxxEMSLog = new RsSlxxEMSLog();
                    rsSlxxEMSLog.setUrl(xdurl);
                    rsSlxxEMSLog.setRtn(e.getMessage());
                    this.emsLogMapper.insert(rsSlxxEMSLog);
                    e.printStackTrace();
                }
              }
            }


    @Override
    public void initOrder(OrderDTO dto) {
        SlxxEMSOrderPO slxxOrderPO = new SlxxEMSOrderPO();
        QueryWrapper<VRsWbBjList> queryWrapper = new QueryWrapper<>();
        VRsWbBjList vRsWbBjList = this.vRsWbBjListMapper.selectOne(queryWrapper);
        String custOrderId = "ZJRCZ"+vRsWbBjList.getSlbh();
        BeanUtils.copyProperties(dto,slxxOrderPO);
        slxxOrderPO.setCustOrderId(custOrderId);
        slxxOrderPO.setCjsj(getDateTime());
        this.emsMapper.insert(slxxOrderPO);
    }

    @Override
    public AjaxResponse getWlxx(EMSORderXxDTO dto) {
        LOG.info("物流信息获取接口");
        AjaxResponse ajaxResponse = new AjaxResponse();
        QueryWrapper <SlxxEMSOrderPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("SLLSH",dto.getSllsh());
        queryWrapper.eq("orderstatus","2");
        SlxxEMSOrderPO slxxEMSOrderPO = this.emsMapper.selectOne(queryWrapper);
        JSONObject returnJson = new JSONObject();
        RsSlxxEMSLog rsSlxxEMSLog = new RsSlxxEMSLog();
        try{
            JSONObject paramJson = new JSONObject();
            if (org.apache.commons.lang.StringUtils.isNotBlank(slxxEMSOrderPO.getExpressNbr())){
                paramJson.put("expressNbr", slxxEMSOrderPO.getExpressNbr());
            }else{
                throw new AppException("邮件号不能为空");
            }
            JSONArray array = new JSONArray();
            array.add(paramJson);
            LOG.info(array.toString());
            String param = EncryptionUtil.encodeContent(array.toString(),key);
            LOG.info(param);
                rsSlxxEMSLog.setUrl(wlurl);
                String result = HttpUtil.restTemplate(wlurl+param, null, HttpMethod.POST); //http://10.201.27.146
                LOG.info(result);
                if (!StringUtils.isEmpty(result)) {
                    result = EncryptionUtil.decodeContent(result,key);
                    JSONObject resJson = JSONObject.parseObject(result);
                    if (resJson.containsKey("data")) {
                        JSONArray data = resJson.getJSONArray("data");
                        returnJson.put("map", new JSONArray());
                        if (!data.isEmpty()) {
                            if (data.getJSONObject(0).containsKey("mail_track_infos")) {
                                ajaxResponse.setMsg("查询成功");
                                ajaxResponse.setData("data", data.getJSONObject(0).getJSONArray("mail_track_infos"));
                            } else {
                                ajaxResponse.setMsg("暂无物流信息!");
                            }
                        }
                    }
                }
        }catch (Exception e){
            LOG.error("物流信息接口异常:" + e.getMessage());
            e.printStackTrace();
            rsSlxxEMSLog.setRtn(e.getMessage());
            rsSlxxEMSLog.setJg("0");
        }
        this.emsLogMapper.insert(rsSlxxEMSLog);
        return ajaxResponse;
    }


    @Override
    public void getZfZtTz(ZfzttzPO po) {
        RsSlxxEMSLog rsSlxxEMSLog = new RsSlxxEMSLog();
        rsSlxxEMSLog.setCs(po.toString());
        QueryWrapper<SlxxEMSOrderPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("custOrderId",po.getOrderId());
        SlxxEMSOrderPO slxxEMSOrderPO1 = this.emsMapper.selectOne(queryWrapper);
        this.emsLogMapper.insert(rsSlxxEMSLog);
        UpdateWrapper<SlxxEMSOrderPO> updateWrapper = new UpdateWrapper<>();
        SlxxEMSOrderPO slxxEMSOrderPO = new SlxxEMSOrderPO();
        slxxEMSOrderPO.setPaymentWay(po.getPaymentWay());
        updateWrapper.eq("custOrderId",po.getOrderId());
        this.emsMapper.update(slxxEMSOrderPO,updateWrapper);
        //写领取结果，结果领取信息已存在时，不回写
        writeLqjg(slxxEMSOrderPO1.getSllsh(),slxxEMSOrderPO1.getExpressNbr());
    }
    //写领取结果，结果领取信息已存在时，不回写
    private void writeLqjg(String sllsh,String nbr){
        LOG.info("EMS领取结果,回写，sllsh="+sllsh);
        LOG.info("EMS领取结果,回写，nbr="+nbr);
        if(org.apache.commons.lang.StringUtils.isBlank(sllsh) || org.apache.commons.lang.StringUtils.isBlank(nbr) ){
            return ;
        }
        QueryWrapper<SlxxJglqPO> queryWrapperJglq = new QueryWrapper<>();
        queryWrapperJglq.eq("sllsh",sllsh);
        SlxxJglqPO jglqPO = this.rsSlxxJglqMapper.selectOne(queryWrapperJglq);
        if (jglqPO == null){//写领取结果
            SlxxJglqPO slxxJglqPO = new SlxxJglqPO();
            slxxJglqPO.setRsslxxjglqlsh(UUID.randomUUID().toString().replace("-", ""));
            slxxJglqPO.setSllsh(sllsh);
            slxxJglqPO.setLqr("EMS");
            slxxJglqPO.setBae005(getDateTime());
            this.rsSlxxJglqMapper.insert(slxxJglqPO);
        }
    }

    @Override
    public PageResult queryWlList(SxblQueryDTO dto) {
        CurrentUser currentUser = getCurrentUser();
        String userid = currentUser.getUsername() == null ? "" : currentUser.getUsername().trim();
//        String userid = "7bc55d7e394644a7828a9875f0069cef";
        Page<WlListResultDTO> page = new Page<>(dto.getPagenum(), dto.getPagesize());

        Page<WlListResultDTO> pageResult = null;
        VRsGgfwUser user = this.vRsGgfwUserMapper.selectById(userid);
        LOG.info("我的物流列表，单位类型："+user.getFwdx());
        if(user.getFwdx().equals("2")){
            pageResult = (Page) this.vRsWbBjListMapper.getWlList(page,dto);
        }

        PageResult result = PageUtil.PageResult(pageResult);
        return result;
    }

    @Override
    public AjaxResponse queryOrderXx(EMSORderXxDTO dto) {
        AjaxResponse ajaxResponse = new AjaxResponse();
        EMSORderXxDTO resdto =  this.emsMapper.queryOrderXx(dto);
        if (org.apache.commons.lang.StringUtils.isNotBlank(resdto.getTcustprovince())) {
            resdto.setTcustaddress(resdto.getTcustprovince()+resdto.getTcustaddress());
        }
       if (org.apache.commons.lang.StringUtils.isNotBlank(resdto.getOrderStatus())) {
           if (resdto.getOrderStatus().equals("1")) {//未支付，调用支付接口
//            EMSOrderDTO emsOrderDTO = this.emsMapper.queryNeedZfSx(dto.getSllsh());//获取需要支付事项的收寄人信息
               JSONObject object1 = new JSONObject();
               object1.put("orderId", resdto.getCustOrderId());
               object1.put("itemRule",orderRule);
               object1.put("description", "湛江市人社局");
               if (org.apache.commons.lang.StringUtils.isBlank(dto.getPayway())) {
                   ajaxResponse.setErrorMsg("支付方式不能为空");
                   ajaxResponse.setAppcode("1");
                   return ajaxResponse;
               }
               object1.put("paymentWay", dto.getPayway());
               List<JSONObject> arrays = new ArrayList<>();
               arrays.add(object1);
               for (JSONObject params : arrays) {
                   try {
                       RsSlxxEMSLog rsSlxxEMSLog = new RsSlxxEMSLog();
                       rsSlxxEMSLog.setCs(object1.toString());
                       String result = HttpUtil.restTemplate(zfurl, params.toString(), HttpMethod.POST); //http://10.201.27.146
                       if (!StringUtils.isEmpty(result)) {
                           LOG.info(result);
                           rsSlxxEMSLog.setRtn(result);
                           this.emsLogMapper.insert(rsSlxxEMSLog);
                       }
                   } catch (Exception e) {
                       LOG.error("支付接口异常:" + e.getMessage());
                       e.printStackTrace();
                   }
               }
           }
       }
       if(resdto.getPostfee().length()>2){
           resdto.setPostfee(resdto.getPostfee().substring(0,2));
       }
        ajaxResponse.setData("data",resdto);
        return ajaxResponse;

    }

    @Override
    public AjaxResponse getOrderStatus(EMSORderXxDTO dto) {
        AjaxResponse ajaxResponse = new AjaxResponse();
        QueryWrapper<SlxxEMSOrderPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("SLLSH",dto.getSllsh());
        SlxxEMSOrderPO slxxEMSOrderPO = this.emsMapper.selectOne(queryWrapper);
        ajaxResponse.setData("data",slxxEMSOrderPO);
        return ajaxResponse;
    }

    @Override
    public void saveWxxcxZftz(String params) {
        String decodeStr = null;
        try {
            decodeStr = URLDecoder.decode(params,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        RsSlxxEMSLog rsSlxxEMSLog = new RsSlxxEMSLog();
        rsSlxxEMSLog.setCs(JSONObject.toJSONString(decodeStr));
        rsSlxxEMSLog.setCjsj(getDateTime());
        QueryWrapper<VRsWbBjList> wbBjListQueryWrapper = new QueryWrapper<>();
        JSONObject jsonObject = JSONObject.parseObject(decodeStr);
        String orderNo = (String)jsonObject.get("orderNo");
        Integer totalfee = (Integer)jsonObject.get("totalFee");
        String payStatus = (String)jsonObject.get("payStatus");
        String transactionId = (String)jsonObject.get("transactionId");
        String payTime = (String)jsonObject.get("payTime");
        String paymentWay = (String)jsonObject.get("paymentWay");
        String slbh = orderNo.substring(5);
       wbBjListQueryWrapper.eq("SLBH",slbh);
        VRsWbBjList vRsWbBjList = this.vRsWbBjListMapper.selectOne(wbBjListQueryWrapper);
        if (vRsWbBjList == null) {
            LOG.error("办件申请列表里没有该受理编号:{}", slbh);
            rsSlxxEMSLog.setRtn("办件申请列表里没有该受理编号:"+slbh);
            rsSlxxEMSLog.setJg("0");
        } else {
            QueryWrapper<SlxxEMSOrderPO> queryWrapper = new QueryWrapper();
            queryWrapper.eq("SLLSH", vRsWbBjList.getSllsh());
            SlxxEMSOrderPO slxxEMSOrderPO1 = this.emsMapper.selectOne(queryWrapper);
            rsSlxxEMSLog.setCustOrderId(slxxEMSOrderPO1.getCustOrderId());
            if (!(slxxEMSOrderPO1.getPostFee().equals(String.valueOf(totalfee)))){
                rsSlxxEMSLog.setRtn("支付金额与订单金额不一致");
                LOG.error("支付金额与订单金额不一致");
            }
            //更新订单表
            UpdateWrapper<SlxxEMSOrderPO> updateWrapper = new UpdateWrapper<>();
            SlxxEMSOrderPO slxxEMSOrderPO = new SlxxEMSOrderPO();
            rsSlxxEMSLog.setCustOrderId(orderNo);
            if (payStatus.equals("2")) {
                slxxEMSOrderPO.setPayTime(payTime);
            }
            this.emsMapper.update(slxxEMSOrderPO, updateWrapper);
            //写领取结果，结果领取信息已存在时，不回写
            writeLqjg(slxxEMSOrderPO1.getSllsh(),slxxEMSOrderPO1.getExpressNbr());
        }
        this.emsLogMapper.insert(rsSlxxEMSLog);
    }

    @Override
    public AjaxResponse doUnifiedOrder(XcxPayDTO dto) {
        AjaxResponse ajaxResponse = new AjaxResponse();
        if (org.apache.commons.lang.StringUtils.isBlank(dto.getOpenId())){
            LOG.error("openId为空");
            ajaxResponse.setErrorMsg("系统异常");
            ajaxResponse.setAppcode("1");
            return ajaxResponse;
        }
        //生成的随机字符串
        String nonce_str = WXPayUtil.generateNonceStr();
        //统一下单接口参数
        HashMap<String, Object> data = new HashMap<String, Object>();
        data.put("customCode",customCode);
        data.put("serviceId",serviceId);
        data.put("returnUrl","https://www.baidu.com");
        data.put("paymentWay", "WECHAT");
        data.put("openid", dto.getOpenId());
        String s = null;
        try {
            s = WXPayUtil.generateSignature(data,xcxkey);
           LOG.info("加密后的参数"+s);
        } catch (Exception e) {
            LOG.error("加密异常："+e.getMessage());
        }
        data.put("sign",s);
        LOG.info("小程序下单参数:{}",JSON.toJSONString(data));
        RsSlxxEMSLog rsSlxxEMSLog = new RsSlxxEMSLog();
        rsSlxxEMSLog.setCs(JSON.toJSONString(data));
        rsSlxxEMSLog.setUrl(xcxzfurl);
        try {
            String result = HttpUtil.restTemplate(xcxzfurl, JSON.toJSONString(data), HttpMethod.POST);
           LOG.info("支付下单返回参数"+result);
            JSONObject jsonObject = JSON.parseObject(result);
            ajaxResponse.setData("data", jsonObject.getJSONObject("data"));
            ajaxResponse.setMsg(jsonObject.getString("msg"));
            rsSlxxEMSLog.setJg("1");
            rsSlxxEMSLog.setRtn(result);
        } catch (Exception e) {
            LOG.error("小程序支付接口异常:{}",e.getMessage());
            rsSlxxEMSLog.setJg("0");
            rsSlxxEMSLog.setRtn(e.getMessage());
            ajaxResponse.setAppcode("1");
            ajaxResponse.setMsg(e.getMessage());
        }
        this.emsLogMapper.insert(rsSlxxEMSLog);
        return ajaxResponse;
    }


    private String getDateTime() {
        return this.commBLO.getCurrenttime();//获取当前时间
    }

    private int getLength(String str) {
        int length = 0;
        if (org.apache.commons.lang.StringUtils.isNotBlank(str)) {
            try {
                length = str.trim().getBytes("GBK").length;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return length;
    }
}
