package com.winsun.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.winsun.auth.core.annotion.Permission;
import com.winsun.auth.core.base.controller.BaseController;
import com.winsun.auth.core.common.model.ResponseData;
import com.winsun.auth.core.shiro.ShiroUser;
import com.winsun.auth.core.util.DateUtil;
import com.winsun.auth.core.util.ResponseEntity;
import com.winsun.auth.model.user.User;
import com.winsun.bean.HhrUser;
import com.winsun.bean.SysUser;
import com.winsun.mapper.AppMapper;
import com.winsun.mapper.HhrUserMapper;
import com.winsun.mapper.SysUserMapper;
import com.winsun.smsUtils.SendSmsAndMail;
import com.winsun.utils.MyBatisPlusUpdateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: hsl
 * @Date: 2020/4/23 10:54
 */
@RequestMapping("PersonalCenter")
@RestController
@Slf4j
public class PersonalCenter extends BaseController {

    private static HhrUserMapper hhrUserMapper;

    private static SysUserMapper sysUserMapper;

    private static AppMapper appMapper;

    private static StringRedisTemplate stringRedisTemplate;

    private static long CODETIME = 1000 * 60 * 5;

    private String EDITPHONE = "EditPhone";

    @Autowired
    public PersonalCenter(SysUserMapper sysUserMapper, HhrUserMapper hhrUserMapper, AppMapper appMapper,StringRedisTemplate stringRedisTemplate) {
        PersonalCenter.sysUserMapper = sysUserMapper;
        PersonalCenter.hhrUserMapper = hhrUserMapper;
        PersonalCenter.appMapper = appMapper;
        PersonalCenter.stringRedisTemplate = stringRedisTemplate;
    }

    @Permission(menuname = "修改手机号", value = "editPhone", method = RequestMethod.POST)
    public ResponseData<String> editPhone(String partner,String phone,String verificationCode) {
        ShiroUser user = getShiroUser();
        if(!partner.equals(String.valueOf(user.getId()))){
            return ResponseData.error("当前登录账户和修改账号冲突！");
        }
        String key = user.getAccount() + EDITPHONE;
        String code = stringRedisTemplate.opsForValue().get(key);
        if(!verificationCode.equals(code)){
            return ResponseData.error("验证码错误，请重新输入！");
        }
        if(phone.length() != 11){
            return ResponseData.error("手机号码，请重新输入！");
        }
        Wrapper<SysUser> wrapper = new EntityWrapper<>();
        wrapper.eq("id",user.getId());
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("phone",phone);
        dataMap.put("updateTime",new Date());
        Integer integer = sysUserMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(dataMap), wrapper);
        if(integer == 1){
            return ResponseData.success("修改成功！");
        }else {
            return ResponseData.error("修改失败！");
        }
    }

    @Permission(menuname = "修改手机号发送短信", value = "sentEditPhone", method = RequestMethod.POST)
    public ResponseData<String> sentEditPhone(String partner) {
        ShiroUser user = getShiroUser();
        if(!partner.equals(String.valueOf(user.getId()))){
            return ResponseData.error("当前登录账户和修改账号冲突！");
        }
        String id = String.valueOf(user.getId());
        return  phoneCode(id,EDITPHONE);
    }

    public static ResponseData<String> phoneCode(String id,String type) {
        SysUser sysUser = sysUserMapper.selectById(id);
        if(sysUser==null){
            return ResponseData.error("当前登录账户异常！");
        }
        //5分钟内有效
        String code = sysUser.getAccount() + type;
        Long expire = stringRedisTemplate.getExpire(code);
        //验证码 有效时间是五分钟倒计时
        if (expire > (60 * 4)) {
            return ResponseData.error("请勿频繁发送手机验证码操作！");
        }
        String verificationCode = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        stringRedisTemplate.opsForValue().set(code, verificationCode, CODETIME, TimeUnit.MILLISECONDS);
        try {
                if (sysUser.getPhone().length() == 11) {
                    SendSmsAndMail.sendSms(sysUser.getPhone(), verificationCode, "7");
                    return ResponseData.success("发送成功！");
                } else {
                    return ResponseData.error("当前用户手机号码不合法！");
                }
        } catch (Exception e) {
            log.info("错误信息：{}"+ e.getMessage(),e);
            return ResponseData.error("手机短信发送失败！");
        }
    }

    @Permission(menuname = "个人中心用户详情", value = "partnerInfo", method = RequestMethod.POST)
    public ResponseData<Map<String, Object>> selectPartnerInfo(String partner) {
        SysUser sysUser = sysUserMapper.selectById(partner);
        if (sysUser==null) {
            return ResponseData.error("当前用户不存在！");
        }
        HhrUser hhrUser = hhrUserMapper.selectById(partner);
        if (hhrUser==null) {
            return ResponseData.error("当前用户异常！");
        }
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("phone", sysUser.getPhone());
        hashMap.put("account", sysUser.getAccount());
        hashMap.put("userName", sysUser.getName());
        hashMap.put("sex", sysUser.getSex());
        hashMap.put("grade", hhrUser.getGrade());
        hashMap.put("idCard", hhrUser.getIdCard());
        hashMap.put("substName", sysUser.getSubstName());
        String schoolId = appMapper.selectSchoolId(partner);
        String school = appMapper.selectSchoolById(schoolId);
        hashMap.put("school", school);
        hashMap.put("position", hhrUser.getPosition());
        hashMap.put("createtime", sysUser.getCreatetime());
        hashMap.put("wxNickName", hhrUser.getWxNickName());
        hashMap.put("wxHeadImgUrl",hhrUser.getWxHeadImgUrl());
        return ResponseData.success(hashMap);
    }


}
