/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.manager.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.*;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springblade.core.cache.utils.CacheUtil;
import org.springblade.core.excel.util.ExcelUtil;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.support.Kv;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.manager.dto.FormElementDTO;
import org.springblade.manager.dto.WbsTreeDTO;
import org.springblade.manager.entity.WbsFormElement;
import org.springblade.manager.entity.WbsTree;
import org.springblade.manager.excel.WbsExcelUtil;
import org.springblade.manager.excel.WbsTreeExcel;
import org.springblade.manager.service.IWbsFormElementService;
import org.springblade.manager.vo.WbsNodeTableVO;
import org.springblade.manager.vo.WbsTreeVO;
import org.springblade.system.cache.DictCache;
import org.springblade.system.enums.DictEnum;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import org.springblade.manager.wrapper.WbsTreeWrapper;
import org.springblade.manager.service.IWbsTreeService;
import org.springblade.core.boot.ctrl.BladeController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.*;

import static org.springblade.core.cache.constant.CacheConstant.SYS_CACHE;

/**
 * 控制器
 *
 * @author liuyc
 * @since 2022-04-25
 */
@RestController
@AllArgsConstructor
@RequestMapping("/wbsTree")
@Api(value = "wbs动态库节点", tags = "wbs动态库节点接口")
public class WbsTreeController extends BladeController {

    private final IWbsTreeService wbsTreeService;
    private final IWbsFormElementService wbsFormElementService;

    /**
     * 详情
     */
    @GetMapping("/detail")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "详情", notes = "传入WbsTreeId,请求头token")
    @ApiImplicitParam(name = "id", value = "id", required = true)
    public R<WbsTreeVO> detail(WbsTree wbsTree) {
        WbsTree detail = wbsTreeService.getOne(Condition.getQueryWrapper(wbsTree));
        if (detail != null) {
            return R.data(WbsTreeWrapper.build().entityVO(detail));
        }
        return R.fail(200, "未查询到信息");
    }

    /**
     * 懒加载获取项目节点树形结构
     */
    @GetMapping("/lazy-tree")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "懒加载节点树形结构", notes = "传入wbsId，parentId，请求头token")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "wbsId", value = "wbsId", required = true),
            @ApiImplicitParam(name = "parentId", value = "父级id", required = true),
    })
    public R<List<WbsTreeVO>> lazyTree(String wbsId, Long parentId, BladeUser bladeUser, String tenantId) {
        List<WbsTreeVO> tree = wbsTreeService.lazyTree(wbsId, Func.toStrWithEmpty(tenantId, bladeUser.getTenantId()), parentId);
        if (tree != null && tree.size() > 0) {
            return R.data(tree);
        }
        return R.fail(200, "未查询到信息");
    }

    /**
     * 获取项目节点树形结构 (新增、修改加载、分配合同wbs树加载type=1)
     *
     * @return
     */
    @GetMapping("/tree")
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "节点树形结构", notes = "传入租户Id、wbsId、type、请求头token")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "tenantId", value = "租户id", required = false),
            @ApiImplicitParam(name = "wbsId", value = "wbsId", required = true),
            @ApiImplicitParam(name = "type", value = "节点类型type '1'节点or'2'表单", defaultValue = "", required = false),
    })
    public R<List<WbsTreeVO>> tree(String wbsId, String type, String tenantId, BladeUser bladeUser) {
        List<WbsTreeVO> tree = wbsTreeService.tree(wbsId, Func.toStrWithEmpty(tenantId, bladeUser.getTenantId()), type);
        if (tree != null && tree.size() > 0) {
            return R.data(tree);
        }
        return R.fail(200, "未查询到信息");
    }

    /**
     * 新增或修改
     */
    @PostMapping("/submit")
    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "新增或修改", notes = "WbsTreeDTO")
    public R submit(@Valid @RequestBody WbsTreeDTO WbsTreeDTO) {
        if (wbsTreeService.submit(WbsTreeDTO)) {
            CacheUtil.clear(SYS_CACHE);
            // 返回懒加载树更新节点所需字段
            Kv kv = Kv.create().set("id", String.valueOf(WbsTreeDTO.getId())).set("tenantId", WbsTreeDTO.getTenantId())
                    .set("deptCategoryName", DictCache.getValue(DictEnum.ORG_CATEGORY, WbsTreeDTO.getDeptCategory()));
            return R.data(kv);
        }
        return R.fail("操作失败");
    }


    /**
     * 逻辑删除
     */
    @PostMapping("/remove")
    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "逻辑删除", notes = "传入ids")
    public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
        return R.status(wbsTreeService.deleteLogic(Func.toLongList(ids)));
    }


    /**
     * 查询当前节点下所有表单（根据节点ID查询当前表单）
     */
    @GetMapping("/selectByNodeTable")
    @ApiOperationSupport(order = 6)
    @ApiOperation(value = "查询当前节点下所有表单", notes = "传入父节点id")
    public R<List<WbsNodeTableVO>> selectByNodeTable(@ApiParam(value = "父节点id", required = true) @RequestParam String id) {
        List<WbsNodeTableVO> rs = wbsTreeService.selectByNodeTable(id);
        if (!("").equals(rs) && rs.size() > 0) {
            return R.data(rs);
        }
        return R.fail(200, "未查询到数据");
    }

    /**
     * 删除表单
     */
    @GetMapping("/removeTableById")
    @ApiOperationSupport(order = 7)
    @ApiOperation(value = "表单删除", notes = "传入id")
    @ApiImplicitParam(name = "id", value = "表单id", required = true)
    public R removeTableById(@RequestParam("id") String id) {
        if (StringUtils.isNotEmpty(id)) {
            // 先查询表单下是否有元素，有元素则无法删除
            List<WbsFormElement> wbsFormElements = wbsTreeService.selectFormElements(id);
            if (wbsFormElements.size() > 0) {
                return R.fail("删除失败，请先移除表单中的元素！");
            }
            //删除表单
            boolean restul = wbsTreeService.removeTableById(id);
            if (restul) {
                return R.success("删除成功");
            }
        }
        return R.fail("删除失败");
    }

    /**
     * 根据表单id查询所有元素
     */
    @GetMapping("/selectFormElements")
    @ApiOperationSupport(order = 7)
    @ApiOperation(value = "根据表单id查询所有元素", notes = "传入表单id")
    @ApiImplicitParam(name = "id", value = "表单id", required = true)
    public R<List<WbsFormElement>> selectFormElements(@RequestParam("id") String id) {
        List<WbsFormElement> wbsFormElements = null;
        if (StringUtils.isNotEmpty(id)) {
            wbsFormElements = wbsTreeService.selectFormElements(id);
            if (wbsFormElements.size() > 0 && !"".equals(wbsFormElements)) {
                return R.data(wbsFormElements);
            }
        }
        return R.data(wbsFormElements, "未查询到元素");
    }


    /**
     * 新增表单与元素
     */
    @PostMapping("/saveFormAndElement")
    @ApiOperationSupport(order = 8)
    @ApiOperation(value = "表单与元素新增", notes = "传入FormElementDTO")
    public R saveFormElement(@RequestBody FormElementDTO formElementDTO) {
        return wbsTreeService.saveFormElement(formElementDTO);
    }

    /**
     * 编辑表单元素批量修改
     */
    @PostMapping("/updateBatchElements")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "编辑表单元素批量修改", notes = "传入WbsFormElement")
    @ApiImplicitParam(name = "ids", value = "元素的id集合", required = true)
    public R updateBatchElements(@RequestBody List<WbsFormElement> wbsFormElementList) {
        boolean b = wbsFormElementService.updateBatchById(wbsFormElementList);
        if (b) {
            return R.success("修改成功");
        }
        return R.fail("修改失败");
    }


    /**
     * 导出Wbs树模板
     */
    @GetMapping("/export-template")
    @ApiOperationSupport(order = 10)
    @ApiOperation(value = "导出WBS树节点模板")
    public void exportWbsTree(HttpServletResponse response) {
        List<WbsTreeExcel> list = new ArrayList<>();
        ExcelUtil.export(response, "WBS树节点模板", "WBS树节点表", list, WbsTreeExcel.class);
    }


    /**
     * 导入Wbs模板树
     */
    @ApiOperationSupport(order = 11)
    @ApiOperation(value = "导入WBS树节点", notes = "传入excel文件")
    @RequestMapping(value = "/import-wbsTree", method = RequestMethod.POST)
    public R importWbsTree(@RequestPart("excelFile") MultipartFile excelFile,
                           @RequestPart("wbsTreeFu") WbsTree wbsTreeFu) throws IOException {
        /*查询创建的二级工程节点是否已导入相同excel模板,判断是否是导入节点ProjectNodeId字段是否相同,如果是返回false*/
        Long parentId = wbsTreeFu.getParentId();
        WbsTree wbsTree1 = wbsTreeService.getById(parentId);
        if (wbsTree1.getProjectNodeId().equals(parentId)) {
            return R.fail("该节点下已存工程节点数据,请重新选择节点导入!");
        }
        //导入
        Boolean b = wbsTreeService.importWbsTree(excelFile, wbsTreeFu, wbsTree1);
        if (b) {
            return R.success("导入成功");
        }
        return R.fail("导入失败");
    }


}


