package com.gree.mall.miniapp.controller.common;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.miniapp.annotation.ApiNotAuth;
import com.gree.mall.miniapp.bean.user.CurrentCompanyWechat;
import com.gree.mall.miniapp.constant.Constant;
import com.gree.mall.miniapp.exception.RemoteServiceException;
import com.gree.mall.miniapp.helper.ResponseHelper;
import com.gree.mall.miniapp.logic.CarouselMapLogic;
import com.gree.mall.miniapp.logic.ExpressLogic;
import com.gree.mall.miniapp.logic.common.CommonLogic;
import com.gree.mall.miniapp.logic.common.outside.WechatLogic;
import com.gree.mall.miniapp.plus.entity.*;
import com.gree.mall.miniapp.plus.service.AdminCompanyWechatOtherService;
import com.gree.mall.miniapp.plus.service.OrderDetailService;
import com.gree.mall.miniapp.plus.service.OrderInfoService;
import com.gree.mall.miniapp.plus.service.OrderTaxService;
import com.gree.mall.miniapp.utils.RedisUtil;
import com.gree.mall.miniapp.utils.VerifiUtils;
import com.gree.mall.miniapp.utils.qywx.AesException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;
import java.util.UUID;


@Slf4j
@RestController
@Api(value = "公共API", tags = {"公共API"})
@RequestMapping(value = "/common", produces = "application/json; charset=utf-8")
public class CommonController {

//    @Value("${wechat.cp.corpId}")
//    private String corpId;
//    @Value("${work.token}")
//    private String workToken;
//    @Value("${work.encodingAesKey}")
//    private String encodingAesKey;
//    @Autowired
//    FucaiLogic fucaiLogic;

    @Autowired
    CommonLogic commonLogic;
    @Autowired
    ExpressLogic expressLogic;
    @Autowired
    OrderTaxService orderTaxService;
    @Autowired
    RedisUtil redisUtil;

    @Resource
    CarouselMapLogic carouselMapLogic;
//    @Autowired
//    WechatLogic wechatLogic;

    @Autowired
    OrderInfoService orderInfoService;
    @Autowired
    OrderDetailService orderDetailService;
    @Autowired
    AdminCompanyWechatOtherService adminCompanyWechatOtherService;
    @Resource
    WechatLogic wechatLogic;

    @PostMapping("/upload")
    @ApiOperation(value = "文件上传")
    public ResponseHelper<CommonFile> upload(
            @ApiParam(required = true, value = "附件") @RequestParam(required = true) MultipartFile file
    ) throws IOException, RemoteServiceException {
        log.info("文件上传开始时间 {}", DateUtil.formatDateTime(DateUtil.date()));
        CommonFile commonFile = commonLogic.uploadFile(file);
        log.info("文件上传结束时间 {}", DateUtil.formatDateTime(DateUtil.date()));
        return ResponseHelper.success(commonFile);
    }

    @GetMapping("/express/company")
    @ApiOperation(value = "所有物流公司")
    public ResponseHelper<List<ExpressCompany>> companyList(
    ) throws IOException, RemoteServiceException {
        List<ExpressCompany> expressCompanies = expressLogic.expressCompanyList();
        return ResponseHelper.success(expressCompanies);
    }

    @GetMapping("/express")
    @ApiOperation(value = "查看物流")
    public ResponseHelper<List<ExpressInfo>> express(
            @ApiParam(required = true, value = "附件") @RequestParam(required = true) String logisticsNo,
            @ApiParam(required = true, value = "物流公司code") @RequestParam(required = true) String companyCode
    ) throws IOException, RemoteServiceException {
        List<ExpressInfo> expressInfos = expressLogic.queryExpress(logisticsNo, companyCode);
        return ResponseHelper.success(expressInfos);
    }


    @GetMapping("/street")
    @ApiOperation(value = "街道")
    public ResponseHelper<List<Map>> street(
            @ApiParam(value = "省", required = true) @RequestParam(required = true) String province,
            @ApiParam(value = "市", required = true) @RequestParam(required = true) String city,
            @ApiParam(value = "区", required = true) @RequestParam(required = true) String area
    ) throws RemoteServiceException {
        List<Map> street = commonLogic.street(province, city, area);
        return ResponseHelper.success(street);
    }

    @ApiNotAuth
    @GetMapping("/list/page")
    @ApiOperation(value = "轮播图列表")
    public ResponseHelper<Page<CarouselMap>> page(
            HttpServletRequest request,
            @ApiParam(value = "状态(true：启用 false:禁用", required = false) @RequestParam(required = false) Boolean state,
            @ApiParam(value = "轮播图类型 SHOP=商城 ESHOP=二手商城 YJHX=以旧换新入口", required = false) @RequestParam(required = false) String port,
            @ApiParam(value = "页号", required = true) @RequestParam(required = true) Integer pageNum,
            @ApiParam(value = "页大小", required = true) @RequestParam(required = true) Integer pageSize
    ) throws RemoteServiceException {
        IPage<CarouselMap> page = carouselMapLogic.page(request, state, port, pageNum, pageSize);
        return ResponseHelper.success(page);
    }

    @GetMapping("/wechat/detail")
    @ApiOperation(value = "微信配置")
    public ResponseHelper<CurrentCompanyWechat> detail(
            HttpServletRequest request
    ) throws RemoteServiceException {
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat(request);
        //设置其他配置
        AdminCompanyWechatOther one = adminCompanyWechatOtherService.lambdaQuery()
                .eq(AdminCompanyWechatOther::getCompanyWechatId, currentCompanyWechat.getCompanyWechatId())
                .one();
        currentCompanyWechat.setAdminCompanyWechatOther(one);
        return ResponseHelper.success(currentCompanyWechat);
    }


    @GetMapping("/scene")
    @ApiOperation(value = "获取微信scene参数")
    public ResponseHelper<String> page(
            @ApiParam(value = "微信scene", required = true) @RequestParam(required = true) String scene
    ) throws RemoteServiceException {
        String sceneValue = commonLogic.getSceneValue(scene);
        return ResponseHelper.success(sceneValue);
    }

    //企业微信回调
//    @ApiNotAuth
//    @RequestMapping(value = "/callback",method = {RequestMethod.GET})
//    public String rece(
//            @RequestParam(name="msg_signature") String msgSignature,
//            @RequestParam(name="timestamp") String timestamp,
//            @RequestParam(name="nonce") String nonce,
//            @RequestParam(name="echostr",required = false) String echostr
//    ) throws AesException {
//        String s = new WXBizJsonMsgCrypt(workToken, encodingAesKey,corpId)
//                .VerifyURL(msgSignature, timestamp, nonce, echostr);
//        return s;
//    }

    //企业微信回调
    @ApiNotAuth
    @RequestMapping(value = "/callback", method = {RequestMethod.POST})
    public String recePost(
            @RequestParam(name = "msg_signature", required = false) String msgSignature,
            @RequestParam(name = "timestamp", required = false) String timestamp,
            @RequestParam(name = "nonce", required = false) String nonce,
            @RequestParam(name = "echostr", required = false) String echostr
    ) throws AesException {
        //String s = new WXBizJsonMsgCrypt(workToken, encodingAesKey,corpId).VerifyURL(msgSignature, timestamp, nonce, echostr);
        return "success";
    }

    @GetMapping("/getVerifi")
    @ApiOperation(value = "获取拖拽式验证码")
    public ResponseHelper<Map<String, Object>> getVerifi() {
        Map<String, Object> map = VerifiUtils.getVerifi();
        Integer xWidth = (Integer) map.get("xWidth");
        String key = UUID.randomUUID().toString();
        redisUtil.set(Constant.RedisPrefix.VERIFICATION + ":" + key, xWidth, 2 * 60);
        map.remove("xWidth");
        map.put("key", key);
        return ResponseHelper.success(map);
    }

    @ApiNotAuth
    @GetMapping("/not/auth/getVerifi")
    @ApiOperation(value = "无授权获取拖拽式验证码")
    public ResponseHelper<Map<String, Object>> notAuthGetVerifi() {
        Map<String, Object> map = VerifiUtils.getVerifi();
        Integer xWidth = (Integer) map.get("xWidth");
        String key = UUID.randomUUID().toString();
        redisUtil.set(Constant.RedisPrefix.VERIFICATION + ":" + key, xWidth, 2 * 60);
        map.remove("xWidth");
        map.put("key", key);
        return ResponseHelper.success(map);
    }

    @ApiNotAuth
    @GetMapping("/config/get")
    @ApiOperation("获取小程序配置")
    public ResponseHelper<AdminCompanyWechat> getConfig(HttpServletRequest request) {
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat(request);
        //剔除不返回的内容
        currentCompanyWechat.setAppId(null);
        currentCompanyWechat.setSubAppId(null);
        currentCompanyWechat.setSubSecret(null);
        currentCompanyWechat.setSecret1(null);
        currentCompanyWechat.setSecret2(null);
        currentCompanyWechat.setSecret3(null);
        currentCompanyWechat.setMchKey(null);
        currentCompanyWechat.setMchId(null);
        currentCompanyWechat.setCorpId(null);
        return ResponseHelper.success(currentCompanyWechat);
    }


//    @PostMapping("/online/pay")
//    @ApiOperation(value = "所有物流公司")
//    public ResponseHelper onlinePay(
//            @ApiParam(value = "key",required = true) @RequestParam(required = true) String key,
//            @ApiParam(value = "openId",required = true) @RequestParam(required = true) String openId
//    ) throws IOException, RemoteServiceException {
//        Map<String, Object> stringObjectMap = fucaiLogic.onlinePay(key, openId);
//        return ResponseHelper.success(stringObjectMap);
//    }


    @ApiNotAuth
    @GetMapping("/getfile")
    public ResponseHelper<String> getfile(@RequestParam(required = true) String id) {
        OrderTax orderTax = orderTaxService.getById(id);
        String taxLink = orderTax.getTaxLink();
        return ResponseHelper.success(taxLink);
    }


//    @ApiNotAuth
//    @GetMapping("/token/get")
//    public ResponseHelper<String> getToken() throws RemoteServiceException {
//        return ResponseHelper.success(wechatLogic.getAccessToken());
//    }

//    @PostMapping("/jindie")
//    public ResponseHelper jindie(
//           @RequestParam List<String> orderIds
//    ) throws RemoteServiceException {
//        for(String orderId : orderIds) {
//            OrderInfo orderInfo = orderInfoService.getById(orderId);
//            List<OrderDetail> list = orderDetailService.lambdaQuery().eq(OrderDetail::getOrderId, orderId).list();
//
//            fucaiLogic.sendSaleOrder(list,orderInfo,orderInfo.getWebsitNumber());
//        }
//        return ResponseHelper.success();
//    }

//    @PostMapping("/jindie2")
//    public ResponseHelper jindie2(
//            @RequestParam String orderId
//    ) throws RemoteServiceException {
//
//            OrderInfo orderInfo = orderInfoService.getById(orderId);
//            List<OrderDetail> list = orderDetailService.lambdaQuery().eq(OrderDetail::getOrderId, orderId).list();
//
//            fucaiLogic.sendSaleOrder(list,orderInfo,orderInfo.getWebsitNumber());
//
//        return ResponseHelper.success();
//    }


    @ApiNotAuth
    @GetMapping("/oss/config")
    public ResponseHelper getOSSConfig() throws UnsupportedEncodingException {
        Map<String, String> ossConfig = commonLogic.getOSSConfig();
        return ResponseHelper.success(ossConfig);
    }

    @ApiNotAuth
    @GetMapping("/img/get")
    @ApiOperation(value = "获取图片")
    public void getImg(
            @ApiParam(required = true, value = "附件key") @RequestParam(required = true) String key,
            HttpServletResponse response
    ) throws IOException, RemoteServiceException {
        String file = commonLogic.getFile(key);
        response.sendRedirect(file);
    }


    @PostMapping("region")
    @ApiOperation(value = "查询省市区街道")
    public ResponseHelper<List<Region>> queryRegionList(
            @RequestParam(required = false) String parentId
    ) {
        List<Region> region = commonLogic.getRegion(parentId);
        return ResponseHelper.success(region);
    }

    @PostMapping("/get/mp/qrcode")
    @ApiOperation("生成带参数的二维码")
    public ResponseHelper<WxMpQrCodeTicket> getMpQrcode(
            @RequestParam String userId,
            @RequestParam String companyWechatId
    ) throws Exception {
        return wechatLogic.getMpQrcode(userId, companyWechatId);
    }

}
