package cn.com.capcloud.api.action.myself.system.nosession;

import cn.com.capcloud.api.action.service.ApiDao;
import cn.com.capcloud.api.action.service.ApiService;
import cn.com.capcloud.api.action.service.MongoService;
import cn.com.capcloud.api.action.service.NoSessionService;
import cn.com.capcloud.ccui.core.common.json.JackJSONObject;
import cn.com.capcloud.core.noentitydb.BaseService;
import cn.com.capcloud.core.system.user.UserService;
import cn.com.capcloud.core.util.ReadProperty;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

//重置khcadmin密码
@Component
public class NoSessionResetKhcadminPasswordAction {

    @Resource
    private BaseService baseService;
    @Resource
    private UserService userService;
    @Resource
    private ApiService apiService;
    @Resource
    private NoSessionService noSessionService;
    @Resource
    private MongoTemplate mongoTemplate;
    @Resource
    private JdbcTemplate jdbcTemplate;
    @Resource
    private MongoService mongoService;
    @Resource
    private ReadProperty readProperty;
    private static NoSessionResetKhcadminPasswordAction action;
    @PostConstruct
    public void init(){
        action=this;
        action.baseService=this.baseService;
        action.userService=this.userService;
        action.apiService =this.apiService;
        action.mongoTemplate=this.mongoTemplate;
        action.mongoService=this.mongoService;
        action.jdbcTemplate=this.jdbcTemplate;
        action.noSessionService=this.noSessionService;
        action.readProperty=this.readProperty;
    }
    public Map<String,Object> resetKhcadminPassword(String jsonStr, JackJSONObject retJson, HttpServletRequest request){
        String khcKey=action.apiService.getJsonValueByKey(jsonStr,retJson,"khcKey");
        Map<String,Object> map=new HashMap<>();
        if(!action.readProperty.getKhcKey().equals(khcKey)){
            retJson.put("status","no_code");
            retJson.put("message","操作失败请使用正确的khcKey");
            return new HashMap<>();
        }
        BCryptPasswordEncoder encoder =new BCryptPasswordEncoder();
        String password= ApiDao.getRandomNum(12);
        String hashed=encoder.encode(password.trim());
        String encodedPassword="{bcrypt}"+hashed;
        String sql="update tbl_system_user set user_password='"+encodedPassword+"',login_count=0 where id=1";//id写死
        action.jdbcTemplate.execute(sql);
        System.out.println("重置成功 khcadmin 新密码是："+password);
        map.put("data","");
        map.put("message","重置成功，请在控制台查看新密码");
        return map;
    }
}
