package com.platform.api;

import com.alibaba.fastjson.JSONObject;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.platform.annotation.LoginUser;
import com.platform.entity.Result;
import com.platform.entity.SmsLogVo;
import com.platform.entity.UserVo;
import com.platform.exception.CommonBaseException;
import com.platform.interceptor.AuthorizationInterceptor;
import com.platform.service.ApiUserService;
import com.platform.service.custom.MyApiTmBrandAdminService;
import com.platform.service.custom.MySysUserBrandService;
import com.platform.service.impl.ZhiHouseService;
import com.platform.util.ApiBaseAction;
import com.platform.utils.CharUtil;

import com.platform.utils.SmsUtil;
import com.platform.vos.ReturnDTO;
import com.platform.vos.TbUser;
import com.qiniu.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者: @author Harmon <br>
 * 时间: 2017-08-11 08:32<br>
 * @gitee https://gitee.com/fuyang_lipengjun/platform
 * 描述: ApiIndexController <br>
 */
@Api(tags = "会员信息接口")
@RestController
@RequestMapping("/api/user")
public class ApiUserController extends ApiBaseAction {
    @Autowired
    private ApiUserService userService;


    @Autowired
    private MyApiTmBrandAdminService myApiTmBrandAdminService;

    @Autowired
    private MySysUserBrandService mySysUserBrandService;

    @Autowired
    private ZhiHouseService zhiHouseService;


    @ApiOperation(value = "获取用户个人信息")
    @PostMapping("getUerInfo")
    public Object getUerInfo() {
        String weixinOpenid = getWeixinOpenid();
        if(ObjectUtils.isEmpty(weixinOpenid)){
            throw new CommonBaseException(401,"请先登录");
        }
        UserVo userVo = userService.queryByOpenId(weixinOpenid);
        if(ObjectUtils.isEmpty(userVo)){
            throw new CommonBaseException(401,"请先登录");
        }
        if(org.apache.commons.lang.StringUtils.isNotBlank(userVo.getMobile())){
            TbUser sysUserEntity = zhiHouseService.queryByUserMobile(userVo.getMobile());
            if(null == sysUserEntity){
                userVo.setIsAdmin(0);
            }else{
                List<Long> brandIdList = mySysUserBrandService.queryBrandIdList(sysUserEntity.getId());
                if(!CollectionUtils.isEmpty(brandIdList)){
                    userVo.setIsAdmin(1);
                }else{
                    userVo.setIsAdmin(0);
                }
            }

        }else{
            //默认用户为非管理员
            userVo.setIsAdmin(0);
        }
        return toResponsSuccess(userVo);
    }

    @ApiOperation(value = "修改用户个人信息")
    @PostMapping("updateUerInfo")
    public Object updateUerInfo( @ApiParam(name = "UserVo对象", value = "传入json格式", required = true)  @RequestBody UserVo loginUser) {
        long userId = loginUser.getUserId();
        UserVo userVo = userService.queryObject(userId);
        if(null == userVo){
            return Result.failure("用户不存在");
        }
        userService.update(loginUser);
        String token = request.getHeader(AuthorizationInterceptor.LOGIN_TOKEN_KEY);
        if(!ObjectUtils.isEmpty(loginUser.getMobile())){
            ReturnDTO returnDTO = zhiHouseService.wcLogin(loginUser.getWeixin_openid(), loginUser.getMobile(), null, null);
            token = JSONObject.parseObject(JSONObject.toJSONString(returnDTO.getMessage())).getString("token");
            if (StringUtils.isNullOrEmpty(token)) {
                logger.error("更新用户信息失败");
                return toResponsFail("更新用户信息失败");
            }
        }
        Map<String, Object> resultObj = new HashMap<>();
        resultObj.put("token", token);
        return toResponsSuccess(resultObj);
    }

    /**
     * 发送短信
     */
    @ApiOperation(value = "发送短信")
    @PostMapping("smscode")
    public Object smscode(@LoginUser UserVo loginUser) {
        JSONObject jsonParams = getJsonRequest();
        String phone = jsonParams.getString("phone");
        String regex = "^1[3-9][0-9]\\d{8}$";
        if(!phone.matches(regex)){
            return toResponsFail("手机号不符合格式");
        }
        // 一分钟之内不能重复发送短信
        SmsLogVo smsLogVo = userService.querySmsCodeByUserId(loginUser.getUserId());
        if (null != smsLogVo && (System.currentTimeMillis() / 1000 - smsLogVo.getLog_date()) < 1 * 60) {
            return toResponsFail("短信已发送");
        }
        //生成验证码
        String sms_code = CharUtil.getRandomNum(4);
        //
        String sms_txt = "验证码：" + sms_code + "，感谢您使用四维商圈，请输入验证码以完成身份验证，有效期5分钟。如非本人操作，请忽略此消息。";
        //获取云存储配置信息
//        SmsConfig config = sysConfigService.getConfigObject(Constant.SMS_CONFIG_KEY, SmsConfig.class);
//        if (StringUtils.isNullOrEmpty(config)) {
//            return toResponsFail("请先配置短信平台信息");
//        }
//        if (StringUtils.isNullOrEmpty(config.getAppid())) {
//            return toResponsFail("请先配置短信平台APPID");
//        }
//        if (StringUtils.isNullOrEmpty(config.getAppkey())) {
//            return toResponsFail("请先配置短信平台KEY");
//        }
//        if (StringUtils.isNullOrEmpty(config.getSign())) {
//            return toResponsFail("请先配置短信平台签名");
//        }
        // 发送短信
        SmsSingleSenderResult result;
        boolean falg = false;
        int templateId = 23;
        try {
            //腾讯云短信平台
//            result = SmsUtil.crSendSms(config.getAppid(), config.getAppkey(), phone, templateId, new String[]{sms_code}, "");
            //阿里云短信平台
            falg = SmsUtil.sendAliSms(phone, "{\"code\":\"" + sms_code + "\"}", "SMS_184816840");
        } catch (Exception e) {
            return toResponsFail("短信发送失败");
        }

//        if (result.result == 0) {
        if (falg) {
            smsLogVo = new SmsLogVo();
            smsLogVo.setLog_date(System.currentTimeMillis() / 1000);
            smsLogVo.setUser_id(loginUser.getUserId());
            smsLogVo.setPhone(phone);
            smsLogVo.setSms_code(Integer.parseInt(sms_code));
            smsLogVo.setSms_text(sms_txt);
            userService.saveSmsCodeLog(smsLogVo);
            return toResponsSuccess("短信发送成功");
        } else {
            return toResponsFail("短信发送失败");
        }
    }

    /**
     * 获取当前会员等级
     *
     * @param loginUser
     * @return
     */
    @ApiOperation(value = "获取当前会员等级")
    @PostMapping("getUserLevel")
    public Object getUserLevel(@LoginUser UserVo loginUser) {
        String userLevel = userService.getUserLevel(loginUser);
        return toResponsSuccess(userLevel);
    }
    @ApiOperation(value = "获取当前用户挂在的店铺列表")
    @PostMapping("getAdminBrands")
    public Result getAdminBrands() {
        List<Map<String , Object>> brandList = myApiTmBrandAdminService.getUserBrand(getUserId());
         return  Result.success("成功" , brandList);
    }


    /**
     * 绑定手机
     */
    @ApiOperation(value = "绑定手机")
    @PostMapping("bindMobile")
    public Object bindMobile(@LoginUser UserVo loginUser, @RequestParam(value = "mobileCode", defaultValue = "1") Integer mobile_code,
                             @RequestParam(value = "mobile", defaultValue = "10") String mobile) {
        SmsLogVo smsLogVo = userService.querySmsCodeByUserId(loginUser.getUserId());

        if (mobile_code != smsLogVo.getSms_code()) {
            return toResponsFail("验证码错误");
        }
        UserVo userVo = userService.queryObject(loginUser.getUserId());
        userVo.setMobile(mobile);
        userService.update(userVo);
        return toResponsSuccess("手机绑定成功");
    }
}
