/**
 * 文件：MateriaCategoryController.java 版本：1.0.0 日期： Copyright &reg; All right
 * reserved.
 */
package com.mortals.xhx.module.materia.web;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.mortals.framework.ap.SysConstains;
import com.mortals.framework.common.IBaseEnum;
import com.mortals.framework.common.code.YesNo;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.util.StringUtils;
import com.mortals.framework.web.BaseCRUDJsonMappingController;
import com.mortals.xhx.common.code.TreeTypeEnum;
import com.mortals.xhx.module.materia.model.*;
import com.mortals.xhx.module.materia.service.MateriaCategoryService;
import com.mortals.xhx.module.materia.service.MateriaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * Title: 产品类目表
 * </p>
 * <p>
 * Description: MateriaCategoryController
 * </p>
 * <p>
 * Copyright: Copyright &reg;
 * </p>
 * <p>
 * Company:
 * </p>
 *
 * @author
 * @version 1.0.0
 */
@RestController
@RequestMapping("materia/category")
public class MateriaCategoryController extends
        BaseCRUDJsonMappingController<MateriaCategoryService, MateriaCategoryForm, MateriaCategoryEntity, Long> {


    @Autowired
    private MateriaService materiaService;

    public MateriaCategoryController() {
        super.setFormClass(MateriaCategoryForm.class);
        super.setModuleDesc("产品类目表");
    }

    @Override
    protected void init(HttpServletRequest request, HttpServletResponse response, MateriaCategoryForm form,
                        Map<String, Object> model, Context context) {
        this.addDict(model, "enabled", IBaseEnum.getEnumMap(YesNo.class));
        this.addDict(model, "isCodec", IBaseEnum.getEnumMap(YesNo.class));
        super.init(request, response, form, model, context);
    }

    @Override
    @PostMapping(value = "list")
    public String list(MateriaCategoryForm form) {
        try {
            if (StringUtils.isNotEmpty(form.getQuery().getName())) {
                MateriaCategoryQuery categoryquery = new MateriaCategoryQuery();
                categoryquery.setName("%" + form.getQuery().getName() + "%");
                categoryquery.setCode("%" + form.getQuery().getCode() + "%");
                form.getQuery().setAndConditionList(Lists.newArrayList(categoryquery));// 使用OR条件查询
                form.getQuery().setName(null);
                form.getQuery().setCode(null);
            }

            return super.list(form);
        } catch (Exception e) {
            log.error("查询区域信息列表错误", e);
            JSONObject ret = new JSONObject();
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, super.convertException(e));
            return ret.toJSONString();
        }
    }


    @PostMapping(value = "getListByParentId")
    public String getListByParentId(@RequestParam(value = "type", required = false) Long type, @RequestParam(value = "parentId", required = false) Long parentId) {
        JSONObject ret = new JSONObject();
        try {
            MateriaCategoryQuery query = new MateriaCategoryQuery();
            query.setParentId(parentId);
            List<HashMap<String, Object>> childList = service.find(query, getContext()).stream().map(item -> {
                HashMap<String, Object> data = new HashMap<>();
                data.put("id", item.getId());
                data.put("name", "[" + item.getCode() + "]" + item.getName());
                data.put("parentId", item.getParentId());
                data.put("isLeaf", item.getIsLeaf() == 1 ? true : false);
                data.put("type", TreeTypeEnum.DIR.getValue());
                data.put("icon", "el-icon-folder");
                List<HashMap<String, Object>> children = getMaterias(item.getId());
                if (children.size() > 0) {
                    if (type != null) {
                        data.put("isLeaf", false);
                    }
                    data.put("children", children);
                }

                return data;
            }).collect(Collectors.toList());

            List<HashMap<String, Object>> materias = getMaterias(parentId);
            if (materias.size() > 0) {
                childList.addAll(materias);
            }
            JSONObject data = new JSONObject();
            data.put(SysConstains.RESULT_KEY, childList);
            //data.put("bomList", materiaBomEntities);
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
            ret.put(KEY_RESULT_DATA, data);
        } catch (Exception e) {
            log.error("根据parentId查询子信息错误", e);
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, e.getMessage());
        }
        return ret.toJSONString();
    }

    /**
     * @param parentId
     * @Description 根据parentId查询当前目录能否创建子目录
     * @Return java.lang.String
     * @date 2021/3/18 16:59
     * @Author fuJun
     */
    @PostMapping(value = "getLevel")
    public String getLevel(@RequestParam(value = "parentId", required = true) Long parentId) {
        JSONObject ret = new JSONObject();
        try {
            JSONObject data = new JSONObject();
            boolean isEndLevel = getService().checklevel(parentId, 1, getContext());
            ret.put("isNotEndLevel", isEndLevel);
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
            ret.put(KEY_RESULT_DATA, data);
        } catch (Exception e) {
            log.error("根据parentId查询当前Level", e);
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, e.getMessage());
        }
        return ret.toJSONString();
    }

    @PostMapping(value = "getDirListByParentId")
    public String getDirListByParentId(@RequestParam(value = "type", required = false) Long type, @RequestParam(value = "parentId", required = false) Long parentId) {
        JSONObject ret = new JSONObject();
        try {
            MateriaCategoryQuery query = new MateriaCategoryQuery();
            query.setParentId(parentId);
            List<HashMap<String, Object>> childList = service.find(query, getContext()).stream().map(item -> {
                HashMap<String, Object> data = new HashMap<>();
                data.put("id", item.getId());
                data.put("name", "[" + item.getCode() + "]" + item.getName());
                data.put("parentId", item.getParentId());
                data.put("isLeaf", item.getIsLeaf() == 1 ? true : false);
                data.put("type", TreeTypeEnum.DIR.getValue());
                data.put("icon", "el-icon-folder");

                return data;
            }).collect(Collectors.toList());

            JSONObject data = new JSONObject();
            data.put(SysConstains.RESULT_KEY, childList);
            //data.put("bomList", materiaBomEntities);
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
            ret.put(KEY_RESULT_DATA, data);
        } catch (Exception e) {
            log.error("根据parentId查询子信息错误", e);
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, e.getMessage());
        }
        return ret.toJSONString();
    }

    private List<HashMap<String, Object>> getMaterias(Long categoryId) {
        MateriaQuery materiaQuery = new MateriaQuery();
        materiaQuery.setCategoryId(categoryId);
        return materiaService.find(materiaQuery, getContext()).stream().map(item -> {
            HashMap<String, Object> data = new HashMap<>();
            data.put("id", item.getId());
            data.put("name", "[" + item.getCode() + "]" + item.getName());
            data.put("isLeaf", true);
            data.put("type", TreeTypeEnum.BOM_ITEM.getValue());
            data.put("icon", TreeTypeEnum.BOM_ITEM.getDesc());

            return data;
        }).collect(Collectors.toList());
    }

    @Override
    protected void addAfter(HttpServletRequest request, HttpServletResponse response, MateriaCategoryForm form,
                            Map<String, Object> model) throws AppException {
        form.getEntity().setEnabled(YesNo.YES.getValue());
        if (form.getQuery().getParentId() == null) {
            form.getEntity().setParentId(-1L);
        } else {
            MateriaCategoryEntity pCategory = getService().get(form.getQuery().getParentId(), true);
            form.getEntity().setParentId(form.getQuery().getParentId());
            form.getEntity().setCode(pCategory.getCode());
        }
        super.addAfter(request, response, form, model);
    }

    @Override
    protected void saveBefore(HttpServletRequest request, HttpServletResponse response, MateriaCategoryForm form,
                              Map<String, Object> model, Context context) throws AppException {

        //校验名称唯一性
        MateriaCategoryQuery query = new MateriaCategoryQuery();
        query.setName(form.getEntity().getName());
        query.setParentId(form.getEntity().getParentId());
        MateriaCategoryEntity materiaCategoryEntity = this.service.find(query, null).stream().findAny().orElseGet(() -> null);
        if (!ObjectUtils.isEmpty(materiaCategoryEntity)) {
            if (form.getEntity().newEntity()) {
                //新增，存在新
                throw new AppException("当前类目名称已存在，请重新修改后提交！");
            } else {
                //判断是否修改类目名称
                if (form.getEntity().getId() != materiaCategoryEntity.getId()) {
                    throw new AppException("当前类目名称已存在，请重新修改后提交！");
                }
            }
        }

        super.saveBefore(request, response, form, model, context);
    }


}