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

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bohuikeji.delivery.backstage.entity.*;
import com.bohuikeji.delivery.backstage.entity.wx.TWxUser;
import com.bohuikeji.delivery.backstage.listener.order.OrderCreateListener;
import com.bohuikeji.delivery.backstage.listener.order.OrderDelayCancelListener;
import com.bohuikeji.delivery.backstage.service.*;
import com.bohuikeji.delivery.backstage.service.third.ThirdUtils;
import com.bohuikeji.frame.module.admin.base.ApiController;
import com.bohuikeji.frame.module.admin.component.MqTool;
import com.bohuikeji.frame.module.admin.component.RedisUtil;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.entity.sys.SysConfig;
import com.bohuikeji.frame.module.admin.entity.vo.AddressVo;
import com.bohuikeji.frame.module.admin.service.ISysConfigService;
import com.bohuikeji.frame.module.admin.utils.*;
import com.bohuikeji.frame.module.admin.utils.wx.WxUtils;
import com.google.common.primitives.Ints;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import jodd.http.HttpRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author zhouliwu
 * 客户相关接口
 */
@Slf4j
@Api(tags = {"支付客户登陆相关接口"})
@RestController
@RequestMapping("/api/ali/log")
public class aliLandApi extends ApiController {
    @Autowired
    ITCustomerService customerService;
    @Autowired
    ITOrderService orderService;
    @Autowired
    ITCustomerWalletService customerWalletService;
    @Autowired
    ITCustomerAddressService itCustomerAddressService;
    @Autowired
    ISysConfigService sysConfigService;
    @Autowired
    ITCourierService courierService;
    @Autowired
    IWxUserService wxUserService;
    @Autowired
    ITNewsService newsService;
    @Autowired
    MqTool mqTool;
    @Autowired
    IGmsService gmsService;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    CustomerV2Api customerV2Api;



    /**
     * 客户App注册/验证码登陆
     * @return
     */
    @ApiOperation("客户App注册/验证码登陆")
    @ApiImplicitParams({
            @ApiImplicitParam(name="customerPhone",value="客户手机号",dataType="String", paramType = "query",example="15771331234",required=true),
            @ApiImplicitParam(name="verCode",value="短信验证码",dataType="String", paramType = "query",example="",required=true),
            @ApiImplicitParam(name="aliCode",value="授权code",dataType="String", paramType = "query",example="",required=true),
            @ApiImplicitParam(name="channel",value="授权标识",dataType="String", paramType = "query",example="",required=true)})
    @PostMapping("/login/register")
    public APIEntity loginRegister(String customerPhone,String verCode,String aliCode,String channel,@RequestHeader String token){
        Object code = redisUtil.get("gms:customer:"+customerPhone);
        String num=NumberUtils.getShort();
        if(code==null){
            return APIEntity.fail("验证码无效，请重新获取！");
        }
        if (!code.toString().equals(verCode)){
            return APIEntity.fail("验证码错误！");
        }
        TCustomer customer= customerService.getOne(new QueryWrapper<TCustomer>().notIn("customer_status","已注销").eq("customer_phone",customerPhone),false);
        // 清理使用过的token
        redisUtil.del(token);
        if(customer != null) {
            if("微信用户".equals(customer.getCustomerName())){
                customer.setCustomerName("客户"+num);
                customerService.updateById(customer);
            }
        }else {
            customer = new TCustomer();
            customer.setCustomerName("客户"+num);
            customer.setCustomerPhone(customerPhone);
            customer.setCustomerPwd("000000");
            customer.setCustomerStatus("已激活");
            //tCustomer.setRegistratMeth("APP");
            customer.setCreateTime(LocalDateTime.now());
            customer.setUpdateTime(LocalDateTime.now());
            if (!customerService.save(customer)) {
                log.error("派送员注册失败，创建失败，派送员：" + customer);
                return APIEntity.fail("系统繁忙，请稍后重试！");
            }
        }
        customerV2Api.grantChannel(customer.getCustomerId(),aliCode,channel);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("customerId",customer.getCustomerId());
        jsonObject.put("customerPhone",customer.getCustomerPhone());
        jsonObject.put("token",JwtTokenUtil.createToken("客户",customer.getCustomerId()));
        jsonObject.put("isType",customer.getIsType());
        return APIEntity.success(jsonObject);
    }


    /**
     *客户App获取验证码
     * @return
     */
    @ApiOperation("客户App获取验证码(手机号、验证码登陆）")
    @ApiImplicitParams({
            @ApiImplicitParam(name="customerPhone",value="客户手机号",dataType="String", paramType = "query",example="15500000000",required=true)})
    @GetMapping("/get/code")
    public APIEntity getVerCode(String customerPhone,HttpServletRequest request){
        if(StringUtils.isBlank(customerPhone)){
            return APIEntity.fail("手机号不能为空");
        }
        if("15295598596".equals(customerPhone)){
            return APIEntity.fail("该账户已注销");
        }
        String code=gmsService.sendCode(customerPhone,request);
        //10分钟有效
        redisUtil.set("gms:customer:"+customerPhone,code,60*10);
        return APIEntity.success(code);
    }


}
