/**
 * 文件：MateriaBomTreeController.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.base.system.param.service.ParamService;
import com.mortals.xhx.common.code.BomStatusEnum;
import com.mortals.xhx.common.code.TreeTypeEnum;
import com.mortals.xhx.common.key.Constant;
import com.mortals.xhx.module.attach.model.AttachEntity;
import com.mortals.xhx.module.attach.model.AttachQuery;
import com.mortals.xhx.module.attach.service.AttachService;
import com.mortals.xhx.module.materia.model.*;
import com.mortals.xhx.module.materia.service.MateriaBomItemService;
import com.mortals.xhx.module.materia.service.MateriaBomService;
import com.mortals.xhx.module.materia.service.MateriaBomTreeService;
import com.mortals.xhx.module.materia.service.MateriaService;
import com.mortals.xhx.module.partner.model.PartnerQuery;
import com.mortals.xhx.module.partner.service.PartnerService;
import org.springframework.beans.BeanUtils;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>Title: 物料BOM类目表</p>
 * <p>Description: MateriaBomTreeController  </p>
 * <p>Copyright: Copyright &reg;  </p>
 * <p>Company: </p>
 *
 * @author
 * @version 1.0.0
 */
@RestController
@RequestMapping("materia/bom/tree")
public class MateriaBomTreeController extends BaseCRUDJsonMappingController<MateriaBomTreeService, MateriaBomTreeForm, MateriaBomTreeEntity, Long> {

    @Autowired
    private MateriaBomService materiaBomService;
    @Autowired
    private MateriaBomItemService materiaBomItemService;
    @Autowired
    private ParamService paramService;
    @Autowired
    private PartnerService partnerService;
    @Autowired
    private AttachService attachService;
    @Autowired
    private MateriaService materiaService;


    public MateriaBomTreeController() {
        super.setFormClass(MateriaBomTreeForm.class);
        super.setModuleDesc("物料BOM类目表");
    }

    @Override
    protected void doListBefore(HttpServletRequest request, HttpServletResponse response, MateriaBomTreeForm form, Map<String, Object> model, Context context) throws AppException {
        if (StringUtils.isNotEmpty(form.getQuery().getName())) {
            MateriaBomTreeQuery categoryquery = new MateriaBomTreeQuery();
            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);
        }

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


    /**
     * 根据parentId查询子信息
     */
    @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 {
            ArrayList<MateriaBomEntity> materiaBomEntities = new ArrayList<>();
            //查询当前目录下 所有的bom
            MateriaBomQuery materiaBomQuery = new MateriaBomQuery();
            materiaBomQuery.setBomTreeId(parentId);
            if(!ObjectUtils.isEmpty(type)){
                //过滤bom
                materiaBomQuery.setStatus(BomStatusEnum.BOM_EDIT.getValue());
            }
            MateriaBomTreeQuery query = new MateriaBomTreeQuery();
            query.setParentId(parentId);
            List<HashMap<String, Object>> childList = service.find(query, getContext()).stream().map(item -> {
                HashMap<String, Object> data = new HashMap<>();

                String materiaName="";

                if(!ObjectUtils.isEmpty(item.getMateriaId())){
                    MateriaEntity materiaEntity = materiaService.get(item.getMateriaId(), null);
                    materiaName=materiaEntity.getName();
                }

                if(!ObjectUtils.isEmpty(materiaName)){
                    materiaName="{"+materiaName+"}";
                }
                data.put("id", item.getId());
                data.put("materiaId", item.getMateriaId()==null?"":item.getMateriaId());
                data.put("name", item.getCode() == null ? item.getName() : "[" + item.getCode() + "]" + item.getName()+materiaName);
                data.put("parentId", item.getParentId());
                data.put("code", item.getCode());

                data.put("isLeaf", item.getIsLeaf() == 1 ? true : false);
                data.put("type", TreeTypeEnum.DIR.getValue());
                data.put("icon", TreeTypeEnum.DIR.getDesc());

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

            List<HashMap<String, Object>> collect = materiaBomService.find(materiaBomQuery, getContext()).stream().map(bom -> {
                materiaBomEntities.add(bom);
                HashMap<String, Object> bomMap = new HashMap<>();
                bomMap.put("bomId", bom.getId());
                bomMap.put("type", TreeTypeEnum.BOM.getValue());
                bomMap.put("icon", TreeTypeEnum.BOM.getDesc());

                bomMap.put("name", bom.getCode() == null ? bom.getMateriaName() : "[" + bom.getCode()+"."+bom.getSelfCode() + "]" + bom.getMateriaName());
                bomMap.put("bomCode", bom.getCode());
                bomMap.put("isLeaf", true);
                return bomMap;
            }).collect(Collectors.toList());

            JSONObject data = new JSONObject();

            if(!ObjectUtils.isEmpty(type)&&type==2){
                childList.addAll(collect);
                data.put("bomList", materiaBomEntities);
            }
            data.put(SysConstains.RESULT_KEY, childList);

            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();
    }


    /**
     * @Description 根据parentId查询当前目录能否创建子目录
     * @param 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 = "checkBom")
    public String checkBom(@RequestParam(value = "treeId", required = true) Long treeId) {
        JSONObject ret = new JSONObject();
        try {
            JSONObject data = new JSONObject();
            getService().checkBom(treeId, getContext());
            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();
    }

    /**
     * 根据parentId查询bom版本信息（只有已发布并有BOM版本的BOM可选择， 用于资产管理的编辑时）
     */
    @PostMapping(value = "getBomVersionListByParentId")
    public String getBomVersionListByParentId(@RequestParam(value = "type", required = false) Long type, @RequestParam(value = "parentId", required = false) Long parentId) {
        JSONObject ret = new JSONObject();
        try {
            ArrayList<MateriaBomEntity> materiaBomEntities = new ArrayList<>();
            //查询当前目录下 所有的bom
            MateriaBomQuery materiaBomQuery = new MateriaBomQuery();
            materiaBomQuery.setBomTreeId(parentId);
            if(!ObjectUtils.isEmpty(type)){
                //过滤bom
                materiaBomQuery.setStatus(BomStatusEnum.BOM_PUBLISH.getValue());
            }
            MateriaBomTreeQuery query = new MateriaBomTreeQuery();
            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() == null ? item.getName() : "[" + item.getCode() + "]" + item.getName());
                data.put("parentId", item.getParentId());
                data.put("code", item.getCode());

                data.put("isLeaf", item.getIsLeaf() == 1 ? true : false);
                data.put("type", TreeTypeEnum.DIR.getValue());
                data.put("icon", TreeTypeEnum.DIR.getDesc());

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

            List<HashMap<String, Object>> collect = materiaBomService.find(materiaBomQuery, getContext()).stream().map(bom -> {
                materiaBomEntities.add(bom);
                HashMap<String, Object> bomMap = new HashMap<>();
                bomMap.put("bomId", bom.getId());
                bomMap.put("type", TreeTypeEnum.BOM.getValue());
                bomMap.put("icon", TreeTypeEnum.BOM.getDesc());
                bomMap.put("name", bom.getCode() == null ? bom.getMateriaName() : "[" + bom.getCode() + "]" + bom.getMateriaName());
                bomMap.put("bomCode", bom.getCode());
                bomMap.put("isLeaf", true);
                return bomMap;
            }).collect(Collectors.toList());


            childList.addAll(collect);

            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();
    }
    /**
     *
     */
    @PostMapping(value = "queryBoms")
    public String queryBoms(@RequestParam(value = "id", required = false) Long id) {
        JSONObject ret = new JSONObject();
        try {

            MateriaBomQuery bomQuery = new MateriaBomQuery();
            bomQuery.setBomTreeId(id);
            List<MateriaBomCustomEntity> materiaBomEntities = materiaBomService.find(bomQuery, null).stream().map(entity -> {
                MateriaBomCustomEntity materiaBomCustomEntity = new MateriaBomCustomEntity();
                BeanUtils.copyProperties(entity, materiaBomCustomEntity);
                MateriaEntity materiaEntity = materiaService.get(entity.getMateriaId(), null);
                materiaBomCustomEntity.setMainPicUrl(materiaEntity.getMainPicUrl());
                materiaBomCustomEntity.setSpecModel(materiaEntity.getSpecModel());
                return materiaBomCustomEntity;
            }).peek(item -> {

                AttachQuery attachQuery = new AttachQuery();
                attachQuery.setTableCode(Constant.PARAM_MORTALS_IOT_MATERIA_BOM);
                attachQuery.setTableDataId(item.getId());
                List<AttachEntity> attachEntityList = attachService.find(attachQuery, null);

                if(!ObjectUtils.isEmpty(attachEntityList)){
                    item.setAttachEntityList(attachEntityList);
                }

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

            JSONObject data = new JSONObject();
            data.put("bomList", materiaBomEntities);

            ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
            ret.put(KEY_RESULT_DATA, data);
        } catch (Exception e) {
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, e.getMessage());
        }
        return ret.toJSONString();
    }

    /**
     * 根据目录id查询bom bomid
     */
    @PostMapping(value = "queryBomById")
    public String queryBomById(@RequestParam(value = "id", required = false) Long id) {
        JSONObject ret = new JSONObject();
        try {
            ArrayList<MateriaBomEntity> materiaBomEntities = new ArrayList<>();
            MateriaBomEntity bomEntity = materiaBomService.get(id, getContext());
            materiaBomEntities.add(bomEntity);

            MateriaBomItemQuery itemQuery = new MateriaBomItemQuery();
            itemQuery.setBomId(bomEntity.getId());
            List<MateriaBomItemEntity> items = materiaBomItemService.find(itemQuery, getContext());

            JSONObject data = new JSONObject();
            data.put("bomList", materiaBomEntities);
            data.put("bomItemList", items);

            ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
            ret.put(KEY_RESULT_DATA, data);
        } catch (Exception e) {
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, e.getMessage());
        }
        return ret.toJSONString();
    }

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

//        MateriaBomTreeQuery query = new MateriaBomTreeQuery();
//        query.setName(form.getEntity().getName());
//
//        MateriaBomTreeEntity bomTreeEntity = this.service.find(query, null).stream().findAny().orElseGet(() -> null);
//        if(!ObjectUtils.isEmpty(bomTreeEntity)){
//            throw new AppException("当前类目名称已存在，请重新修改后提交！");
//        }

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

    @Override
    protected void init(HttpServletRequest request, HttpServletResponse response, MateriaBomTreeForm form, Map<String, Object> model, Context context) {
        this.addDict(model, "useType", paramService.getParamByFirstOrganize("BomUseType"));
        this.addDict(model, "status", paramService.getParamByFirstOrganize("BomStatus"));
        this.addDict(model, "required", IBaseEnum.getEnumMap(YesNo.class));
        this.addDict(model, "supplierId", partnerService.find(new PartnerQuery(),getContext()).stream().collect(Collectors.toMap(x->x.getId().toString(), y->y.getName(),(o, n)->n)));
        this.addDict(model, "supplyType", paramService.getParamByFirstOrganize("MatriaSupplyType"));

    }
}