package com.miaxis.app.controller.film;


import com.alibaba.fastjson.JSONObject;
import com.miaxis.common.config.WxpayConfig;
import com.miaxis.common.constant.Constants;
import com.miaxis.common.enums.OrderStatusEnum;
import com.miaxis.common.exception.CustomException;
import com.miaxis.common.utils.SecurityUtils;
import com.miaxis.feign.dto.WxSend;
import com.miaxis.feign.service.IWxSendService;
import com.miaxis.wx.domain.WxOrder;
import com.miaxis.wx.dto.FilmWxOrderJsonData;
import com.miaxis.wx.dto.WxOrderNotifyDTO;
import com.miaxis.wx.service.IRefundRecordService;
import com.miaxis.wx.service.IWxOrderService;
import com.miaxis.wx.service.IWxXcxMessageService;
import com.wechat.pay.contrib.apache.httpclient.auth.AutoUpdateCertificatesVerifier;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

import java.text.SimpleDateFormat;
import java.util.Date;

import static com.miaxis.common.utils.OrderCodeFactory.getOrderCode;

@RestController
@RequiredArgsConstructor
@RequestMapping(Constants.OPEN_PREFIX+"/film/notify")
@Api(tags = {"【小程序-电影回调】"})
@Slf4j
public class FilmNotifyController {


    @Autowired
    private WxpayConfig wxpayConfig;


    @Autowired
    private IWxOrderService wxOrderService;

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Autowired
    private  IRefundRecordService  refundRecordService;

    @Autowired
    IWxXcxMessageService wxXcxMessageService;

    @Resource
    private IWxSendService wxSendService;



    /**
     * 电影回调接口
     */
    @PostMapping(value = "/filmOrder")
    @ApiOperation("电影订单回调")
    public FilmNotifyReturnDTO wxOrderNotify(WxOrderNotifyDTO wxOrderNotifyDTO ,String sign, String appKey) {
        log.info("电影回调订单:"+wxOrderNotifyDTO.getThirdOrderId()+",入参:"+JSONObject.toJSONString(wxOrderNotifyDTO));
        WxOrder wxOrder = wxOrderService.getByOutTradeNo(wxOrderNotifyDTO.getThirdOrderId());
       //todo 检查sign
        String orderDataJson = wxOrder.getOrderDataJson();
        FilmWxOrderJsonData wxOrderJsonData = JSONObject.parseObject(orderDataJson, FilmWxOrderJsonData.class);
        WxOrderNotifyDTO dbWxOrderNotifyDTO= wxOrderJsonData.getWxOrderNotifyDTO();
        if (dbWxOrderNotifyDTO == null){
            dbWxOrderNotifyDTO = wxOrderNotifyDTO;
        }else{
            dbWxOrderNotifyDTO.setEventName(wxOrderNotifyDTO.getEventName());
            if (wxOrderNotifyDTO.getOrderPrice()!= null)
                dbWxOrderNotifyDTO.setOrderPrice(wxOrderNotifyDTO.getOrderPrice());
            if (wxOrderNotifyDTO.getCloseCause()!= null)
                dbWxOrderNotifyDTO.setCloseCause(wxOrderNotifyDTO.getCloseCause());
            if (wxOrderNotifyDTO.getRealSeat()!= null)
                dbWxOrderNotifyDTO.setRealSeat(wxOrderNotifyDTO.getRealSeat());
            if (wxOrderNotifyDTO.getTicketCode()!= null)
                dbWxOrderNotifyDTO.setTicketCode(wxOrderNotifyDTO.getTicketCode());
            if (wxOrderNotifyDTO.getTicketImage()!= null)
                dbWxOrderNotifyDTO.setTicketImage(wxOrderNotifyDTO.getTicketImage());
        }
        wxOrderJsonData.setWxOrderNotifyDTO(dbWxOrderNotifyDTO);
        wxOrder.setOrderDataJson(JSONObject.toJSONString(wxOrderJsonData));
        //UserInfo student = SecurityUtils.getLoginUser().getStudent();
        //如果订单状态成功，则调用小程序推送服务
        if ("TICKET_SUCCESS".equals(wxOrderNotifyDTO.getEventName())){
            wxOrder.setOrderStatus(OrderStatusEnum.SUCCESS.getCode());
            threadPoolTaskExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        sendXcxMessage(wxOrder);
                    } catch (Exception e) {
                        e.printStackTrace();
                        throw new CustomException("订单:"+wxOrder.getOutTradeNo()+"推送消息失败");
                    }
                }
            });

        }



        //如果回调回来的订单关闭，则调用退款
        if ("ORDER_CLOSE".equals(wxOrderNotifyDTO.getEventName())){
            String refundCode = getOrderCode(null);
            wxOrder.setOrderStatus(OrderStatusEnum.FAILD.getCode());
            wxOrder.setOutRefundNo(refundCode);
            threadPoolTaskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                    try {
                        refundRecordService.refund(wxOrder,refundCode,"电影购票失败,原因:"+wxOrderNotifyDTO.getCloseCause());
                    } catch (Exception e) {
                        throw new CustomException("订单:"+wxOrder.getOutTradeNo()+"退款失败");
                    }
                }
            });

        }

        wxOrderService.updateById(wxOrder);

        FilmNotifyReturnDTO filmNotifyReturnDTO = new FilmNotifyReturnDTO();
        filmNotifyReturnDTO.setCode("200");
        filmNotifyReturnDTO.setMessage("请求成功");
        filmNotifyReturnDTO.setSuccess(true);
        return filmNotifyReturnDTO;
    }

    private void sendXcxMessage(WxOrder wxOrder) {
        String xcxMessageToken = wxXcxMessageService.getXcxMessageToken();
        WxSend wxSend = new WxSend();
        //wxSend.setAccess_token(xcxMessageToken);
        String openid = wxOrder.getOpenid();
        wxSend.setTouser(openid);
        wxSend.setTemplate_id("Q4-tQrDwtzFUSLt_PR2kuTxBJ3d62V4Yp2iwx4PAcIE");
        wxSend.setPage("/pages/cinema/orderdes?outTradeNo="+wxOrder.getOutTradeNo());

        JSONObject jsonObject = new JSONObject();
        JSONObject jsonObject1 = new JSONObject();
        JSONObject jsonObject2 = new JSONObject();
        JSONObject jsonObject3 = new JSONObject();
        JSONObject jsonObject4 = new JSONObject();
        JSONObject jsonObject5 = new JSONObject();

        jsonObject1.put("value",wxOrder.getOutTradeNo());
        jsonObject2.put("value","￥"+wxOrder.getTotal()/100.0);
        jsonObject3.put("value",new SimpleDateFormat("yyyy年MM月dd日 HH:mm").format(new Date()));
        jsonObject4.put("value","电影票");
        jsonObject5.put("value","点击查看取票二维码");

        jsonObject.put("character_string1",jsonObject1);
        jsonObject.put("amount3",jsonObject2);
        jsonObject.put("date4",jsonObject3);
        jsonObject.put("thing6",jsonObject4);
        jsonObject.put("thing5",jsonObject5);


        wxSend.setData(jsonObject);

        log.info("发送推送请求数据:"+jsonObject);
//        wxSend.setMiniprogram_state("developer");
        wxSend.setLang("zh_CN");
        String result = wxSendService.sendMessage(xcxMessageToken,wxSend);
        log.info("小程序推送请求数据返回值:"+result);
    }


    @Data
    public class FilmNotifyReturnDTO {
        String code;
        String message;
        Boolean success;
    }

    public static void main(String[] args) {
        System.out.println(3680/100.0);
    }

}
