package xiaoqu.home.open.controller;

import com.alibaba.fastjson.JSONObject;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import xiaoqu.home.open.aop.AvoidRepeatSubmit;
import xiaoqu.home.open.controller.input.webpage.AuthorityUserInput;
import xiaoqu.home.open.controller.input.webpage.AuthorityUserSetInput;
import xiaoqu.home.open.controller.output.user.UserAuthorityOutput;
import xiaoqu.home.open.model.db1.Agent;
import xiaoqu.home.open.model.db1.User;
import xiaoqu.home.open.model.db2.Authority;
import xiaoqu.home.open.publicBean.BaseOutput;
import xiaoqu.home.open.publicBean.PageOutput;
import xiaoqu.home.open.service.db1.AgentService;
import xiaoqu.home.open.service.db1.UserService;
import xiaoqu.home.open.service.db2.AuthorityService;
import xiaoqu.home.open.utils.ResultResponseBeanUtil;
import xiaoqu.home.open.utils.UserUtils;
import xiaoqu.home.open.utils.WrapperUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Api(value = "权限组相关")
@Controller
@RequestMapping("/authority")
public class AuthorityController {
    private Logger log = LoggerFactory.getLogger("Controller");
    @Autowired
    AuthorityService authorityService;
    @Autowired
    UserService userService;
    @Autowired
    AgentService agentService;

    @ApiOperation(value = "设置物业平台权限组人员")
    @ResponseBody
    @RequestMapping(value = "/setAuthorityUser", method = RequestMethod.POST)
    @AvoidRepeatSubmit
    public BaseOutput<String> setAuthorityUser(HttpServletRequest request, @RequestBody AuthorityUserSetInput input) {
        User user = UserUtils.getUser(request);
        if (user == null) {
            return ResultResponseBeanUtil.fail("请重新登录");
        }
        log.info("【setAuthorityUser】添加权限组人员：user" + user.getName() + "设置" + JSONObject.toJSONString(input));
        if (input.getAuthorityId() == null) {
            return ResultResponseBeanUtil.fail("请选择权限组");
        }
        String userIds = input.getUserIds();
        String[] split = userIds.split(",");
        Set<String> checkSet = new HashSet<>(Arrays.asList(split));
        Iterator<String> iterator = checkSet.iterator();
        StringBuilder name = new StringBuilder();
        while (iterator.hasNext()) {
            String userId = iterator.next();
            User curuser = userService.getById(userId);

            if (curuser.getPropertyAuthorityId()!=null && curuser.getPropertyAuthorityId() != 0 && input.getAuthorityId() != 0 && curuser.getPropertyAuthorityId() .equals( input.getAuthorityId())) {
                name.append(curuser.getName()).append( "，");
                continue;
            }
            curuser.setPropertyAuthorityId(input.getAuthorityId());
            userService.updateById(curuser);
        }
        if (name.length() > 0) {
            return ResultResponseBeanUtil.fail("用户" + name.toString() + "已加入其它权限组");
        }
//        try {
//            QueryWrapper<User> wrapper = WrapperUtils.getWrapper(false);
//            wrapper.eq("authority_id",input.getAuthorityId());
//            List<User> userlist = userService.list(wrapper);
//            Iterator<User> oldCehckIterator = userlist.iterator();
//            int removeCount=0;
//            while (oldCehckIterator.hasNext()){
//                User next = oldCehckIterator.next();
//                if(checkSet.contains(next.getId().toString())){
//                    checkSet.remove(next.getId().toString());
//                }else{
//                    //取消了的怎么处理
//                    if(input.getClearOldFlag()){
//                        next.setModifyTime(new Date());
//                        next.setAuthorityId(0L);
//                        userService.updateById(next);
//                        removeCount++;
//                    }
//                }
//            }
//            int addCount=0;
//            if(checkSet.size()>0){
//                Iterator newCheck = checkSet.iterator();
//                while (newCheck.hasNext()){
//                    String userId = newCheck.next().toString();
//                    User byId = userService.getById(userId);
//                    if(byId!=null){
//                        byId.setModifyTime(new Date());
//                        byId.setAuthorityId(input.getAuthorityId());
//                        userService.updateById(byId);
//                        addCount++;
//                    }
//                }
//            }
//            log.info("【setAuthorityUser】user:" + user.getName() + ",input:" + JSONObject.toJSONString(input)+"新增"+addCount+"，去除"+removeCount);
//            return ResultResponseBeanUtil.success("权限组人员添加成功");
//        } catch (Exception e) {
//            log.info("【setAuthorityUser】user:" + user.getName() + ",input:" + JSONObject.toJSONString(input));
//            e.printStackTrace();
//        }
        return ResultResponseBeanUtil.success("权限组人员添加成功");
    }


    @ApiOperation(value = "已选中权限组人员")
    @ResponseBody
    @RequestMapping(value = "/getAuthorityUserList", method = RequestMethod.POST)
    @AvoidRepeatSubmit
    public BaseOutput<PageOutput<UserAuthorityOutput>> getAuthorityUserList(HttpServletRequest request, @RequestBody AuthorityUserInput input) {
        User user = UserUtils.getUser(request);
        if (user == null) {
            return ResultResponseBeanUtil.fail("请重新登录");
        }

        QueryWrapper<User> wrapper = WrapperUtils.getWrapper(false);
        if(input.getAuthorityId()!=null&&input.getAuthorityId()>0){
            wrapper.eq("property_authority_id",input.getAuthorityId());
            input.setAuthorityId(null);
        }
        WrapperUtils.beanToWrapper(wrapper, input);
        Page<User> pageList = new Page<>(input.getPage(), input.getRows());
        pageList = userService.page(pageList, wrapper);
        List<User> userList = pageList.getRecords();
        Iterator<User> iterator = userList.iterator();
        PageOutput<UserAuthorityOutput> output = new PageOutput<>();
        ArrayList<UserAuthorityOutput> userAuthorityOutputs = new ArrayList<>();

        while (iterator.hasNext()) {
            User next = iterator.next();
            UserAuthorityOutput userAuthorityOutput = new UserAuthorityOutput();
            BeanUtils.copyProperties(next, userAuthorityOutput);
            userAuthorityOutputs.add(userAuthorityOutput);
        }
        output.setPage(pageList.getCurrent());
        output.setRecords(pageList.getTotal());
        output.setTotal(pageList.getPages());
        output.setRows(userAuthorityOutputs);
        return ResultResponseBeanUtil.success(output);
    }

//
//    @ApiOperation(value = "验证是否行权限")
//    @ResponseBody
//    @RequestMapping(value = "/checkIsAgent", method = RequestMethod.GET)
//    public BaseOutput<String> checkIsAgent(HttpServletRequest request) {
//        User user = UserUtils.getUser(request);
//        if (user == null) {
//            return ResultResponseBeanUtil.fail("请重新登录");
//        }
//        Authority byId = authorityService.getById(user.getAuthorityId());
//        if (byId != null) {
//            if (byId.getIsagent() == 0) {
//                Agent byId1 = agentService.getById(user.getAgentId());
//                if (byId1.getChannelNo().equals("Z")) {
//                    return ResultResponseBeanUtil.success("false");
//                }
//            }
//        }
//        return ResultResponseBeanUtil.success("true");
//
//    }
}
