package xiaoqu.home.open.controller;


import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import xiaoqu.home.open.aop.AvoidRepeatSubmit;
import xiaoqu.home.open.controller.input.webpage.AuthorityPageInput;
import xiaoqu.home.open.controller.input.webpage.ButtonFieldInput;
import xiaoqu.home.open.controller.input.webpage.PageFieldInput;
import xiaoqu.home.open.controller.input.webpage.WebpageAuthorityParamInput;
import xiaoqu.home.open.controller.output.webpage.AuthorityOutput;
import xiaoqu.home.open.controller.output.webpage.WebPageAuthorityOutput;
import xiaoqu.home.open.controller.output.webpage.WebPageOutput;
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.model.db2.Button;
import xiaoqu.home.open.model.db2.ButtonField;
import xiaoqu.home.open.model.db2.ButtonWebpageAuthority;
import xiaoqu.home.open.model.db2.FieldWebpageAuthority;
import xiaoqu.home.open.model.db2.PageField;
import xiaoqu.home.open.model.db2.Webpage;
import xiaoqu.home.open.model.db2.WebpageAuthority;
import xiaoqu.home.open.publicBean.BaseOutput;
import xiaoqu.home.open.publicBean.PageInput;
import xiaoqu.home.open.publicBean.PageOutput;
import xiaoqu.home.open.service.RedisService4;
import xiaoqu.home.open.service.RedisService5;
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.service.db2.ButtonFieldService;
import xiaoqu.home.open.service.db2.ButtonService;
import xiaoqu.home.open.service.db2.ButtonWebpageAuthorityService;
import xiaoqu.home.open.service.db2.FieldWebpageAuthorityService;
import xiaoqu.home.open.service.db2.PageFieldService;
import xiaoqu.home.open.service.db2.WebpageAuthorityService;
import xiaoqu.home.open.service.db2.WebpageService;
import xiaoqu.home.open.utils.ResultResponseBeanUtil;
import xiaoqu.home.open.utils.UserUtils;
import xiaoqu.home.open.utils.WrapperUtils;

/**
 * <p>
 * 页面配置 权限组，页面，页面功能，页面列
 * </p>
 *
 * @author mk
 * @since 2020-09-07
 */
@Api(value = "页面相关")
@Controller
@RequestMapping("/webpage")
@Slf4j
public class WebPageController {
    @Autowired
    WebpageService webpageService;
    @Autowired
    WebpageAuthorityService webpageAuthorityService;
    @Autowired
    PageFieldService pageFieldService;
    @Autowired
    ButtonFieldService buttonFieldService;
    @Autowired
    AuthorityService authorityService;
    @Autowired
    ButtonWebpageAuthorityService buttonWebpageAuthorityService;
    @Autowired
    FieldWebpageAuthorityService fieldWebpageAuthorityService;
    @Autowired
    ButtonService buttonService;
    @Autowired
    private RedisService5 redisService5;
    @Autowired
    private RedisService4 redisService4;

    @Autowired
    UserService userService;
    @Autowired
    AgentService agentService;
/*

    添加块
 */

    @ApiOperation(value = "添加页面")
    @ResponseBody
    @RequestMapping(value = "/addWebpage", method = RequestMethod.POST)
    @AvoidRepeatSubmit
    public BaseOutput<String> addWebpage(HttpServletRequest request, @RequestBody Webpage input) {
        log.info("【addWebpage】Webpage" + JSONObject.toJSONString(input));
        User user = UserUtils.getUser(request);
        if (user == null) {
            return ResultResponseBeanUtil.fail("请重新登录");
        }
        QueryWrapper<Webpage> wrapper = WrapperUtils.getWrapper(false);
        wrapper.eq("title", input.getTitle());
        wrapper.eq("soft_delete", 0);

        List<Webpage> list = webpageService.list(wrapper);
        if (!list.isEmpty()) {
            return ResultResponseBeanUtil.fail("页面名称已存在，请变更");
        }
        input.setStatus(1);

        boolean save = webpageService.save(input);

        setWebpageAuthority(input, 1L);
        if (save) {
            return ResultResponseBeanUtil.success("页面添加成功");
        } else {
            return ResultResponseBeanUtil.fail("页面添加失败");
        }
    }


    @ApiOperation(value = "根据路径获取页面id")
    @ResponseBody
    @RequestMapping(value = "/getIdByPath", method = RequestMethod.GET)
    @AvoidRepeatSubmit
    public BaseOutput<Long> getIdByPath(HttpServletRequest request, @RequestParam(name = "path") String path) {
        log.info("【getIdByPath】path:" + path);

        QueryWrapper<Webpage> wrapper = WrapperUtils.getWrapper(false);
        wrapper.eq("path", path);
        wrapper.eq("soft_delete", 0);

        List<Webpage> list = webpageService.list(wrapper);
        if (!list.isEmpty()) {
            return ResultResponseBeanUtil.success(list.get(0).getId());
        }else{
            return ResultResponseBeanUtil.fail("页面未找到");

        }
    }



    private void setWebpageAuthority(Webpage input, Long authorityId) {
        WebpageAuthority webpageAuthority = new WebpageAuthority();
        BeanUtils.copyProperties(input, webpageAuthority);
        webpageAuthority.setId(null);
        webpageAuthority.setAuthorityId(authorityId);
        webpageAuthority.setWebId(input.getId());
        webpageAuthority.setCheckStatus(1);
        webpageAuthorityService.save(webpageAuthority);
    }


    @ApiOperation(value = "添加按钮")
    @ResponseBody
    @RequestMapping(value = "/addButton", method = RequestMethod.POST)
    @AvoidRepeatSubmit
    public BaseOutput<String> addButton(HttpServletRequest request, @RequestBody Button input) {
        log.info("【addButton】input" + JSONObject.toJSONString(input));
        User user = UserUtils.getUser(request);
        if (user == null) {
            return ResultResponseBeanUtil.fail("请重新登录");
        }
        Webpage webpage = webpageService.getById(input.getWebId());
        if (webpage.getType() == 2) {
            return ResultResponseBeanUtil.fail("该页面为菜单，按钮添加失败");
        }
        boolean save = buttonService.save(input);
        //超管权限
        setButtonToButtonWebpageAuthority(user, 1L, input);
        if (save) {
            return ResultResponseBeanUtil.success("按钮添加成功");
        } else {
            return ResultResponseBeanUtil.fail("按钮添加失败");
        }

    }

    @ApiOperation(value = "自动添加列")
    @ResponseBody
    @RequestMapping(value = "/addPageField", method = RequestMethod.POST)
    @AvoidRepeatSubmit
    public BaseOutput<String> addPageField(HttpServletRequest request, @RequestBody PageFieldInput input) {
        log.info("【addPageField】input" + JSONObject.toJSONString(input));
        User user = UserUtils.getUser(request);
        if (user == null) {
            return ResultResponseBeanUtil.fail("请重新登录");
        }
        Class<?> aClass;
        try {
            aClass = Class.forName(input.getOutputName());
            int i = 1;
            Field[] declaredFields = aClass.getDeclaredFields();
            for (Field field : declaredFields) {
                if (field.getName().equals("serialVersionUID")) {
                    continue;
                }
                PageField pageField = getPageField(input, field);
                pageField.setOrderBy(i++);
                ApiModelProperty api = field.getAnnotation(ApiModelProperty.class);
                if (api == null) {
                    pageField.setCnName(field.getName());

                } else {
                    pageField.setCnName(api.value());

                }
                pageFieldService.save(pageField);
                setFieldToFidelWebpageAuthority(user, 1L, pageField);
            }

            Class<?> superclass = aClass.getSuperclass();
            Field[] supperdeclaredFields = superclass.getDeclaredFields();
            for (Field field : supperdeclaredFields) {

                PageField pageField = new PageField();
                String name = field.getName();
                if (name.equals("serialVersionUID")) {
                    continue;
                }
                String lowerCasename = field.getName().toLowerCase();
                pageField.setEnName(name);
                pageField.setClassName(input.getOutputName());
                if (lowerCasename.contains("status") || lowerCasename.contains("state") || lowerCasename.contains("type")) {
                    pageField.setFieldType("select");
                    pageField.setWidth(90);

                } else if (lowerCasename.contains("time") || lowerCasename.contains("date")) {
                    pageField.setFieldType("date");
                    pageField.setWidth(200);
                } else if (lowerCasename.contains("id") && !lowerCasename.equals("id")) {
                    pageField.setFieldType("inputSelect");
                    pageField.setWidth(80);

                } else {
                    pageField.setFieldType("string");
                    pageField.setWidth(150);
                }
                pageField.setWebId(input.getWebId());
                pageField.setIsSelect(1);
                pageField.setNavSelect(0);
                pageField.setOrderBy(i++);
                pageField.setIsTableShow(1);
                ApiModelProperty api = field.getAnnotation(ApiModelProperty.class);
                if (api == null) {
                    pageField.setCnName(name);
                } else {
                    pageField.setCnName(api.value());

                }
                if (lowerCasename.contains("id") && !lowerCasename.equals("id")) {
                    pageField.setFieldType("inputSelect");
                    pageField.setNavSelect(1);
//                    PageField idNamePageField = getPageField(input, field);
//                    String nameField = name.replace("Id", "Name");
//                    idNamePageField.setCnName(nameField);
//                    idNamePageField.setOrderBy(i++);
//                    pageFieldService.save(idNamePageField);
//                    setFieldToFidelWebpageAuthority(user, 1L, idNamePageField);
                }
                pageFieldService.save(pageField);
                setFieldToFidelWebpageAuthority(user, 1L, pageField);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return ResultResponseBeanUtil.fail("列添加失败");

        }
        return ResultResponseBeanUtil.success("列添加成功");

    }


    @ApiOperation(value = "人工单独添加列")
    @ResponseBody
    @RequestMapping(value = "/addSingleField", method = RequestMethod.POST)
    @AvoidRepeatSubmit
    public BaseOutput<String> addSingleField(HttpServletRequest request, @RequestBody PageField input) {
        log.info("【addSingleField】input" + JSONObject.toJSONString(input));
        User user = UserUtils.getUser(request);
        if (user == null) {
            return ResultResponseBeanUtil.fail("请重新登录");
        }
        if (input.getWebId() == null || input.getWebId() == 0) {
            return ResultResponseBeanUtil.fail("请设置所属页面");
        }
        if (input.getFieldType() == null || input.getFieldType().equals("")) {
            return ResultResponseBeanUtil.fail("请设置字段所属类型（select,inputSelect,string,date）");
        }
        boolean save = pageFieldService.save(input);

        try {
            if (save) {
//                QueryWrapper<FieldWebpageAuthority> wrapper = WrapperUtils.getWrapper(false);
//                wrapper.eq("field_id", input.getId());
//                List<FieldWebpageAuthority> list = fieldWebpageAuthorityService.list(wrapper);
//                for (FieldWebpageAuthority fieldWebpageAuthority : list) {
//                    fieldWebpageAuthority.setCnName(input.getCnName());
//                    fieldWebpageAuthority.setEnName(input.getEnName());
//                    fieldWebpageAuthority.setIsSelect(input.getIsSelect());
//                    fieldWebpageAuthority.setFieldType(input.getFieldType());
//                    fieldWebpageAuthority.setNavSelect(input.getNavSelect());
//                    fieldWebpageAuthority.setOrderBy(input.getOrderBy());
//                    fieldWebpageAuthority.setParam(input.getParam());
//                    fieldWebpageAuthorityService.updateById(fieldWebpageAuthority);
//                }

                setFieldToFidelWebpageAuthority(user, 1L, input);

                return ResultResponseBeanUtil.success("字段添加成功");
            } else {
                return ResultResponseBeanUtil.fail("字段添加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultResponseBeanUtil.fail("修改权限关联字段失败");
        }
    }


    @ApiOperation(value = "添加权限组")
    @ResponseBody
    @RequestMapping(value = "/addAuthority", method = RequestMethod.POST)
    @AvoidRepeatSubmit
    public BaseOutput<String> addAuthority(HttpServletRequest request, @RequestBody Authority input) {
        log.info("【addAuthority】input" + JSONObject.toJSONString(input));
        User user = UserUtils.getUser(request);
        if (user == null) {
            return ResultResponseBeanUtil.fail("请重新登录");
        }
//        if (input.getIsagent() == null) {
//            return ResultResponseBeanUtil.fail("请选择行权限");
//        }

        input.setCreateId(user.getId());
        input.setAgentId(user.getAgentId());
        input.setParentId(user.getPropertyAuthorityId());
        if(user.getEnterpriseType()==2){
            input.setPropertyId(user.getPropertyId());
            input.setIsagent(0);
        }else{
            input.setPropertyId(0L);
            input.setIsagent(1);
        }
        QueryWrapper<Authority> wrapper = WrapperUtils.getWrapper(false);
        wrapper.eq("name", input.getName());
        wrapper.eq("agent_id", input.getAgentId());
        wrapper.eq("property_id", input.getPropertyId());
        int count = authorityService.count(wrapper);
        if(count>0){
                        return ResultResponseBeanUtil.fail("同名权限组已存在");
        }
//        wrapper.eq("is_table_show", 1);
        wrapper.orderByAsc("order_by");


        boolean save = authorityService.save(input);
        redisService5.set("name:PropertyAuthority:" + input.getId(), input.getName());

        if (save) {
            return ResultResponseBeanUtil.success("权限组添加成功");
        } else {
            return ResultResponseBeanUtil.fail("权限组添加失败");
        }
    }


    @ApiOperation(value = "添加页面权限组关联")
    @ResponseBody
    @RequestMapping(value = "/addWebpageAuthority", method = RequestMethod.POST)
    @AvoidRepeatSubmit
    public BaseOutput<String> addWebpageAuthority(HttpServletRequest request, @RequestBody WebpageAuthorityParamInput input) {
        log.info("【addWebpageAuthority】input" + JSONObject.toJSONString(input));
        User user = UserUtils.getUser(request);
        if (user == null) {
            return ResultResponseBeanUtil.fail("请重新登录");
        }
        if( input.getAuthorityId()==null||input.getAuthorityId()==0){
            return ResultResponseBeanUtil.fail("权限组异常，请刷新页面重新选择");
        }

        QueryWrapper<WebpageAuthority> wrapper = WrapperUtils.getWrapper(false);
        wrapper.eq("authority_id", input.getAuthorityId());
        List<WebpageAuthority> list = webpageAuthorityService.list(wrapper);
        Map<Long, WebpageAuthority> maps = list.stream().collect(Collectors.toMap(WebpageAuthority::getWebId, Function.identity(), (key1, key2) -> key2));
        Set<Long> longs = new HashSet<>();

        if(input.getIds()==null||input.getIds().trim()==""){
            if(input.getAuthorityId()!=1){
                for (Map.Entry<Long, WebpageAuthority> next : maps.entrySet()) {
                    WebpageAuthority byId = webpageAuthorityService.getById(next.getValue().getId());
                    if (byId != null) {
                        byId.setSoftDelete(1);
                        byId.setModifyTime(new Date());
                        webpageAuthorityService.updateById(byId);
                    }
                }
                return ResultResponseBeanUtil.success("权限页面设置成功");
            }else{
                return ResultResponseBeanUtil.success("系统管理员权限组不可为空");
            }

        }
        String[] split = input.getIds().split(",");
        if (!input.getIds().trim().equals("") && split.length > 0) {

            for (String s : split) {
                Webpage webpage = webpageService.getById(Long.parseLong(s));
                if (webpage == null) {
                    continue;
                }
                longs.add(webpage.getId());
                longs.add(webpage.getParentId());
//                checkWebPageParentId(input, webpage);
                savewebpageAuthority(input, webpage);
            }
            for (Long next : longs) {
                maps.remove(next);
            }
            log.info("【addWebpageAuthority】checkCount:" + longs.size());

            for (Map.Entry<Long, WebpageAuthority> next : maps.entrySet()) {
                WebpageAuthority byId = webpageAuthorityService.getById(next.getValue().getId());
                if (byId != null) {
                    byId.setSoftDelete(1);
                    byId.setModifyTime(new Date());
                    webpageAuthorityService.updateById(byId);
                }
            }
            log.info("【addWebpageAuthority】uncheckCount" + maps.size());
        }

//        }
        return ResultResponseBeanUtil.success("权限页面添加成功");
    }

    @ApiOperation(value = "添加权限组按钮关联")
    @ResponseBody
    @RequestMapping(value = "/addButtonWebpageAuthority", method = RequestMethod.POST)
    @AvoidRepeatSubmit
    public BaseOutput<String> addButtonWebpageAuthority(HttpServletRequest request, @RequestBody WebpageAuthorityParamInput input) {
        log.info("【addButtonWebpageAuthority】input" + JSONObject.toJSONString(input));
        User user = UserUtils.getUser(request);
        if (user == null) {
            return ResultResponseBeanUtil.fail("请重新登录");
        }
        QueryWrapper<ButtonWebpageAuthority> subwrapper = WrapperUtils.getWrapper(false);
        subwrapper.eq("authority_id", input.getAuthorityId());
        subwrapper.eq("web_id", input.getWebId());
        List<ButtonWebpageAuthority> sublist = buttonWebpageAuthorityService.list(subwrapper);
        Map<Long, ButtonWebpageAuthority> submaps = sublist.stream().collect(Collectors.toMap(ButtonWebpageAuthority::getButtonId, Function.identity(), (key1, key2) -> key2));
        log.info("【addButtonWebpageAuthority】submaps.size:" + submaps.size());
        if (input.getIds() != null) {
            String[] split;
            try {
                split = input.getIds().split(",");
                if (!input.getIds().trim().equals("") && split.length != 0) {

                    log.info("【addButtonWebpageAuthority】add.size:" + split.length);
                    Long authorityId = input.getAuthorityId();
                    for (String s : split) {
                        Button button = buttonService.getById(Long.parseLong(s));
                        submaps.remove(button.getId());
                        if (!setButtonToButtonWebpageAuthority(user, authorityId, button)) {

                            log.info("【addButtonWebpageAuthority】按钮数量异常" + JSONObject.toJSONString(input));
                        }
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
                return ResultResponseBeanUtil.fail("功能添加失败");
            }
        }
        log.info("【addFieldWebpageAuthority】remove.size:" + submaps.size());

        for (Map.Entry<Long, ButtonWebpageAuthority> longButtonWebpageAuthorityEntry : submaps.entrySet()) {
            ButtonWebpageAuthority value = longButtonWebpageAuthorityEntry.getValue();
            value.setCheckStatus(0);
            //20210621
            value.setSoftDelete(1);

            value.setModifyTime(new Date());
            buttonWebpageAuthorityService.updateById(value);
//            buttonWebpageAuthorityService.removeById(value.getId());
        }
        return ResultResponseBeanUtil.success("功能添加成功");


    }

    private boolean setButtonToButtonWebpageAuthority(User user, Long authorityId, Button button) {
        QueryWrapper<ButtonWebpageAuthority> wrapper = WrapperUtils.getWrapper(false);
        wrapper.eq("authority_id", authorityId);
        wrapper.eq("button_id", button.getId());

        ButtonWebpageAuthority one = buttonWebpageAuthorityService.getOne(wrapper);
        if (one != null) {
            if (one.getCheckStatus() == 0) {
                one.setCheckStatus(1);
                one.setModifyTime(new Date());
                buttonWebpageAuthorityService.updateById(one);
                return true;
            } else {
                return false;
            }
        } else {
            ButtonWebpageAuthority buttonWebpageAuthority = new ButtonWebpageAuthority();
            BeanUtils.copyProperties(button, buttonWebpageAuthority);
            buttonWebpageAuthority.setId(null);
            buttonWebpageAuthority.setButtonId(button.getId());
            buttonWebpageAuthority.setCreateTime(new Date());
            buttonWebpageAuthority.setModifyTime(new Date());
            buttonWebpageAuthority.setCheckStatus(1);
            buttonWebpageAuthority.setCreateId(user.getId());
            buttonWebpageAuthority.setAuthorityId(authorityId);
            buttonWebpageAuthorityService.save(buttonWebpageAuthority);
            return true;

        }

    }

    @ApiOperation(value = "添加权限列(重置)")
    @ResponseBody
    @RequestMapping(value = "/addFieldWebpageAuthority", method = RequestMethod.POST)
    @AvoidRepeatSubmit
    public BaseOutput<String> addFieldWebpageAuthority(HttpServletRequest request, @RequestBody WebpageAuthorityParamInput input) {
        log.info("【addFieldWebpageAuthority】input" + JSONObject.toJSONString(input));
        User user = UserUtils.getUser(request);
        if (user == null) {
            return ResultResponseBeanUtil.fail("请重新登录");
        }
        Long authorityId = input.getAuthorityId();

        QueryWrapper<FieldWebpageAuthority> subwrapper = WrapperUtils.getWrapper(false);
        subwrapper.eq("authority_id", authorityId);
        subwrapper.eq("web_id", input.getWebId());
        List<FieldWebpageAuthority> sublist = fieldWebpageAuthorityService.list(subwrapper);
        Map<Long, FieldWebpageAuthority> submaps = sublist.stream().collect(Collectors.toMap(FieldWebpageAuthority::getFieldId, Function.identity(), (key1, key2) -> key2));
        log.info("【addFieldWebpageAuthority】submaps.size:" + submaps.size());

        String[] split;
        try {
            split = input.getIds().split(",");
            if (!input.getIds().trim().equals("") && split.length != 0) {

                log.info("【addFieldWebpageAuthority】add.size:" + split.length);

                for (String s : split) {
                    PageField field = pageFieldService.getById(Long.parseLong(s));
                    submaps.remove(field.getId());
                    if (!setFieldToFidelWebpageAuthority(user, authorityId, field)) {
                        log.info("【addFieldWebpageAuthority】字段数量异常" + JSONObject.toJSONString(input));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultResponseBeanUtil.fail("字段添加失败");
        }
        log.info("【addFieldWebpageAuthority】remove.size:" + submaps.size());

        for (Map.Entry<Long, FieldWebpageAuthority> longFieldWebpageAuthorityEntry : submaps.entrySet()) {
            FieldWebpageAuthority value = longFieldWebpageAuthorityEntry.getValue();
            value.setCheckStatus(0);

            //20210621
            value.setSoftDelete(1);
            value.setModifyTime(new Date());
            fieldWebpageAuthorityService.updateById(value);
        }
        return ResultResponseBeanUtil.success("字段添加成功");


    }


    private boolean setFieldToFidelWebpageAuthority(User user, Long authorityId, PageField field) {
        QueryWrapper<FieldWebpageAuthority> wrapper = WrapperUtils.getWrapper(false);
        wrapper.eq("authority_id", authorityId);
        wrapper.eq("field_id", field.getId());
        FieldWebpageAuthority one = fieldWebpageAuthorityService.getOne(wrapper);
        if (one != null) {
            if (one.getCheckStatus() == 0) {
                one.setCheckStatus(1);
                one.setModifyTime(new Date());
                fieldWebpageAuthorityService.updateById(one);
            }
            return true;
        }

        FieldWebpageAuthority fieldWebpageAuthority = new FieldWebpageAuthority();
        BeanUtils.copyProperties(field, fieldWebpageAuthority);
        fieldWebpageAuthority.setId(null);
//        fieldWebpageAuthority.setWebId(field.getWebId());
        fieldWebpageAuthority.setCreateTime(new Date());
        fieldWebpageAuthority.setFieldId(field.getId());
        fieldWebpageAuthority.setCheckStatus(1);
        fieldWebpageAuthority.setModifyTime(new Date());
        fieldWebpageAuthority.setCreateId(user.getId());
        fieldWebpageAuthority.setAuthorityId(authorityId);
        fieldWebpageAuthorityService.save(fieldWebpageAuthority);
        return false;
    }

/*
   查询块
 */


    @ApiOperation(value = "查询页面(可配置)")
    @ResponseBody
    @RequestMapping(value = "/queryWebPageOutput", method = RequestMethod.GET)
    public BaseOutput<WebPageOutput> queryWebPageOutput(HttpServletRequest request, @RequestParam(name = "parentId") Long parentId) {
        log.info("【queryWebPageOutput】parentId" + parentId);

        User user = UserUtils.getUser(request);
        if (user == null) {
            return ResultResponseBeanUtil.fail("请重新登录");
        }
        if (!webpageAuthorityService.checkAuthorityByAuthorityId(user.getPropertyAuthorityId(), null)) {
            return ResultResponseBeanUtil.fail("未找到所属页面");
        }
        QueryWrapper<Webpage> wrapper = WrapperUtils.getWrapper(false);
        wrapper.eq("status", 1);
//        wrapper.eq("is_table_show", 1);
        wrapper.orderByAsc("order_by");

        List<Webpage> list = webpageService.list(wrapper);
        Map<Long, List<Webpage>> webpagemap = new HashMap<>();
        for (Webpage webpage : list) {
            if (webpagemap.containsKey(webpage.getParentId())) {
                webpagemap.get(webpage.getParentId()).add(webpage);
            } else {
                List<Webpage> subwebpages = new ArrayList<>();
                subwebpages.add(webpage);
                webpagemap.put(webpage.getParentId(), subwebpages);
            }
        }
        WebPageOutput webPageOutPut = getWebPageOutPut(parentId, webpagemap, null);
        if (webPageOutPut.getSize() > 0) {
            return ResultResponseBeanUtil.success(webPageOutPut);
        } else {
            return ResultResponseBeanUtil.fail("未找到所属页面");
        }
    }


    @ApiOperation(value = "查询菜单")
    @ResponseBody
    @RequestMapping(value = "/queryWebPageOutputByType", method = RequestMethod.GET)
    public BaseOutput<WebPageOutput> queryWebPageOutputByType(HttpServletRequest request, @RequestParam(name = "type") Integer type) {
        log.info("【queryWebPageOutputByType】type:" + type);

        User user = UserUtils.getUser(request);
        if (user == null) {
            return ResultResponseBeanUtil.fail("请重新登录");
        }
        if (!webpageAuthorityService.checkAuthorityByAuthorityId(user.getPropertyAuthorityId(), null)) {
            return ResultResponseBeanUtil.fail("未找到所属菜单");
        }
        QueryWrapper<WebpageAuthority> wrapper = WrapperUtils.getWrapper(false);
        wrapper.eq("type", type);
        wrapper.eq("is_table_show", 1);
        wrapper.orderByAsc("order_by");
        List<Webpage> list = webpageService.list();
        Map<Long, List<Webpage>> webpagemap = new HashMap<>();
        for (Webpage webpage : list) {
            if (webpagemap.containsKey(webpage.getParentId())) {
                webpagemap.get(webpage.getParentId()).add(webpage);
            } else {
                List<Webpage> subwebpages = new ArrayList<>();
                subwebpages.add(webpage);
                webpagemap.put(webpage.getParentId(), subwebpages);
            }
        }
        WebPageOutput webPageOutPut = getWebPageOutPut(0L, webpagemap, null);
        if (webPageOutPut.getSize() > 0) {
            return ResultResponseBeanUtil.success(webPageOutPut);
        } else {
            return ResultResponseBeanUtil.fail("未找到所属页面");
        }
    }


    @ApiOperation(value = "权限组页面配置查询（全查询）")
    @ResponseBody
    @RequestMapping(value = "/queryWebPageAuthoritOutputConfig", method = RequestMethod.GET)
    public BaseOutput<WebPageAuthorityOutput> queryWebPageAuthoritOutputConfig(HttpServletRequest request, @RequestParam(name = "authorityId") Long authorityId) {
        log.info("【queryWebPageAuthoritOutputConfig】authorityId:" + authorityId);

        User user = UserUtils.getUser(request);
        if (user == null) {
            return ResultResponseBeanUtil.fail("请重新登录");
        }
        if (!webpageAuthorityService.checkAuthorityByAuthorityId(user.getPropertyAuthorityId(), 1)) {
            return ResultResponseBeanUtil.fail("未找到所属页面");
        }

//        if (user.getAuthorityId().longValue() != authorityId.longValue()) {
//            Authority subAuthority = authorityService.getById(authorityId);
//            if (user.getAuthorityId().longValue() != subAuthority.getParentId().longValue()) {
//                return ResultResponseBeanUtil.fail("无此权限组配置权限");
//            }
//        }
        QueryWrapper<WebpageAuthority> wrapper = WrapperUtils.getWrapper(false);
        wrapper.eq("authority_id", user.getPropertyAuthorityId());
        wrapper.orderByAsc("order_by");

        List<WebpageAuthority> list = webpageAuthorityService.list(wrapper);
        Map<Long, List<WebpageAuthority>> webpagemap = new HashMap<>();
        for (WebpageAuthority webpageAuthority : list) {
            if (webpagemap.containsKey(webpageAuthority.getParentId())) {
                webpagemap.get(webpageAuthority.getParentId()).add(webpageAuthority);
            } else {
                List<WebpageAuthority> subwebpages = new ArrayList<>();
                subwebpages.add(webpageAuthority);
                webpagemap.put(webpageAuthority.getParentId(), subwebpages);
            }
        }

        WebPageAuthorityOutput webPageAuthorityOutput = getWebPageAuthorityOutPut(0L, webpagemap, null, false);
        if (webPageAuthorityOutput.getSize() > 0) {
            return ResultResponseBeanUtil.success(webPageAuthorityOutput);
        } else {
            return ResultResponseBeanUtil.fail("未找到所属页面");
        }
    }


    @ApiOperation(value = "高权限组对低权限组页面配置")
    @ResponseBody
    @RequestMapping(value = "/setWebPageAuthoritOutputConfig", method = RequestMethod.GET)
    public BaseOutput<WebPageAuthorityOutput> setWebPageAuthoritOutputConfig(HttpServletRequest request, @RequestParam(name = "authorityId") Long authorityId) {
        log.info("【setWebPageAuthoritOutputConfig】authorityId:" + authorityId);

        try {
            User user = UserUtils.getUser(request);
            if (user == null) {
                return ResultResponseBeanUtil.fail("请重新登录");
            }
            if (!webpageAuthorityService.checkAuthorityByAuthorityId(user.getPropertyAuthorityId(), 1)) {
                return ResultResponseBeanUtil.fail("未找到所属页面");
            }

//        if (user.getAuthorityId().longValue() != authorityId.longValue()) {
//            Authority subAuthority = authorityService.getById(authorityId);
//            if (user.getAuthorityId().longValue() != subAuthority.getParentId().longValue()) {
//                return ResultResponseBeanUtil.fail("无此权限组配置权限");
//            }
//        }
            QueryWrapper<WebpageAuthority> wrapper = WrapperUtils.getWrapper(false);
            wrapper.eq("authority_id", user.getPropertyAuthorityId());
            wrapper.eq("is_table_show", 1);
            List<WebpageAuthority> list = webpageAuthorityService.list(wrapper);
            QueryWrapper<WebpageAuthority> subwrapper = WrapperUtils.getWrapper(false);
            subwrapper.eq("authority_id", authorityId);
            subwrapper.eq("is_table_show", 1);

            List<WebpageAuthority> sublist = webpageAuthorityService.list(subwrapper);
            Map<Long, WebpageAuthority> submaps = sublist.stream().collect(Collectors.toMap(WebpageAuthority::getWebId, Function.identity(), (key1, key2) -> key2));
            Map<Long, List<WebpageAuthority>> webpagemap = new HashMap<>();
            for (WebpageAuthority webpageAuthority : list) {
                if (webpagemap.containsKey(webpageAuthority.getParentId())) {
                    webpagemap.get(webpageAuthority.getParentId()).add(webpageAuthority);
                } else {
                    List<WebpageAuthority> subwebpages = new ArrayList<>();
                    subwebpages.add(webpageAuthority);
                    webpagemap.put(webpageAuthority.getParentId(), subwebpages);
                }
                if (submaps.containsKey(webpageAuthority.getWebId())) {
                    webpageAuthority.setCheckStatus(1);
                } else {
                    webpageAuthority.setCheckStatus(0);
                }
            }
            WebPageAuthorityOutput webPageAuthorityOutput = getWebPageAuthorityOutPut(0L, webpagemap, null, false);
            if (webPageAuthorityOutput.getSize() > 0) {
                return ResultResponseBeanUtil.success(webPageAuthorityOutput);
            } else {
                return ResultResponseBeanUtil.fail("未找到所属页面");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultResponseBeanUtil.fail("参数异常，请联系技术人员");
        }
    }


    @ApiOperation(value = "权限组页面展示（选中查询）")
    @ResponseBody
    @RequestMapping(value = "/showWebPageAuthoritOutput", method = RequestMethod.GET)
    public BaseOutput<WebPageAuthorityOutput> showWebPageAuthoritOutput(HttpServletRequest request) {

        User user = UserUtils.getUser(request);
        if (user == null) {
            return ResultResponseBeanUtil.fail("请重新登录");
        }
        if (!webpageAuthorityService.checkAuthorityByAuthorityId(user.getPropertyAuthorityId(), 1)) {
            return ResultResponseBeanUtil.fail("未找到所属页面");
        }
        log.info("【showWebPageAuthoritOutput】user:" + JSONObject.toJSONString(user));

        QueryWrapper<WebpageAuthority> wrapper = WrapperUtils.getWrapper(false);
        wrapper.eq("authority_id", user.getPropertyAuthorityId());
        wrapper.eq("check_status", 1);
        wrapper.eq("is_table_show", 1);
        wrapper.orderByAsc("order_by");
        List<WebpageAuthority> list = webpageAuthorityService.list(wrapper);
        Map<Long, List<WebpageAuthority>> webpagemap = new HashMap<>();
        for (WebpageAuthority webpageAuthority : list) {
            if (webpagemap.containsKey(webpageAuthority.getParentId())) {
                webpagemap.get(webpageAuthority.getParentId()).add(webpageAuthority);
            } else {
                List<WebpageAuthority> subwebpages = new ArrayList<>();
                subwebpages.add(webpageAuthority);
                webpagemap.put(webpageAuthority.getParentId(), subwebpages);
            }
        }
        WebPageAuthorityOutput webPageAuthorityOutput = getWebPageAuthorityOutPut(0L, webpagemap, null, false);
        if (webPageAuthorityOutput.getSize() > 0) {
            return ResultResponseBeanUtil.success(webPageAuthorityOutput);
        } else {
            return ResultResponseBeanUtil.fail("未找到所属页面");
        }
    }


    @ApiOperation(value = "权限组页面展示（缓存）")
    @ResponseBody
    @RequestMapping(value = "/showWebPageAuthoritOutputCache", method = RequestMethod.GET)
    public BaseOutput<WebPageAuthorityOutput> showWebPageAuthoritOutputCache(HttpServletRequest request) {

        User user = UserUtils.getUser(request);
        if (user == null) {
            return ResultResponseBeanUtil.fail("请重新登录");
        }
        if (!webpageAuthorityService.checkAuthorityByAuthorityId(user.getPropertyAuthorityId(), 1)) {
            return ResultResponseBeanUtil.fail("未找到所属页面");
        }
        log.info("【showWebPageAuthoritOutput】user:" + JSONObject.toJSONString(user));

        QueryWrapper<WebpageAuthority> wrapper = WrapperUtils.getWrapper(false);
        wrapper.eq("authority_id", user.getPropertyAuthorityId());
        wrapper.eq("check_status", 1);
        wrapper.orderByAsc("order_by");
        List<WebpageAuthority> list = webpageAuthorityService.list(wrapper);
        Map<Long, List<WebpageAuthority>> webpagemap = new HashMap<>();
        for (WebpageAuthority webpageAuthority : list) {
            if (webpagemap.containsKey(webpageAuthority.getParentId())) {
                webpagemap.get(webpageAuthority.getParentId()).add(webpageAuthority);
            } else {
                List<WebpageAuthority> subwebpages = new ArrayList<>();
                subwebpages.add(webpageAuthority);
                webpagemap.put(webpageAuthority.getParentId(), subwebpages);
            }
        }
        WebPageAuthorityOutput webPageAuthorityOutput = getWebPageAuthorityOutPut(0L, webpagemap, null, true);
        if (webPageAuthorityOutput.getSize() > 0) {
            return ResultResponseBeanUtil.success(webPageAuthorityOutput);
        } else {
            return ResultResponseBeanUtil.fail("未找到所属页面");
        }
    }


    @ApiOperation(value = "查询权限组")
    @ResponseBody
    @RequestMapping(value = "/queryAuthority", method = RequestMethod.POST)
    @AvoidRepeatSubmit
    public BaseOutput<PageOutput<AuthorityOutput>> queryAuthority(HttpServletRequest request, @RequestBody AuthorityPageInput input) {
        log.info("【queryAuthority】input" + JSONObject.toJSONString(input));

        User user = UserUtils.getUser(request);
        if (user == null) {
            return ResultResponseBeanUtil.fail("请重新登录");
        }


        PageOutput<AuthorityOutput> output = new PageOutput<>();

        List<AuthorityOutput> authorityOutputs = new ArrayList<>();
        QueryWrapper<Authority> wrapper = WrapperUtils.getWrapper(false);
        Agent agent = agentService.getById(user.getAgentId());
        //总部查询所有
        if (!agent.getChannelNo().equals("Z")) {
//            //非总部仅查询当前
//        } else {
            wrapper.eq("agent_id", user.getAgentId());
        }
        if(user.getEnterpriseType()==2){
            if(user.getPropertyId()>0){
                wrapper.eq("property_id", user.getPropertyId());

            }else{
                //不显示
                wrapper.eq("property_id", "-1");

            }
        }


//        wrapper.orderByDesc("modify_time");
        wrapper = WrapperUtils.beanToWrapper(wrapper, input);

        Page<Authority> page = new Page<>(input.getPage(), input.getRows());
        Page<Authority> pageList = authorityService.page(page, wrapper);
        List<Authority> records = pageList.getRecords();
        QueryWrapper<User> countwrapper = WrapperUtils.getWrapper(false);
        for (Authority authority : records) {
            AuthorityOutput authorityOutput = new AuthorityOutput();
            BeanUtils.copyProperties(authority, authorityOutput);
            if(authority.getIsagent()==1){
                String agentName = redisService5.get("name:Agent:" + authority.getAgentId());
                authorityOutput.setAgentName(agentName);
            }else{
                String propertyname = redisService5.get("name:Properyt:" + authority.getPropertyId());
                authorityOutput.setAgentName(propertyname);
            }

            countwrapper.eq("authority_id", authority.getId());
            int count = userService.count(countwrapper);
            authorityOutput.setUserCount(count);
            authorityOutputs.add(authorityOutput);
        }
        output.setPage(pageList.getCurrent());
        output.setRecords(pageList.getTotal());
        output.setTotal(pageList.getPages());
        output.setRows(authorityOutputs);

        return ResultResponseBeanUtil.success(output);
    }


    @ApiOperation(value = "查询页面按钮")
    @ResponseBody
    @RequestMapping(value = "/queryButtonByWeb", method = RequestMethod.GET)
    @AvoidRepeatSubmit
    public BaseOutput<List<Button>> queryButtonByWeb(HttpServletRequest request, @RequestParam Long webId) {
        log.info("【queryButtonByWeb】webId:" + webId);
        QueryWrapper<Button> wrapper = WrapperUtils.getWrapper(false);
        wrapper.eq("web_id", webId);
        wrapper.orderByAsc("order_by");
        List<Button> list = buttonService.list(wrapper);
        return ResultResponseBeanUtil.success(list);
    }

    @ApiOperation(value = "查询页面字段")
    @ResponseBody
    @RequestMapping(value = "/queryFieldByWeb", method = RequestMethod.GET)
    @AvoidRepeatSubmit
    public BaseOutput<List<PageField>> queryFieldByWeb(HttpServletRequest request, @RequestParam Long webId) {
        log.info("【queryFieldByWeb】webId:" + webId);

        QueryWrapper<PageField> wrapper = WrapperUtils.getWrapper(false);
        wrapper.eq("web_id", webId);
        wrapper.orderByAsc("order_by");
        List<PageField> list = pageFieldService.list(wrapper);
        return ResultResponseBeanUtil.success(list);
    }

    @ApiOperation(value = "获取权限组关联页面字段")
    @ResponseBody
    @RequestMapping(value = "/showFieldWebpageAuthority", method = RequestMethod.POST)
    @AvoidRepeatSubmit
    public BaseOutput<List<FieldWebpageAuthority>> showFieldWebpageAuthority(HttpServletRequest request, @RequestBody WebpageAuthorityParamInput input) {
        log.info("【showFieldWebpageAuthority】input" + JSONObject.toJSONString(input));
        User user = UserUtils.getUser(request);
        if (user == null) {
            return ResultResponseBeanUtil.fail("请重新登录");
        }
        QueryWrapper<FieldWebpageAuthority> wrapper = WrapperUtils.getWrapper(false);
        wrapper.eq("web_id", input.getWebId());
        wrapper.eq("authority_id", user.getPropertyAuthorityId());
        wrapper.eq("check_status", 1);
        wrapper.orderByAsc("order_by");
        List<FieldWebpageAuthority> list = fieldWebpageAuthorityService.list(wrapper);
        return ResultResponseBeanUtil.success(list);
    }


    @ApiOperation(value = "查询权限组页面按钮配置")
    @ResponseBody
    @RequestMapping(value = "/queryButtonWebpageAuthorityConfig", method = RequestMethod.POST)
    @AvoidRepeatSubmit
    public BaseOutput<List<ButtonWebpageAuthority>> queryButtonWebpageAuthorityConfig(HttpServletRequest request, @RequestBody WebpageAuthorityParamInput input) {
        log.info("【queryButtonWebpageAuthorityConfig】input" + JSONObject.toJSONString(input));
        User user = UserUtils.getUser(request);
        if (user == null) {
            return ResultResponseBeanUtil.fail("请重新登录");
        }
        List<ButtonWebpageAuthority> list;
        QueryWrapper<ButtonWebpageAuthority> wrapper = WrapperUtils.getWrapper(false);
        wrapper.eq("web_id", input.getWebId());
        wrapper.eq("authority_id", input.getAuthorityId());
        wrapper.orderByAsc("order_by");
        list = buttonWebpageAuthorityService.list(wrapper);
        if (user.getPropertyAuthorityId().equals(input.getAuthorityId())) {
            return ResultResponseBeanUtil.success(list);
        } else {
            Map<Long, ButtonWebpageAuthority> curmaps = list.stream().collect(Collectors.toMap(ButtonWebpageAuthority::getButtonId, Function.identity(), (key1, key2) -> key2));

            Authority curAuthority = authorityService.getById(input.getAuthorityId());
//            Authority parentAuthority = authorityService.getById(curAuthority.getParentId());
            QueryWrapper<ButtonWebpageAuthority> curwrapper = WrapperUtils.getWrapper(false);
            curwrapper.eq("web_id", input.getWebId());
            curwrapper.eq("authority_id", curAuthority.getParentId());
            curwrapper.orderByAsc("order_by");
            List<ButtonWebpageAuthority> parentList = buttonWebpageAuthorityService.list(curwrapper);
            for (ButtonWebpageAuthority next : parentList) {
                if (curmaps.containsKey(next.getButtonId())) {
                    ButtonWebpageAuthority buttonWebpageAuthority = curmaps.get(next.getButtonId());
                    next.setCheckStatus(buttonWebpageAuthority.getCheckStatus());
                } else {
                    next.setCheckStatus(0);
                }
            }
            return ResultResponseBeanUtil.success(parentList);

        }

    }

    @ApiOperation(value = "查询权限组页面字段配置")
    @ResponseBody
    @RequestMapping(value = "/queryFieldWebpageAuthorityConfig", method = RequestMethod.POST)
    @AvoidRepeatSubmit
    public BaseOutput<List<FieldWebpageAuthority>> queryFieldWebpageAuthorityConfig(HttpServletRequest request, @RequestBody WebpageAuthorityParamInput input) {
        log.info("【queryFieldWebpageAuthorityConfig】input" + JSONObject.toJSONString(input));
        User user = UserUtils.getUser(request);
        if (user == null) {
            return ResultResponseBeanUtil.fail("请重新登录");
        }
        QueryWrapper<FieldWebpageAuthority> wrapper = WrapperUtils.getWrapper(false);
        wrapper.eq("web_id", input.getWebId());
        wrapper.eq("authority_id", input.getAuthorityId());
        wrapper.orderByAsc("order_by");
        List<FieldWebpageAuthority> list = fieldWebpageAuthorityService.list(wrapper);


        if (user.getPropertyAuthorityId().equals(input.getAuthorityId())) {
            return ResultResponseBeanUtil.success(list);
        } else {
            Map<Long, FieldWebpageAuthority> curmaps = list.stream().collect(Collectors.toMap(FieldWebpageAuthority::getFieldId, Function.identity(), (key1, key2) -> key2));

            Authority curAuthority = authorityService.getById(input.getAuthorityId());
            QueryWrapper<FieldWebpageAuthority> curwrapper = WrapperUtils.getWrapper(false);
            curwrapper.eq("web_id", input.getWebId());
            curwrapper.eq("authority_id", curAuthority.getParentId());
            curwrapper.orderByAsc("order_by");
            List<FieldWebpageAuthority> parentList = fieldWebpageAuthorityService.list(curwrapper);
            for (FieldWebpageAuthority next : parentList) {
                if (curmaps.containsKey(next.getFieldId())) {
                    FieldWebpageAuthority fieldWebpageAuthority = curmaps.get(next.getFieldId());
                    next.setCheckStatus(fieldWebpageAuthority.getCheckStatus());
                } else {
                    next.setCheckStatus(0);
                }
            }
            return ResultResponseBeanUtil.success(parentList);

        }


    }


    @ApiOperation(value = "获取权限组页面按钮")
    @ResponseBody
    @RequestMapping(value = "/showButtonWebpageAuthority", method = RequestMethod.POST)
    @AvoidRepeatSubmit
    public BaseOutput<List<ButtonWebpageAuthority>> showButtonWebpageAuthority(HttpServletRequest request, @RequestBody WebpageAuthorityParamInput input) {
        log.info("【showButtonWebpageAuthority】input" + JSONObject.toJSONString(input));
        User user = UserUtils.getUser(request);
        if (user == null) {
            return ResultResponseBeanUtil.fail("请重新登录");
        }
        QueryWrapper<ButtonWebpageAuthority> wrapper = WrapperUtils.getWrapper(false);
        wrapper.eq("web_id", input.getWebId());
        wrapper.eq("authority_id", user.getPropertyAuthorityId());
        wrapper.eq("check_status", 1);
        wrapper.orderByAsc("order_by");
        List<ButtonWebpageAuthority> list = buttonWebpageAuthorityService.list(wrapper);
        return ResultResponseBeanUtil.success(list);
    }

    /*
    变更块
     */
    @ApiOperation(value = "修改页面")
    @ResponseBody
    @RequestMapping(value = "/updateWebpage", method = RequestMethod.POST)
    @AvoidRepeatSubmit
    public BaseOutput<String> updateWebpage(HttpServletRequest request, @RequestBody Webpage input) {
        log.info("【updateWebpage】Webpage" + JSONObject.toJSONString(input));
        User user = UserUtils.getUser(request);
        if (user == null) {
            return ResultResponseBeanUtil.fail("请重新登录");
        }
        QueryWrapper<Webpage> checkwrapper = WrapperUtils.getWrapper(false);
        checkwrapper.eq("title", input.getTitle());
        checkwrapper.eq("soft_delete", 0);
        List<Webpage> checklist = webpageService.list(checkwrapper);
        if (!checklist.isEmpty()) {
            if (checklist.size() <= 1) {
                if (checklist.get(0).getId().intValue() != input.getId().intValue()) {
                    return ResultResponseBeanUtil.fail("存在同名页面，请修改页面名称");
                }

            } else {
                return ResultResponseBeanUtil.fail("存在同名页面，请修改页面名称");

            }
        }


        Webpage webpage = webpageService.getById(input.getId());
        webpage.setTitle(input.getTitle());
        webpage.setPath(input.getPath());
        webpage.setOrderBy(input.getOrderBy());
        webpage.setIcon(input.getIcon());
        webpage.setDescription(input.getDescription());
        webpage.setParentId(input.getParentId());
        webpage.setType(input.getType());
        webpage.setIsTableShow(input.getIsTableShow());
        webpageService.updateById(webpage);
        QueryWrapper<WebpageAuthority> wrapper = WrapperUtils.getWrapper(false);
        wrapper.eq("web_id", webpage.getId());
        List<WebpageAuthority> list = webpageAuthorityService.list(wrapper);
        for (WebpageAuthority webpageAuthority : list) {
            webpageAuthority.setTitle(webpage.getTitle());
            webpageAuthority.setPath(webpage.getPath());
            webpageAuthority.setOrderBy(webpage.getOrderBy());
            webpageAuthority.setIcon(webpage.getIcon());
            webpageAuthority.setDescription(input.getDescription());
            webpageAuthority.setType(input.getType());
            webpageAuthority.setParentId(input.getParentId());
            webpageAuthority.setIsTableShow(input.getIsTableShow());
        }
        webpageAuthorityService.updateBatchById(list);

        return ResultResponseBeanUtil.success("修改成功");
    }

    @ApiOperation(value = "修改页面按钮关联")
    @ResponseBody
    @RequestMapping(value = "/updateButton", method = RequestMethod.POST)
    @AvoidRepeatSubmit
    public BaseOutput<String> updateButton(HttpServletRequest request, @RequestBody Button input) {
        log.info("【updateButton】Button" + JSONObject.toJSONString(input));
        User user = UserUtils.getUser(request);
        if (user == null) {
            return ResultResponseBeanUtil.fail("请重新登录");
        }
        try {
            Button button = buttonService.getById(input.getId());

            button.setCnName(input.getCnName());
            button.setEnName(input.getEnName());
            button.setIcon(input.getIcon());
            button.setOrderBy(input.getOrderBy());
            button.setType(input.getType());
            button.setClassName(input.getClassName());
            button.setTheme(input.getTheme());


            buttonService.updateById(button);
            QueryWrapper<ButtonWebpageAuthority> wrapper = WrapperUtils.getWrapper(false);
            wrapper.eq("button_id", input.getId());
            List<ButtonWebpageAuthority> list = buttonWebpageAuthorityService.list(wrapper);
            for (ButtonWebpageAuthority buttonWebpageAuthority : list) {
                buttonWebpageAuthority.setCnName(button.getCnName());
                buttonWebpageAuthority.setEnName(button.getEnName());
                buttonWebpageAuthority.setIcon(button.getIcon());
                buttonWebpageAuthority.setOrderBy(button.getOrderBy());
                buttonWebpageAuthority.setType(button.getType());
                buttonWebpageAuthority.setClassName(button.getClassName());
                buttonWebpageAuthority.setTheme(input.getTheme());
                buttonWebpageAuthorityService.updateById(buttonWebpageAuthority);
            }
            return ResultResponseBeanUtil.success("修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultResponseBeanUtil.fail("修改失败");

        }
    }


    @ApiOperation(value = "修改权限组")
    @ResponseBody
    @RequestMapping(value = "/updateAuthority", method = RequestMethod.POST)
    @AvoidRepeatSubmit
    public BaseOutput<String> updateAuthority(HttpServletRequest request, @RequestBody Authority input) {
        log.info("【updateAuthority】Authority" + JSONObject.toJSONString(input));
        User user = UserUtils.getUser(request);
        if (user == null) {
            return ResultResponseBeanUtil.fail("请重新登录");
        }
        Authority curauthority = authorityService.getById(input.getId());

        QueryWrapper<Authority> wrapper = WrapperUtils.getWrapper(false);
        wrapper.eq("name", input.getName());
        wrapper.eq("agent_id", input.getAgentId());
        wrapper.eq("property_id", input.getPropertyId());
        List<Authority> list = authorityService.list(wrapper);
        if(!list.isEmpty()){
            Authority authority = list.get(0);
            if(authority.getId()!=curauthority.getId()){
                return ResultResponseBeanUtil.fail("同名权限组已存在");
            }
        }



        curauthority.setName(input.getName());
//        authority.setIsagent(input.getIsagent());
        curauthority.setMemo(input.getMemo());
        if(input.getMemo()==null){
            curauthority.setMemo("");
        }
        authorityService.updateById(curauthority);
        redisService5.set("name:PropertyAuthority:" + curauthority.getId(), curauthority.getName());

//        QueryWrapper<ButtonWebpageAuthority> wrapper = WrapperUtils.getWrapper(false);
//        wrapper.eq("button_id", input.getId());
//        List<ButtonWebpageAuthority> list = buttonWebpageAuthorityService.list(wrapper);
//        buttonWebpageAuthorityService.update(wrapper);

        return ResultResponseBeanUtil.success("修改成功");
    }


    @ApiOperation(value = "修改权限组页面关联")
    @ResponseBody
    @RequestMapping(value = "/updateWebpageAuthority", method = RequestMethod.POST)
    @AvoidRepeatSubmit
    public BaseOutput<String> updateWebpageAuthority(HttpServletRequest request, @RequestBody WebpageAuthority input) {
        log.info("【updateWebpageAuthority】input" + JSONObject.toJSONString(input));
        User user = UserUtils.getUser(request);
        if (user == null) {
            return ResultResponseBeanUtil.fail("请重新登录");
        }
        WebpageAuthority webpageAuthority = webpageAuthorityService.getById(input.getId());
        webpageAuthority.setCheckStatus(input.getCheckStatus());

        webpageAuthorityService.updateById(webpageAuthority);
        if (input.getCheckStatus() == 0) {
            QueryWrapper<FieldWebpageAuthority> fieldwrapper = WrapperUtils.getWrapper(false);
            fieldwrapper.eq("web_id", input.getWebId());
            fieldwrapper.eq("authority_id", input.getAuthorityId());

            List<FieldWebpageAuthority> fildlist = fieldWebpageAuthorityService.list(fieldwrapper);
            for (FieldWebpageAuthority next : fildlist) {
                next.setSoftDelete(1);
                next.setModifyTime(new Date());
                fieldWebpageAuthorityService.updateById(next);
            }
            QueryWrapper<ButtonWebpageAuthority> buttonwrapper = WrapperUtils.getWrapper(false);
            buttonwrapper.eq("web_id", input.getWebId());
            buttonwrapper.eq("authority_id", input.getAuthorityId());

            List<ButtonWebpageAuthority> buttonlist = buttonWebpageAuthorityService.list(buttonwrapper);
            for (ButtonWebpageAuthority next : buttonlist) {
                next.setSoftDelete(1);
                next.setModifyTime(new Date());
                buttonWebpageAuthorityService.updateById(next);
            }

        }
        return ResultResponseBeanUtil.success("页面修改成功");

    }

    @ApiOperation(value = "修改页面字段关联")
    @ResponseBody
    @RequestMapping(value = "/updatePageField", method = RequestMethod.POST)
    @AvoidRepeatSubmit
    public BaseOutput<String> updatePageField(HttpServletRequest request, @RequestBody PageField input) {
        log.info("【updatePageField】input" + JSONObject.toJSONString(input));
        PageField pageField = pageFieldService.getById(input.getId());
        pageField.setCnName(input.getCnName());
        pageField.setEnName(input.getEnName());
        pageField.setIsSelect(input.getIsSelect());
        pageField.setFieldType(input.getFieldType());
        pageField.setNavSelect(input.getNavSelect());
        pageField.setOrderBy(input.getOrderBy());
        pageField.setParam(input.getParam());
        pageField.setWidth(input.getWidth());
        pageField.setIsTableShow(input.getIsTableShow());
        boolean save = pageFieldService.updateById(pageField);

        try {
            if (save) {
                QueryWrapper<FieldWebpageAuthority> wrapper = WrapperUtils.getWrapper(false);
                wrapper.eq("field_id", input.getId());
                List<FieldWebpageAuthority> list = fieldWebpageAuthorityService.list(wrapper);
                for (FieldWebpageAuthority fieldWebpageAuthority : list) {
                    fieldWebpageAuthority.setCnName(input.getCnName());
                    fieldWebpageAuthority.setEnName(input.getEnName());
                    fieldWebpageAuthority.setIsSelect(input.getIsSelect());
                    fieldWebpageAuthority.setFieldType(input.getFieldType());
                    fieldWebpageAuthority.setNavSelect(input.getNavSelect());
                    fieldWebpageAuthority.setOrderBy(input.getOrderBy());
                    fieldWebpageAuthority.setParam(input.getParam());
                    fieldWebpageAuthority.setIsTableShow(input.getIsTableShow());
                    fieldWebpageAuthority.setWidth(input.getWidth());
                    fieldWebpageAuthorityService.updateById(fieldWebpageAuthority);
                }
                return ResultResponseBeanUtil.success("字段修改成功");
            } else {
                return ResultResponseBeanUtil.fail("字段修改失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultResponseBeanUtil.fail("修改权限关联字段失败");
        }
    }

    @ApiOperation(value = "修改权限组页面按钮关联")
    @ResponseBody
    @RequestMapping(value = "/updateButtonWebpageAuthority", method = RequestMethod.POST)
    @AvoidRepeatSubmit
    public BaseOutput<String> updateButtonWebpageAuthority(HttpServletRequest request, @RequestBody ButtonWebpageAuthority input) {
        log.info("【updateButtonWebpageAuthority】input" + JSONObject.toJSONString(input));

        ButtonWebpageAuthority byId = buttonWebpageAuthorityService.getById(input.getId());
        byId.setCheckStatus(input.getCheckStatus());
        boolean save = buttonWebpageAuthorityService.updateById(byId);
        if (save) {
            return ResultResponseBeanUtil.success("权限的页面按钮修改成功");
        } else {
            return ResultResponseBeanUtil.fail("权限的页面按钮修改失败");
        }
    }

    @ApiOperation(value = "修改权限组页面字段关联")
    @ResponseBody
    @RequestMapping(value = "/updateFieldWebpageAuthority", method = RequestMethod.POST)
    @AvoidRepeatSubmit
    public BaseOutput<String> updateFieldWebpageAuthority(HttpServletRequest request, @RequestBody FieldWebpageAuthority input) {
        log.info("【updateFieldWebpageAuthority】input" + JSONObject.toJSONString(input));
//        User user = UserUtils.getUser(request);
//        if (user == null) {
//            return ResultResponseBeanUtil.fail("请重新登录");
//        }
        FieldWebpageAuthority byId = fieldWebpageAuthorityService.getById(input.getId());
        byId.setCheckStatus(input.getCheckStatus());
        boolean save = fieldWebpageAuthorityService.updateById(byId);
        if (save) {
            return ResultResponseBeanUtil.success("修改权限组页面字段关联成功");
        } else {
            return ResultResponseBeanUtil.fail("修改权限组页面字段关联失败");
        }
    }


    @ApiOperation(value = "删除页面")
    @ResponseBody
    @RequestMapping(value = "/deleteWebpage", method = RequestMethod.GET)
    public BaseOutput<Void> deleteWebpage(HttpServletRequest request, @RequestParam(name = "webId") Long webId) {
        log.info("【deleteWebpage】webid:" + webId);
        User user = UserUtils.getUser(request);
        if (user == null) {
            return ResultResponseBeanUtil.fail("请重新登录");
        }
        //删除页面的权限
        log.info("【deleteWebpage】user:" + user.getName() + "清除id为" + webId + "的页面");
        Webpage byId = webpageService.getById(webId);
        byId.setSoftDelete(1);
        byId.setModifyTime(new Date());
        byId.setModifyId(user.getId());
        webpageService.updateById(byId);

        QueryWrapper<WebpageAuthority> wrapper = WrapperUtils.getWrapper(false);
        wrapper.eq("web_id", webId);
        List<WebpageAuthority> list = webpageAuthorityService.list(wrapper);
        for (WebpageAuthority next : list) {
            next.setSoftDelete(1);
            next.setModifyTime(new Date());
            next.setModifyId(user.getId());
            webpageAuthorityService.updateById(next);
        }
        QueryWrapper<FieldWebpageAuthority> fieldwrapper = WrapperUtils.getWrapper(false);
        fieldwrapper.eq("web_id", webId);
        List<FieldWebpageAuthority> fildlist = fieldWebpageAuthorityService.list(fieldwrapper);
        for (FieldWebpageAuthority next : fildlist) {
            next.setSoftDelete(1);
            next.setModifyTime(new Date());
            next.setModifyId(user.getId());
            fieldWebpageAuthorityService.updateById(next);
        }
        QueryWrapper<ButtonWebpageAuthority> buttonwrapper = WrapperUtils.getWrapper(false);
        buttonwrapper.eq("web_id", webId);
        List<ButtonWebpageAuthority> buttonlist = buttonWebpageAuthorityService.list(buttonwrapper);
        for (ButtonWebpageAuthority next : buttonlist) {
            next.setSoftDelete(1);
            next.setModifyTime(new Date());
            next.setModifyId(user.getId());
            buttonWebpageAuthorityService.updateById(next);
        }


        return ResultResponseBeanUtil.success();
    }

//
//    @ApiOperation(value = "取消权限组页面")
//    @ResponseBody
//    @RequestMapping(value = "/deleteWebpageAuthority", method = RequestMethod.POST)
//    public BaseOutput<Void> deleteWebpageAuthority(HttpServletRequest request, @RequestBody WebpageAuthorityParamInput input) {
//        log.info("【deleteWebpageAuthority】input:" + JSONObject.toJSONString(input));
//        User user = UserUtils.getUser(request);
//        if (user == null) {
//            return ResultResponseBeanUtil.fail("请重新登录");
//        }
//        //删除页面的权限
//        log.info("【deleteWebpage】user:" + user.getName() + "清除id为" + webId + "的页面");
//        webpageService.removeById(webId);
//        QueryWrapper<WebpageAuthority> wrapper = WrapperUtils.getWrapper(false);
//        wrapper.eq("web_id", webId);
//        webpageAuthorityService.remove(wrapper);
//        QueryWrapper<ButtonWebpageAuthority> buttonwrapper = WrapperUtils.getWrapper(false);
//        buttonwrapper.eq("web_id", webId);
//        buttonWebpageAuthorityService.remove(buttonwrapper);
//        QueryWrapper<FieldWebpageAuthority> fieldwrapper = WrapperUtils.getWrapper(false);
//        fieldwrapper.eq("web_id", webId);
//        fieldWebpageAuthorityService.remove(fieldwrapper);
//        return ResultResponseBeanUtil.success();
//    }

    @ApiOperation(value = "删除权限组")
    @ResponseBody
    @RequestMapping(value = "/deleteAuthority", method = RequestMethod.GET)
    public BaseOutput<Void> deleteAuthority(HttpServletRequest request, @RequestParam(name = "authorityId") Long authorityId) {
        log.info("【deleteWebpage】authorityId:" + authorityId);
        User user = UserUtils.getUser(request);
        if (user == null) {
            return ResultResponseBeanUtil.fail("请重新登录");
        }
        if (authorityId == 1) {
            return ResultResponseBeanUtil.fail("系统权限组不允许删除");
        }
        log.info("【deleteWebpage】user:" + user.getName() + "清除id为" + authorityId + "的权限组");
        Authority curAuthority = authorityService.getById(authorityId);

        Authority byId = authorityService.getById(user.getPropertyAuthorityId());
        if (byId.getParentId() != 1 && !byId.getParentId().equals(user.getPropertyAuthorityId())) {
            if (user.getPropertyAuthorityId() != 1) {
                return ResultResponseBeanUtil.fail("无此权限组删除权限");
            }
        }
        curAuthority.setModifyId(user.getId());
        curAuthority.setSoftDelete(1);
        curAuthority.setModifyTime(new Date());
        authorityService.updateById(curAuthority);

        UpdateWrapper<User> updateWrapper = WrapperUtils.getUpdateWrapper(false);
        updateWrapper.eq("property_authority_id", authorityId);
        updateWrapper.setSql("property_authority_id=" + 0 + ", modify_time= NOW()");
        userService.update(updateWrapper);

        QueryWrapper<WebpageAuthority> wrapper = WrapperUtils.getWrapper(false);
        wrapper.eq("authority_id", authorityId);
        List<WebpageAuthority> list = webpageAuthorityService.list(wrapper);
        for (WebpageAuthority next : list) {
            next.setSoftDelete(1);
            next.setModifyTime(new Date());
            next.setModifyId(user.getId());

            webpageAuthorityService.updateById(next);
        }

        QueryWrapper<ButtonWebpageAuthority> buttonwrapper = WrapperUtils.getWrapper(false);
        buttonwrapper.eq("authority_id", authorityId);
        List<ButtonWebpageAuthority> buttonlist = buttonWebpageAuthorityService.list(buttonwrapper);
        for (ButtonWebpageAuthority next : buttonlist) {
            next.setSoftDelete(1);
            next.setModifyTime(new Date());
            next.setModifyId(user.getId());

            buttonWebpageAuthorityService.updateById(next);
        }

        QueryWrapper<FieldWebpageAuthority> fieldwrapper = WrapperUtils.getWrapper(false);
        fieldwrapper.eq("authority_id", authorityId);
        List<FieldWebpageAuthority> fildlist = fieldWebpageAuthorityService.list(fieldwrapper);
        for (FieldWebpageAuthority next : fildlist) {
            next.setSoftDelete(1);
            next.setModifyTime(new Date());
            next.setModifyId(user.getId());

            fieldWebpageAuthorityService.updateById(next);
        }

        QueryWrapper<User> userwrapper = WrapperUtils.getWrapper(false);
        userwrapper.eq("property_authority_id", authorityId);
        List<User> userlist = userService.list(userwrapper);
        for (User next : userlist) {
            next.setModifyTime(new Date());
            next.setAuthorityId(0L);
            next.setModifyId(user.getId());
            userService.updateById(next);
        }
        return ResultResponseBeanUtil.success();
    }


    @ApiOperation(value = "删除页面字段")
    @ResponseBody
    @RequestMapping(value = "/deleteField", method = RequestMethod.GET)
    public BaseOutput<Void> deleteField(HttpServletRequest request, @RequestParam(name = "fieldId") Long fieldId) {
        log.info("【deleteField】fieldId:" + fieldId);
        User user = UserUtils.getUser(request);
        if (user == null) {
            return ResultResponseBeanUtil.fail("请重新登录");
        }
        log.info("【deleteField】user:" + user.getName() + "清除id为" + fieldId + "的列");

        PageField byId = pageFieldService.getById(fieldId);
        byId.setSoftDelete(1);
        byId.setModifyTime(new Date());
        boolean b = pageFieldService.updateById(byId);

//        pageFieldService.removeById(fieldId);
        QueryWrapper<FieldWebpageAuthority> fieldwrapper = WrapperUtils.getWrapper(false);
        fieldwrapper.eq("field_id", fieldId);
        List<FieldWebpageAuthority> fildlist = fieldWebpageAuthorityService.list(fieldwrapper);
        for (FieldWebpageAuthority next : fildlist) {
            next.setSoftDelete(1);
            next.setModifyTime(new Date());
            next.setModifyId(user.getId());

            fieldWebpageAuthorityService.updateById(next);
        }
        return ResultResponseBeanUtil.success();
    }

    @ApiOperation(value = "删除页面按钮")
    @ResponseBody
    @RequestMapping(value = "/deleteButton", method = RequestMethod.GET)
    public BaseOutput<Void> deleteButton(HttpServletRequest request, @RequestParam(name = "buttonId") Long buttonId) {
        log.info("【deleteButton】buttonId:" + buttonId);
        User user = UserUtils.getUser(request);
        if (user == null) {
            return ResultResponseBeanUtil.fail("请重新登录");
        }
        log.info("【deleteButton】user:" + user.getName() + "清除id为" + buttonId + "的页面按钮");
        Button byId = buttonService.getById(buttonId);
        byId.setSoftDelete(1);
        byId.setModifyTime(new Date());
        byId.setModifyId(user.getId());

        buttonService.updateById(byId);

        QueryWrapper<ButtonWebpageAuthority> buttonwrapper = WrapperUtils.getWrapper(false);
        buttonwrapper.eq("button_id", buttonId);
        List<ButtonWebpageAuthority> buttonlist = buttonWebpageAuthorityService.list(buttonwrapper);
        for (ButtonWebpageAuthority next : buttonlist) {
            next.setSoftDelete(1);
            next.setModifyTime(new Date());
            next.setModifyId(user.getId());

            buttonWebpageAuthorityService.updateById(next);
        }
        return ResultResponseBeanUtil.success();
    }


    /*
    检查父id页面是否添加，如未添加则增加
     */
    private void checkWebPageParentId(WebpageAuthorityParamInput input, Webpage webpage) {
        Set<String> members =   redisService4.setMembers("AuthorityWebpage:" + input.getAuthorityId());

        assert members != null;
        if (!members.contains(webpage.getParentId() + "")) {
            Webpage parentwebpage = webpageService.getById(webpage.getParentId());
            if (parentwebpage != null) {
                savewebpageAuthority(input, parentwebpage);

            }
        }
    }

    private void savewebpageAuthority(WebpageAuthorityParamInput input, Webpage webpage) {


        WebpageAuthority webpageAuthority = new WebpageAuthority();
        QueryWrapper<WebpageAuthority> wrapper = WrapperUtils.getWrapper(false);
        wrapper.eq("authority_id", input.getAuthorityId());
        wrapper.eq("web_id", webpage.getId());
        int count = webpageAuthorityService.count(wrapper);
        if (count > 0) {
            return;
        }

        webpageAuthority.setWebId(webpage.getId());
        BeanUtils.copyProperties(webpage, webpageAuthority);
        webpageAuthority.setId(null);
        webpageAuthority.setCreateTime(new Date());
        webpageAuthority.setAuthorityId(input.getAuthorityId());
        webpageAuthority.setCheckStatus(1);
        log.info("【savewebpageAuthority】webpageAuthority:" + webpage.getTitle() + "----" + input.getAuthorityId());
        redisService4.add("AuthorityWebpage:" + input.getAuthorityId(), webpage.getId() + "");
        webpageAuthorityService.save(webpageAuthority);
    }

    private PageField getPageField(PageFieldInput input, Field field) {
        PageField pageField = new PageField();
        String name = field.getName();
        String lowerCasename = field.getName().toLowerCase();
        pageField.setEnName(name);
        pageField.setClassName(input.getOutputName());
        if (lowerCasename.contains("status") || lowerCasename.contains("state") || lowerCasename.contains("type")) {
            pageField.setFieldType("select");
            pageField.setWidth(90);

        } else if (lowerCasename.contains("time") || lowerCasename.contains("date")) {
            pageField.setFieldType("date");
            pageField.setWidth(200);
        } else if (lowerCasename.contains("id") && !lowerCasename.equals("id")) {
            pageField.setFieldType("inputSelect");
            pageField.setWidth(80);

        } else {
            pageField.setFieldType("string");
            pageField.setWidth(150);
        }
        pageField.setWebId(input.getWebId());
        pageField.setIsSelect(0);
        pageField.setNavSelect(0);
        pageField.setIsTableShow(1);
        return pageField;
    }

    private ButtonField getButtonField(ButtonFieldInput input, Field field) {
        ButtonField buttonField = new ButtonField();
        String name = field.getName();
        String lowerCasename = field.getName().toLowerCase();
        buttonField.setEnName(name);
        buttonField.setClassName(input.getOutputName());
        if (lowerCasename.contains("status") || lowerCasename.contains("state") || lowerCasename.contains("type")) {
            buttonField.setFieldType("select");
        } else if (lowerCasename.contains("time") || lowerCasename.contains("date")) {
            buttonField.setFieldType("date");
        } else if (lowerCasename.contains("id") && !lowerCasename.equals("id")) {
            buttonField.setFieldType("inputSelect");
        } else {
            buttonField.setFieldType("string");
        }
        buttonField.setButtonId(input.getButtonId());
        buttonField.setIsSelect(0);
        buttonField.setNavSelect(0);
        buttonField.setIsTableShow(1);
        return buttonField;
    }


    /**
     * 页面层级结构
     *
     * @param parentId
     * @param webPageMap
     * @return
     */
    private WebPageOutput getWebPageOutPut(Long parentId, Map<Long, List<Webpage>> webPageMap, Webpage webpageParent) {
        WebPageOutput webPageOutput = new WebPageOutput();
        List<WebPageOutput> webPageOutputs = new ArrayList<>();
        webPageOutput.setChildren(webPageOutputs);
        if (webpageParent != null) {
            BeanUtils.copyProperties(webpageParent, webPageOutput);
        }
        if (webPageMap.containsKey(parentId)) {
            List<Webpage> webpages = webPageMap.get(parentId);
            List<WebPageOutput> subWebPageList = webPageOutput.getChildren();
            for (Webpage webpage : webpages) {
                WebPageOutput webPageOutPut = getWebPageOutPut(webpage.getId(), webPageMap, webpage);
                subWebPageList.add(webPageOutPut);
            }
        } else {
            return webPageOutput;
        }
        webPageOutput.setSize(webPageOutput.getChildren().size());

        return webPageOutput;
    }

    /**
     * 权限页面结构
     *
     * @param parentId
     * @param webPageMap
     * @return
     */
    private WebPageAuthorityOutput getWebPageAuthorityOutPut(Long parentId, Map<Long, List<WebpageAuthority>> webPageMap, WebpageAuthority webpageAuthority, Boolean cache) {
        WebPageAuthorityOutput webPageAuthorityOutput = new WebPageAuthorityOutput();
        List<WebPageAuthorityOutput> webPageAuthorityOutputs = new ArrayList<>();
        webPageAuthorityOutput.setChildren(webPageAuthorityOutputs);
        if (webpageAuthority != null) {
            BeanUtils.copyProperties(webpageAuthority, webPageAuthorityOutput);
        }
        if (webPageMap.containsKey(parentId)) {
            List<WebpageAuthority> webpages = webPageMap.get(parentId);
            List<WebPageAuthorityOutput> subWebPageList = webPageAuthorityOutput.getChildren();
            for (WebpageAuthority subwebpageAuthority : webpages) {
                WebPageAuthorityOutput webPageAuthorityOutPut = getWebPageAuthorityOutPut(subwebpageAuthority.getWebId(), webPageMap, subwebpageAuthority, cache);
                if (cache) {
                    QueryWrapper<FieldWebpageAuthority> wrapper = WrapperUtils.getWrapper(false);
                    wrapper.eq("authority_id", webPageAuthorityOutPut.getAuthorityId());
                    wrapper.eq("web_id", webPageAuthorityOutPut.getWebId());
                    int count = fieldWebpageAuthorityService.count(wrapper);
                    webPageAuthorityOutPut.setFieldSize(count);
                }
                subWebPageList.add(webPageAuthorityOutPut);
            }
        } else {
            webPageAuthorityOutput.setSize(0);
            return webPageAuthorityOutput;
        }
        webPageAuthorityOutput.setSize(webPageAuthorityOutput.getChildren().size());
        return webPageAuthorityOutput;
    }


    @ApiOperation(value = "设置全页面——按钮——字段")
    @ResponseBody
    @RequestMapping(value = "/setAuthorityAll", method = RequestMethod.POST)
    @AvoidRepeatSubmit
    public BaseOutput<String> setAuthorityAll(HttpServletRequest request) {
        User user = UserUtils.getUser(request);
        if (user == null) {
            return ResultResponseBeanUtil.fail("请重新登录");
        }
        QueryWrapper<Webpage> pagewrapper = WrapperUtils.getWrapper(false);
        List<Webpage> list = webpageService.list(pagewrapper);
        QueryWrapper<Button> buttonwrapper = WrapperUtils.getWrapper(false);
        List<Button> buttonListlist = buttonService.list(buttonwrapper);
        QueryWrapper<PageField> fieldwrapper = WrapperUtils.getWrapper(false);
        List<PageField> fieldListlist = pageFieldService.list(fieldwrapper);
        for (PageField next : fieldListlist) {
            setFieldToFidelWebpageAuthority(user, 1L, next);

        }
        for (Button next : buttonListlist) {
            setButtonToButtonWebpageAuthority(user, 1L, next);
        }
        for (Webpage next : list) {
            setWebpageAuthority(next, 1L);
        }
        return ResultResponseBeanUtil.success("按钮添加成功");

    }


    @ApiOperation(value = "自动添加子页面列")
    @ResponseBody
    @RequestMapping(value = "/addButtonField", method = RequestMethod.POST)
    @AvoidRepeatSubmit
    public BaseOutput<String> addButtonField(HttpServletRequest request, @RequestBody ButtonFieldInput input) {
        log.info("【addButtonField】input" + JSONObject.toJSONString(input));
        User user = UserUtils.getUser(request);
        if (user == null) {
            return ResultResponseBeanUtil.fail("请重新登录");
        }
        Class<?> aClass;
        try {
            aClass = Class.forName(input.getOutputName());
            int i = 1;
            Field[] declaredFields = aClass.getDeclaredFields();
            for (Field field : declaredFields) {
                if (field.getName().equals("serialVersionUID")) {
                    continue;
                }
                ButtonField buttonField = getButtonField(input, field);
                buttonField.setOrderBy(i++);
                ApiModelProperty api = field.getAnnotation(ApiModelProperty.class);
                if(api!=null){
                    buttonField.setCnName(api.value());

                }else{
                    buttonField.setCnName("");

                }

                buttonFieldService.save(buttonField);
//                setFieldToFidelWebpageAuthority(user, 1L, pageField);
            }


            Class<?> superclass = aClass.getSuperclass();
            Field[] supperdeclaredFields = superclass.getDeclaredFields();
            for (Field field : supperdeclaredFields) {

                ButtonField buttonField = new ButtonField();
                String name = field.getName();
                if (name.equals("serialVersionUID")) {
                    continue;
                }
                String lowerCasename = field.getName().toLowerCase();
                buttonField.setEnName(name);
                buttonField.setClassName(input.getOutputName());
                if (lowerCasename.contains("status") || lowerCasename.contains("state") || lowerCasename.contains("type")) {
                    buttonField.setFieldType("select");
                } else if (lowerCasename.contains("time") || lowerCasename.contains("date")) {
                    buttonField.setFieldType("date");
                } else if (lowerCasename.contains("id") && !lowerCasename.equals("id")) {
                    buttonField.setFieldType("inputSelect");
                } else {
                    buttonField.setFieldType("string");
                }
                buttonField.setButtonId(input.getButtonId());
                buttonField.setIsSelect(1);
                buttonField.setNavSelect(0);
                buttonField.setOrderBy(i++);
                buttonField.setIsTableShow(1);
                ApiModelProperty api = field.getAnnotation(ApiModelProperty.class);
                if (api == null) {
                    buttonField.setCnName(name);
                } else {
                    buttonField.setCnName(api.value());

                }
                if (lowerCasename.contains("id") && !lowerCasename.equals("id")) {
                    buttonField.setFieldType("inputSelect");
                    buttonField.setNavSelect(1);
//                    PageField idNamePageField = getPageField(input, field);
//                    String nameField = name.replace("Id", "Name");
//                    idNamePageField.setCnName(nameField);
//                    idNamePageField.setOrderBy(i++);
//                    pageFieldService.save(idNamePageField);
//                    setFieldToFidelWebpageAuthority(user, 1L, idNamePageField);
                }
                buttonFieldService.save(buttonField);
//                setFieldToFidelWebpageAuthority(user, 1L, pageField);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return ResultResponseBeanUtil.fail("列添加失败");
        }
        return ResultResponseBeanUtil.success("列添加成功");
    }


    @ApiOperation(value = "人工单独添加子页面列")
    @ResponseBody
    @RequestMapping(value = "/addSingleButtonField", method = RequestMethod.POST)
    @AvoidRepeatSubmit
    public BaseOutput<String> addSingleButtonField(HttpServletRequest request, @RequestBody ButtonField input) {
        log.info("【addSingleField】input" + JSONObject.toJSONString(input));
        User user = UserUtils.getUser(request);
        if (user == null) {
            return ResultResponseBeanUtil.fail("请重新登录");
        }
        if (input.getButtonId() == null || input.getButtonId() == 0) {
            return ResultResponseBeanUtil.fail("请设置所属按钮");
        }
        if (input.getFieldType() == null || input.getFieldType().equals("")) {
            return ResultResponseBeanUtil.fail("请设置字段所属类型（select,inputSelect,string,date）");
        }
        boolean save = buttonFieldService.save(input);

        try {
            if (save) {
//                QueryWrapper<FieldWebpageAuthority> wrapper = WrapperUtils.getWrapper(false);
//                wrapper.eq("field_id", input.getId());
//                List<FieldWebpageAuthority> list = fieldWebpageAuthorityService.list(wrapper);
//                for (FieldWebpageAuthority fieldWebpageAuthority : list) {
//                    fieldWebpageAuthority.setCnName(input.getCnName());
//                    fieldWebpageAuthority.setEnName(input.getEnName());
//                    fieldWebpageAuthority.setIsSelect(input.getIsSelect());
//                    fieldWebpageAuthority.setFieldType(input.getFieldType());
//                    fieldWebpageAuthority.setNavSelect(input.getNavSelect());
//                    fieldWebpageAuthority.setOrderBy(input.getOrderBy());
//                    fieldWebpageAuthority.setParam(input.getParam());
//                    fieldWebpageAuthorityService.updateById(fieldWebpageAuthority);
//                }

//                setFieldToFidelWebpageAuthority(user, 1L, input);

                return ResultResponseBeanUtil.success("字段添加成功");
            } else {
                return ResultResponseBeanUtil.fail("字段添加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultResponseBeanUtil.fail("修改权限关联字段失败");
        }
    }


    @ApiOperation(value = "查询子页面字段")
    @ResponseBody
    @RequestMapping(value = "/queryButtonFieldByButton", method = RequestMethod.GET)
    @AvoidRepeatSubmit
    public BaseOutput<List<ButtonField>> queryButtonFieldByButton(HttpServletRequest request, @RequestParam Long buttonId) {
        log.info("【queryButtonFieldByButton】buttonId:" + buttonId);

        QueryWrapper<ButtonField> wrapper = WrapperUtils.getWrapper(false);
        wrapper.eq("button_id", buttonId);
        wrapper.orderByAsc("order_by");
        List<ButtonField> list = buttonFieldService.list(wrapper);
        return ResultResponseBeanUtil.success(list);
    }


    @ApiOperation(value = "删除子页面字段")
    @ResponseBody
    @RequestMapping(value = "/deleteButtonField", method = RequestMethod.GET)
    public BaseOutput<Void> deleteButtonField(HttpServletRequest request, @RequestParam(name = "fieldId") Long fieldId) {
        log.info("【deleteButtonField】fieldId:" + fieldId);
        User user = UserUtils.getUser(request);
        if (user == null) {
            return ResultResponseBeanUtil.fail("请重新登录");
        }
        log.info("【deleteButtonField】user:" + user.getName() + "清除id为" + fieldId + "的列");

        ButtonField byId = buttonFieldService.getById(fieldId);
        byId.setSoftDelete(1);
        byId.setModifyTime(new Date());
        buttonFieldService.updateById(byId);
        return ResultResponseBeanUtil.success();
    }


    @ApiOperation(value = "修改子页面字段关联")
    @ResponseBody
    @RequestMapping(value = "/updateButtonField", method = RequestMethod.POST)
    @AvoidRepeatSubmit
    public BaseOutput<String> updateButtonField(HttpServletRequest request, @RequestBody ButtonField input) {
        log.info("【updateButtonField】input" + JSONObject.toJSONString(input));
        ButtonField buttonField = buttonFieldService.getById(input.getId());
        buttonField.setCnName(input.getCnName());
        buttonField.setEnName(input.getEnName());
        buttonField.setIsSelect(input.getIsSelect());
        buttonField.setFieldType(input.getFieldType());
        buttonField.setNavSelect(input.getNavSelect());
        buttonField.setOrderBy(input.getOrderBy());
        buttonField.setParam(input.getParam());
        buttonField.setIsTableShow(input.getIsTableShow());
        buttonFieldService.updateById(buttonField);
        return ResultResponseBeanUtil.success("字段修改成功");
    }

}

