/*
 *      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.business.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.*;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.springblade.business.entity.ContractTreeDrawings;
import org.springblade.business.feignClient.ClientTreePublicCodeClientImpl;
import org.springblade.business.service.IContractTreeDrawingsService;
import org.springblade.business.vo.FileUserVO;
import org.springblade.business.vo.InformationQueryVO;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.manager.entity.ContractInfo;
import org.springblade.manager.entity.WbsTreeContract;
import org.springblade.manager.entity.WbsTreePrivate;
import org.springblade.manager.feign.ContractClient;
import org.springblade.manager.feign.WbsTreeContractClient;
import org.springblade.manager.feign.WbsTreePrivateClient;
import org.springblade.manager.vo.WbsTreeContractTreeVOS;
import org.springblade.manager.vo.WbsTreePrivateVO;
import org.springblade.system.entity.DictBiz;
import org.springblade.system.feign.IDictBizClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import org.springblade.business.entity.InformationQuery;
import org.springblade.business.service.IInformationQueryService;
import org.springblade.core.boot.ctrl.BladeController;

import java.util.List;

/**
 *  资料填报及查询控制器
 *
 * @author BladeX
 * @since 2022-06-08
 */
@RestController
@AllArgsConstructor
@RequestMapping("/informationWriteQuery")
@Api(tags = "资料查询接口")
public class InformationWriteQueryController extends BladeController {

	private final ContractClient contractClient;

	private final WbsTreeContractClient wbsTreeContractClient;

	private final WbsTreePrivateClient wbsTreePrivateClient;

	private final IInformationQueryService informationQueryService;

	private final IDictBizClient dictBizClient;

	private final IContractTreeDrawingsService contractTreeDrawingsService;

	private final ClientTreePublicCodeClientImpl clientTreePublicCodeClient;

	/**
	 * 修改节点信息
	 * @param node 节点信息
	 * @return 修改结果
	 */
	@PostMapping("/updateContractNodeParameter")
	@ApiOperationSupport(order = 13)
	@ApiOperation(value = "修改节点信息")
	@ApiImplicitParam(name = "node", value = "节点信息（目前只允许修改名称），需要将pKeyId传入")
	public R<Boolean> updateContractNodeParameter(@Valid @RequestBody WbsTreeContract node){
		//只允许修改节点名称
		if(StringUtils.isEmpty(node.getDeptName()) || "null".equals(String.valueOf(node.getPKeyId())) || StringUtils.isNotEmpty(String.valueOf(node.getPKeyId()))){
			return R.data(-1, false , "缺少参数");
		}
		return R.data(this.wbsTreeContractClient.updateContractNodeParameter(node));
	}

	/**
	 * 获取节点信息
	 * @param primaryKeyId 节点的primaryKeyId
	 * @return 节点信息
	 */
	@GetMapping("/getContractNodeByPrimaryKeyId")
	@ApiOperationSupport(order = 12)
	@ApiOperation(value = "获取节点信息")
	@ApiImplicitParam(name = "primaryKeyId", value = "节点的primaryKeyId")
	public R<WbsTreeContract> getContractNodeByPrimaryKeyId(@RequestParam String primaryKeyId){
		return R.data(this.wbsTreeContractClient.getContractNodeByPrimaryKeyId(primaryKeyId));
	}


	/**
	 * 删除节点
	 * @param ids 节点的primaryKeyId
	 * @return 删除结果
	 */
	@PostMapping("/removeContractTreeNode")
	@ApiOperationSupport(order = 11)
	@ApiOperation(value = "删除节点")
	@ApiImplicitParam(name = "ids", value = "节点的primaryKeyId")
	public R<Boolean> removeContractTreeNode(@RequestParam String ids){
		return R.data(this.wbsTreeContractClient.removeContractTreeNode(ids));
	}

	/**
	 * 新增子节点
	 * @param contractNodePrimaryKeyId 新增的节点所在位置，即当前点出菜单栏的节点PrimaryKeyId
	 * @param projectNodePrimaryKeyId 被选中的新增节点
	 * @return 新增结果
	 */
	@PostMapping("/saveContractTreeNode")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "新增节点及其子节点")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "contractNodePrimaryKeyId", value = "新增的节点所在位置，即当前点出菜单栏的节点PrimaryKeyId", required = true),
			@ApiImplicitParam(name = "projectNodePrimaryKeyId", value = "被选中的新增节点", required = true)
	})
	public R<Boolean> saveContractTreeNode(@RequestParam String contractNodePrimaryKeyId, @RequestParam String projectNodePrimaryKeyId){
		//先获取当前节点的信息
		WbsTreeContract treeContract = this.wbsTreeContractClient.getContractWbsTreeByPrimaryKeyId(Long.parseLong(contractNodePrimaryKeyId));
		//检查当前节点下是否添加了子节点

		return null;
	}

	/**
	 * 懒加载项目级工程划分树
	 * @param projectId 项目ID
	 * @param id 节点ID
	 * @return 结果集
	 */
	@PostMapping("/queryWbsTreePrivateByProjectIdAndId")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "懒加载项目级工程划分树")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "projectId", value = "项目ID"),
			@ApiImplicitParam(name = "id", value = "点击节点ID")
	})
	public R<List<WbsTreePrivateVO>> queryWbsTreePrivateByProjectIdAndId(@RequestParam String projectId, @RequestParam String id){
		return R.data(this.wbsTreePrivateClient.queryWbsTreePrivateByProjectIdAndId(projectId, Long.parseLong(id)));
	}

	/**
	 * 获取与当前节点平级的项目级节点
	 * @param primaryKeyId 主键
	 * @return 结果
	 */
	@PostMapping("/queryPeersNode")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "获取与当前节点平级的项目级节点")
	@ApiImplicitParam(name = "primaryKeyId", value = "需要新增子节点的节点ID，即当前点出菜单栏的节点ID")
	public R<WbsTreePrivate> queryPeersNode(@RequestParam String primaryKeyId){
		if(StringUtils.isEmpty(primaryKeyId) || "null".equals(primaryKeyId)){
			return R.data(null);
		}

		//首先获取当前节点信息
		WbsTreeContract treeContract = this.wbsTreeContractClient.getContractWbsTreeByPrimaryKeyId(Long.parseLong(primaryKeyId));
		//获取与其平级对应的项目级节点
		WbsTreePrivate treePrivate = this.wbsTreePrivateClient.queryPeersNodeByProjectIdAndId(treeContract.getProjectId(), treeContract.getId());

		return R.data(treePrivate);
	}


	/**
	 * 获取流程状态分类和文件类型分类
	 */
	@GetMapping("/getDictBizClassifyByCode")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "获取流程状态分类和文件类型分类")
	@ApiImplicitParam(name = "code", value = "获取流程状态分类：flowTaskStatus；获取文件类型分类：fileType")
	public R<List<DictBiz>> getDictBizClassifyByCode(@RequestParam String code){
		return this.dictBizClient.getList(code, "notRoot");
	}

	/**
	 * 获取当前合同段下所有的上报批次
	 * @param contractId 合同段ID
	 * @return 结果
	 */
	@GetMapping("/getReportNumberByContractId")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "获取当前合同段下所有的上报批次")
	@ApiImplicitParam(name = "contractId", value = "合同段ID", required = true)
	public R<List<Integer>> getReportNumberByContractId(@RequestParam String contractId){
		//获取合同段信息
		ContractInfo contract = this.contractClient.getContractById(Long.valueOf(contractId));
		return R.data(this.informationQueryService.getReportNumberByContractId(contract.getContractType() == null ? 1 : contract.getContractType(), contractId));
	}

	/**
	 * 根据合同段ID获取所有填报人
	 * @param contractId 合同段ID
	 * @return 填报人集合
	 */
	@GetMapping("/getFileUserByContractId")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "根据合同段ID获取所有填报人")
	@ApiImplicitParam(name = "contractId", value = "合同段ID", required = true)
	public R<List<FileUserVO>> getFileUserByContractId(@RequestParam String contractId){
		//获取合同段信息
		ContractInfo contract = this.contractClient.getContractById(Long.valueOf(contractId));
		return R.data(this.informationQueryService.queryFileUserByContractId(contract.getContractType() == null ? 1 : contract.getContractType(), contractId));
	}

	/**
	 * 分页
	 * @param vo 查询条件
	 * @return 结果
	 */
	@PostMapping("/page")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "分页")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "size", value = "当前页条数", required = true),
			@ApiImplicitParam(name = "current", value = "当前页", required = true),
			@ApiImplicitParam(name = "wbsId", value = "节点ID", required = true),
			@ApiImplicitParam(name = "contractId", value = "合同段ID", required = true)
	})
	public R<IPage<InformationQueryVO>> page(@RequestBody InformationQueryVO vo){
		if("null".equals(String.valueOf(vo.getContractId())) || StringUtils.isEmpty(String.valueOf(vo.getContractId()))){
			return R.data(-1, null, "数据查询失败");
		}
		//封装分页信息
		Query query = new Query();
		query.setSize(vo.getSize());
		query.setCurrent(vo.getCurrent());
		//获取合同段信息
		ContractInfo contract = this.contractClient.getContractById(vo.getContractId());
		vo.setClassify(contract.getContractType() == null ? 1 : contract.getContractType());

		return R.data(this.informationQueryService.selectInformationQueryPage(Condition.getPage(query), vo));
	}

	/**
	 * 获取当前合同段的划分树
	 * @return 结果
	 */
	@GetMapping("/queryContractWbsTreeByContractIdAndType")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "获取当前合同段的划分树")
	@ApiImplicitParams(value = {
			@ApiImplicitParam(name = "parentId", value = "父节点，为空则查询第一级节点"),
			@ApiImplicitParam(name = "contractId", value = "合同段ID", required = true)
	})
	public R<List<WbsTreeContractTreeVOS>> queryContractWbsTreeByContractIdAndType(@RequestParam String parentId, @RequestParam String contractId){
		List<WbsTreeContractTreeVOS> rootTreeNode;

		if(com.alibaba.nacos.common.utils.StringUtils.isEmpty(parentId)){
			//为空，说明初始化
			//获取根节点
			rootTreeNode = this.clientTreePublicCodeClient.queryContractWbsTreeByContractIdAndType(contractId, 1, "0");
		} else {
			//不为空，获取其下子节点
			rootTreeNode = this.wbsTreeContractClient.queryContractWbsTreeByContractIdAndType(contractId, 1, parentId);
		}

		//获取上传的图纸
		if(rootTreeNode != null && rootTreeNode.size() != 0){
			rootTreeNode.forEach(vo -> {
				ContractTreeDrawings drawings = this.contractTreeDrawingsService.queryCurrentNodeDrawings(vo.getPrimaryKeyId());
				if(drawings != null){
					//主键
					vo.setDrawingsId(drawings.getId());
					//文件路径
					vo.setFileUrl(drawings.getFileUrl());
				}
			});
		}

		return R.data(rootTreeNode);
	}

	/**
	 * 修改 
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "修改(只能修改编号和文件名)")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "name", value = "文件名称, 必须有值", required = true),
			@ApiImplicitParam(name = "number", value = "文件编号，可以为空")
	})
	public R<Boolean> update(@Valid @RequestBody InformationQuery informationQuery) {
		if("null".equals(String.valueOf(informationQuery.getId())) || StringUtils.isEmpty(String.valueOf(informationQuery.getId()))){
			return R.data(-1, false, "数据操作失败");
		}
		return R.status(informationQueryService.update(Wrappers.<InformationQuery>lambdaUpdate().set(InformationQuery::getName, informationQuery.getName()).set(InformationQuery::getNumber, informationQuery.getNumber()).eq(InformationQuery::getId, informationQuery.getId())));
	}

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

	
}
