package com.gree.mall.miniapp.controller.user;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.gree.mall.miniapp.annotation.ApiNotAuth;
import com.gree.mall.miniapp.bean.Page;
import com.gree.mall.miniapp.bean.common.WxJsApiSignBean;
import com.gree.mall.miniapp.bean.settle.OrderShareBean;
import com.gree.mall.miniapp.bean.user.*;
import com.gree.mall.miniapp.constant.Constant;
import com.gree.mall.miniapp.exception.RemoteServiceException;
import com.gree.mall.miniapp.helper.ResponseHelper;
import com.gree.mall.miniapp.logic.common.CommonLogic;
import com.gree.mall.miniapp.logic.common.SMSLogic;
import com.gree.mall.miniapp.logic.common.outside.WechatLogic;
import com.gree.mall.miniapp.logic.user.UserLogic;
import com.gree.mall.miniapp.plus.entity.SettleExpenseItem;
import com.gree.mall.miniapp.plus.entity.User;
import com.gree.mall.miniapp.plus.service.UserService;
import com.gree.mall.miniapp.utils.CommonUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;

@Slf4j
@RestController
@Api(value = "小程序用户", tags ={"小程序用户"} )
@RequestMapping(value = "/user", produces = "application/json; charset=utf-8")
public class UserController {


    @Autowired
    UserService userService;
    @Autowired
    UserLogic userLogic;
    @Autowired
    WechatLogic wechatLogic;
    @Autowired
    SMSLogic smsLogic;
    @Autowired
    CommonLogic commonLogic;


    @PostMapping("/bind")
    @ApiOperation(value = "绑定业务员")
    public ResponseHelper grantMobile(
            @ApiParam(required = true, value = "用户id") @RequestParam(required = true) String userId,
            @ApiParam(required = false, value = "业务员用户id") @RequestParam(required = false) String serviceId,
            @ApiParam(required = false, value = "业务员openId") @RequestParam(required = false) String serviceOpenId
    ) throws Exception {
        userLogic.bind(userId,serviceId,serviceOpenId);
        return ResponseHelper.success();
    }

    @GetMapping("/qrcode/bind")
    @ApiOperation(value = "获取业务员绑定小程序码")
    public ResponseHelper bindQrCode(HttpServletRequest request) throws Exception {
        return ResponseHelper.success(userLogic.bindQrCode(request));
    }
    @GetMapping("/rank")
    @ApiOperation(value = "上月业绩排行榜")
    public ResponseHelper rank(HttpServletRequest request) throws Exception {
        RankBean rank = userLogic.rank(request);
        if(rank != null && !CollectionUtils.isEmpty(rank.getRankList())) {
            for (RankItemBean bean : rank.getRankList()) {
                if (StringUtils.isNotBlank(bean.getWorkUserName())) {
                    bean.setWorkUserName(bean.getWorkUserName().charAt(0) + "**");
                }
            }
        }
        return ResponseHelper.success(rank);
    }


    @ApiNotAuth
    @PostMapping("/auth")
    @ApiOperation(value = "微信授权")
    public ResponseHelper<UserWxBean> auth(
            @ApiParam(required = false,value="业务员用户id") @RequestParam(required = false) String serviceId,
            @ApiParam(required = true, value = "授权openid登陆code") @RequestParam(required = true) String code,
            @ApiParam(required = false, value = "获取验证手机号码code") @RequestParam(required = false) String phoneCode,
            @ApiParam(required = false, value = "公众号openid") @RequestParam(required = false) String mpOpenId,
            HttpServletRequest request
    ) throws RemoteServiceException, WxErrorException, InterruptedException {
        UserWxBean userWxBean = userLogic.addUser(code,phoneCode,serviceId,mpOpenId,request);
        userLogic.addVisit(request, userWxBean.getUserId());
        return ResponseHelper.success(userWxBean);
    }

    @ApiNotAuth
    @PostMapping("/auth2")
    @ApiOperation(value = "微信公众号授权")
    public ResponseHelper<UserWxBean> auth2(
            @ApiParam(required = false,value="业务员用户id") @RequestParam(required = false) String serviceId,
            @ApiParam(required = true, value = "授权openid登陆code") @RequestParam(required = true) String code,
            HttpServletRequest request
    ) throws RemoteServiceException, WxErrorException, InterruptedException {
        UserWxBean userWxBean = userLogic.addUser(code,serviceId,request);
        userLogic.addVisit(request, userWxBean.getUserId());
        return ResponseHelper.success(userWxBean);
    }




    @ApiNotAuth
    @PostMapping("/pub/auth")
    @ApiOperation(value = "公众号微信授权绑定小程序链接")
    public ResponseHelper<String> pubAuth(
            @ApiParam(required = false,value="公众号appid") @RequestParam(required = false) String pubAppId,
            @ApiParam(required = true, value = "授权openid登陆code") @RequestParam(required = true) String code,
            HttpServletRequest request
    ) throws RemoteServiceException, WxErrorException, InterruptedException {
        String url = wechatLogic.getPubAuthUrl(code, pubAppId);
        return ResponseHelper.success(url);
    }


//    @ApiNotAuth
//    @PostMapping("/mobile/grant")
//    @ApiOperation(value = "授权手机号")
//    public ResponseHelper<UserWxBean> grantMobile(
//            @ApiParam(required = true, value = "iv") @RequestParam(required = true) String iv,
//            @ApiParam(required = false, value = "encryptedData") @RequestParam(required = false) String encryptedData,
//            @ApiParam(required = true, value = "用户id") @RequestParam(required = true) String userId,
//            HttpServletRequest request
//    ) throws Exception {
//        UserWxBean wxMobile = userLogic.getWxMobile(iv, encryptedData, userId,request);
//        return ResponseHelper.success(wxMobile);
//    }

    @GetMapping("/user/detail")
    @ApiOperation(value = "个人信息")
    public ResponseHelper<UserWxBean> detail(
            @ApiParam(required = true, value = "code") @RequestParam(required = true) String userId,
            HttpServletRequest request
    ) throws RemoteServiceException {
        UserWxBean userWxBean = userLogic.userDetail(userId,request);
        return ResponseHelper.success(userWxBean);
    }

    @GetMapping("/user/log")
    @ApiOperation(value = "记录登录信息")
    public ResponseHelper detail(

    ) throws RemoteServiceException {
       userLogic.getUserLog();
        return ResponseHelper.success();
    }

    @PostMapping("/userinfo/save")
    @ApiOperation(value = "保存微信账号的用户信息")
    public ResponseHelper<User> saveUserInfo(
            @ApiParam(required = true, value = "用户id") @RequestParam(required = true) String userId,
            @ApiParam(required = false, value = "用户昵称") @RequestParam(required = false) String nickName,
            @ApiParam(required = false, value = "性别( 未知 男 女)") @RequestParam(required = false) String sex,
            @ApiParam(required = false, value = "头像") @RequestParam(required = false) String avatarUrl,
            @ApiParam(required = false, value = "国家") @RequestParam(required = false) String country,
            @ApiParam(required = false, value = "省") @RequestParam(required = false) String province,
            @ApiParam(required = false, value = "城市") @RequestParam(required = false) String city
    ) throws Exception{
        User user = userLogic.saveUserInfo(userId, nickName, sex, avatarUrl, country, province, city);
        return ResponseHelper.success(user);
    }


    @GetMapping("/profit")
    @ApiOperation(value = "我的收益统计")
    public ResponseHelper<MyProfitBean> userProfit(
            @ApiParam(required = true, value = "用户id") @RequestParam(required = true) String userId
    ) throws RemoteServiceException {
        MyProfitBean myProfitBean = userLogic.myProfit(userId);
        return ResponseHelper.success(myProfitBean);
    }

    @GetMapping("/profit/list")
    @ApiOperation(value = "我的收益明细列表")
    public ResponseHelper<IPage<OrderShareBean>> userProfitList(
            @ApiParam(required = true, value = "用户id") @RequestParam(required = true) String userId,
            @ApiParam(required = false, value = "ING=结算中  OVER=已结算  CANCEL=已取消  EXCEPTION=异常结算") @RequestParam(required = false) String status,
            @ApiParam(value = "页号",required = true) @RequestParam Integer pageNum,
            @ApiParam(value = "页大小",required = true) @RequestParam Integer pageSize
    ) throws RemoteServiceException {
        IPage<OrderShareBean> myProfit = userLogic.myProfitList(userId,status,pageNum,pageSize);
        return ResponseHelper.success(myProfit);
    }




    @GetMapping("/profit/total")
    @ApiOperation(value = "总计收益")
    public ResponseHelper<BigDecimal> totalProfit(
            @ApiParam(required = true, value = "用户id") @RequestParam(required = true) String userId
    ) throws RemoteServiceException {
        BigDecimal bigDecimal = userLogic.totalProfit(userId);
        return ResponseHelper.success(bigDecimal);
    }

    @GetMapping("/customer")
    @ApiOperation(value = "我的客户列表")
    public ResponseHelper<Page<User>> customerList(
            @ApiParam(required = true, value = "用户id") @RequestParam(required = true) String userId,
            @ApiParam(required = true, value = "pageNum") @RequestParam(required = true) Integer pageNum,
            @ApiParam(required = true, value = "pageSize") @RequestParam(required = true)Integer pageSize
    ) throws RemoteServiceException {
        IPage<User> userIPage = userLogic.customerList(userId, pageNum, pageSize);
        return ResponseHelper.success(userIPage);
    }


    @GetMapping("/parent")
    @ApiOperation(value = "我的客户经理")
    public ResponseHelper<User> parentList(
            @ApiParam(required = true, value = "用户id") @RequestParam(required = true) String userId
    ) throws RemoteServiceException {
        User user = userLogic.parentUser(userId);
        return ResponseHelper.success(user);
    }



    @GetMapping("/apply/websit")
    @ApiOperation("入驻的网点列表")
    public ResponseHelper<List<AdminWebsitApplyBean>> applyWebsitList(
            @ApiParam(value = "是否查询所有可入驻网点(包含未入驻的)",required = false) @RequestParam(required = false) Boolean isAll,
            @ApiParam(value = "是否为增置服务网点",required = false) @RequestParam(required = false) Boolean isIncre,
            @ApiParam(value = "增值服务ID",required = false) @RequestParam(required = false) String increId,
            @ApiParam(value = "经度",required = false) @RequestParam(required = false) String lng,
            @ApiParam(value = "纬度",required = false) @RequestParam(required = false) String lat
    ){
        List<AdminWebsitApplyBean> adminWebsitApplyBeans = userLogic.websitList(isAll,increId,isIncre,lng,lat);
        return ResponseHelper.success(adminWebsitApplyBeans);
    }

    @PostMapping("/default/websit")
    @ApiOperation(value = "设置默认网点")
    public ResponseHelper defaultWebsit(
            @ApiParam(required = true,value="默认网点id") @RequestParam String websitId
    ){
        userLogic.defaultWebsit(websitId);
        return ResponseHelper.success();
    }

    @PostMapping("/apply")
    @ApiOperation(value = "师傅入驻和分销员入驻")
    public ResponseHelper apply(
            @RequestBody UserApplyBean userApplyBean
    ){
        userLogic.apply(userApplyBean);
        return ResponseHelper.success();
    }

    @GetMapping("/my/count")
    @ApiOperation(value = "我的相关统计")
    public ResponseHelper<MyCountBean> myCount(
            @ApiParam(required = true, value = "用户id") @RequestParam(required = true) String userId
    ) throws RemoteServiceException {
        MyCountBean myCountBean = userLogic.myCount(userId);
        return ResponseHelper.success(myCountBean);
    }


    @PostMapping("/jsapi/sign")
    @ApiOperation(value = "获取公众号jsapi sign")
    public ResponseHelper<WxJsApiSignBean> apply(
            @ApiParam(required = true, value = "当前页面路径") @RequestParam(required = true) String url
    ){
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        WxJsApiSignBean pubJsapiSign = wechatLogic.getPubJsapiSign(currentCompanyWechat.getCompanyWechatId(), url);
        return ResponseHelper.success(pubJsapiSign);
    }


    @PostMapping("/sms/send")
    @ApiOperation(value = "发送验证码（绑定手机号专用）")
    public ResponseHelper sendSms(
            @ApiParam(value = "手机号码",required = true) @RequestParam String phone,
            @ApiParam(value = "滑动验证key",required = false) @RequestParam(required = false) String key,
            @ApiParam(value = "滑动验证数值",required = false) @RequestParam(required = false) String vrifyCode
    ) throws Exception {
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        Integer count = userService.lambdaQuery().eq(User::getMobile, phone).eq(User::getCompanyWechatId, currentCompanyWechat.getCompanyWechatId()).count();
        if(count > 0){
            throw new RemoteServiceException("手机号已被绑定，请勿重复绑定");
        }
        smsLogic.sendSms(phone,key,vrifyCode);
        return ResponseHelper.success();
    }

    @PostMapping("phone/bind")
    @ApiOperation("绑定手机号")
    public ResponseHelper bindPhone(
            @ApiParam(value = "手机号码",required = true) @RequestParam String phone,
            @ApiParam(value = "短信验证码",required = true) @RequestParam String code
    ){
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        smsLogic.checkSmsCode(phone, code);

        User user = userService.getById(currentCompanyWechat.getUserId());
        user.setMobile(phone).updateById();
        //User user = userService.lambdaQuery().eq(User::getMobile, phone).last("limit 1").one();
        //授权手机号后检查是否有预设置的师傅身份信息
        if(StringUtils.isNotBlank(user.getMobile())){
            userLogic.userTypeInit(user);
        }
        return ResponseHelper.success();
    }

    @PostMapping("open/bindOpenId")
    @ApiOperation("绑定手机号")
    public ResponseHelper bindOpenId(

    ){
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        String miniOpenId = commonLogic.getMiniOpenId();
        userService.lambdaUpdate().set(User::getMiniOpenId,miniOpenId).eq(User::getUserId,currentCompanyWechat.getUserId()).update();
        return ResponseHelper.success();
    }

    @PostMapping("/my/settle")
    @ApiOperation("我的安维费")
    public ResponseHelper<IPage<SettleMonthWagesWorkerBean>> mySettle(
            @ApiParam(required = true, value = "pageNum") @RequestParam Integer pageNum,
            @ApiParam(required = true, value = "pageSize") @RequestParam Integer pageSize
    ){
        IPage<SettleMonthWagesWorkerBean> page = userLogic.mySettle(pageNum, pageSize);
        return ResponseHelper.success(page);
    }

    @PostMapping("/my/settle/item")
    @ApiOperation("费用明细")
    public ResponseHelper<List<SettleExpenseItem>> mySettleItem(
            @ApiParam(required = true, value = "月度工资汇总id") @RequestParam String settleMonthWagesId
    ){
        List<SettleExpenseItem> list = userLogic.mySettleItem(settleMonthWagesId);
        return ResponseHelper.success(list);
    }

    @PostMapping("/my/settle/item/detail")
    @ApiOperation("费用明细详情")
    public ResponseHelper<SettleExpenseItem> mySettleItemDetail(
            @ApiParam(required = true, value = "id") @RequestParam String id
    ){
        SettleExpenseItem detail = userLogic.mySettleItemDetail(id);
        return ResponseHelper.success(detail);
    }

    @ApiNotAuth
    @GetMapping("/send/message/code")
    @ApiOperation(value = "发送短信验证码")
    public ResponseHelper messageCode(
            @ApiParam(value = "手机码",required = true) @RequestParam String mobile,
            @ApiParam(value = "滑动验证key",required = false) @RequestParam(required = false) String key,
            @ApiParam(value = "滑动验证数值",required = false) @RequestParam(required = false) String vrifyCode
    ) throws Exception {
        userLogic.sendMessageCode(mobile, key, vrifyCode);
        return ResponseHelper.success();
    }

    @ApiNotAuth
    @PostMapping("/worker/mobile/login")
    @ApiOperation(value = "师傅手机号登录")
    public ResponseHelper<UserWxBean> workerMobileLogin(
            @ApiParam(value = "手机号",required = true) @RequestParam String mobile,
            @ApiParam(value = "短信code",required = true) @RequestParam String messageCode
    ) throws Exception {
        UserWxBean userWxBean = userLogic.workerMobileLogin(mobile, messageCode);
        userLogic.addVisit(userWxBean);
        return ResponseHelper.success(userWxBean);
    }

    @PostMapping("/worker/mobile/logout")
    @ApiOperation(value = "师傅手机号退出登录")
    public ResponseHelper logout(
            HttpServletRequest request
    ) throws Exception {
        userLogic.workerMobileLogout(request);
        return ResponseHelper.success();
    }
}
