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.bean.HhrUser;
import com.winsun.bean.SysUser;
import com.winsun.mapper.AppMapper;
import com.winsun.mapper.HhrUserMapper;
import com.winsun.mapper.SchoolMapper;
import com.winsun.mapper.SysUserMapper;
import com.winsun.smsUtils.SendSmsAndMail;
import com.winsun.utils.IDCardUtil;
import com.winsun.utils.MyBatisPlusUpdateUtils;
import com.winsun.utils.PicturesUtil;
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.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

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

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

    private static HhrUserMapper hhrUserMapper;

    private static SysUserMapper sysUserMapper;

    private static AppMapper appMapper;

    private static StringRedisTemplate stringRedisTemplate;

    private static SchoolMapper schoolMapper;

    private static long CODETIME = 1000 * 60 * 5;

    private String EDITPHONE = "EditPhone";

    private String EDITPWD = "EditPwd";

    private static String PATHTYPE="idCard";

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

    @Permission(menuname = "登录后微信解绑", value = "WXUnbundling", method = RequestMethod.POST)
    public ResponseData<String> WXUnbundling(String partner, String openid) {
        ShiroUser user = getShiroUser();
        if (!partner.equals(String.valueOf(user.getId()))) {
            return ResponseData.error("当前登录账户异常！");
        }
        if (StringUtils.isBlank(openid)) {
            return ResponseData.error("解绑失败，当前登录无权解绑，请退出登录，在登录页面解绑！");
        }
        HhrUser hhrUser = hhrUserMapper.selectById(partner);
        if(!hhrUser.getOpenId().equals(openid)){
            return ResponseData.error("解绑失败，当前登录无权解绑，请退出登录，在登录页面解绑！");
        }
        Wrapper<HhrUser> wrapper = new EntityWrapper<>();
        wrapper.eq("id", user.getId());
        wrapper.eq("open_id", openid);
        Map<String, Object> dataMapping = new HashMap<>();
        dataMapping.put("open_id", null);
        Integer integer = hhrUserMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(dataMapping), wrapper);
        if(integer == 1){
            return ResponseData.success("解绑成功！");
        }
        return ResponseData.error("解绑失败，请退出登录，在登录页面解绑！");
    }

    @Permission(menuname = "上传当前登录用户证件照", value = "uploadCard", method = RequestMethod.POST)
    public ResponseData<String> uploadCard(String partner, String idCard, String stuCard) {
        ShiroUser user = getShiroUser();
        if (!partner.equals(String.valueOf(user.getId()))) {
            return ResponseData.error("当前登录账户异常！");
        }
        Wrapper<SysUser> wrapper = new EntityWrapper<>();
        wrapper.eq("id", user.getId());
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("updateTime", new Date());
        sysUserMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(dataMap), wrapper);
        Wrapper<HhrUser> wrapper1 = new EntityWrapper<>();
        wrapper1.eq("id", user.getId());
        Map<String, Object> dataMap1 = new HashMap<>();
        dataMap1.put("idcard_img_url", PicturesUtil.uploadPictures(idCard, String.valueOf(user.getId()),PATHTYPE));
        dataMap1.put("student_img_url",  PicturesUtil.uploadPictures(stuCard, String.valueOf(user.getId()),PATHTYPE));
        Integer integer1 = hhrUserMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(dataMap1), wrapper1);
        if(integer1==1){
            return ResponseData.success("上传成功！");
        }
        return ResponseData.error("上传失败！");
    }

    @Permission(menuname = "查询当前登录用户证件照", value = "selectPicture", method = RequestMethod.POST)
    public ResponseData<Map<String, Object>> selectPicture(String partner) {
        ShiroUser user = getShiroUser();
        if (!partner.equals(String.valueOf(user.getId()))) {
            return ResponseData.error("当前登录账户操作异常！");
        }
        HhrUser hhrUser = hhrUserMapper.selectById(user.getId());
        if (hhrUser == null) {
            return ResponseData.error("当前登录账户信息异常！");
        }
        Map<String, Object> hashMap = new HashMap<>();
        if (StringUtils.isNotBlank(hhrUser.getStudentImgUrl())) {
            hashMap.put("stuCard", hhrUser.getStudentImgUrl());
        }
        if (StringUtils.isNotBlank(hhrUser.getIdcardImgUrl())) {
            hashMap.put("idCard", hhrUser.getIdcardImgUrl());
        }
        return ResponseData.success(hashMap);
    }

    @Permission(menuname = "修改用户信息", value = "editPartnerInfo", method = RequestMethod.POST)
    public ResponseData<String> editPartnerInfo(String partner, String userName, String sex, String grade,
                                                String position, String idCard, String substName, String school) {
        if (StringUtils.isBlank(partner) || StringUtils.isBlank(userName) || StringUtils.isBlank(sex) ||
                StringUtils.isBlank(grade) || StringUtils.isBlank(position) || StringUtils.isBlank(idCard) ||
                StringUtils.isBlank(substName) || StringUtils.isBlank(school)) {
            return ResponseData.error("用户详情未提交完整！");
        }
        ShiroUser user = getShiroUser();
        if (!partner.equals(String.valueOf(user.getId()))) {
            return ResponseData.error("当前登录账户和修改账号冲突！");
        }
        if (!IDCardUtil.IDCardValidate(idCard)) {
            return ResponseData.error("身份证号码有误！");
        }
        Wrapper<SysUser> wrapper = new EntityWrapper<>();
        wrapper.eq("id", user.getId());
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("name", userName);
        dataMap.put("sex", sex);
        dataMap.put("substName", substName);
        dataMap.put("updateTime", new Date());
        Integer integer = sysUserMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(dataMap), wrapper);
        Wrapper<HhrUser> wrapper1 = new EntityWrapper<>();
        wrapper1.eq("id", user.getId());
        Map<String, Object> dataMap1 = new HashMap<>();
        dataMap1.put("grade", grade);
        dataMap1.put("position", position);
        dataMap1.put("id_card", idCard);
        integer += hhrUserMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(dataMap1), wrapper1);
        String sch = schoolMapper.selectSchoolIdByUserId(String.valueOf(user.getId()));
        if (StringUtils.isBlank(sch)) {
            integer += schoolMapper.insertUserSchool(String.valueOf(user.getId()), school);
        } else {
            integer += schoolMapper.updateUserSchool(String.valueOf(user.getId()), school);
        }
        if (integer != 3) {
            return ResponseData.error("修改异常，请重新修改！");
        }
        return ResponseData.success("修改成功！");
    }


    @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);
    }

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

    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("schoolId", schoolId);
        hashMap.put("position", hhrUser.getPosition());
        hashMap.put("createtime", sysUser.getCreatetime());
        hashMap.put("wxNickName", hhrUser.getWxNickName());
        hashMap.put("wxHeadImgUrl", hhrUser.getWxHeadImgUrl());
        return ResponseData.success(hashMap);
    }


}
