package com.bohuikeji.delivery.backstage.controller.admin;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bohuikeji.delivery.backstage.entity.TCustomer;
import com.bohuikeji.delivery.backstage.entity.TCustomerBig;
import com.bohuikeji.delivery.backstage.service.IGmsService;
import com.bohuikeji.delivery.backstage.service.ITCustomerBigService;
import com.bohuikeji.delivery.backstage.service.ITCustomerService;
import com.bohuikeji.delivery.backstage.service.ITMaltFieldService;
import com.bohuikeji.delivery.backstage.util.maiyatian.maltUtils;
import com.bohuikeji.frame.module.admin.base.ControllerBase;
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.AddressVo;
import com.bohuikeji.frame.module.admin.service.ISysMenuService;
import com.bohuikeji.frame.module.admin.service.ISysUserService;
import com.bohuikeji.frame.module.admin.utils.MapUtils;
import com.bohuikeji.frame.module.admin.utils.NumberUtils;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import com.wf.captcha.utils.CaptchaUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.net.URL;
import java.net.URLDecoder;
import java.time.LocalDateTime;


/**
 * 登陆，登出等处理
 * @author 10552
 */
@RestController
@RequestMapping("/grant")
@Slf4j
public class GrantLoginController extends ControllerBase {
    @Autowired
    ISysUserService userService;
    @Autowired
    ISysMenuService menuService;
    @Autowired
    IGmsService gmsService;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    ITCustomerService customerService;
    @Autowired
    ITMaltFieldService maltFieldService;
    @Autowired
    ITCustomerBigService customerBigService;

    /**
     *客户App获取验证码
     * @return
     */
    @GetMapping("/get/malt/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("发送成功");
    }


    /**
     * 客户App密码登录
     * @param customerPhone
     * @param customerPwd
     * @param request
     * @returnzhang'j'ao
     */
    //@InitLog(value = "系统框架——用户登陆",action = "登陆")
    @GetMapping(value="/authorized/login")
    public APIEntity phoneByPwdLogin(String customerPhone,String captcha,HttpServletRequest request) throws Exception {
        Object code = redisUtil.get("gms:customer:"+customerPhone);
        if(code==null){
            return APIEntity.fail("验证码无效，请重新获取！");
        }
        if(!code.toString().equals(captcha)){
            return APIEntity.fail("验证码错误！");
        }
        TCustomer customer =customerService.getOne(new QueryWrapper<TCustomer>().notIn("customer_status","已注销").eq("customer_phone",customerPhone));
        if (customer==null){
            return APIEntity.fail("账号不存在！");
        }
        TCustomerBig customerBig = customerBigService.getOne(new QueryWrapper<TCustomerBig>().eq("customer_id",customer.getCustomerId()));
        if(customerBig==null){
            return APIEntity.fail("未添加商户信息，无法授权，请去APP或小程序中“绑定商户”添加商户信息！");
        }else {
            customerBig.setBigNum(NumberUtils.getRandom(6));
            customerBigService.updateById(customerBig);
        }
        String value = request.getHeader("referer");
        URL path = new URL(value);
        JSONObject jsonObject = new JSONObject();
        String queryString = path.getQuery();
        String[] array = queryString.split("&");
        for (String str : array) {
            String[] pair = str.split("=");
            jsonObject.put(pair[0],pair[1]);
        }
        String urls = URLDecoder.decode(jsonObject.getString("redirect_uri"),"UTF-8");
        AddressVo adrass= MapUtils.getAddressGeo(customerBig.getBigAddress());
        JSONObject tokenjsn = maltUtils.getAccessToken(jsonObject.getString("code"),customerPhone,customerBig.getBigNum(),adrass);
        log.info("@@@@@@@@@@@@@@@@麦芽田换取TOKEN:{}",tokenjsn);
        if(tokenjsn == null){
            return APIEntity.fail("获取TOKEN失败！");
        }
        if(tokenjsn != null && tokenjsn.getInteger("code") == 500){
            return APIEntity.fail(tokenjsn.getString("msg"));
        }
        JSONObject data = JSONObject.parseObject(tokenjsn.getString("data"));
        maltFieldService.saveMalt(data,customer);
        log.info("@@@@@@@@@@@@@@@@重定向地址:{}",StrUtil.format(urls+"?state={}",jsonObject.getString("state")));
        return APIEntity.success(StrUtil.format(urls+"?state={}",jsonObject.getString("state")));
    }
}
