package org.jeecg.modules.basedata.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.NotDuplicate;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.basedata.entity.FdMilestoneTemplateItem;
import org.jeecg.modules.basedata.entity.FdMilestoneTemplateItemTree;
import org.jeecg.modules.basedata.service.IFdMilestoneTemplateItemService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;

/**
 * @Title: Controller
 * @Description: 里程碑模板项目
 * @author： jeecg-boot
 * @date： 2019-05-14
 * @version： V1.0
 */
@RestController
@RequestMapping("/basedata/fdMilestoneTemplateItem")
@Slf4j
public class FdMilestoneTemplateItemController {
    @Autowired
    private IFdMilestoneTemplateItemService fdMilestoneTemplateItemService;

    /**
     * 分页列表查询
     *
     * @param fdMilestoneTemplateItem
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/list")
    public Result<IPage<FdMilestoneTemplateItem>> queryPageList(FdMilestoneTemplateItem fdMilestoneTemplateItem,
                                                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                HttpServletRequest req) {
        Result<IPage<FdMilestoneTemplateItem>> result = new Result<IPage<FdMilestoneTemplateItem>>();
        QueryWrapper<FdMilestoneTemplateItem> queryWrapper = QueryGenerator.initQueryWrapper(fdMilestoneTemplateItem, req.getParameterMap());
        Page<FdMilestoneTemplateItem> page = new Page<FdMilestoneTemplateItem>(pageNo, pageSize);
        IPage<FdMilestoneTemplateItem> pageList = fdMilestoneTemplateItemService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }


    /**
     * 父子级查询
     */
    @GetMapping(value = "/queryTreeList")
    public Result<List<FdMilestoneTemplateItemTree>> queryTreeList(@RequestParam(name = "parent") String parent) {
        Result<List<FdMilestoneTemplateItemTree>> result = new Result<>();
        try {
            LambdaQueryWrapper<FdMilestoneTemplateItem> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(FdMilestoneTemplateItem::getPkMilestoneTemplate, parent);
            lambdaQueryWrapper.orderBy(true, true, FdMilestoneTemplateItem::getCode);
            List<FdMilestoneTemplateItem> list = fdMilestoneTemplateItemService.list(lambdaQueryWrapper);
            List<FdMilestoneTemplateItemTree> treeLists = new ArrayList<>();
            getTreeList(treeLists, list, null);
            findLeaf(treeLists);
            result.setResult(treeLists);
        } catch (Exception e) {
            e.fillInStackTrace();
        }
        return result;
    }

    private void getTreeList(List<FdMilestoneTemplateItemTree> treeList, List<FdMilestoneTemplateItem> fdlist, FdMilestoneTemplateItemTree temp) {
        for (FdMilestoneTemplateItem fdMilestoneTemplateItem : fdlist) {
            String tempPid = fdMilestoneTemplateItem.getParentId();
            FdMilestoneTemplateItemTree tree = new FdMilestoneTemplateItemTree(fdMilestoneTemplateItem);
            if (temp == null && oConvertUtils.isEmpty(tempPid)) {
                treeList.add(tree);
                if (!tree.getIsLeaf()) {
                    getTreeList(treeList, fdlist, tree);
                }
            } else if (temp != null && tempPid != null && tempPid.equals(temp.getId())) {
                temp.getChildren().add(tree);
                if (!tree.getIsLeaf()) {
                    getTreeList(treeList, fdlist, tree);
                }
            }

        }
    }

    /**
     * 判断是否有父级,如果有将id 与 父类id的拼接
     */
    public void scFdMilestoneTemplate() {
        List<FdMilestoneTemplateItem> list = fdMilestoneTemplateItemService.list();
        for (FdMilestoneTemplateItem fdMilestoneTemplateItem : list) {
            if (oConvertUtils.isNotEmpty(fdMilestoneTemplateItem.getParentId()) == true) {
                fdMilestoneTemplateItem.setParentIds(fdMilestoneTemplateItem.getParentId() + "," + fdMilestoneTemplateItem.getId());
                fdMilestoneTemplateItemService.updateById(fdMilestoneTemplateItem);
            }
        }
    }

    private void findLeaf(List<FdMilestoneTemplateItemTree> treeList) {
        for (FdMilestoneTemplateItemTree fdMilestoneTemplateItemTree : treeList) {
            //是否关键点  用于树形的swith
            if(fdMilestoneTemplateItemTree.getIsKeypoint().equals("1")){
                fdMilestoneTemplateItemTree.setKeypointBoo(true);
                fdMilestoneTemplateItemTree.setKeypointBoolean(true);
            }else{
                fdMilestoneTemplateItemTree.setKeypointBoo(false);
                fdMilestoneTemplateItemTree.setKeypointBoolean(false);
            }

            if (fdMilestoneTemplateItemTree.getChildren().isEmpty()) {
                fdMilestoneTemplateItemTree.setIsLeaf(true);
                fdMilestoneTemplateItemTree.setChildren(null);
            } else {
                findLeaf(fdMilestoneTemplateItemTree.getChildren());
            }
        }
    }


    /**
     * 添加
     *
     * @param fdMilestoneTemplateItem
     * @return
     */
    @PostMapping(value = "/add")
    @NotDuplicate
    public Result<FdMilestoneTemplateItem> add(@RequestBody @Valid FdMilestoneTemplateItem fdMilestoneTemplateItem, BindingResult bindingResult) {
        Result<FdMilestoneTemplateItem> result = new Result<FdMilestoneTemplateItem>();
        try {
            StringBuilder stringBuilder = new StringBuilder();
            if (bindingResult.hasErrors()) {
                //实体错误信息
                bindingResult.getAllErrors().stream().forEach(error -> stringBuilder.append(error.getDefaultMessage() + "<br/>"));
                result.error500(stringBuilder.toString());
                return result;
            }
            fdMilestoneTemplateItem.setDelFlag(CommonConstant.DEL_FLAG_0.toString());
            fdMilestoneTemplateItemService.save(fdMilestoneTemplateItem);
            result.success("添加成功！");
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            result.error500("操作失败:" + e.getMessage());

        }
        return result;
    }

    /**
     * 编辑
     *
     * @param fdMilestoneTemplateItem
     * @return
     */
    @PutMapping(value = "/edit")
    @NotDuplicate
    public Result<FdMilestoneTemplateItem> edit(@RequestBody @Valid FdMilestoneTemplateItem fdMilestoneTemplateItem, BindingResult bindingResult) {
        Result<FdMilestoneTemplateItem> result = new Result<FdMilestoneTemplateItem>();
        FdMilestoneTemplateItem fdMilestoneTemplateItemEntity = fdMilestoneTemplateItemService.getById(fdMilestoneTemplateItem.getId());
        if (fdMilestoneTemplateItemEntity == null) {
            StringBuilder stringBuilder = new StringBuilder();
            if (bindingResult.hasErrors()) {
                //实体错误信息
                bindingResult.getAllErrors().stream().forEach(error -> stringBuilder.append(error.getDefaultMessage() + "<br/>"));
                result.error500(stringBuilder.toString());
                return result;
            }
            result.error500("未找到对应实体");
        } else {
            boolean ok = fdMilestoneTemplateItemService.updateById(fdMilestoneTemplateItem);
            //TODO 返回false说明什么？
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/delete")
    public Result<FdMilestoneTemplateItem> delete(@RequestParam(name = "id", required = true) String id) {
        Result<FdMilestoneTemplateItem> result = new Result<FdMilestoneTemplateItem>();
        FdMilestoneTemplateItem fdMilestoneTemplateItem = fdMilestoneTemplateItemService.getById(id);
        if (fdMilestoneTemplateItem == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = fdMilestoneTemplateItemService.removeById(id);
            if (ok) {
                result.success("删除成功!");
            }
        }

        return result;
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping(value = "/deleteBatch")
    public Result<FdMilestoneTemplateItem> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<FdMilestoneTemplateItem> result = new Result<FdMilestoneTemplateItem>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.fdMilestoneTemplateItemService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public Result<FdMilestoneTemplateItem> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<FdMilestoneTemplateItem> result = new Result<FdMilestoneTemplateItem>();
        FdMilestoneTemplateItem fdMilestoneTemplateItem = fdMilestoneTemplateItemService.getById(id);
        if (fdMilestoneTemplateItem == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(fdMilestoneTemplateItem);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
        // Step.1 组装查询条件
        QueryWrapper<FdMilestoneTemplateItem> queryWrapper = null;
        try {
            String paramsStr = request.getParameter("paramsStr");
            if (oConvertUtils.isNotEmpty(paramsStr)) {
                String deString = URLDecoder.decode(paramsStr, "UTF-8");
                FdMilestoneTemplateItem fdMilestoneTemplateItem = JSON.parseObject(deString, FdMilestoneTemplateItem.class);
                queryWrapper = QueryGenerator.initQueryWrapper(fdMilestoneTemplateItem, request.getParameterMap());
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<FdMilestoneTemplateItem> pageList = fdMilestoneTemplateItemService.list(queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "里程碑模板项目列表");
        mv.addObject(NormalExcelConstants.CLASS, FdMilestoneTemplateItem.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("里程碑模板项目列表数据", "导出人:Jeecg", "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<FdMilestoneTemplateItem> listFdMilestoneTemplateItems = ExcelImportUtil.importExcel(file.getInputStream(), FdMilestoneTemplateItem.class, params);
                for (FdMilestoneTemplateItem fdMilestoneTemplateItemExcel : listFdMilestoneTemplateItems) {
                    fdMilestoneTemplateItemService.save(fdMilestoneTemplateItemExcel);
                }
                return Result.ok("文件导入成功！数据行数：" + listFdMilestoneTemplateItems.size());
            } catch (Exception e) {
                log.error(e.getMessage());
                return Result.error("文件导入失败！");
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }

    /*
     *
     * 查询除本身及以下的上级项目
     * @author 陈创
     * @date 2019/5/21
     * @param 里程碑模板对象
     * @return 里程碑项目集合
     */
    @GetMapping(value = "/queryByNotParentId")
    public Result<List<FdMilestoneTemplateItem>> queryByNotParentId(FdMilestoneTemplateItem fdMilestoneTemplateItem) {
        Result<List<FdMilestoneTemplateItem>> result = new Result<List<FdMilestoneTemplateItem>>();
        LambdaQueryWrapper<FdMilestoneTemplateItem> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(FdMilestoneTemplateItem::getDelFlag,"0");
        lambdaQueryWrapper.eq(FdMilestoneTemplateItem::getPkMilestoneTemplate, fdMilestoneTemplateItem.getPkMilestoneTemplate());//等于修改对象模板外键
        whereParent(lambdaQueryWrapper,fdMilestoneTemplateItem);//排除子级
        lambdaQueryWrapper.or();//或者
        lambdaQueryWrapper.isNull(FdMilestoneTemplateItem::getParentId);//为null
        lambdaQueryWrapper.or();//或者
        lambdaQueryWrapper.eq(FdMilestoneTemplateItem::getParentId, "");//为空
        lambdaQueryWrapper.orderByAsc(FdMilestoneTemplateItem::getCode);//排序
        List<FdMilestoneTemplateItem> fdMilestoneTemplateItemList = fdMilestoneTemplateItemService.list(lambdaQueryWrapper);
        if (fdMilestoneTemplateItemList == null) {
            result.error500("未找到对应实体");
        } else {
            //排除需修改对象
            for(FdMilestoneTemplateItem temItem: fdMilestoneTemplateItemList){
                if(temItem.getId().equals(fdMilestoneTemplateItem.getId())){
                    //与修改对象id相等则移除
                    fdMilestoneTemplateItemList.remove(temItem);
                    break;
                }
            }
            result.setResult(fdMilestoneTemplateItemList);
            result.setSuccess(true);
        }
        return result;
    }

    //递归排除修改对象的子级以及以下节点数据
    public void whereParent(LambdaQueryWrapper<FdMilestoneTemplateItem> lambdaQueryWrapper,FdMilestoneTemplateItem fdMilestoneTemplateItem){
        lambdaQueryWrapper.ne(FdMilestoneTemplateItem::getParentId,fdMilestoneTemplateItem.getId());//排除子级
        LambdaQueryWrapper<FdMilestoneTemplateItem> lambdaQueryWrapper2=new LambdaQueryWrapper<>();
        lambdaQueryWrapper2.eq(FdMilestoneTemplateItem::getDelFlag,"0");
        lambdaQueryWrapper2.eq(FdMilestoneTemplateItem::getParentId,fdMilestoneTemplateItem.getId());//父级id
        List<FdMilestoneTemplateItem> list=fdMilestoneTemplateItemService.list(lambdaQueryWrapper2);//根据父级id查询子级
        for(FdMilestoneTemplateItem mileItem:list){
            whereParent(lambdaQueryWrapper,mileItem);
        }
    }

}
