package com.mortals.xhx.module.classify.web;

import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.annotation.RepeatSubmit;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.xhx.base.system.param.service.ParamService;
import com.mortals.xhx.common.key.Constant;
import com.mortals.xhx.module.basics.model.BasicsEntity;
import com.mortals.xhx.module.basics.web.BasicsForm;
import com.mortals.xhx.module.classify.model.*;
import com.mortals.xhx.module.classify.service.ClassifyOptionService;
import com.mortals.xhx.module.classify.service.ClassifyRelationService;
import com.mortals.xhx.utils.QRCodeUtil;
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 com.mortals.framework.web.BaseCRUDJsonMappingController;
import com.mortals.xhx.module.classify.service.ClassifyService;

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


/**
 * <p>Title: 一件事问题分类</p>
 * <p>Description: ClassifyController  </p>
 * <p>Copyright: Copyright &reg;  </p>
 * <p>Company: </p>
 *
 * @author zxfei
 * @version 1.0.0
 */
@RestController
@RequestMapping("classify")
public class ClassifyController extends BaseCRUDJsonMappingController<ClassifyService, ClassifyForm, ClassifyEntity, Long> {

    @Autowired
    private ClassifyOptionService optionService;
    @Autowired
    private ClassifyRelationService relationService;
    @Autowired
    private ParamService paramService;

    public ClassifyController() {
        super.setFormClass(ClassifyForm.class);
        super.setModuleDesc("一件事问题分类");
    }

    @Override
    protected void init(HttpServletRequest request, HttpServletResponse response, ClassifyForm form, Map<String, Object> model, Context context) {
        this.addDict(model, "typeOptions", paramService.getParamByFirstOrganize(Constant.Param_typeOptions));

    }

    /**
     * 根据一件事查询问题树
     */
    @PostMapping(value = "getListByBasicsId")
    public String getListByParentId(@RequestParam(value = "basicsId") Long basicsId) {
        JSONObject ret = new JSONObject();
        ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
        try {
            //根据id获取所有事项
            List<ClassifyEntity> classifyEntityList = this.service.find(new ClassifyQuery().basicsId(basicsId));
            //构建问题树的根节点
            ClassifyEntity root = classifyEntityList.stream().filter(f -> f.getParentId() == -1L).findFirst().orElseGet(() -> null);
            if (!ObjectUtils.isEmpty(root)) {
                ClassifyTreeNode classifyTreeNode = new ClassifyTreeNode();
                classifyTreeNode.setName(root.getName());
                classifyTreeNode.setId(root.getId());
                classifyTreeNode.setIsmust(root.getIsmust());
                classifyTreeNode.setType(root.getType());
                classifyTreeNode.setLevel(root.getLevel());
                //设置问题库
                List<ClassifyOptionEntity> classifyOptionEntities = this.optionService.find(new ClassifyOptionQuery().classifyId(root.getId()));
                classifyTreeNode.setQuestion(classifyOptionEntities);
                ClassifyTreeNode data = this.recursionTree(classifyTreeNode);
                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 = "saveClassify")
    @RepeatSubmit
    public String saveClassify(ClassifyVo classifyVo) {
        JSONObject ret = new JSONObject();
        Map<String, Object> model = new HashMap();
        String busiDesc = "保存" + this.getModuleDesc();
        try {
            ClassifyEntity entity = this.service.saveOrUpdateClassifyTree(classifyVo, getContext());

            //更新
           // String preAnsOptionId = request.getParameter("preAnsOption");
            if (!ObjectUtils.isEmpty(entity.getParentOptionId())) {
                ClassifyOptionEntity optionEntity = new ClassifyOptionEntity();
                optionEntity.setClassifyNextId(entity.getId());
                optionEntity.setUpdateUser(getContext().getUser().getLoginName());
                optionEntity.setUpdateTime(new Date());
                optionService.updateBatch(optionEntity, new ClassifyOptionQuery().id(entity.getParentOptionId()), getContext());
            }

            model.put("id", entity.getId());
            ret.put(KEY_RESULT_DATA, model);
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
            recordSysLog(request, busiDesc + " 【成功】");
        } catch (Exception e) {
            log.error("保存或更新问题树", e);
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, super.convertException(e));
            this.doException(request, busiDesc, model, e);
        }

        return ret.toJSONString();
    }


    /**
     * 新增时校验返回问题选项
     */
    @PostMapping(value = "checkAddQuestion")
    public String checkAddQuestion(@RequestParam(value = "classifyId") Long classifyId) {
        JSONObject ret = new JSONObject();
        Map<String, Object> model = new HashMap();
        String busiDesc = "校验新增问题" + this.getModuleDesc();
        try {
            //查询当前问题下子节点已有个数
            List<ClassifyOptionEntity> classifyEntityList = this.optionService.find(new ClassifyOptionQuery().classifyId(classifyId));

            List<ClassifyEntity> classifyChilds = this.service.find(new ClassifyQuery().parentId(classifyId));
            if (classifyChilds.size() >= classifyEntityList.size()) {
                //当前节点子节点已经满了，不能再新增，请先编辑添加当前节点问题选项再添加子问题
                ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
                ret.put(KEY_RESULT_MSG, "请先编辑添加当前节点问题选项再添加子问题!");
                return ret.toJSONString();
            }

            //查询当前问题下子节点已有个数
            List<ClassifyOptionEntity> unChildList = classifyEntityList.stream().filter(f -> f.getClassifyNextId() == 0 || f.getClassifyNextId() == null).collect(Collectors.toList());
            //List<ClassifyOptionEntity> haveChildList = this.optionService.find(new ClassifyOptionQuery().classifyNextId(classifyId));


            //求差集，返回新增节点可选择的子问题
            // List<ClassifyOptionEntity> unChildList = this.optionService.diffList(classifyEntityList, haveChildList);

            model.put("preAnsOptions", unChildList);
            ret.put(KEY_RESULT_DATA, model);
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
            recordSysLog(request, busiDesc + " 【成功】");
        } catch (Exception e) {
            log.error("校验新增问题", e);
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, super.convertException(e));
            this.doException(request, busiDesc, model, e);
        }

        return ret.toJSONString();
    }


    @PostMapping(value = "getQuestionById")
    public String getQuestionById(@RequestParam(value = "classifyId") Long classifyId) {
        JSONObject ret = new JSONObject();
        Map<String, Object> model = new HashMap();
        String busiDesc = "获取问题" + this.getModuleDesc();
        try {
            ClassifyEntity entity = this.service.get(classifyId);
            List<ClassifyOptionEntity> optionList = this.optionService.find(new ClassifyOptionQuery().classifyId(classifyId));
            ClassifyOptionEntity curOption = this.optionService.selectOne(new ClassifyOptionQuery().classifyId(entity.getParentId()).classifyNextId(entity.getId()), getContext());
            List<ClassifyOptionEntity> unChildList = this.optionService.find(new ClassifyOptionQuery().classifyId(entity.getParentId())).stream().filter(f -> f.getClassifyNextId() == 0 || f.getClassifyNextId() == null).collect(Collectors.toList());

            unChildList.add(curOption);
            model.put("preAnsOptions", unChildList);
            model.put(KEY_RESULT_ENTITY, entity);
            model.put(KEY_RESULT_LIST, optionList);
            ret.put(KEY_RESULT_DATA, model);
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
            recordSysLog(request, busiDesc + " 【成功】");
        } catch (Exception e) {
            log.error("获取问题", e);
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, super.convertException(e));
            this.doException(request, busiDesc, model, e);
        }

        return ret.toJSONString();
    }


    @PostMapping(value = "removeQuestion")
    public String removeQuestion(@RequestParam(value = "basicsId") Long basicsId) {
        JSONObject ret = new JSONObject();
        Map<String, Object> model = new HashMap();
        String busiDesc = "清除问题" + this.getModuleDesc();
        try {
            this.service.removeQueston(basicsId,getContext());
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
            recordSysLog(request, busiDesc + " 【成功】");
        } catch (Exception e) {
            log.error("清除问题", e);
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, super.convertException(e));
            this.doException(request, busiDesc, model, e);
        }

        return ret.toJSONString();
    }


    public ClassifyTreeNode recursionTree(ClassifyTreeNode node) {

        List<ClassifyEntity> list = this.service.find(new ClassifyQuery().parentId(node.getId()));
        list.stream().peek(item -> {
            ClassifyTreeNode classifyTreeNode = new ClassifyTreeNode();
            classifyTreeNode.setId(item.getId());
            classifyTreeNode.setName(item.getName());
            classifyTreeNode.setIsmust(item.getIsmust());
            classifyTreeNode.setType(item.getType());
            classifyTreeNode.setLevel(item.getLevel());
            List<ClassifyOptionEntity> classifyOptionList = this.optionService.find(new ClassifyOptionQuery().classifyId(item.getId()));
            classifyTreeNode.setQuestion(classifyOptionList);

            //设置当前问题关联的上一个问题选项
            ClassifyOptionEntity preClassifyOptionEntity = this.optionService.selectOne(new ClassifyOptionQuery().classifyNextId(item.getId()), null);
            classifyTreeNode.setPreQuestion(preClassifyOptionEntity);
            node.getChildren().add(recursionTree(classifyTreeNode));
        }).count();
        return node;
    }

}