package com.cweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.cweb.config.SysConst;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.security.*;
import com.hai.common.utils.ImageUtils;
import com.hai.common.utils.RedisUtil;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.config.CommonConfig;
import com.hai.entity.HighOrder;
import com.hai.entity.HighUser;
import com.hai.entity.HighUserCoupon;
import com.hai.entity.HighUserPayPassword;
import com.hai.model.HighUserModel;
import com.hai.model.ResponseData;
import com.hai.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Auther: 袁野
 * @Description:
 * @Date: 2021/3/30 22:50
 */
@Controller
@RequestMapping(value = "/highUser")
@Api(value = "用户接口")
public class HighUserController {

    private static Logger log = LoggerFactory.getLogger(HighMerchantStoreController.class);

    @Autowired
    private UserCenter userCenter;

    @Resource
    private HighUserService highUserService;

    @Resource
    private HighUserPayPasswordService highUserPayPasswordService;

    @Resource
    private HltUnionCardVipService hltUnionCardVipService;

    @Resource
    private BsDistributionUserRelService bsDistributionUserRelService;

    @Resource
    private HighOrderService highOrderService;

    @Resource
    private RedisUtil redisUtil;

    @RequestMapping(value = "/findUser", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据id查询详情")
    public ResponseData findById( HttpServletRequest request) {
        try {
            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();

            return ResponseMsgUtil.success(highUserService.getDetailDataByUser(userInfoModel.getHighUser().getId()));

        } catch (Exception e) {
            log.error("HighUserController --> findByUserId() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value = "/bindUserPhone", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "绑定用户手机号")
    public ResponseData bindUserPhone(@RequestParam(value = "phone", required = true) String phone,
                                        @RequestParam(value = "code", required = true) String code,
                                        HttpServletRequest request, HttpServletResponse response) {
        try {
            VerifyCode verifyCode = VerifyCodeStorage.getDate(phone);
            if(verifyCode == null) {
                log.error("HighUserController --> bindUserPhone() error!", "验证码错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "验证码错误");
            }
            if(!verifyCode.getObject().equals(code)) {
                log.error("HighUserController --> bindUserPhone() error!", "验证码错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "验证码错误");
            }

            HighUser highUser = highUserService.bindUserPhone(phone, request);

            // 定义个人所有数据
            HighUserModel highUserModel = new HighUserModel();
            HighUser detailData = highUserService.getDetailDataByUser(highUser.getId());
            detailData.setPassword(null);
            highUserModel.setHighUser(detailData);
            SessionObject so = new SessionObject(detailData.getPhone(), 1 , highUserModel);
            return ResponseMsgUtil.success(so);

        } catch (Exception e) {
            log.error("HighUserController --> bindUserPhone() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/isSetPayPwd", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "用户是否设置支付密码")
    public ResponseData isSetPayPwd(HttpServletRequest request) {
        try {
            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();
            return ResponseMsgUtil.success(highUserPayPasswordService.isSetPayPwd(userInfoModel.getHighUser().getId()));

        } catch (Exception e) {
            log.error("HighUserController --> setUserPayPwd() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/setUserPayPwd", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "设置用户支付密码")
    public ResponseData setUserPayPwd(@RequestBody JSONObject body,HttpServletRequest request, HttpServletResponse response) {
        try {
            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();

            if (StringUtils.isBlank(body.getString("password"))
                    || body.getString("password").length() != 6){
                log.error("HighUserController --> setUserPayPwd() error!", "请设置6位支付密码");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "请设置6支付密码");
            }

            // 查询用户密码
            HighUserPayPassword userPayPassword = highUserPayPasswordService.getDetailByUser(userInfoModel.getHighUser().getId());
            if (userPayPassword != null) {
                log.error("HighUserController --> setUserPayPwd() error!", "您已设置了支付密码");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REPEAT_SET_USER_PAY_PWD, "");
            }

            userPayPassword = new HighUserPayPassword();
            userPayPassword.setUserId(userInfoModel.getHighUser().getId());
            userPayPassword.setPassword(AESEncodeUtil.aesEncrypt(body.getString("password")));
            highUserPayPasswordService.editUserPayPwd(userPayPassword);

            // 定义个人所有数据
            HighUserModel highUserModel = new HighUserModel();
            HighUser detailData = highUserService.getDetailDataByUser(userInfoModel.getHighUser().getId());
            detailData.setPassword(null);
            highUserModel.setHighUser(detailData);
            SessionObject so = new SessionObject(detailData.getPhone(), 1 , highUserModel);
            return ResponseMsgUtil.success(so);

        } catch (Exception e) {
            log.error("HighUserController --> setUserPayPwd() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/updateUserPayPwd", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改用户支付密码")
    public ResponseData updateUserPayPwd(@RequestBody JSONObject body,HttpServletRequest request, HttpServletResponse response) {
        try {
            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();
            if ( StringUtils.isBlank(body.getString("newPassword")) || StringUtils.isBlank(body.getString("code"))) {
                log.error("HighUserController --> setUserPayPwd() error!", "");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 查询用户密码
            HighUserPayPassword userPayPassword = highUserPayPasswordService.getDetailByUser(userInfoModel.getHighUser().getId());
            if (userPayPassword == null) {
                log.error("HighUserController --> setUserPayPwd() error!", "修改失败，未设置支付密码");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_SET_USER_PAY_PWD, "");
            }

            // 获取手机号验证码
            String phoneSmsCode = (String) redisUtil.get("SMS_"+ userInfoModel.getHighUser().getPhone());
            // 验证码校验
            if (StringUtils.isNotBlank(phoneSmsCode) && Objects.equals(phoneSmsCode,body.getString("code"))) {
                userPayPassword.setPassword(AESEncodeUtil.aesEncrypt(body.getString("newPassword")));
                highUserPayPasswordService.editUserPayPwd(userPayPassword);
                return ResponseMsgUtil.success("操作成功");
            } else {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "操作失败");
            }

        } catch (Exception e) {
            log.error("HighUserController --> updateUserPayPwd() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/setCacheParam",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "设置用户参数")
    public ResponseData setCacheParam(@RequestBody JSONObject body) {
        try {
            if (body == null
                    || StringUtils.isBlank(body.getString("key"))
                    || StringUtils.isBlank(body.getString("value"))) {
                log.error("HighUserController --> setUserPayPwd() error!", "请求参数校验失败");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            redisUtil.hset("PROVISIONAL_CACHE_PARAM", body.getString("key"), body.getString("value"), 60*5);

            return ResponseMsgUtil.success("设置成功");

        } catch (Exception e) {
            log.error("CommonController --> setCacheParam() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/getCacheParam",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取设置用户参数")
    public ResponseData getCacheParam(@RequestParam(name = "key", required = true) String key) {
        try {

            return ResponseMsgUtil.success(redisUtil.hget("PROVISIONAL_CACHE_PARAM", key));

        } catch (Exception e) {
            log.error("CommonController --> getCacheParam() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/delCacheParam",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "删除设置用户参数")
    public ResponseData delCacheParam(@RequestParam(name = "key", required = true) String key) {
        try {

            Object param = redisUtil.hget("PROVISIONAL_CACHE_PARAM", key);
            if (param != null) {
                redisUtil.hdel("PROVISIONAL_CACHE_PARAM", key);
            }
            return ResponseMsgUtil.success("操作成功");

        } catch (Exception e) {
            log.error("CommonController --> delCacheParam() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/GetMembershipLevel", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "请求会员体系")
    public ResponseData GetMembershipLevel(@RequestParam(name = "phone", required = true) String phone , @RequestParam(name = "regionId", required = true) String regionId ) {
        try {
            return ResponseMsgUtil.success(hltUnionCardVipService.GetMembershipLevel(phone , regionId));
        } catch (Exception e) {
            log.error("HighOrderController --> getBackendToken() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/userDistributionStatistics", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询分销用户统计内容")
    public ResponseData userDistributionStatistics(HttpServletRequest request) {
        try {
            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();
            return ResponseMsgUtil.success(bsDistributionUserRelService.userDistributionStatistics(userInfoModel.getHighUser().getId()));
        } catch (Exception e) {
            log.error("HighOrderController --> getBackendToken() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/distributionInviteList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询分销用户邀请列表")
    public ResponseData distributionInviteList(HttpServletRequest request,
                                               @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                               @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {
            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();

            Map<String , Object> map = new HashMap<>();
            map.put("popularizeUserId" , userInfoModel.getHighUser().getId());


            PageHelper.startPage(pageNum,pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(bsDistributionUserRelService.getDistributionUserRelList(map)));
        } catch (Exception e) {
            log.error("HighOrderController --> getBackendToken() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/distributionOrderList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询分销用户积分列表")
    public ResponseData distributionOrderList(HttpServletRequest request,
                                              @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                              @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {
            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();

            Map<String , Object> map = new HashMap<>();
            map.put("popularizeUserId" , userInfoModel.getHighUser().getId());
            PageHelper.startPage(pageNum,pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(bsDistributionUserRelService.getDistributionRebateList(map)));
        } catch (Exception e) {
            log.error("HighOrderController --> getBackendToken() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/promotionalPosters", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "生成推广海报")
    public ResponseData promotionalPosters(HttpServletRequest request) {
        try {
            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();

            String path = ImageUtils.QrCodeImg(SysConst.getSysConfig().getQrCodeUrl() , userInfoModel.getHighUser().getId().intValue());

            CommonConfig.overlapImage(path , userInfoModel.getHighUser().getId().toString());

            return ResponseMsgUtil.success(SysConst.getSysConfig().getImgUrl() + path);
        } catch (Exception e) {
            log.error("HighOrderController --> getBackendToken() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/promoteOrderList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询用户推广列表")
    public ResponseData promoteOrderList(HttpServletRequest request,
                                         @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                         @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {
            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();

            PageHelper.startPage(pageNum,pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(highOrderService.promoteOrderList(userInfoModel.getHighUser().getId())));
        } catch (Exception e) {
            log.error("HighOrderController --> getBackendToken() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }
}
