package com.bohuikeji.delivery.backstage.controller.api.v2;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bohuikeji.delivery.backstage.constants.WxAppEm;
import com.bohuikeji.delivery.backstage.entity.AliPayConfig;
import com.bohuikeji.delivery.backstage.entity.TCourier;
import com.bohuikeji.delivery.backstage.entity.TCourierCard;
import com.bohuikeji.delivery.backstage.entity.TCustomer;
import com.bohuikeji.delivery.backstage.entity.wx.TWxUser;
import com.bohuikeji.delivery.backstage.pay.KuaiShouPay;
import com.bohuikeji.delivery.backstage.service.*;
import com.bohuikeji.frame.module.admin.base.ApiController;
import com.bohuikeji.frame.module.admin.component.RedisUtil;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.entity.vo.WXPayVo;
import com.bohuikeji.frame.module.admin.service.ISysConfigService;
import com.bohuikeji.frame.module.admin.service.ITFranchiseeInformationService;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;


@Api(tags = {"app绑定微信功能"})
@RestController
@Slf4j
@RequestMapping("/api/v2/bind")
@RequiredArgsConstructor
public class WxAppLoginV2Api extends ApiController {

    final ITOrderService orderService;
    final RedisUtil redisUtil;
    final RabbitTemplate rabbitTemplate;
    final ISysConfigService sysConfigService;
    final ITCourierService courierService;
    final ITNewsService newsService;
    final ITPayService payService;
    final ITRefundService refundService;
    final ITCustomerService customerService;
    final ITCustomerWalletService customerWalletService;
    final ITCustomerPayService customerPayService;
    final ITwxtransfersService twxtransfersService;
    final ITwalletDetailService twalletDetailService;
    final ITFranchiseeInformationService franServer;
    final ITCustomerBigService customerBigService;
    final ITCustomerTemplateService customerTemplateService;
    final ITCourierCardService itCourierCardService;
    final IWxUserService wxUserService;


    @ApiOperation("获取客户App绑定微信状态")
    @GetMapping("/cust/bindinfo")
    public APIEntity custBindInfo(@RequestAttribute("JwtUserId") Integer id) {
        TCustomer customer = customerService.getOne(new QueryWrapper<TCustomer>().eq("customer_id",id));
        if(StringUtils.isBlank(customer.getCustAppOpenId())){
            return APIEntity.success("未绑定");
        }
        return APIEntity.success("已绑定");
    }

    /**
     * 客户App绑定微信用户
     * 获取微信用户信息
     * @param id
     * @param
     * @return
     */
    @ApiOperation("客户App绑定微信")
    @GetMapping("/custinfo")
    public APIEntity custUserInfo(@RequestAttribute("JwtUserId") Integer id,String openId) {
        TCustomer customer = customerService.getOne(new QueryWrapper<TCustomer>().eq("customer_id",id));
        if(customer==null){
            return APIEntity.fail("无法识别用户信息").setStatus(412);
        }
        if(StringUtils.isBlank(customer.getCustAppOpenId())){
            customer.setCustAppOpenId(openId);
            customerService.updateById(customer);
            return APIEntity.success(customer);
        }
        return APIEntity.success(customer);
    }

    /**
     * 客户App绑定微信
     * @param id
     * @param openId
     * @return
     */
    @ApiOperation("客户App绑定微信")
    @PostMapping("/app/bind/wx")
    @ApiImplicitParams({})
    public APIEntity kuaishouAuthorization(@RequestAttribute("JwtUserId") Integer id,String openId){
        TCustomer customer = customerService.getOne(new QueryWrapper<TCustomer>().eq("customer_id",id));
        if(openId == null){
            return APIEntity.fail("未获取微信用户openid");
        }
        TWxUser wxUser = new TWxUser();
        wxUser.setUserId(Long.valueOf(customer.getCustomerId()));
        wxUser.setUserType(WxAppEm.WX_USER_TYPE_CUSTOMER);
        wxUser.setWxAppId(WXPayVo.getCustAppID());
        wxUser.setWxAppType("WxApp");
        wxUser.setWxAppName("客户端App（微信）");
        wxUser.setWxUserOpenid(openId);
        wxUserService.save(wxUser);
        return APIEntity.success("授权成功");
    }


    @ApiOperation("获取骑手App绑定微信状态")
    @GetMapping("/cour/bindinfo")
    public APIEntity courBindInfo(@RequestAttribute("JwtUserId") Integer id) {
        TCourierCard courierCard = itCourierCardService.getOne(new QueryWrapper<TCourierCard>().eq("courier_id",id).eq("card_bank","微信"),false);
        if(courierCard == null){
            return APIEntity.success("未绑定");
        }
        return APIEntity.success("已绑定");
    }

    /**
     * 骑手App绑定微信用户
     * @param id
     * @param openId
     * @return
     */
    @ApiOperation("骑手App绑定微信")
    @GetMapping("/courinfo")
    public APIEntity courUserInfo(@RequestAttribute("JwtUserId") Integer id,String openId) {
        TCourier courier = courierService.getOne(new QueryWrapper<TCourier>().eq("courier_id",id));
        if(courier==null){
            return APIEntity.fail("无法识别用户信息").setStatus(412);
        }
        TCourierCard card=new TCourierCard();
        card.setCreateDate(LocalDateTime.now());
        card.setCardName(courier.getCourierName());
        card.setIdNumber(courier.getCourierCard());
        card.setCourierId(id);
        card.setCardBank("微信");
        card.setCardNum(openId);
        card.setBankType("APP");
        return APIEntity.success(itCourierCardService.save(card));
    }
   /* @ApiOperation("App绑定微信，获取微信用户信息")
    @PostMapping("/courinfo")
    public APIEntity courUserInfo(@RequestAttribute("JwtUserId") Integer id,String code) {
        TCourier courier = courierService.getOne(new QueryWrapper<TCourier>().eq("customer_id",id));
        if(courier==null){
            return APIEntity.fail("无法识别用户信息").setStatus(412);
        }
        //获取微信用户信息
        JSONObject wxUserInfoJson= WxAppLoginUtils.custhatLogin(code);
        if(wxUserInfoJson==null){
            log.error("更新用户信息失败，用户:[{}],ID=[{}]，未授权",courier.getCourierName(),courier.getCourierId());
            return APIEntity.fail("用户未授权");
        }
        if(courier.getCourierPhone().equals(wxUserInfoJson.getString("phoneNumber"))){
            return APIEntity.fail("当前登陆的手机号与微信绑定的手机号不一致，请检查");
        }
        log.info("骑手端绑定微信获取openId:[{}]",wxUserInfoJson.getString("openId"));
        TCourierCard card=new TCourierCard();
        card.setCreateDate(LocalDateTime.now());
        card.setCardName(courier.getCourierName());
        card.setIdNumber(courier.getCourierCard());
        card.setCourierId(id);
        card.setCardBank("微信");
        card.setCardNum(wxUserInfoJson.getString("openId"));
        //courier.setCustAppOpenId(wxUserInfoJson.getString("openId"));
        //customerService.updateById(courier);
        return APIEntity.success(courier);
    }*/

}
