package com.ruoyi.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.annotations.UserLoginToken;
import com.ruoyi.code.PublicCommon;
import com.ruoyi.common.exception.enums.CoreExceptionEnum;
import com.ruoyi.controller.req.*;
import com.ruoyi.controller.resp.UserResultInfo;
import com.ruoyi.enums.user.UserEnums;
import com.ruoyi.frequency.customer.entity.Customer;
import com.ruoyi.frequency.customer.service.CustomerService;
import com.ruoyi.frequency.customer.service.UserService;
import com.ruoyi.frequency.enterprise.service.EnterpriseService;
import com.ruoyi.frequency.sale.entity.Sale;
import com.ruoyi.frequency.sale.service.SaleService;
import com.ruoyi.frequency.store.entity.Store;
import com.ruoyi.frequency.store.service.StoreService;
import com.ruoyi.response.ResponseData;
import com.ruoyi.utils.LoginUtil;
import com.ruoyi.vo.RyController;
import com.ruoyi.vo.UserInfo;
import com.ruoyi.vo.UserVo;
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.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.util.HashMap;
import java.util.Map;

/**
 * 登入相关
 *
 * @author liwenlong
 */
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/api")
@Api(tags = "登入相关")
public class ApiCLoginController extends RyController {

    @Autowired
    private LoginUtil loginUtil;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private StoreService storeService;

    @Autowired
    private SaleService saleService;


    /**
     * 注册
     *
     * @param req
     * @return
     */
    @PostMapping("/register")
    @ApiOperation(value = "注册")
    public ResponseData register(@Valid @RequestBody RegisterUserReq req) {
        return loginUtil.register(req);
    }

    /**
     * 忘记密码
     *
     * @param req
     * @return
     */
    @RequestMapping(value = "/forgetPwd", method = RequestMethod.POST)
    @ApiOperation(value = "忘记密码")
    public ResponseData forgetPwd(@RequestBody @Valid UserForgetPwdLoginReq req) {
        return loginUtil.forgetPwd(req);
    }

    /**
     * 修改密码
     *
     * @param req
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/editPwd", method = RequestMethod.POST)
    @ApiOperation(value = "修改密码")
    public ResponseData editPwd(@RequestBody UserEditPwdLoginReq req) {
        return loginUtil.editPwd(req, getUserVo());
    }

    /**
     * 忘记支付密码
     *
     * @param req
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/forgetPayPwd", method = RequestMethod.POST)
    @ApiOperation(value = "忘记支付密码")
    public ResponseData forgetPayPwd(@RequestBody @Valid UserForgetPwdLoginReq req) {
        return loginUtil.forgetPayPwd(req, getUserVo());
    }

    /**
     * 校验支付密码
     *
     * @param pwd
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/checkPayPwd", method = RequestMethod.POST)
    @ApiOperation(value = "校验支付密码")
    public ResponseData checkPayPwd(@NotEmpty(message = "密码不能为空") @RequestBody String pwd) {
        return loginUtil.checkPayPwd(pwd, getUserVo());
    }

    /**
     * 修改支付密码
     *
     * @param pwd
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/editPayPwd", method = RequestMethod.POST)
    @ApiOperation(value = "修改支付密码")
    public ResponseData editPayPwd(@NotEmpty(message = "密码不能为空") @RequestBody String pwd) {
        return loginUtil.editPayPwd(pwd, getUserVo());
    }

    /**
     * 退出
     *
     * @return
     */
    @UserLoginToken
    @PostMapping("/logout")
    @ApiOperation(value = "退出")
    public ResponseData logout() {
        return loginUtil.logout(getUserVo());
    }


    /**
     * 注销
     *
     * @return
     */
    @PostMapping("/cancellation")
    @UserLoginToken
    @ApiOperation(value = "注销")
    public ResponseData cancellation() {
        UserVo userVo = getUserVo();
        //判断是否可以注销
        if (UserEnums.customer.getCode().equals(userVo.getUserType())) {
            customerService.canCancellation(userVo.getUserId());
        } else if (UserEnums.store.getCode().equals(userVo.getUserType())) {
            storeService.canCancellation(userVo.getUserId());
        }

        return loginUtil.cancellation(userVo);
    }

    /**
     * 校验旧手机号
     *
     * @param req
     * @return
     */
    @RequestMapping(value = "/checkOldMobile", method = RequestMethod.POST)
    @ApiOperation(value = "校验旧手机号")
    @UserLoginToken
    public ResponseData checkOldMobile(@RequestBody @Valid CheckOldMobileReq req) {
        return loginUtil.checkOldMobile(req, getUserVo());
    }


    /**
     * 换绑手机号
     *
     * @param req
     * @return
     */
    @RequestMapping(value = "/changeBindingMobile", method = RequestMethod.POST)
    @ApiOperation(value = "换绑手机号")
    @UserLoginToken
    public ResponseData changeBindingMobile(@RequestBody @Valid ChangeBindingMobileReq req) {
        return loginUtil.changeBindingMobile(req, getUserVo());
    }


    /**
     * 对方
     *
     * @param otherUserVo
     * @return
     */
    @RequestMapping(value = "/userRelationship", method = RequestMethod.POST)
    @ApiOperation(value = "获取两个用户之间的关系")
    @UserLoginToken
    public ResponseData userRelationship(@RequestBody @Valid UserVo otherUserVo) {
        return userService.userRelationship(otherUserVo, getUserVo());
    }


    /**
     * 修改用户信息
     *
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/editInfo", method = RequestMethod.POST)
    @ApiOperation(value = "修改用户信息")
    public ResponseData editInfo(@RequestBody UserEditReqVo req) {

        UserVo userVo = getUserVo();

        //用户类型 1设计师 2表现师 3销售(推广员)

        if (ObjectUtil.equal(userVo.getUserType(), PublicCommon.设计师)) {
            return customerService.editInfo(req, userVo);
        } else if (ObjectUtil.equal(userVo.getUserType(), PublicCommon.表现师)) {
            return storeService.editInfo(req, userVo);
        } else if (ObjectUtil.equal(userVo.getUserType(), PublicCommon.销售)) {
            return saleService.editInfo(req, userVo);
        } else if (ObjectUtil.equal(userVo.getUserType(), PublicCommon.企业)) {
            return enterpriseService.editInfo(req, userVo);
        }
        return ResponseData.error(CoreExceptionEnum.ERROR_PARAM);

    }


    /**
     * 个人信息
     *
     * @return
     */
    @UserLoginToken
    @PostMapping("/info")
    @ApiOperation(value = "个人信息", notes = "个人信息")
    public ResponseData info() {

        UserVo userVo = getUserVo();

        Map<UserVo, UserInfo> userVoUserInfoMap = userService.selectUserInfoMap(CollectionUtil.newHashSet(userVo), userVo);

        //用户类型 1设计师 2表现师 3销售(推广员)
        if (ObjectUtil.equal(userVo.getUserType(), PublicCommon.设计师)) {
            UserResultInfo userResultInfo = (UserResultInfo) customerService.info(userVo).getData();
            userResultInfo.setUserInfo(userVoUserInfoMap.get(userVo));
            return ResponseData.success(userResultInfo);
        } else if (ObjectUtil.equal(userVo.getUserType(), PublicCommon.表现师)) {
            Store store = (Store) storeService.info(userVo).getData();
            store.setUserInfo(userVoUserInfoMap.get(userVo));
            return ResponseData.success(store);
        } else if (ObjectUtil.equal(userVo.getUserType(), PublicCommon.销售)) {
            Sale sale = (Sale) saleService.info(userVo).getData();
            sale.setUserInfo(userVoUserInfoMap.get(userVo));
            return ResponseData.success(sale);
        } else if (ObjectUtil.equal(userVo.getUserType(), PublicCommon.企业)) {
            Store one = storeService.getOne(new QueryWrapper<Store>().lambda().eq(Store::getBindEnterpriseId, userVo.getUserId()));

            if (one == null) {
                return ResponseData.error(700, "token过期");
            }
            Store store = (Store) storeService.info(new UserVo(UserEnums.store.getCode(), one.getId())).getData();
            store.setUserInfo(userVoUserInfoMap.get(userVo));
            return ResponseData.success(store);
        }

        return ResponseData.error(CoreExceptionEnum.ERROR_PARAM);
    }

    @Autowired
    private UserService userService;

    @Autowired
    private EnterpriseService enterpriseService;

    /**
     * 查看他人信息
     *
     * @return
     */
    @PostMapping("/otherInfo")
    @ApiOperation(value = "查看他人信息", notes = "查看他人信息")
    public ResponseData otherInfo(@RequestBody UserVo userVo) {

        UserVo userVo1 = getUserVo();
        Map<UserVo, UserInfo> userVoUserInfoMap = userService.selectUserInfoMap(CollectionUtil.newHashSet(userVo), userVo1);
        //用户类型 1设计师 2表现师 3销售(推广员)
        if (ObjectUtil.equal(userVo.getUserType(), PublicCommon.设计师)) {
            UserResultInfo userResultInfo = (UserResultInfo) customerService.info(userVo).getData();
            userResultInfo.setUserInfo(userVoUserInfoMap.get(userVo));
            return ResponseData.success(userResultInfo);
        } else if (ObjectUtil.equal(userVo.getUserType(), PublicCommon.表现师)) {
            Store store = (Store) storeService.info(userVo).getData();
            store.setUserInfo(userVoUserInfoMap.get(userVo));
            return ResponseData.success(store);
        } else if (ObjectUtil.equal(userVo.getUserType(), PublicCommon.销售)) {
            Sale sale = (Sale) saleService.info(userVo).getData();
            sale.setUserInfo(userVoUserInfoMap.get(userVo));
            return ResponseData.success(sale);
        } else if (ObjectUtil.equal(userVo.getUserType(), PublicCommon.企业)) {
            Store one = storeService.getOne(new QueryWrapper<Store>().lambda().eq(Store::getBindEnterpriseId, userVo.getUserId()));
            Store store = new Store();
            if (one != null) {
                store = (Store) storeService.info(new UserVo(UserEnums.store.getCode(), one.getId())).getData();
            } else {
                store.setEnterprise(enterpriseService.getById(userVo.getUserId()));
            }

            store.setUserInfo(userVoUserInfoMap.get(userVo));
            return ResponseData.success(store);
        }

        return ResponseData.error(CoreExceptionEnum.ERROR_PARAM);
    }

    @Value("${wxpay.appid}")
    private String appId;

    @Value("${wxpay.app-secret}")
    private String appSecret;

    /**
     * 获取wxopenId
     *
     * @return
     */
    @PostMapping("/getWxOpenId")
    @ApiOperation(value = "获取wxopenId", notes = "获取wxopenId")
    public ResponseData getWxOpenId(@RequestBody String code) {
        //2.判断是否授权成功
        if (StrUtil.isBlank(code)) {
            log.info("-----------no shou quan!-------------------");
            return ResponseData.error("授权失败");
        }

        //4.获取access_token,以及通过token获取openid
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=" + appId +
                "&secret=" + appSecret +
                "&code=" + code +
                "&grant_type=authorization_code";
        String result = HttpUtil.get(url);
        log.info("请求获取的access_token值是：" + result);
        JSONObject resultObject = JSONObject.parseObject(result);
        System.out.println("-----" + JSONObject.toJSONString(resultObject));
        //获取openid
        String unionid = (String) resultObject.get("unionid");
        return ResponseData.success(unionid);
    }


    @PostMapping("/getAppletOpenId/{type}")
    @ApiOperation(value = "获取小程序openId", notes = "获取小程序openId")
    public ResponseData getAppletOpenId(@PathVariable("type") String type, @RequestBody String code) {
        if (code == null) {
            return ResponseData.error("暂未授权！");
        }

        String appid = "";

        String secret = "";

        //type :  DD_drawing DD画图, DD_co_creation DD共创
        if (ObjectUtil.equal(type, "DD_drawing")) {
            appid = DD_drawingAppId;

            secret = DD_drawingSecret;
        } else {
            appid = DD_co_creationAppId;

            secret = DD_co_creationSecret;
        }

        //1.通过code获取openId
        String str = "https://api.weixin.qq.com/sns/jscode2session?appid=" +
                appid +
                "&secret=" +
                secret +
                "&js_code=" +
                code +
                "&grant_type=authorization_code";
        String result = HttpUtil.get(str);

        //判断是否获取成功
        if (ObjectUtil.isEmpty(result)) {
            return ResponseData.error("获取参数错误");
        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        //System.out.println("-----" + JSONObject.toJSONString(jsonObject));
        //String unionid = (String) jsonObject.get("unionid");
        return ResponseData.success(jsonObject);
    }

    @PostMapping("/getAppletMobile/{type}")
    @ApiOperation(value = "获取小程序手机号", notes = "获取小程序手机号")
    public ResponseData getAppletMobile(@PathVariable("type") String type, @RequestBody String code) {
        if (code == null) {
            return ResponseData.error("暂未授权！");
        }

        //1.通过code获取手机号
        String str = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + getToken(type);
        Map<String, Object> bodyMap = new HashMap<>();
        bodyMap.put("code", code);
        String result = HttpUtil.createPost(str).body(JSONObject.toJSONString(bodyMap)).execute().body();

        System.out.println(result);
        //判断是否获取成功
        if (ObjectUtil.isEmpty(result)) {
            return ResponseData.error("获取参数错误");
        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        Map map = (Map) jsonObject.get("phone_info");
        return ResponseData.success(map);
    }


    //https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=ACCESS_TOKEN

    @Value("${DD_drawing.appid}")
    private String DD_drawingAppId;

    @Value("${DD_drawing.secret}")
    private String DD_drawingSecret;

    @Value("${DD_co_creation.appid}")
    private String DD_co_creationAppId;

    @Value("${DD_co_creation.secret}")
    private String DD_co_creationSecret;

    /**
     * 获取access_token
     *
     * @return
     */
    public String getToken(String type) {

        String appid = "";

        String secret = "";

        //type :  DD_drawing DD画图, DD_co_creation DD共创
        if (ObjectUtil.equal(type, "DD_drawing")) {
            appid = DD_drawingAppId;

            secret = DD_drawingSecret;
        } else {
            appid = DD_co_creationAppId;

            secret = DD_co_creationSecret;
        }

        String url = "https://api.weixin.qq.com/cgi-bin/token" + "?grant_type=" + "client_credential" + "&appid=" + appid + "&secret=" + secret;
        String result = HttpRequest.get(url).execute().body();
        System.err.println(result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        //服务断了status会有值
        Integer errcode = (Integer) jsonObject.get("errcode");
        if (errcode == null) {
            String access_token = (String) jsonObject.get("access_token");
            return access_token;
        } else {
            log.info("获取access_token失败:{}", jsonObject.toJSONString());
        }
        return "";
    }

    public static void main(String[] args) {
        //Map<String, Object> map = new HashMap<>();
        //map.put("code", "554547887");
        //System.out.println(JSONObject.toJSONString(map));

        String url = "https://api.weixin.qq.com/cgi-bin/token" + "?grant_type=" + "client_credential" + "&appid=" + "wxed96e8fe10ea8992" + "&secret=" + "5a1da24f97e49aa5762897045dd593b6";
        String result = HttpRequest.get(url).execute().body();
        System.err.println(result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        //服务断了status会有值
        Integer errcode = (Integer) jsonObject.get("errcode");
        if (errcode == null) {
            String access_token = (String) jsonObject.get("access_token");
            System.out.printf(access_token);
        } else {
            log.info("获取access_token失败:{}", jsonObject.toJSONString());
        }
    }
}
