package com.mortals.xhx.base.system.menu.web;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.OrderCol;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.xhx.base.system.param.service.ParamService;
import com.mortals.xhx.common.code.*;
import com.mortals.xhx.base.system.menu.model.MenuQuery;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import com.mortals.framework.model.Context;
import com.mortals.xhx.base.system.menu.model.MenuEntity;
import com.mortals.xhx.base.system.menu.service.MenuService;
import com.mortals.xhx.base.system.menu.model.MenuTreeSelect;
import org.apache.commons.lang3.ArrayUtils;
import com.mortals.framework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;
import com.alibaba.fastjson.JSONObject;

import static com.mortals.framework.ap.SysConstains.*;
/**
*
* 菜单信息
*
* @author zxfei
* @date 2023-04-10
*/
@RestController
@RequestMapping("menu")
public class MenuController extends BaseCRUDJsonBodyMappingController<MenuService,MenuEntity,Long> {

    @Autowired
    private ParamService paramService;


    @Override
    protected void doListBefore(MenuEntity query, Map<String, Object> model, Context context) throws AppException {
        List<OrderCol> orderColList = new ArrayList<OrderCol>();
        orderColList.add(new OrderCol("parentId"));
        orderColList.add(new OrderCol("orderId"));
        query.setOrderColList(orderColList);
    }

    @Override
    protected void init(Map<String, Object> model, Context context) {
        Map<String, Object> status = new HashMap<String, Object>();
        status.put("status", DataSatus.getEnumMap(DataSatus.CLOSE.getValue(), DataSatus.DELETE.getValue(), DataSatus.OVERDUE.getValue(), DataSatus.USEOUT.getValue()));
        status.put("linkType", MenuLinkType.getEnumMap());
        status.put("commMenu", MenuComm.getEnumMap());
        status.put("menuType", MenuType.getEnumMap());
        status.put("authType", MenuAuthType.getEnumMap());
        model.put(KEY_RESULT_DICT, status);
    }

    /**
     * 改变状态
     */
    @RequestMapping(value = "change/status")
    public String changeStatus(@RequestBody com.mortals.xhx.base.system.menu.model.MenuEntity query) {
        JSONObject ret = new JSONObject();
        Context context = getContext();
        try {
            MenuEntity entity = this.service.get(query.getId(), context);//.doSubmitAudit(form.getEntity(), context);
            if (null == entity) {
                throw new AppException("菜单不存在!");
            }
            if (null == entity.getStatus()) {
                throw new AppException("菜单状态不能为空!");
            }
            if (entity.getStatus() != DataSatus.ENABLE.getValue() && entity.getStatus() != DataSatus.DISENABLE.getValue()) {
                throw new AppException("非法菜单状态!");
            }
            String busiDesc = DataSatus.getByValue(entity.getStatus()).getDesc();
            entity.setStatus(entity.getStatus());
            this.service.update(entity, context);
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
            ret.put(KEY_RESULT_MSG, busiDesc + "成功");
            recordSysLog(request, busiDesc + " 【成功】 [id:" + entity.getId() + "]");

        } catch (Exception e) {
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, super.convertException(e));
        }
        return ret.toJSONString();
    }


    /**
     * 更换排序
     */
    @PostMapping(value = "upOrDown")
    public String upOrDownTopicList(@RequestBody MenuEntity query) {
        JSONObject ret = new JSONObject();
        ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
        try {
            this.service.upOrDown(query.getId(), query.getType());
        } catch (Exception e) {
            log.error("更新错误", e);
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, e.getMessage());
        }
        return ret.toJSONString();
    }

    @PostMapping("list/exclude")
    public String excludeList(@RequestBody MenuEntity query) {
        Map<String, Object> model = new HashMap<>();
        JSONObject ret = new JSONObject();
        String busiDesc = "查询" + this.getModuleDesc();
        int code=VALUE_RESULT_SUCCESS;
        try {
            //查询所有菜单 排除当前菜单路径
            Set<Long> idSet = new HashSet<>();
            idSet.add(query.getId());
            //Set<Long> idSets = this.service.getPathSetById(query.getId(), getContext());
            List<MenuEntity> collect = this.service.find(new MenuQuery()).stream().map(item -> {
                if(idSet.contains(item.getId())) return null;
                //if(idSets.contains(item.getId())) return null;
                //ArrayUtils.contains()
//                if(ObjectUtils.isEmpty(item.getAncestors())){
//                    return null;
//                }
//                if (item.getId().intValue() == id || ArrayUtils.contains(StringUtils.split(item.getAncestors(), ","), id + "")) {
//                    return null;
//                }
                return item;
            }).filter(f -> f != null).collect(Collectors.toList());
            model.put("data", collect);
            recordSysLog(request, busiDesc + " 【成功】");
        } catch (Exception e) {
            code = VALUE_RESULT_FAILURE;
            this.doException(request, busiDesc, model, e);
        }
        ret.put(KEY_RESULT_DATA, model);
        ret.put(KEY_RESULT_CODE, code);
        return ret.toJSONString();
    }


    /**
     * 获取站点下拉树列表
     */
    @PostMapping("treeselect")
    public String treeselect(MenuEntity query) {
        Map<String, Object> model = new HashMap<>();
        JSONObject ret = new JSONObject();
        String busiDesc = "查询" + this.getModuleDesc();
        int code=VALUE_RESULT_SUCCESS;
        try {
            List<MenuEntity> list = this.service.find(new MenuQuery());
            List<MenuTreeSelect> treeSelects = this.service.buildMenuTreeSelect(list);
             model.put("result", treeSelects);
            recordSysLog(request, busiDesc + " 【成功】");
        } catch (Exception e) {
            code = VALUE_RESULT_FAILURE;
            this.doException(request, busiDesc, model, e);
        }
        ret.put(KEY_RESULT_DATA, model);
        ret.put(KEY_RESULT_CODE, code);
        return ret.toJSONString();
    }


    /**
    * 根据parentId查询子信息
    */
    @GetMapping(value = "getListByParentId")
    public String getListByParentId(Long parentId) {
        JSONObject ret = new JSONObject();
        Map<String, Object> model = new HashMap<>();
        String busiDesc = "查询" + this.getModuleDesc()+"子节点";
        try {
            List<MenuTreeSelect> treeList = this.service.getListByParentId(parentId, getContext());
            model.put(RESULT_KEY,treeList);
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
            ret.put(KEY_RESULT_DATA, model);
            recordSysLog(request, busiDesc+"【成功】");
        } catch (Exception e) {
            log.error("根据parentId查询子信息错误", e);
            this.doException(request, busiDesc, model, e);
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, e.getMessage());
        }
        return ret.toJSONString();
    }


}