package com.ssm.controller;


import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.ssm.manage.response.GenericResponse;
import com.ssm.manage.response.PageResponse;
import com.ssm.manage.utils.SessionHelp;
import com.ssm.core.utils.FtpUtils;
import com.ssm.manage.dto.PlatformCouponDto;
import com.ssm.manage.dto.Token;
import com.ssm.manage.entity.BaseStores;
import com.ssm.manage.entity.PlatformCoupon;
import com.ssm.manage.entity.UploadFiles;
import com.ssm.manage.query.InstanceVariables;
import com.ssm.manage.query.PlatformCouponRequest;
import com.ssm.manage.query.StoreRequest;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.service.PlatformCouponService;
import com.ssm.manage.service.SsmBaseStoreService;
import com.ssm.manage.utils.Constant;
import com.ssm.manage.utils.HttpClientUtil;
import com.ssm.manage.utils.HttpUtils;
import com.ssm.manage.utils.XmlUtil;
import com.ssm.wxpay.sdk.WXPayConstants;
import com.ssm.wxpay.sdk.WXPayUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.nio.charset.Charset;
import java.util.*;

/**
 * (PlatformCoupon)表控制层
 *
 * @author makejava
 * @since 2022-06-11 14:58:52
 */
@RestController
@RequestMapping("platformCoupon")
@Api(tags = "优惠券表")
@Slf4j
public class PlatformCouponController {
    /**
     * 服务对象
     */
    @Autowired
    private PlatformCouponService platformCouponService;

    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;


    private static String appid = "wx094b8c7fb88ba28d";
    private static String secret = "2777bb81ea8a1afbb112c07529041d2f";

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return
     */
    @GetMapping("{id}")
    @ApiOperation("通过主键查询单条数据")
//@RequiresPermissions("system:platformCoupon:query")
    public PageResponse get(@PathVariable String id) {
        PageResponse<PlatformCoupon> pageResponse = new PageResponse<>();
        ArrayList<PlatformCoupon> platformCoupons = new ArrayList<>();
        try {
            PlatformCoupon platformCoupon = platformCouponService.queryById(id);
            platformCoupons.add(platformCoupon);
        } catch (Exception e) {
            log.error("SsmProjectController.id", e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setData(platformCoupons);
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        return pageResponse;

    }

    /**
     * 分页查询
     *
     * @param dto
     * @return
     */
    @GetMapping
    @ApiOperation("分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", defaultValue = "1", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页数量", defaultValue = "10", required = true)
    })
//@RequiresPermissions("system:platformCoupon:query")
    public PageResponse listPage(PlatformCouponDto dto) {
        PageResponse<PlatformCoupon> pageResponse = new PageResponse<>();
        PageInfo<PlatformCoupon> pageInfo = new PageInfo<>();
        try {
            pageInfo = platformCouponService.queryByPage(dto);
        } catch (Exception e) {
            log.error("SsmProjectController.page", e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setPageInfo(pageInfo);
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        return pageResponse;

    }

     /**
     * 分页查询
     *
     * @param dto
     * @return
     */
    @PostMapping("shareDiscounts")
    @ApiOperation("门店优惠查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", defaultValue = "1", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页数量", defaultValue = "10", required = true)
    })
//@RequiresPermissions("system:platformCoupon:query")
    public PageResponse shareDiscounts(@RequestBody PlatformCouponDto dto) {
        PageResponse<PlatformCoupon> pageResponse = new PageResponse<>();
        List<PlatformCoupon> pageInfo = new ArrayList<>();
        try {
            pageInfo = platformCouponService.shareDiscounts(dto);
        } catch (Exception e) {
            log.error("SsmProjectController.page", e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setData(pageInfo);
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        return pageResponse;

    }

    @PostMapping("/thePublic")
    @ApiOperation("查询公众号图片")
    public void thePublic(HttpServletRequest request, HttpServletResponse response,HttpSession session) {
        String key = SessionHelp.getLoginAccount(session);
        Long storeId = SessionHelp.getStoreId(session);
        try {
//            platformCouponService.thePublic(request,response,key);
            platformCouponService.thePublic(request,response,key,session);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    @PostMapping("/openid")
    @ApiOperation("获取当前openid")
    public PageResponse openid(HttpServletRequest request, HttpServletResponse response) {
        PageResponse<String> pageResponse = new PageResponse<>();
        List<String> pageInfo = new ArrayList<>();
        try {
            pageInfo=platformCouponService.obtainOpenid(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        pageResponse.setData(pageInfo);
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        return pageResponse;
    }


    //清除当前的openid
    @PostMapping("/gcopenid")
    @ApiOperation("清除当前openid")
    public PageResponse gcopenid(HttpServletRequest request, HttpServletResponse response) {
        PageResponse<String> pageResponse = new PageResponse<>();
        InstanceVariables.setOpenid(null);
        InstanceVariables.setDate(null);
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        return pageResponse;
    }


    /**
     * 新增
     *
     * @param platformCoupon
     * @return
     */
    @PostMapping("/add")
    @ApiOperation("新增")
//@RequiresPermissions("system:platformCoupon:add")
    public GenericResponse add(PlatformCouponRequest platformCoupon, MultipartFile multipartFile, HttpSession session) {
        //文件信息list
        List<UploadFiles> uploadFilesInfo = new ArrayList<>();
        FtpUtils ftp = new FtpUtils();
        GenericResponse<PlatformCoupon> genericResponse = new GenericResponse<>();
        String key = SessionHelp.getLoginAccount(session);
        Long storeId = SessionHelp.getStoreId(session);
        UploadFiles uploadFiles = new UploadFiles();
        String fileName = multipartFile.getOriginalFilename();//获取文件名
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());//获取文件后缀
        String saveName = UUID.randomUUID() + "." + suffix;//将文件名用时间重命名
        String path = Constant.filePath + "/" + SessionHelp.getStoreId(session);//文件上传路径
        uploadFiles.setFileName(saveName);
        uploadFiles.setFilePath(path);
        uploadFilesInfo.add(uploadFiles);

        InputStream inputStream = null;
        try {
            inputStream = multipartFile.getInputStream();
            ftp.uploadFile(path, saveName, inputStream);
        } catch (IOException e) {
            log.error("PlatformCouponController.add:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FILE_UPLOAD_FAILED);
            return genericResponse;
        }

        int i = 0;
        try {
            i = platformCouponService.add(platformCoupon, key, uploadFilesInfo);
        } catch (Exception e) {
            log.error("PlatformCouponController.add", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }

        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }

    @PostMapping("moneyReceipt")
    @ApiOperation("打款回执上传")
    public GenericResponse moneyReceipt(PlatformCouponRequest platformCoupon, MultipartFile multipartFile, HttpSession session) {
        //文件信息list
        List<UploadFiles> uploadFilesInfo = new ArrayList<>();
        FtpUtils ftp = new FtpUtils();
        GenericResponse<PlatformCoupon> genericResponse = new GenericResponse<>();
        String key = SessionHelp.getLoginAccount(session);
        Long storeId = SessionHelp.getStoreId(session);
        if (null!=multipartFile){
            UploadFiles uploadFiles = new UploadFiles();
            String fileName = multipartFile.getOriginalFilename();//获取文件名
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());//获取文件后缀
            String saveName = UUID.randomUUID() + "." + suffix;//将文件名用时间重命名
            String path = Constant.filePath + "/" + SessionHelp.getStoreId(session);//文件上传路径
            uploadFiles.setFileName(saveName);
            uploadFiles.setFilePath(path);
            uploadFilesInfo.add(uploadFiles);

            InputStream inputStream = null;
            try {
                inputStream = multipartFile.getInputStream();
                ftp.uploadFile(path, saveName, inputStream);
            } catch (IOException e) {
                log.error("PlatformCouponController.moneyReceipt:", e);
                genericResponse.setCodeAndMsg(ResponseCode.FILE_UPLOAD_FAILED);
                return genericResponse;
            }
        }
        int i;
        try {
            i = platformCouponService.moneyReceipt(platformCoupon, key, uploadFilesInfo);

//            ftp.uploadFile(path, saveName, inputStream);
        } catch (Exception e) {
            log.error("PlatformCouponController.moneyReceipt", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }


    /**
     * 选择门店
     */
    @PostMapping("pagesorganizations")
    @ApiOperation("选择门店")
    public GenericResponse<BaseStores> pagesorganizations(@RequestBody StoreRequest storeRequest, HttpSession session) {
        GenericResponse<BaseStores> genericResponse = new GenericResponse<>();
        storeRequest.setId(SessionHelp.getStoreId(session));
        List<BaseStores> pageInfo = new ArrayList<>();
        try {
            pageInfo = ssmBaseStoreService.pagesorganizations(storeRequest);
        } catch (Exception e) {
            log.error("SsmBaseStoreController.selectPage", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setRows(pageInfo);
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        return genericResponse;
    }

    /**
     * 编辑
     *
     * @param platformCoupon
     */
    @PutMapping("update")
    @ApiOperation("编辑")
//@RequiresPermissions("system:platformCoupon:edit")
    public GenericResponse edit(PlatformCouponRequest platformCoupon, MultipartFile multipartFile, HttpSession session) {

        GenericResponse<PlatformCoupon> genericResponse = new GenericResponse<>();
        //文件信息list
        List<UploadFiles> uploadFilesInfo = new ArrayList<>();
        FtpUtils ftp = new FtpUtils();
//        String key = null;
//        Long storeId = null;
//        String saveName = null;
//        String path = null;
        InputStream inputStream = null;
        UploadFiles uploadFiles = new UploadFiles();
        String key = SessionHelp.getLoginAccount(session);
        Long storeId = SessionHelp.getStoreId(session);
        if (null != multipartFile) {
            String fileName = multipartFile.getOriginalFilename();//获取文件名
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());//获取文件后缀
            String saveName = UUID.randomUUID() + "." + suffix;//将文件名用时间重命名
            String path = Constant.filePath + "/" + SessionHelp.getStoreId(session);//文件上传路径
            uploadFiles.setFileName(saveName);
            uploadFiles.setFilePath(path);
            uploadFilesInfo.add(uploadFiles);
            try {
                inputStream = multipartFile.getInputStream();
                ftp.uploadFile(path, saveName, inputStream);

            } catch (IOException e) {
                log.error("PlatformCouponController.update:", e);
                genericResponse.setCodeAndMsg(ResponseCode.FILE_UPLOAD_FAILED);
                return genericResponse;
            }
        }


        int i;
        try {
            i = platformCouponService.edit(platformCoupon, key, uploadFilesInfo);
//            ftp.uploadFile(path, saveName, inputStream);
        } catch (Exception e) {
            log.error("PlatformCouponController.update", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }


    //    @PostMapping("newCheck")
//    @ApiOperation("新建审核")
//    public GenericResponse newCheck(PlatformCoupon platformCoupon, HttpSession session){
//        String key = SessionHelp.getLoginAccount(session);
//        Long storeId = SessionHelp.getStoreId(session);
//        GenericResponse<PlatformCoupon> genericResponse = new GenericResponse<>();
//        int i = 0;
//        try {
//            i = platformCouponService.newCheck(platformCoupon,key);
//        } catch (Exception e) {
//            log.error("PlatformCouponController.newCheck", e);
//            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
//            return genericResponse;
//        }
//        if (i > 0) {
//            genericResponse.setCodeAndMsg(ResponseCode.OK);
//        }
//        return genericResponse;
//    }
    @PostMapping("shopCheck")
    @ApiOperation("门店审核")
    public GenericResponse shopCheck(@RequestBody PlatformCouponRequest platformCoupon, HttpSession session) {
        String key = SessionHelp.getLoginAccount(session);
        Long storeId = SessionHelp.getStoreId(session);
        GenericResponse<PlatformCoupon> genericResponse = new GenericResponse<>();
        int i = 0;
        try {
            i = platformCouponService.shopCheck(platformCoupon, key);
        } catch (Exception e) {
            log.error("PlatformCouponController.shopCheck", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }

    @PostMapping("platformCheck")
    @ApiOperation("平台审核")
    public GenericResponse platformCheck(@RequestBody PlatformCouponRequest platformCoupon, HttpSession session) {
        String key = SessionHelp.getLoginAccount(session);
        Long storeId = SessionHelp.getStoreId(session);
        GenericResponse<PlatformCoupon> genericResponse = new GenericResponse<>();
        int i = 0;
        try {
            i = platformCouponService.platformCheck(platformCoupon, key);
        } catch (Exception e) {
            log.error("PlatformCouponController.platformCheck", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }

    @PostMapping("token")
    @ApiOperation("小程序token")
    public GenericResponse token() {
        GenericResponse<Token> genericResponse = new GenericResponse<>();
//        int i = 0;
        Token token = null;
        try {

            String s = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
            String result = HttpClientUtil.doGet(s);
            JSONObject jsonObject = JSONObject.parseObject(result);
            if (null != jsonObject) {
                token = new Token();
                String access_token = jsonObject.getString("access_token");
                if(null != access_token && !"".equals(access_token)){
                    token.setAccessToken(access_token);
                    token.setExpiresIn(jsonObject.getIntValue("expires_in"));
                }else {
                    token = null;
                    // 获取token失败
                    log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getIntValue("errcode"), jsonObject.getString("errmsg"));
                }
            }
            genericResponse.setData(token);

        } catch (Exception e) {
            log.error("PlatformCouponController.token", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
//        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
//        }
        return genericResponse;
    }


    @PostMapping("obtainPhone")
    @ApiOperation("获取手机号")
    public GenericResponse obtainPhone(@RequestParam String accessToken,@RequestParam String code) {
        GenericResponse<String> genericResponse = new GenericResponse<>();
        String s;
        try {
        s = platformCouponService.obtainPhone(accessToken, code);
        genericResponse.setData(s);
        } catch (Exception e) {
            log.error("PlatformCouponController.obtainPhone", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        return genericResponse;
    }



        /**
         * 根据主键删除
         *
         * @param id 主键
         * @return
         */
    @DeleteMapping("{id}")
    @ApiOperation("根据主键删除")
//@RequiresPermissions("system:platformCoupon:delete")
    public int delete(@PathVariable Serializable id) {
        return this.platformCouponService.delete(id);
    }



    @PostMapping("unifiedOrder")
    @ApiOperation("测试微信支付统一下单接口")
    public GenericResponse unifiedOrder(String openId, HttpServletRequest request, String money){

        GenericResponse<Map<String,String>> genericResponse = new GenericResponse<>();

        //获取ip
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getRemoteAddr();
        }
        if (ip.contains(",")){
            String[] ips = ip.split(",");
            ip = ips[0].trim();
        }
//        String xml = mpPayUtil.generateUniPayXml(unifiedParam);
        String xml = platformCouponService.generateUniPayXml(openId,ip,money);
        String url= "https://api.mch.weixin.qq.com/pay/unifiedorder";
        String xmlResult  = HttpUtils.doPost(url, xml);

        //发送请求成功
        if (xmlResult.indexOf("SUCCESS")!=-1) {
            Map<String, String> map = null;
            try {
                Map<String, String> parseXmlToMap = WXPayUtil.xmlToMap(xmlResult);
                map = platformCouponService.secondSign(parseXmlToMap);
            } catch (Exception e) {
                e.printStackTrace();
            }
            genericResponse.setData(map);
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }else{
            //throw new RuntimeException("统一支付错误");
            genericResponse.setCodeAndMsg(ResponseCode.FAILED,"统一支付错误");
        }
        return genericResponse;
    }

    /*
    * 微信支付成功回调函数
    * */
    @PostMapping("fallback")
    public void fallback(HttpServletRequest request,HttpServletResponse response) throws IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = null;
        try (InputStream inputStream = request.getInputStream()) {
            reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
            String line = "";
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            log.error("getBodyString错误");
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    log.error(String.valueOf(e));
                }
            }
        }

        String notifyXml=sb.toString();
        Map<String, String> params = (Map<String, String>) XmlUtil.fromXML(notifyXml,Map.class);
        boolean result = false;
        String resultXml;
        if ("SUCCESS".equals(params.get("return_code"))) {//通信成功,非交易标识
            //验证签名
            try {
                if (WXPayUtil.isSignatureValid(notifyXml, WXPayConstants.APP_SECRET)) {
                    //执行业务逻辑
                    result=true;
                }else{
                    log.error("微信支付成功回调验证签名错误！");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            log.error("Fallback回调结果 : "+params.get("return_msg"));
        }

        if (result){
            resultXml="<xml><return_code><![CDATA[SUCCESS]]></return_code>" +
                    "<return_msg><![CDATA[OK]]></return_msg></xml>";
        }else {
            resultXml="<xml><return_code><![CDATA[FAIL]]></return_code>"
                    + "<return_msg><![CDATA[ERROR]]></return_msg></xml> ";
        }

        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.println(result);
        outputStream.close();
    }

}