package com.ruoyi.applet.contoller;

import com.alibaba.fastjson.JSONObject;
import com.cyl.h5.pojo.request.OrderPayRequest;
import com.cyl.h5.pojo.response.OrderPayResponse;
import com.cyl.manager.staff.domain.BondTransaction;
import com.cyl.manager.ums.domain.Member;
import com.cyl.wechat.WechatPayData;
import com.cyl.wechat.WechatPayService;
import com.cyl.wechat.WechatPayUtil;
import com.ruoyi.applet.utils.tencent.TencentUtil;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisService;
import com.ruoyi.common.enums.BondOrderStatus;
import com.ruoyi.common.enums.BondTransactionType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.config.LocalDataUtil;
import com.ruoyi.model.domain.AppUsers;
import com.ruoyi.model.domain.AppletUsersTeacher;
import com.ruoyi.model.service.IAppUsersService;
import com.ruoyi.model.service.IAppletUsersTeacherService;
import com.tencentcloudapi.faceid.v20180301.models.IdCardVerificationResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
@Api(description = "伴宠师-伴宠师认证")
@RestController
@RequestMapping("/applet/UserTeacher")
public class ApiAppletUserTeacherController {
    @Autowired
    private IAppUsersService appUsersService;
    @Autowired
    private IAppletUsersTeacherService appletUsersTeacherService;
    @Autowired
    private WechatPayService wechatPayService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private TencentUtil tencentUtil;


    @ApiOperation("伴宠师工作台-伴宠师列表数据查询")
    @GetMapping("/userList")
    public AjaxResult userList(AppletUsersTeacher usersTeacher){
        List<AppletUsersTeacher> userList = appletUsersTeacherService.selectAppletUsersTeacherList(usersTeacher);
        return AjaxResult.success("伴宠师列表数据",userList);
    }


    @ApiOperation("伴宠师工作台-查询用户是否提交过数据")
    @GetMapping("/getUserOne/{appUserId}")
    public AjaxResult getUserOne(@PathVariable("appUserId") Long appUserId){
        AppletUsersTeacher appletUsersTeacher = appletUsersTeacherService.selectAppletUsersTeacherByUserId(appUserId);
        return AjaxResult.success("认证信息",appletUsersTeacher);
    }





    @ApiOperation("伴宠师工作台-伴宠师基本信息添加")
    @PostMapping("/insertUser")
    public AjaxResult insertUser(@RequestBody AppletUsersTeacher usersTeacher){
        if(usersTeacher.getUserId() == null){
           return AjaxResult.error("userId用户信息标识不能为空");
        }
        usersTeacher.setStatus(0L);
        AppletUsersTeacher appletUsersTeacher = appletUsersTeacherService.selectAppletUsersTeacherByUserId(usersTeacher.getUserId());
        if(appletUsersTeacher != null){
            return AjaxResult.error("您已经提交过了请不要重复提交");
        }

        IdCardVerificationResponse response = tencentUtil
                .verificationIdCard(usersTeacher.getName(),
                        usersTeacher.getIdCard());

        if (!response.getResult().equals("0")){
            return AjaxResult.error(response.getDescription());
        }

        return toAjax(appletUsersTeacherService.insertAppletUsersTeacher(usersTeacher));
    }

    @ApiOperation("伴宠师工作台-伴宠师基本信息修改")
    @PostMapping("/udpateUser")
    public AjaxResult udpateUser(@RequestBody AppletUsersTeacher usersTeacher){
        if(usersTeacher.getId() == null){
            return AjaxResult.error("标识不能为空");
        }
        return toAjax(appletUsersTeacherService.updateAppletUsersTeacher(usersTeacher));
    }

    @ApiOperation("伴宠师工作台-伴宠师基本信息删除")
    @PostMapping("/deleteUser")
    public AjaxResult deleteUser(long id){
        return toAjax(appletUsersTeacherService.deleteAppletUsersTeacherById(id));
    }




    //保证金缴纳
    @ApiOperation("伴宠师工作台-保证金缴纳")
    @PostMapping("/payPrice")
    public OrderPayResponse orderPay(@RequestBody OrderPayRequest req){


        long prepayId = System.currentTimeMillis();

        req.setPayId(prepayId);
        req.setType(1);
        req.setWechatType(2);




        log.info("订单支付","提交的数据："+ JSONObject.toJSONString(req));
        String redisKey = "h5_oms_bcs_pay_"+req.getPayId();
        String redisValue = req.getPayId()+"_"+System.currentTimeMillis();
        try {
            redisService.lock(redisKey, redisValue, 60);
            AppUsers member = appUsersService.selectAppUsersByUserId(req.getMemberId());
            String orderNo = "";
            String desc = "";
            Integer totalAmount = 1;
            String openId =member.getOpenid();
            Long memberId = member.getUserId();
            String appId = "wx01f0f43759922fda";
            String s = wechatPayService.jsapiPayForBCHSHI(
                    orderNo,
                    desc,
                    totalAmount,
                    openId,
                    memberId,
                    appId
            );
//            log.info("【支付】jsapiPay支付成功，预付单ID：" + req.getPayId());
            OrderPayResponse response = new OrderPayResponse();
//            response.setPayType(2);
//            String nonceStr = WechatPayUtil.generateNonceStr();
//            long timeStamp = WechatPayUtil.getCurrentTimestamp();
//            String prepayIds = "prepay_id=" + prepayId;
//            String signType = "RSA";
//            String paySign = null;
//            String signatureStr = Stream.of(
//                            appId,
//                             String.valueOf(timeStamp) ,
//                            nonceStr,
//                            prepayId
//                    ).map(s -> s != null ? s : "") // 防止 null 值
//                    .collect(Collectors.joining("\n", "", "\n"));



//            //timeStamp 转为String
//            String timeStampStr = timeStamp != null ? String.valueOf(timeStamp) : "";
//            // 处理可能的 null 值
//            String signatureStr = Stream.of(
//                    appId != null ? appId : "",
//                    timeStamp != null ? String.valueOf(timeStamp) : "",
//                    nonceStr != null ? nonceStr : "",
//                    prepayId != null ? prepayId : ""
//            ).collect(Collectors.joining("\n", "", "\n"));
            //TODO
//        paySign = "TODO";
//            try {
//                paySign = WechatPayUtil.getSign(signatureStr, WechatPayData.privateKeyPath);
//            } catch (Exception e) {
//                log.error("获取签名失败，");
//                throw new RuntimeException("支付失败");
//            }
//            response.setAppId(appId);
//            response.setTimeStamp(String.valueOf(timeStamp));
//            response.setNonceStr(nonceStr);
//            response.setSignType(signType);
//            response.setPackage_(prepayIds);
//            response.setPaySign(paySign);
//            response.setOrderId(prepayId);
            return response;

        }catch (Exception e){
            log.error("支付方法异常", e);
            throw new RuntimeException(e.getMessage());
        }finally {
            try{
                redisService.unLock(redisKey,redisValue);
            }catch (Exception e){
                log.error("",e);
            }
        }
    }





    protected AjaxResult toAjax(int rows) {
        return rows > 0 ? AjaxResult.success() : AjaxResult.error();
    }
}
