package com.zjrs.ggfw.portal.controller;

import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jakarta.annotation.Resource;
import org.apache.commons.lang.StringUtils;
import org.mohrss.leaf.core.framework.persistens.PageResult;
import org.mohrss.leaf.core.framework.web.controller.AjaxResponse;
import com.zjrs.ggfw.portal.bpo.EMSBPO;
import com.zjrs.ggfw.portal.dto.*;
import com.zjrs.ggfw.portal.po.ZfzttzPO;
import com.zjrs.ggfw.portal.utils.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Api("EMS相关接口")
@RestController
@RequestMapping("/api/portal/ems")
public class EMSController {

    private static final Logger LOG = LoggerFactory.getLogger(EMSController.class);

    @Value("${wxxcx.appId:wxd00f584ae2e775d6}")
    private String appId;

    @Resource
    private EMSBPO emsbpo;

    @ApiOperation(value = "保存订单信息", notes = "保存订单信息")
    @PostMapping("/saveEmsOrder")
    public AjaxResponse initOrder(@RequestBody @Validated OrderDTO dto, BindingResult bindingResult) {
        AjaxResponse ajaxResponse = new AjaxResponse();
        //校验入参
        if(bindingResult.hasErrors()) {
            ajaxResponse.setAppcode("1");
            ajaxResponse.setErrorMsg(bindingResult.getFieldError().getDefaultMessage());
            return ajaxResponse;
        }
        try {
            emsbpo.initOrder(dto);
        } catch (Exception e) {
            LOG.error(e.toString());
            ajaxResponse.setAppcode("1");
            ajaxResponse.setErrorMsg("系统异常");
        }
        return ajaxResponse;
    }

    @ApiOperation(value = "物流查询接口", notes = "物流查询接口")
    @PostMapping("/getWlxx")
    public AjaxResponse wlcx(@RequestBody @Validated EMSORderXxDTO dto, BindingResult bindingResult) {
        AjaxResponse ajaxResponse = new AjaxResponse();
            //校验入参
            if(bindingResult.hasErrors()) {
                ajaxResponse.setAppcode("1");
                ajaxResponse.setErrorMsg(bindingResult.getFieldError().getDefaultMessage());
                return ajaxResponse;
            }
        try {
             ajaxResponse = emsbpo.getWlxx(dto);
        } catch (Exception e) {
            LOG.error(e.getMessage());
            ajaxResponse.setErrorMsg(e.getMessage());
            ajaxResponse.setAppcode("1");
        }
            return ajaxResponse;
    }

    @ApiOperation(value = "EMS回调通知接口", notes = "EMS回调通知接口")
    @PostMapping("/getzfzttz")
    public AjaxResponse getzftz(@RequestBody ZfzttzPO po) {
        LOG.info(po.toString());
        AjaxResponse ajaxResponse = new AjaxResponse();
        //校验入参
        try {
           this.emsbpo.getZfZtTz(po);
        } catch (Exception e) {
            LOG.error(e.getMessage());
        }
        return ajaxResponse;
    }

    @ApiOperation(value = "查询物流列表接口", notes = "查询物流列表接口")
    @PostMapping("/queryWlList")
    public AjaxResponse queryWlList(@RequestBody @Validated SxblQueryDTO dto, BindingResult bindingResult) {
        AjaxResponse ajaxResponse = new AjaxResponse();
        //校验入参
        if(bindingResult.hasErrors()) {
            ajaxResponse.setAppcode("1");
            ajaxResponse.setErrorMsg(bindingResult.getFieldError().getDefaultMessage());
            return ajaxResponse;
        }
        try {
            PageResult pageResult = emsbpo.queryWlList(dto);
            ajaxResponse.setData("data",pageResult);
            ajaxResponse.setData("pagesize",dto.getPagesize());
            ajaxResponse.setData("pagenum",dto.getPagenum());
        } catch (Exception e) {
            LOG.error(e.getMessage());
        }
        return ajaxResponse;
    }


    @ApiOperation(value = "查询订单信息接口", notes = "查询订单信息接口")
    @PostMapping("/queryOrderXx")
    public AjaxResponse queryOrderXx(@RequestBody @Validated EMSORderXxDTO dto, BindingResult bindingResult) {
        AjaxResponse ajaxResponse = new AjaxResponse();
        //校验入参
        if(bindingResult.hasErrors()) {
            ajaxResponse.setAppcode("1");
            ajaxResponse.setErrorMsg(bindingResult.getFieldError().getDefaultMessage());
            return ajaxResponse;
        }
        try {
            ajaxResponse  = emsbpo.queryOrderXx(dto);
        } catch (Exception e) {
            LOG.error(e.getMessage());
        }
        return ajaxResponse;
    }

    @ApiOperation(value = "查询订单状态", notes = "查询订单状态")
    @PostMapping("/getOrderStatus")
    public AjaxResponse getOrderStatus(@RequestBody @Validated EMSORderXxDTO dto, BindingResult bindingResult) {
        AjaxResponse ajaxResponse = new AjaxResponse();
        //校验入参
        if(bindingResult.hasErrors()) {
            ajaxResponse.setAppcode("1");
            ajaxResponse.setErrorMsg(bindingResult.getFieldError().getDefaultMessage());
            return ajaxResponse;
        }
        try {
            ajaxResponse =  emsbpo.getOrderStatus(dto);
        } catch (Exception e) {
            LOG.error(e.toString());
            ajaxResponse.setAppcode("1");
            ajaxResponse.setErrorMsg("系统异常");
        }
        return ajaxResponse;
    }

    @ApiOperation(value = "获取微信小程序用户openId", notes = "获取微信小程序用户openId")
    @PostMapping(value = "/getOpenId")
    public AjaxResponse getOpenId(@RequestBody XcxPayDTO xcxPayDTO) {
        AjaxResponse ajaxResponse = new AjaxResponse();
        if (StringUtils.isBlank(xcxPayDTO.getCode())){
            ajaxResponse.setAppcode("1");
            ajaxResponse.setErrorMsg("系统异常");
            return ajaxResponse;
        }
        Map map = new HashMap();
        try {
            String s = HttpUtil.restTemplate("https://api.weixin.qq.com/sns/jscode2session?appid=" +appId+ "&secret=3f07db94b57983e7b32952a1854d88aa" + "&js_code=" + xcxPayDTO.getCode() + "&grant_type=authorization_code", null, HttpMethod.POST);
            JSONObject resJson = JSONObject.parseObject(s);
            System.out.println("换取OPenID"+s);
            map.put("openId", resJson.getString("openid"));
            ajaxResponse.setData("data",map);
        }catch (Exception e){
            ajaxResponse.setAppcode("1");
            ajaxResponse.setMsg(e.getMessage());
            LOG.error(e.getMessage());
            LOG.error("获取openId出错");
        }
        return ajaxResponse;
    }

    @ApiOperation(value = "小程序下单并支付", notes = "小程序下单并支付")
    @PostMapping("/doUnifiedOrder")
    public AjaxResponse doUnifiedOrder(@RequestBody XcxPayDTO dto) {
        AjaxResponse ajaxResponse = new AjaxResponse();
        try {
            LOG.info("小程序下单入参:{}",JSONObject.toJSONString(dto));
            ajaxResponse =  emsbpo.doUnifiedOrder(dto);
        } catch (Exception e) {
            LOG.error(e.getMessage());
            ajaxResponse.setAppcode("1");
            ajaxResponse.setErrorMsg("系统异常");
        }
        return ajaxResponse;
    }



    @ApiOperation(value = "小程序支付通知接口", notes = "小程序支付通知接口")
    @PostMapping("/wxxcxZftz")
    public String wxxcxZftz(HttpServletRequest request) {
        String data;
        try {
            data = IoUtil.read(request.getInputStream(), StandardCharsets.UTF_8.name());
            LOG.info("小程序支付回调参数"+data);
           emsbpo.saveWxxcxZftz(data);
           return "SUCCESS";
        } catch (Exception e) {
            LOG.error(e.getMessage());
            e.printStackTrace();
            return "FAIL";
        }
    }

}
