package com.hys.app.controller.erp.use;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.hys.app.framework.exception.ServiceException;
import com.hys.app.framework.util.DateUtil;
import com.hys.app.framework.util.JsonUtil;
import com.hys.app.framework.util.ScriptUtil;
import com.hys.app.framework.util.StringUtil;
import com.hys.app.mapper.system.AdminUserMapper;
import com.hys.app.mapper.system.RoleMapper;
import com.hys.app.model.erp.configs.KuangShiConfig;
import com.hys.app.model.erp.dos.OrderCustomerFee;
import com.hys.app.model.erp.dos.OrderDO;
import com.hys.app.model.erp.dto.PayTypeUrl;
import com.hys.app.model.erp.entity.CompanyErp;
import com.hys.app.model.system.dos.AdminUser;
import com.hys.app.model.system.dos.RoleDO;
import com.hys.app.model.system.vo.Menus;
import com.hys.app.pay.ali.AliPayService;
import com.hys.app.pay.ali.PayOrder;
import com.hys.app.pay.ali.UserInfoWx;
import com.hys.app.pay.wx.WxConfig;
import com.hys.app.pay.wx.WxPayServiceMy;
import com.hys.app.service.erp.CompanyErpManager;
import com.hys.app.service.erp.OrderCustomerFeeManager;
import com.hys.app.service.erp.OrderManager;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateIndustry;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.commons.util.IdUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin/erp/pay")
@Api(tags = "订单支付")
@Validated
@AllArgsConstructor
public class PayController extends HttpServlet {
    //    private OrderManager orderManager;
    private AliPayService aliPayService;
    private WxPayServiceMy wxPayServiceMy;
    private CompanyErpManager companyManager;
    private AdminUserMapper adminUserMapper;
    private RoleMapper roleMapper;

    private static final Logger log = LoggerFactory.getLogger(ScriptUtil.class);


    @ApiOperation(value = "扫描完获取拉起支付的url")
    @PostMapping("/getPayUrl")
    public Object getListByScan(@RequestBody @Validated PayTypeUrl payTypeUrl) throws UnknownHostException, WxPayException {
        CompanyErp company = companyManager.getById(payTypeUrl.getId());
        AdminUser user = adminUserMapper.selectById(payTypeUrl.getUserId());
        if (ObjectUtil.isNull(company)) {
            throw new ServiceException("未查询到公司信息");
        }
        PayOrder payOrder = new PayOrder();
//        payOrder.setTraceNo(company.getId().toString());
        payOrder.setTraceNo(IdUtil.simpleUUID());
        payOrder.setSubject("购买公司使用权账号");
        payOrder.setTimeExpire(LocalDateTime.now().plusMinutes(30));
//        payOrder.setTotalAmount(company.getThisMoney().doubleValue());
        payOrder.setTotalAmount(0.01);
        payOrder.setOrderPayType("company");
        switch (payTypeUrl.getPayType()) {
            case "ali":
                return aliPayService.pay(payOrder);
            case "wx":
                if (ObjectUtil.isNotNull(user) && StrUtil.isBlank(user.getOpenid())) {
                    throw new WxPayException("当前用户未绑定微信，请前往我的个人信息里面绑定微信后再支付");
                }
                payOrder.setOpenId(user.getOpenid());
                return wxPayServiceMy.pay(payOrder);
            default:
                return "不支持的支付方式";
        }
    }

    @PostMapping("/aliReturnCall")
    @Transactional(rollbackFor = Exception.class)
    public String aliReturnCall(HttpServletRequest request) throws Exception {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = String.join(",", values);
            params.put(name, valueStr);
        }
        if (aliPayService.checkReturnParam(params)) {
            String passbackParams = URLDecoder.decode(params.get("passback_params"), "UTF-8");
            if ("company".equals(passbackParams)) {
                CompanyErp company = companyManager.getById(params.get("out_trade_no"));
                //如果结束时间大于当前时间，那么就从现在加起
                Date currentDate = company.getEndUseTime();
                if (new Date().compareTo(company.getEndUseTime()) > 0) {
                    currentDate = new Date();

                }
                // 使用 加上套餐包的天数
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(currentDate);
                calendar.add(Calendar.DAY_OF_MONTH, company.getThisDay());

                company.setEndUseTime(calendar.getTime());
                company.setMoney(company.getMoney().add(company.getThisMoney()));
                company.setRoleId(company.getThisRoleId());
                company.setUserNum(company.getThisUserNum());
                company.setCompanyPackageId(company.getThisCompanyPackageId());

                company.setThisDay(0);
                company.setThisCompanyPackageId(0L);
                company.setThisMoney(new BigDecimal(0));
                company.setThisRoleId(0L);
                company.setThisUserNum(0);

                companyManager.updateById(company);
//                //  不管换没换套餐  把新的套餐权限赋值到公司的admin账号上
                AdminUser user = adminUserMapper.selectOne(new LambdaQueryWrapper<AdminUser>()
                        .eq(AdminUser::getCompanyId, company.getId())
                        .eq(AdminUser::getUsername, "admin").last("limit 1"));
                //把这个管理员能看到的所有页面保存起来
                RoleDO roleDO = roleMapper.selectById(company.getThisRoleId());
                List<Menus> menusList = JsonUtil.jsonToList(roleDO.getAuthIds(), Menus.class);
                List<Menus> list = new ArrayList<>();
                assert menusList != null;
                for (Menus menu : menusList) {
                    if (CollUtil.isNotEmpty(menu.getChildren())) {
                        list.add(menu);
                        getMenus(list, menu);
                    } else {
                        list.add(menu);
                    }
                }
                //这个角色所有已勾选的菜单
                Set<Menus> collect = list.stream().filter(Menus::isChecked).collect(Collectors.toSet());
                for (Menus menus1 : collect) {
                    menus1.setChildren(collect.stream().filter(item -> item.getParentId().equals(menus1.getId())).collect(Collectors.toList()));
                }
                List<Menus> collect2 = collect.stream().filter(item -> item.getParentId() == 0).collect(Collectors.toList());
                user.setAuthIds(JSON.toJSONString(collect2));
                adminUserMapper.updateById(user);
            }
        }
        return "success";
    }

    private void getMenus(List<Menus> list, Menus menus) {
        for (Menus child : menus.getChildren()) {
            list.add(child);
            getMenus(list, child);
        }
    }


    @PostMapping("/wxpay/notify")
    public String parseOrderNotify(@RequestBody String xmlData) {
        try {
            System.out.println("微信支付回调来了啊+11111111111111111111111111111111111111111111111111111111111");
            WxPayServiceImpl wxPayService = new WxPayServiceImpl();
            // 解析支付通知结果
            WxPayOrderNotifyResult notifyResult = wxPayService.parseOrderNotifyResult(xmlData);
            // 处理订单逻辑
        } catch (WxPayException e) {
            // 处理解析异常，记录日志
            e.printStackTrace();
        }
//        return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[解析失败]]></return_msg></xml>";
        return "<xml>" +
                "<return_code><![CDATA[" + "SUCCESS" + "]]></return_code>" +
                "<return_msg><![CDATA[" + "OK" + "]]></return_msg>" +
                "</xml>";
    }

    @PostMapping("getOpenIdCode/{userId}")
    public String getOpenIdCode(@PathVariable Long userId, @RequestBody @Validated Map map) throws UnsupportedEncodingException {
        String openIdCode = wxPayServiceMy.getOpenIdCode(userId, map.get("ip").toString());
        System.out.println("授权地址+“--------------------------------------------------------" + openIdCode + "ip-----------------" + map.get("ip").toString());
        return wxPayServiceMy.getOpenIdCode(userId, map.get("ip").toString());
    }

    @GetMapping("/weixin/callback/openidCode")
    public void handleWeixinCallback(@RequestParam("code") String code, @RequestParam("state") String state, HttpSession session, HttpServletResponse response) throws Exception {
        log.info("授权回调来了啊" +code+"----------" +state );
        if (!state.equals(session.getAttribute("WEIXIN_OAUTH_STATE"))) {
            log.error("用户授权，state错误");
        }
        AdminUser user = adminUserMapper.selectById(state);
        if (ObjectUtil.isNull(user)) {
            log.error("未查询到用户信息：" + state);
        }
        String openId = wxPayServiceMy.getOpenId(code);
        user.setOpenid(openId);
        adminUserMapper.updateById(user);
//        String accessToken = wxPayServiceMy.getAccessToken(code);
//        String userInfo = wxPayServiceMy.getUserInfo(accessToken, openId);
//        UserInfoWx userInfoWx = JSON.parseObject(JSON.toJSONString(userInfo), UserInfoWx.class);
//        System.out.println(userInfo+"--------------1111111111");
//        System.out.println(userInfoWx+"--------------2222222222222222");
    }


    @GetMapping("/sendMsg")
    public void sendMsg(String openid) throws WxErrorException {
//        AdminUser user = adminUserMapper.selectById(1811346086600843265L);
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser(openid)
                .templateId("BmtA7g2Z2KomlIvNS0OtmEVu4ySqPUlSYZNo9zBZxtc")
                .build();

        templateMessage.addData(new WxMpTemplateData("thing3", "黄理志"))
                .addData(new WxMpTemplateData("time4", "2022-11-17 22:04:40", "#173177"))
                .addData(new WxMpTemplateData("character_string6", "A14010001688", "#173177"))
                .addData(new WxMpTemplateData("thing8", "贸易通订单流程待处理通知", "#173177"))
                .addData(new WxMpTemplateData("character_string13", "202308060001！", "#173177"));
        WxMpService wxService = new WxMpServiceImpl();
        WxMpDefaultConfigImpl config = new WxMpDefaultConfigImpl();
        config.setAppId("wx51e98f2dee35237d");  // 替换为你的 AppID
        config.setSecret("13803c1b0d911e023c7da0b300cbce89");  // 替换为你的 AppSecret
        wxService.setWxMpConfigStorage(config);
        wxService.getTemplateMsgService().sendTemplateMsg(templateMessage);
    }

}
