package com.yn.bftl.thirdparty.common.service.impl;


import com.yn.bftl.common.modules.order.entity.*;
import com.yn.bftl.common.modules.order.enums.PayStatus;
import com.yn.bftl.thirdparty.common.repository.OrderRepository;
import com.yn.bftl.thirdparty.common.repository.RefundRepository;
import com.yn.bftl.thirdparty.common.repository.ReturnRepository;
import com.yn.bftl.thirdparty.common.repository.ShippingRepository;
import com.yn.bftl.thirdparty.common.service.PushMessageCustomerService;
import com.yn.bftl.thirdparty.common.util.ChatCodeUtil;
import com.yn.bftl.thirdparty.common.vo.TemplateData;
import com.yn.bftl.thirdparty.common.vo.WxMssVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

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

/**
 * @Author: mingwei
 * @Date:2021/12/2
 * @Description:
 */
@Service
@Slf4j
public class PushMessageCustomerServiceImpl implements PushMessageCustomerService {

//    @Value("${wxCode.code.requestWeiXinUrl}")
    private  String requestWeiXinUrl;
//    @Value("${wxCode.code.wxPushMessageUrl}")
    private  String wxPushMessageUrl;


//    @Value("${wxCode.templateId.push}")
    private  String push;  //待付款提醒
//    @Value("${wxCode.templateId.deliverPush}")
    private  String deliverPush;//订单发货提醒
//    @Value("${wxCode.templateId.refundPush}")
    private  String refundPush;//订单退款提醒
//    @Value("${wxCode.templateId.toDeliverPush}")
    private  String toDeliverPush;//订单待发货消息推送模板Id
//    @Value("${wxCode.templateId.pickPush}")
    private  String pickPush;//订单待提货消息推送模板Id
//    @Value("${wxCode.templateId.returnPush}")
    private  String returnPush;//商品回寄消息推送模板Id
//    @Value("${wxCode.templateId.evaluatePush}")
    private  String evaluatePush;//订单评价消息推送模板Id

    @Resource
    ReturnRepository returnRepository;
    @Resource
    ChatCodeUtil chatCodeUtil;

    @Resource
    RefundRepository refundRepository;
    @Resource
    OrderRepository orderRepository;
    @Resource
    ShippingRepository shippingAdminRepository;


    //订单待支付通提醒
    @Transactional
    @Override
    public String push(Long orderId) {

        Order order = orderRepository.findById(orderId).orElse(null);
        String openId=null;
        //获取openId
        openId =   order.getCustomer().getOpenId();
        String s = requestWeiXinUrl;
        String accessToken  = null;
        String s1 =null;
        try {
            //获取token
            accessToken =  chatCodeUtil.postToken(s);
            s1=  pushMessage(accessToken,openId,orderId);
        } catch (Exception e) {
            e.printStackTrace();
        }

//        https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token
        return s1;
    }

    //订单待发货提醒
    @Transactional
    @Override
    public String toDeliverPush(Long orderId) {
        Order order = orderRepository.findById(orderId).orElse(null);
        String openId=null;
        //获取openId
        openId = order.getCustomer().getOpenId();
        String s = requestWeiXinUrl;
        String accessToken  = null;
        String s1 =null;
        try {
            //获取token
            accessToken =  chatCodeUtil.postToken(s);
            s1=  toDeliverPushMessage(accessToken,openId,orderId);
        } catch (Exception e) {
            e.printStackTrace();
        }

//        https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token
        return s1;

    }

    //订单待提货
    @Transactional
    @Override
    public String pickPush(Long orderId) {
        Order order = orderRepository.findById(orderId).orElse(null);

        String openId=null;
        //获取openId
        openId =   order.getCustomer().getOpenId();
        String s = requestWeiXinUrl;
        String accessToken  = null;
        String s1 =null;
        try {
            //获取token
            accessToken =  chatCodeUtil.postToken(s);
            s1=  pickPushMessage(accessToken,openId,orderId);
        } catch (Exception e) {
            e.printStackTrace();
        }

//        https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token
        return s1;
    }
    //订单发货消息推送
    @Transactional
    @Override
    public String deliverPush(Long shippingId) {
        Shipping shipping = shippingAdminRepository.findById(shippingId).orElse(null);
        Order order = shipping.getOrders();
        String openId=null;
        //获取openId
        openId =   order.getCustomer().getOpenId();
        String s = requestWeiXinUrl;
        String accessToken  = null;
        String s1 =null;
        try {
            //获取token
            accessToken =  chatCodeUtil.postToken(s);
            s1=  deliverPushMessage(accessToken,openId,shippingId);
        } catch (Exception e) {
            e.printStackTrace();
        }

//        https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token
        return s1;

    }
    //订单退款消息推送
    @Transactional
    @Override
    public String refundPush(Long refundId) {

        Refund refund = refundRepository.findById(refundId).orElse(null);
        Order order= refund.getOrders();
        String openId=null;
        //获取openId
        openId =   order.getCustomer().getOpenId();
        String s = requestWeiXinUrl;
        String accessToken  = null;
        String s1 =null;
        try {
            //获取token
            accessToken =  chatCodeUtil.postToken(s);
            s1=  refundPushMessage(accessToken,openId,refundId);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token
        return s1;
    }
    //商品回寄消息推送
    @Transactional
    @Override
    public String returnPush(Long returnId) {
        Return aReturn = returnRepository.findById(returnId).orElse(null);
        Order order = aReturn.getOrders();
        String openId=null;
        //获取openId
        openId =   order.getCustomer().getOpenId();
        String s = requestWeiXinUrl;
        String accessToken  = null;
        String s1 =null;
        try {
            //获取token
            accessToken =  chatCodeUtil.postToken(s);
            s1=  returnPushMessage(accessToken,openId,returnId);
        } catch (Exception e) {
            e.printStackTrace();
        }

//        https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token
        return s1;
    }
    @Transactional
    @Override
    public String evaluatePush(Long orderId) {
        Order order = orderRepository.findById(orderId).orElse(null);
        String openId=null;
        //获取openId
        openId =   order.getCustomer().getOpenId();
        String s = requestWeiXinUrl;
        String accessToken  = null;
        String s1 =null;
        try {
            //获取token
            accessToken =  chatCodeUtil.postToken(s);
            s1=  evaluatePushPushMessage(accessToken,openId,orderId);
        } catch (Exception e) {
            e.printStackTrace();
        }

//        https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token
        return s1;
    }

    //
    @Transactional
    public String pushMessage(String accessToken,String openId,Long orderId){
        Order order = orderRepository.findById(orderId).orElse(null);
        order.getSn();//订单号
        order.getCreatedOn();//下单时间
        order.getAmount();//订单总额

        RestTemplate restTemplate = new RestTemplate();
        String url =  wxPushMessageUrl + accessToken;
        String page1 = "pages/myPage/myOrder/myOrderDetaile/myOrderDetaile?id=";
        //拼接推送模板
        WxMssVo wxMssVo = new WxMssVo();
        wxMssVo.setTouser(openId);//用户的openid（要发送给那个用户，通常这里应该动态传进来的）
        wxMssVo.setTemplate_id(push);//订阅消息模板id
        wxMssVo.setPage(page1+order.getId().toString());
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String localTime = df.format(order.getCreatedOn());
        Map<String, TemplateData>  m= new HashMap<>(5);
        m.put("character_string3",new TemplateData( order.getSn()));
        m.put("time6",new TemplateData(localTime));
        m.put("amount2",new TemplateData( order.getAmount().toString()));
        m.put("thing7",new TemplateData("5分钟"));
        m.put("thing5",new TemplateData("您有张订单还未支付！"));
        wxMssVo.setData(m);
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(url,wxMssVo,String.class);

        return stringResponseEntity.getBody();
    }
    @Transactional
    public String toDeliverPushMessage(String accessToken,String openId,Long orderId){
        Order order = orderRepository.findById(orderId).orElse(null);
//        order.getSn();//订单号
//        order.getPayDate();//支付时间
//        order.getPaymethod();//支付方式
//        order.getPayAmount();//支付金额
        log.info("订单号"+order.getSn());

        RestTemplate restTemplate = new RestTemplate();
        String url =  wxPushMessageUrl + accessToken;
        //拼接推送模板
        WxMssVo wxMssVo = new WxMssVo();
        wxMssVo.setTouser(openId);//用户的openid（要发送给那个用户，通常这里应该动态传进来的）
        wxMssVo.setTemplate_id(toDeliverPush);//订阅消息模板id
        String page1 = "pages/myPage/myOrder/myOrderDetaile/myOrderDetaile?id=";
//        wxMssVo.setPage("pages/index/index");
        wxMssVo.setPage(page1+order.getId().toString());
        Map<String, TemplateData>  m= new HashMap<>(5);
        String sn = "";
        if (order.getSn()!=null){
            sn=order.getSn();
        }
        m.put("character_string1",new TemplateData(sn));
        DateTimeFormatter df=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String localTime = "0";
       if (CollectionUtils.isNotEmpty(order.getReceipt())){
           Receipt receipt=    order.getReceipt().stream().filter(e->e.getPayStatus().equals(PayStatus.SUCC)).findFirst().orElse(null);
           if (receipt.getPayTime()!=null){
            localTime= df.format(receipt.getPayTime());
           }
       }
        log.info("支付时间"+localTime);
       String name = "0";
       if (order.getPaymethod()!=null){
           if (order.getPaymethod().getName()!=null){
               name =order.getPaymethod().getName();
           }
       }
        log.info("支付方式"+name);
       String payAmount = "0";
       if (order.getPayAmount()!=null){
           payAmount =order.getPayAmount().toString();
       }
        log.info("支付金额"+payAmount);
       m.put("time2",new TemplateData(localTime));
        m.put("phrase3",new TemplateData(name));
        m.put("amount4",new TemplateData(payAmount));
        m.put("thing5",new TemplateData("订单已支付成功"));
        wxMssVo.setData(m);
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(url,wxMssVo,String.class);
        log.info("待收货"+stringResponseEntity.getBody());
        return stringResponseEntity.getBody();
    }
    @Transactional
    public String pickPushMessage(String accessToken,String openId,Long orderId){
        Order order = orderRepository.findById(orderId).orElse(null);
        order.getSn();//订单号
        order.getSellerCompany().getName();//提货门店

        RestTemplate restTemplate = new RestTemplate();
        String url =  wxPushMessageUrl + accessToken;
        //拼接推送模板
        WxMssVo wxMssVo = new WxMssVo();
        wxMssVo.setTouser(openId);//用户的openid（要发送给那个用户，通常这里应该动态传进来的）
        wxMssVo.setTemplate_id(pickPush);//订阅消息模板id
        String page1 = "pages/myPage/myOrder/myOrderDetaile/myOrderDetaile?id=";
        wxMssVo.setPage(page1+order.getId().toString());
//        wxMssVo.setPage("pages/index/index");
        Map<String, TemplateData>  m= new HashMap<>(3);
        m.put("character_string1",new TemplateData(order.getSn()));
        m.put("thing2",new TemplateData(order.getSellerCompany().getName()));
        m.put("thing3",new TemplateData("广东省珠海市香洲区大洲科技园A区1207"));
        m.put("time4",new TemplateData("9:00~21:00"));
        m.put("character_string5",new TemplateData(order.getPickUpCode()));
        wxMssVo.setData(m);
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(url,wxMssVo,String.class);

        return stringResponseEntity.getBody();
    }
    @Transactional
    public String deliverPushMessage(String accessToken,String openId,Long shippingId){
//        Order order = orderRepository.findById(orderId).orElse(null);
//        order.getSn();//订单号
//        order.getSellerCompany().getName();//提货门店
        Shipping shipping = shippingAdminRepository.findById(shippingId).orElse(null);
//        shipping.getOrders().getSn();//订单号
//        shipping.getShippingTime();//发货时间
//        shipping.getDeliveryCorp();//物流公司
//        shipping.getDeliverySn();//物流单号
        RestTemplate restTemplate = new RestTemplate();
        String url =  wxPushMessageUrl + accessToken;
        //拼接推送模板
        WxMssVo wxMssVo = new WxMssVo();
        wxMssVo.setTouser(openId);//用户的openid（要发送给那个用户，通常这里应该动态传进来的）
        wxMssVo.setTemplate_id(deliverPush);//订阅消息模板id
//        wxMssVo.setPage("pages/index/index");
        Map<String,TemplateData> m= new HashMap<>(6);
        String sn = "";
        if (shipping.getOrders()!=null){
            if (shipping.getOrders().getSn()!=null){
                sn =shipping.getOrders().getSn();
            }
        }
        String localTime ="";
        m.put("character_string10",new TemplateData( sn));
        DateTimeFormatter df=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        if (shipping.getShippingTime()!=null){
             localTime=df.format(shipping.getShippingTime());
        }
        m.put("date2",new TemplateData(localTime));
        String deliveryCorp="";
        if (shipping.getDeliveryCorp()!=null){
            deliveryCorp=shipping.getDeliveryCorp();
        }
        m.put("name3",new TemplateData(deliveryCorp));
        String deliverySn ="";
        if (shipping.getDeliverySn()!=null){
            deliverySn =shipping.getDeliverySn();
        }
        m.put("character_string4",new TemplateData(deliverySn));
        wxMssVo.setData(m);
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(url,wxMssVo,String.class);
        log.info("发货"+stringResponseEntity.getBody());
        return stringResponseEntity.getBody();
    }
    @Transactional
    public String returnPushMessage(String accessToken,String openId,Long returnId){
//        Order order = orderRepository.findById(orderId).orElse(null);
//        order.getSn();//订单号
//        order.getSellerCompany().getName();//提货门店
        Return refund =returnRepository.findById(returnId).orElse(null);
//        refund.getOrders().getSn();
//        refund.getOrders().getSellerCompany().getName();
//        refund.getOrders().getSellerCompany().getOfficeAddress();
        DateTimeFormatter df=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String localTime ="";
        if (refund.getCreatedOn()!=null){

             localTime=df.format( refund.getCreatedOn());
        }
        RestTemplate restTemplate = new RestTemplate();
        String url =  wxPushMessageUrl + accessToken;
        //拼接推送模板
        WxMssVo wxMssVo = new WxMssVo();
        wxMssVo.setTouser(openId);//用户的openid（要发送给那个用户，通常这里应该动态传进来的）
        wxMssVo.setTemplate_id(returnPush);//订阅消息模板id
//        wxMssVo.setPage("pages/index/index");
        Map<String,TemplateData>  m= new HashMap<>(5);
        String sn ="";
        if (refund.getOrders()!=null){
            if (refund.getOrders().getSn()!=null){
                sn = refund.getOrders().getSn();
            }
        }
        m.put("character_string1",new TemplateData( sn));
        m.put("time2",new TemplateData(localTime));
        String officeAddress ="";
        if (refund.getOrders()!=null){
            if (refund.getOrders().getSellerCompany()!=null){
                if (refund.getOrders().getSellerCompany().getOfficeAddress()!=null){
                    officeAddress =refund.getOrders().getSellerCompany().getOfficeAddress();
                }
            }

        }
        m.put("thing3",new TemplateData( officeAddress));
        String name ="";
        String phone ="";
        if (refund.getOrders()!=null){
            if (refund.getOrders().getSellerCompany()!=null){
                if (refund.getOrders().getSellerCompany().getName()!=null){
                    name =refund.getOrders().getSellerCompany().getName();
                }
                if (refund.getOrders().getSellerCompany().getPhone()!=null) {
                    phone = refund.getOrders().getSellerCompany().getPhone();
                }
            }
        }
        m.put("thing4",new TemplateData(name));
        m.put("phone_number5",new TemplateData(phone));
        wxMssVo.setData(m);
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(url,wxMssVo,String.class);
        log.info("回寄"+stringResponseEntity.getBody());
        return stringResponseEntity.getBody();
    }
    @Transactional
    public String refundPushMessage(String accessToken,String openId,Long refundId){
//        Order order = orderRepository.findById(orderId).orElse(null);
//        order.getSn();//订单号
//        order.getSellerCompany().getName();//提货门店
        Refund  refund = refundRepository.findById(refundId).orElse(null);
        refund.getOrders().getSn();//订单号
        refund.getAmount();//退款金额
        refund.getRefundTime();//退款时间

        RestTemplate restTemplate = new RestTemplate();
        String url =  wxPushMessageUrl + accessToken;
        //拼接推送模板
        WxMssVo wxMssVo = new WxMssVo();
        wxMssVo.setTouser(openId);//用户的openid（要发送给那个用户，通常这里应该动态传进来的）
        wxMssVo.setTemplate_id(refundPush);//订阅消息模板id
//        wxMssVo.setPage("pages/index/index");
        DateTimeFormatter df=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String localTime=df.format(refund.getRefundTime());
        Map<String, TemplateData>  m= new HashMap<>(3);
        m.put("character_string1",new TemplateData(refund.getOrders().getSn()));
        m.put("time9",new TemplateData(localTime));
        m.put("amount5",new TemplateData(refund.getAmount().toString()));
        m.put("thing10",new TemplateData("亲，您的退款交易已成功"));
        wxMssVo.setData(m);
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(url,wxMssVo,String.class);

        return stringResponseEntity.getBody();
    }
    @Transactional
    public String evaluatePushPushMessage(String accessToken,String openId,Long orderId){
//        Order order = orderRepository.findById(orderId).orElse(null);
//        order.getSn();//订单号
//        order.getSellerCompany().getName();//提货门店
        Order  order = orderRepository.findById(orderId).orElse(null);
        order.getSn();//订单号
        OrderItem orderItem= order.getOrderItems().stream().findFirst().orElse(null);//商品名称
        orderItem.getGoodsName();//商品名称
        RestTemplate restTemplate = new RestTemplate();
        String url =  wxPushMessageUrl + accessToken;
        String page1 = "pages/myPage/myOrder/myOrderDetaile/myOrderDetaile?id=";
        //拼接推送模板
        WxMssVo wxMssVo = new WxMssVo();
        wxMssVo.setTouser(openId);//用户的openid（要发送给那个用户，通常这里应该动态传进来的）
        wxMssVo.setTemplate_id(evaluatePush);//订阅消息模板id
        wxMssVo.setPage(page1+order.getId().toString());
        Map<String, TemplateData>  m= new HashMap<>(3);
        m.put("character_string3",new TemplateData(order.getSn()));
            m.put("thing4",new TemplateData(orderItem.getGoodsName()));
        wxMssVo.setData(m);
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(url,wxMssVo,String.class);
        return stringResponseEntity.getBody();
    }



}
