/**
 * Description: BaseTree控制器
 * Copyright:   Copyright (c)2017
 * Company:     江苏三六五网络股份有限公司
 *
 * @author: 江苏三六五网络股份有限公司
 * @version: 1.0
 * Create at:   2017-12-08 下午 15:16:07
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2017-12-08   江苏三六五网络股份有限公司   1.0         Initial
 */
package com.house365.web.controller;

import com.google.common.base.Function;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.house365.beans.entity.BaseTreeEntity;
import com.house365.beans.entity.UserEntity;
import com.house365.beans.system.Page;
import com.house365.beans.vo.BaseTreeVo;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.SessionConstants;
import com.house365.web.util.StringUtils;
import com.house365.ws.beans.request.BaseTreeListRequest;
import com.house365.ws.beans.request.BaseTreeRequest;
import com.house365.ws.beans.response.BaseTreeListResponse;
import com.house365.ws.beans.response.BaseTreeResponse;
import com.house365.ws.interfaces.server.IBaseTree;
import com.house365.ws.system.ReturnResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.Servlets;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

import static com.house365.rest.context.AppConstant.STATUS_NORMAL;

/**
 * BaseTree控制器<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2017-12-08
 * @see
 * @since 1.0
 */
@Controller
@RequestMapping("/basetree")
public class BaseTreeController extends BaseController {

    /**
     * 自动注入BaseTreeWS实现
     */
    @Autowired
    private IBaseTree baseTree;

    /**
     * 去新增BaseTree
     *
     * @return 结果视图
     */
    @RequestMapping(value = "", params = "action=create")
    public String createForm(Model model) {
        model.addAttribute("action", "create");
        return getAutoUrl("form");
    }

    /**
     * 新增BaseTree
     *
     * @param vo     BaseTree页面表单对象
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "", method = {RequestMethod.POST})
    public String createBaseTree(
            @Valid BaseTreeVo vo, BindingResult result, RedirectAttributes redirectAttributes, Model model
    ) {
        BaseTreeEntity entity = vo.getEntity();
        model.addAttribute("entity", entity);
        // subValidation(result, entity);
        // 表单验证无误,进行提交
        if (result.hasErrors()) {
            model.addAttribute("action", "create");
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return getAutoUrl("form");
        } else {
            try {
                BaseTreeRequest request = new BaseTreeRequest();
                request.setEntity(entity);
                BaseTreeResponse response = baseTree.addBaseTree(request);
                Integer id = response.getEntity().getId();
                return "redirect:/basetree/" + id;
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "create");
                return getAutoUrl("form");
            }
        }
    }

    /**
     * 删除BaseTree
     *
     * @param id BaseTree页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.DELETE})
    @ResponseStatus(HttpStatus.OK)
    public void delete(@PathVariable String id) {
        if (!StringUtils.isEmpty(id)) {
            if (id.contains(",")) {
                String[] ids = id.split(",");
                for (int i = 0; i < ids.length; i++) {
                    baseTree.deleteBaseTreeById(Integer.valueOf(ids[i]));
                }
            } else {
                baseTree.deleteBaseTreeById(Integer.valueOf(id));
            }
        }
    }

    /**
     * 去查看BaseTree
     *
     * @param id BaseTree页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET})
    public String showForm(@PathVariable(value = "id") Integer id, Model model) {
        BaseTreeResponse response = baseTree.getBaseTreeById(id);
        model.addAttribute("entity", response.getEntity());
        return getAutoUrl("form");
    }

    /**
     * 去修改BaseTree
     *
     * @param id BaseTree页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET}, params = "action=edit")
    public String updateForm(@PathVariable(value = "id") Integer id, Model model) {
        BaseTreeResponse response = baseTree.getBaseTreeById(id);
        model.addAttribute("entity", response.getEntity());
        model.addAttribute("action", "edit");
        return getAutoUrl("form");
    }

    /**
     * 修改BaseTree
     *
     * @param vo     BaseTree页面表单对象
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.POST})
    public String updateBaseTree(
            @Valid BaseTreeVo vo, BindingResult result, @PathVariable Integer id, RedirectAttributes redirectAttributes,
            Model model
    ) {
        BaseTreeEntity entity = vo.getEntity();
        model.addAttribute("entity", entity);
        // subValidation(result, entity);
        // 表单验证无误,进行提交
        if (result.hasErrors()) {
            model.addAttribute("action", "create");
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return getAutoUrl("form");
        } else {
            try {
                BaseTreeRequest request = new BaseTreeRequest();
                entity.setStatus(STATUS_NORMAL);
                request.setEntity(entity);
                @SuppressWarnings("unused") BaseTreeResponse rersponse = baseTree.updateBaseTree(request);
                redirectAttributes.addAttribute("message", "更新成功");
                return "redirect:/basetree/" + entity.getId();
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "edit");
                return getAutoUrl("form");
            }
        }
    }

    @RequestMapping(value = {"inner"}, method = RequestMethod.GET)
    public String inner(HttpServletRequest request, Model model) {
        BaseTreeListRequest listReq = new BaseTreeListRequest();
        Map<String, Object> map = new HashMap<>();
        String sourceType = request.getParameter("sourceType");
        BaseTreeEntity baseTreeEntity = baseTree.getRootBySourceType(sourceType);
        BaseTreeResponse deptEntity = baseTree.getBaseTreeById(baseTreeEntity.getId());
        map.put("REGEXP_urlPath",
                "^" + deptEntity.getEntity().getUrlPath() + "$|^" + deptEntity.getEntity().getUrlPath() + "/");
        Page page = new Page(1, Integer.MAX_VALUE);
        listReq.setPaging(page);
        listReq.setSearchParams(map);
        listReq.setOrderColumn("orderNum");
        listReq.setOrderMode("asc");
        BaseTreeListResponse resp = baseTree.getBaseTreeList(listReq);
        List<BaseTreeEntity> models = resp.getObjectList();
        model.addAttribute("trees", models);
        return getAutoUrl();
    }

    /**
     * 查询BaseTree
     *
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public String list(Integer number, Model model, HttpServletRequest request) {
        // 获取查询条件
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        Page page = new Page();
        if (null != number) {
            page.setCurrentPage(number);
        }
        BaseTreeListRequest listRequest = new BaseTreeListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        BaseTreeListResponse response = baseTree.getBaseTreeList(listRequest);
        model.addAttribute("page", response.getPaging());
        model.addAttribute("baseTrees", response.getObjectList());
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
        return getAutoUrl();
    }

    @RequestMapping(value = {"", "main"}, method = RequestMethod.GET)
    public String main(@RequestParam(value = "sourceType", required = true) String sourceType, Model model) {
        model.addAttribute("sourceType", sourceType);
        return getAutoUrl();
    }

    @RequestMapping(value = "tree", method = RequestMethod.GET)
    public String tree(
            HttpServletRequest request, @RequestParam(value = "searchName", required = false) String searchName,
            @RequestParam(value = "show", required = false, defaultValue = "") String show,
            @RequestParam(value = "async", required = false, defaultValue = "false") boolean async, Model model
    ) {
        List<BaseTreeEntity> models = null;
        BaseTreeListRequest listReq = new BaseTreeListRequest();
        Map<String, Object> map = new HashMap<>();
        BaseTreeEntity deptEntity = baseTree.getRootBySourceType(show);
        map.put("REGEXP_urlPath", "^" + deptEntity.getUrlPath() + "$|^" + deptEntity.getUrlPath() + "/");
        Page page = new Page(1, Integer.MAX_VALUE);
        listReq.setPaging(page);
        listReq.setSearchParams(map);
        listReq.setOrderColumn("orderNum");
        listReq.setOrderMode("asc");
        if (!StringUtils.isEmpty(searchName)) {
            map.put("LIKE_name", searchName);
            BaseTreeListResponse resp = baseTree.getBaseTreeList(listReq);
            models = resp.getObjectList();
            // 异步模式只查自己
            if (!async) {
                List<BaseTreeEntity> children = baseTree.findChildrenListByPath(models);
                models.removeAll(children);
                models.addAll(children);
            }
        } else {
            // 非异步 查自己和子子孙孙
            if (!async) {
                BaseTreeListResponse resp = baseTree.getBaseTreeList(listReq);
                models = resp.getObjectList();
            } else { // 异步模式只查根 和 根一级节点
                models = baseTree.findRootAndChild();
            }
        }

        model.addAttribute("trees", models);
        return getAutoUrl();
    }

    @RequestMapping(value = "modalTree", method = RequestMethod.GET)
    public String modalTree(
            HttpServletRequest request, @RequestParam(value = "choseIds", required = false) String choseIds,
            @RequestParam(value = "sourceSel", required = false) String sourceSel,
            @RequestParam(value = "show", required = false, defaultValue = "") String show,
            @RequestParam(value = "async", required = false, defaultValue = "false") boolean async, Model model
    ) {
        List<BaseTreeEntity> models = null;
        BaseTreeListRequest listReq = new BaseTreeListRequest();
        Map<String, Object> map = new HashMap<>(10);
        BaseTreeEntity deptEntity = baseTree.getRootBySourceType(show);
        map.put("REGEXP_urlPath", "^" + deptEntity.getUrlPath() + "$|^" + deptEntity.getUrlPath() + "/");
        Page page = new Page(1, Integer.MAX_VALUE);
        listReq.setPaging(page);
        listReq.setSearchParams(map);
        listReq.setOrderColumn("orderNum");
        listReq.setOrderMode("asc");
        // 非异步 查自己和子子孙孙
        if (!async) {
            BaseTreeListResponse resp = baseTree.getBaseTreeList(listReq);
            models = resp.getObjectList();
        } else { // 异步模式只查根 和 根一级节点
            models = baseTree.findRootAndChild();
        }

        model.addAttribute("trees", models);
        model.addAttribute("choseIds", choseIds);
        model.addAttribute("sourceSel", sourceSel);
        return getAutoUrl();
    }

    @RequestMapping("ajax/autocomplete")
    @ResponseBody
    public Set<String> autocomplete(
            HttpServletRequest request, @RequestParam("term") String name,
            @RequestParam(value = "excludeId", required = false) String excludeId
    ) {
        try {
            name = URLDecoder.decode(name, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage(), e);
        }
        BaseTreeListRequest listReq = new BaseTreeListRequest();
        Map<String, Object> map = new HashMap<>();
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        BaseTreeResponse deptEntity = baseTree.getBaseTreeById(userEntity.getDeptId());
        map.put("REGEXP_urlPath",
                "^" + deptEntity.getEntity().getUrlPath() + "$|^" + deptEntity.getEntity().getUrlPath() + "/");
        Page page = new Page();
        page.setCurrentPage(1);
        page.setPageSize(Integer.MAX_VALUE);
        listReq.setPaging(page);
        listReq.setSearchParams(map);
        listReq.setOrderColumn("orderNum");
        listReq.setOrderMode("asc");
// 按name模糊查
        if (!Strings.isNullOrEmpty(name)) {
            map.put("LIKE_name", name);
        }
        if (!Strings.isNullOrEmpty(excludeId)) {
            map.put("NOTEQ_id", excludeId);
        }

        List<BaseTreeEntity> list = baseTree.getBaseTreeList(listReq).getObjectList();
        return Sets.newHashSet(Lists.transform(list, new Function<BaseTreeEntity, String>() {
            @Override
            public String apply(BaseTreeEntity input) {
                return input.getName();
            }
        }));
    }

    @RequestMapping(value = "ajax/load")
    @ResponseBody
    public Object load(
            HttpServletRequest request, @RequestParam(value = "async", defaultValue = "true") boolean async,
            @RequestParam(value = "asyncLoadAll", defaultValue = "false") boolean asyncLoadAll,
            @RequestParam(value = "searchName", required = false) String searchName,
            @RequestParam(value = "id", required = false) String parentId,
            @RequestParam(value = "excludeId", required = false) Integer excludeId,
            @RequestParam(value = "onlyCheckLeaf", required = false, defaultValue = "false") boolean onlyCheckLeaf,
            @RequestParam(value = "show", required = false) String show
    ) {
        List<BaseTreeEntity> models;
        BaseTreeListRequest listReq = new BaseTreeListRequest();
        Map<String, Object> map = new HashMap<>();
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        BaseTreeResponse deptEntity = baseTree.getBaseTreeById(userEntity.getDeptId());
        map.put("REGEXP_urlPath",
                "^" + deptEntity.getEntity().getUrlPath() + "$|^" + deptEntity.getEntity().getUrlPath() + "/");
        Page page = new Page();
        page.setCurrentPage(1);
        page.setPageSize(Integer.MAX_VALUE);
        listReq.setPaging(page);
        listReq.setSearchParams(map);
        listReq.setOrderColumn("orderNum");
        listReq.setOrderMode("asc");
        try {
            searchName = URLDecoder.decode(searchName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage(), e);
        }
        if (!Strings.isNullOrEmpty(searchName)) {// 按name模糊查
            map.put("LIKE_name", searchName);
            BaseTreeListResponse resp = baseTree.getBaseTreeList(listReq);
            models = resp.getObjectList();
            if (!async || asyncLoadAll) {// 非异步模式 查自己及子子孙孙 但排除
                List<BaseTreeEntity> children = baseTree.findChildrenListByPath(models);
                models.removeAll(children);
                models.addAll(children);
            }
        } else {
            BaseTreeListRequest req = new BaseTreeListRequest();
            Map<String, Object> parameter = new HashMap<>();

            if (parentId != null) {
                parameter.put("EQ_parentId", parentId);
            }

            if (async && !asyncLoadAll && null != excludeId) {
                parameter.put("NOTEQ_id", excludeId);
            }

            if (null == parentId && !asyncLoadAll) {
                models = baseTree.findRootAndChild();
            } else {
                req.setSearchParams(parameter);
                req.setOrderColumn("position");
                req.setOrderMode("asc");
                models = baseTree.getBaseTreeList(req).getObjectList();
            }
        }

        return models;
    }

    @RequestMapping(value = "ajax/{parent}/appendChild", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Object ajaxAppendChild(@PathVariable("parent") Integer parent) {
        BaseTreeEntity child = new BaseTreeEntity();
        child.setName("新节点");
        child.setStatus(STATUS_NORMAL);
        child.setDescripition("新节点");
        Date date = new Date();
        child.setCreateTime(date);
        child.setUpdateTime(date);
        try {
            child = baseTree.appendChild(parent, child);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return child;
    }

    @RequestMapping(value = "ajax/{id}/rename", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Object ajaxRename(
            HttpServletRequest httpRequest, @PathVariable("id") Integer id, @RequestParam("newName") String newName
    ) {
        BaseTreeEntity dept = baseTree.getBaseTreeById(id).getEntity();
        dept.setName(newName);
        try {
            BaseTreeRequest deptRequest = new BaseTreeRequest();
            deptRequest.setEntity(dept);
            baseTree.updateBaseTree(deptRequest);

            BaseTreeEntity realDept = (BaseTreeEntity) httpRequest.getSession().getAttribute(
                    SessionConstants.SESSION_REAL_DEPT_KEY);
            BaseTreeEntity currDept = (BaseTreeEntity) httpRequest.getSession().getAttribute(
                    SessionConstants.SESSION_CURRNET_DEPT_KEY);
            BaseTreeEntity originDept = (BaseTreeEntity) httpRequest.getSession().getAttribute(
                    SessionConstants.SESSION_ORIGIN_DEPT_KEY);
            realDept = baseTree.getBaseTreeById(realDept.getId()).getEntity();
            currDept = baseTree.getBaseTreeById(currDept.getId()).getEntity();
            originDept = baseTree.getBaseTreeById(originDept.getId()).getEntity();
            httpRequest.getSession().setAttribute(SessionConstants.SESSION_REAL_DEPT_KEY, realDept);
            httpRequest.getSession().setAttribute(SessionConstants.SESSION_ORIGIN_DEPT_KEY, originDept);
            httpRequest.getSession().setAttribute(SessionConstants.SESSION_CURRNET_DEPT_KEY, currDept);

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return dept;
    }

    @RequestMapping(value = "ajax/{id}/delete", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Object ajaxDelete(@PathVariable("id") Integer id) {
        BaseTreeListRequest req = new BaseTreeListRequest();
        Map<String, Object> paraMap = new HashMap<>();
        paraMap.put("EQ_parentId", id);
        req.setSearchParams(paraMap);
        req.setPaging(new Page(Integer.MAX_VALUE));
        BaseTreeResponse result = baseTree.getBaseTreeById(id);
        List<BaseTreeEntity> deptList = baseTree.getBaseTreeList(req).getObjectList();
        if (deptList.size() > 0) {
            result.setResultCode(ReturnResult.CHILD_NOT_EMPTY.getResultCode());
            result.setResultMessage(ReturnResult.CHILD_NOT_EMPTY.getResultMessage());
            return result;
        }

        BaseTreeResponse delRsp = baseTree.deleteBaseTreeById(id);
        return delRsp;
    }

    @RequestMapping(value = {"sources/{sourceType}/{categoryId}"}, method = RequestMethod.GET)
    public String sources(
            HttpServletRequest request, @PathVariable(value = "sourceType") String sourceType,
            @PathVariable(value = "categoryId") String categoryId, Model model
    ) {
        return "redirect:/" + sourceType + "/treeList?search_EQ_categoryId=" + categoryId;
    }

    @RequestMapping(value = {"transferNode"}, method = RequestMethod.GET)
    public String transferDept(HttpServletRequest request, Model model) {
        BaseTreeListRequest listReq = new BaseTreeListRequest();
        Map<String, Object> map = new HashMap<>();

        String sourceType = request.getParameter("sourceType");
        BaseTreeEntity baseTreeEntity = baseTree.getRootBySourceType(sourceType);
        map.put("REGEXP_urlPath", "^" + baseTreeEntity.getUrlPath() + "$|^" + baseTreeEntity.getUrlPath() + "/");
        Page page = new Page(1, Integer.MAX_VALUE);
        listReq.setPaging(page);
        listReq.setSearchParams(map);
        listReq.setOrderColumn("orderNum");
        listReq.setOrderMode("asc");
        BaseTreeListResponse resp = baseTree.getBaseTreeList(listReq);
        List<BaseTreeEntity> models = resp.getObjectList();
        model.addAttribute("trees", models);
        return getAutoUrl();
    }

    @RequestMapping(value = {"transferDept/{deptId}/{userId}"}, method = RequestMethod.GET)
    @ResponseBody
    public String transferDeptAction(
            @PathVariable(value = "deptId") Integer deptId, @PathVariable(value = "userId") Integer userId,
            HttpServletRequest request, Model model
    ) {
        BaseTreeEntity deptEntity = baseTree.getBaseTreeById(deptId).getEntity();
        if (deptEntity == null) {
            return null;
        }

        return "success";
    }

}
