package cn.com.countrygarden.bi.main.controller.performance;

import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.model.performance.PerformanceElement;
import cn.com.countrygarden.bi.main.model.performance.UserMessage;
import cn.com.countrygarden.bi.main.model.performance.UserPower;
import cn.com.countrygarden.bi.main.model.performance.UserTarget;
import cn.com.countrygarden.bi.main.model.twerp.hm.TbSysUser;
import cn.com.countrygarden.bi.main.service.UserRoleService;
import cn.com.countrygarden.bi.main.service.performance.PerformanceElementService;
import cn.com.countrygarden.bi.main.service.performance.UserTargetService;
import cn.com.countrygarden.bi.main.service.twerp.hm.TbSysUserService;
import cn.com.countrygarden.bi.main.util.erp.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 绩效权限相关接口
 *
 * @author Max Date：2018/07/30
 * @version 1.0
 * @since 1.8
 */
@Controller("performanceAuthority")
@RequestMapping("performanceAuthority")
public class PerformanceAuthorityController {

    private Logger logger = LoggerFactory.getLogger(PerformanceAuthorityController.class);

    @Autowired
    private UserTargetService userTargetService;

    @Autowired
    private PerformanceElementService performanceElementService;

    @Autowired
    private TbSysUserService tbSysUserService;

    @Autowired
    private UserRoleService userRoleService;

    /**
     * 得到所有的用户名—指标
     *
     * @param pageSize    条数
     * @param pageCurrent 页数
     * @return List
     */
    @ResponseBody
    @RequestMapping(value = "/showAll", method = {RequestMethod.POST, RequestMethod.GET})
    public Object showAll(@RequestParam(value = "pageSize") int pageSize, @RequestParam(value = "pageCurrent") int pageCurrent) {
        Map<String, Integer> map = new HashMap<>();
        map.put("pageCurrent", (pageCurrent - 1) * pageSize);//设置起始行号
        map.put("pageSize", pageSize);//设置页数
        List<String> usertargetList = userTargetService.selectAllUserCode(map);//查询userCode—分页

        //缓存返回前端
        List<UserMessage> userMessages = new ArrayList<>();

        //遍历userCode数据，同时插入相关的指标权限和名字
        for (String userCode : usertargetList) {
            //查询得到该userCode的所有指标权限
            List<PerformanceElement> hasElementList = performanceElementService.selectUserCodePower(1, userCode);
            //设置UserMessage，存放进入List，返回前台
            UserMessage userMessage_temp = new UserMessage();
            userMessage_temp.setUserCode(userCode);//设置UserCode
            userMessage_temp.setUserName(tbSysUserService.findByUserCode(userCode).getUserName());//设置名称
            //查询得到拥有的指标权限，插入返回
            List<UserPower> temp_userPowers = new ArrayList<>();
            for (PerformanceElement performanceElement : hasElementList) {//拥有的权限
                temp_userPowers.add(new UserPower(performanceElement.getElementId().toString(), performanceElement.getName(), "1", userCode));
            }
            userMessage_temp.setUserPowers(temp_userPowers);
            userMessages.add(userMessage_temp);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("total", userTargetService.countSelectAllUserCode());//得到总条数
        result.put("rows", userMessages);
        return Response.response(result);
    }

    /**
     * 搜索框-搜索存在user_target的数据
     *
     * @param userName    用户名
     * @param pageCurrent 当前页码
     * @param pageSize    条数
     * @return List
     */
    @ResponseBody
    @RequestMapping(value = "/searchPowerUser", method = {RequestMethod.POST, RequestMethod.GET})
    public Object searchPowerUser(@RequestParam(value = "userName") String userName,
                                  @RequestParam(value = "pageCurrent") int pageCurrent, @RequestParam(value = "pageSize") int pageSize) {

        Map<String, Integer> map = new HashMap<>();
        map.put("pageCurrent", -1);//表示不分页
        map.put("pageSize", -1);
        List<String> usertargetList = userTargetService.selectAllUserCode(map);
        //分页查询erp符合条件的数据库
        Map<String, Object> result = new HashMap<>();
        result.put("total", tbSysUserService.countSearchUser(userName, usertargetList));//得到总条数

        List<UserMessage> userMessages = new ArrayList<>();

        //设置满足分页的数据量，查询对应的用户名
        List<TbSysUser> tbSysUserList=tbSysUserService.searchUser(userName, usertargetList, (pageCurrent - 1) * pageSize, pageSize);
        //查询该userCode对应的指标权限
        for(TbSysUser tbSysUser:tbSysUserList){
            //TbSysUser tbsu = tbSysUserService.findByUserCode(tbSysUser.getUserCode());//根据UserCode返回唯一一条TbSysUser
            //将数据分别封装到userMessage用来返回
            UserMessage userMessage = new UserMessage();
            userMessage.setUserCode(tbSysUser.getUserCode());//设置UserCode
            userMessage.setUserName(tbSysUser.getUserName());//设置用户名
            //得到该userCode的所有指标
            List<PerformanceElement> hasElementList = performanceElementService.selectUserCodePower(1, tbSysUser.getUserCode());
            List<UserPower> userPowers = new ArrayList<>();
            for (PerformanceElement performanceElement : hasElementList) {//拥有的权限
                userPowers.add(new UserPower(performanceElement.getElementId().toString(), performanceElement.getName(), "1", tbSysUser.getUserCode()));//遍历，存入数据，返给给前台
            }
            userMessage.setUserPowers(userPowers);//设置UserPowers

            userMessages.add(userMessage);
        }
        result.put("rows", userMessages);
        result.put("searchUserName",userName);
        return Response.response(result);
    }

    /**
     * 查询该userCode的所有权限
     *
     * @param userCode UserCode
     * @return List
     */
    @ResponseBody
    @RequestMapping(value = "/selectUserPower", method = {RequestMethod.POST, RequestMethod.GET})
    public Object selectUserPower(@RequestParam(value = "userCode") String userCode) {

        //得到用户所有有权限的指标
        List<PerformanceElement> hasElementList = performanceElementService.selectUserCodePower(1, userCode);
        //得到该userCode的所有指标
        List<UserPower> result = new ArrayList<>();//临时存储，用来返回给前台
        for (PerformanceElement performanceElement : hasElementList) {//拥有的权限
            result.add(new UserPower(performanceElement.getElementId().toString(), performanceElement.getName(), "1", userCode));//遍历，存入数据，返给给前台
        }

        //得到用户所有没有权限的指标
        List<PerformanceElement> unHasElementList = performanceElementService.selectUserCodePower(2, userCode);
        for (PerformanceElement performanceElement : unHasElementList) {//无拥有的权限
            result.add(new UserPower(performanceElement.getElementId().toString(), performanceElement.getName(), "0", userCode));
        }

        return Response.response(result);
    }


    /**
     * 管理指标更新接口
     *
     * @param userPowerList 十五个指标
     * @return List
     */
    @ResponseBody
    @RequestMapping(value = "/updateUserPower", method = {RequestMethod.POST, RequestMethod.GET})
    public Object updateUserPower(@RequestBody List<UserPower> userPowerList) {
        //得到数据，先抽取userCode,将该UserCode的所有数据都删除
        String userCode = userPowerList.get(0).getUserCode();
        userTargetService.deleteUserCodeAll(userCode);
        int temp=0;//用来是否一个指标都没选
        //遍历选中的指标权限，插入
        for (UserPower userPower : userPowerList) {
            if (userPower.getIsSelect().equals("1")) {//表示拥有该权限，进行插入
                UserTarget userTarget = new UserTarget();
                userTarget.setUsercode(userCode);//设置插入数据库的userCode
                userTarget.setElementid(userPower.getElementId());//设置插入数据库的ElementId
                //中心对接人有三个权限，couldRead,couldWrite,couldLock但是没有解锁权限couldUnLock
                userTarget.setCouldread(1);
                userTarget.setCouldwrite(1);
                userTarget.setCouldlock(1);
                userTarget.setCouldunlock(0);
                userTarget.setIsdelete(0);//设置为未删除状态
                userTarget.setCreatedate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));//设置插入时间
                userTargetService.insertSelective(userTarget);//插入新的结果
                temp++;//如果有插入，则加一
            }
        }
        //表示一个权限都没有
        if(temp==0){
            addUser(userCode);//插入一条权限为null的数据
        }
        return Response.response("操作成功");
    }


    /**
     * 删除同一个userCode的所有数据
     *
     * @param userCode userCode
     * @return 成功或失败的信息
     */
    @ResponseBody
    @RequestMapping(value = "/removeAuthority", method = {RequestMethod.POST, RequestMethod.GET})
    public Object removeAuthority(@RequestParam(value = "userCode") String userCode) {
        try {
            if (userTargetService.deleteUserCodeAll(userCode) > 0) {
                return Response.response("删除成功");
            } else {
                return Response.response("非法调用");
            }
        } catch (Exception e) {
            return Response.responseFail("数据库操作失败");
        }
    }


    /**
     * 绩效权限搜索框按照用户名查询
     *
     * @param userName    用户名
     * @param pageCurrent 当前页数
     * @param pageSize    页码
     * @return List
     */
    @ResponseBody
    @RequestMapping(value = "/searchUser", method = {RequestMethod.POST, RequestMethod.GET})
    public Object searchUser(@RequestParam(value = "userName") String userName,
                             @RequestParam(value = "pageCurrent") int pageCurrent, @RequestParam(value = "pageSize") int pageSize) {

        if(StringUtil.isEmpty(userName)||userName.equals("null")){//如果前端传过来为空，查询全量，设置userName为null
            userName=null;
        }

        //查询所有中心对接人userCode，同时排除已经插入在user_target表中的数据
        List<String> userCodes = userRoleService.selectperformanceCenter();
        Map<String, Object> result = new HashMap<>();

        //如果为0，表示所有的中心对接人的账号都填充到user_target表中，直接返回
        if(userCodes.size()==0){
            result.put("total", 0);//得到总条数
            result.put("rows",new ArrayList<TbSysUser>());//设置返回结果
        }else{
            pageCurrent = (pageCurrent - 1) * pageSize;//当前行数
            //设置返回前端的数据格式
            result.put("total", tbSysUserService.countSearchUser(userName, userCodes));//得到总条数
            result.put("rows",tbSysUserService.searchUser(userName, userCodes, pageCurrent, pageSize));//设置返回结果
        }
        return Response.response(result);
    }


    /**
     * 绩效权限新增接口
     * @param userCode UserCode
     * @return 成功或失败信息
     */
    @ResponseBody
    @RequestMapping(value = "/addUser", method = {RequestMethod.POST, RequestMethod.GET})
    public Object addUser(@RequestParam(value = "userCode") String userCode){
        //先查询是否存在该UserCode,避免重复添加
        if(userTargetService.selectExistUser(userCode)>0){
            return Response.responseFail("已存在，不能重复添加");
        }else{//不存在，执行插入
            UserTarget userTarget = new UserTarget();
            userTarget.setUsercode(userCode);//设置插入数据库的userCode
            userTarget.setElementid(null);//设置插入数据库的ElementId为null
            //新插入的数据无任何权限，同时elementId为null
            userTarget.setCouldread(0);
            userTarget.setCouldwrite(0);
            userTarget.setCouldlock(0);
            userTarget.setCouldunlock(0);
            userTarget.setIsdelete(0);//设置为未删除状态
            userTargetService.insertSelective(userTarget);//插入新的结果
            userTarget.setCreatedate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));//设置插入时间
            return Response.response("添加成功");
        }
    }

}
