package com.bcxin.ins.weixin.usercenter.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bcxin.ins.rest.UserSupportUtil;
import com.bcxin.ins.service.user.ClientUserService;
import com.bcxin.ins.core.entity.PageResult;
import com.bcxin.ins.util.Sha1Util;
import com.bcxin.ins.vo.ClientUserVo;
import com.bcxin.ins.weixin.usercenter.dao.WeiXinUserCenterMapper;
import com.bcxin.ins.weixin.usercenter.service.WeiXinUserCenterService;
import com.bcxin.mybatisplus.toolkit.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Service
@Transactional
public class WeiXinUserCenterServiceImpl implements WeiXinUserCenterService {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WeiXinUserCenterMapper dao;

    @Autowired
    private ClientUserService  userService;

    public PageResult query(Map<Object, Object> p) {
        return new PageResult(dao.queryCnt(p), dao.query(p));
    }

    @Override
    public JSONObject savePwd(Map<Object, Object> params, HttpServletRequest req, HttpServletResponse resp, ClientUserVo weixinVo) {
        String status = "300";
        String msg = "旧密码和新密码的数据不能为空！";
        String  oldPassword=String.valueOf(params.get("old_password"));
        String  newPassword=String.valueOf(params.get("new_password"));
        if(StringUtils.isEmpty(oldPassword)||StringUtils.isEmpty(newPassword)){
            return  returnJsonMsg(status,msg);
        }
        if(oldPassword.equals(newPassword)){
            status = "303";
            msg = "旧密码和新密码不能一样！";
            return returnJsonMsg(status,msg);
        }
        if(!Sha1Util.validatePassword(oldPassword,weixinVo.getPassword())){
            status = "302";
            msg = "旧密码错误！";
            return returnJsonMsg(status,msg);
        }
        if(userService.getUserPassword(weixinVo.getLogin_name(),newPassword)){
            weixinVo.setPassword(Sha1Util.entryptPassword(newPassword));
            UserSupportUtil.setSessionWeiXinUser(weixinVo);
            //判断旧的密码是否相同
            status = "200";
            msg = "修改成功";
            return returnJsonMsg(status,msg);
        }
        status = "500";
        msg = "修改失败";
        return  returnJsonMsg(status,msg);
    }

    private JSONObject returnJsonMsg(String status,  String msg) {
        JSONObject obj = new JSONObject();
        obj.put("status", status);
        obj.put("msg", msg);
        logger.debug("retrun,返回给页面的值："+ JSON.toJSONString(obj));
        return obj;
    }
}
