package org.springblade.business.controller;

import cn.hutool.core.date.DateUtil;
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.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
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.utils.Func;
import org.springblade.manager.feign.WbsTreeContractClient;
import org.springblade.manager.vo.WbsTreeContractTreeVOS;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.business.entity.ConstructionLedger;
import org.springblade.business.vo.ConstructionLedgerVO;
import org.springblade.business.wrapper.ConstructionLedgerWrapper;
import org.springblade.business.service.IConstructionLedgerService;
import org.springblade.core.boot.ctrl.BladeController;

import java.util.Date;
import java.util.List;

/**
 *  施工台账控制器
 *
 * @author BladeX
 * @since 2022-05-23
 */
@RestController
@AllArgsConstructor
@RequestMapping("/constructionLedger")
@Api(tags = "施工台账接口")
public class ConstructionLedgerController extends BladeController {

	private final IConstructionLedgerService constructionLedgerService;

	private final WbsTreeContractClient wbsTreeContractClient;

	/**
	 * 获取当前合同段的划分树
	 * @param wbsType 查询类型，1为质检类型划分
	 * @return 结果
	 */
	@GetMapping("/queryContractWbsTreeByContractIdAndType")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "获取当前合同段的划分树")
	@ApiImplicitParams(value = {
			@ApiImplicitParam(name = "wbsType", value = "数据类型，目前质检为1", required = true),
			@ApiImplicitParam(name = "parentId", value = "父节点，为空则查询第一级节点"),
			@ApiImplicitParam(name = "contractId", value = "合同段ID", required = true)
	})
	public R<List<WbsTreeContractTreeVOS>> queryContractWbsTreeByContractIdAndType(@RequestParam Integer wbsType, @RequestParam String parentId, @RequestParam String contractId){
		return StringUtils.isEmpty(parentId) ?
				R.data(this.wbsTreeContractClient.queryContractWbsTreeByContractIdAndType(contractId, wbsType, "0"))
				:
				R.data(this.wbsTreeContractClient.queryContractWbsTreeByContractIdAndType(contractId, wbsType, parentId));
	}

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入id")
	public R<ConstructionLedgerVO> detail(@RequestParam String id) {
		ConstructionLedger detail = this.constructionLedgerService.getById(id);
		return R.data(ConstructionLedgerWrapper.build().entityVO(detail));
	}

	/**
	 * 分页 
	 */
	@PostMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页（建议）", notes = "传入constructionLedger")
	public R<IPage<ConstructionLedgerVO>> list(@Valid @RequestBody ConstructionLedgerVO vo) {
		ConstructionLedger ledger = new ConstructionLedger();
		BeanUtils.copyProperties(vo, ledger);

		Query query = new Query();
		query.setCurrent(vo.getCurrent());
		query.setSize(vo.getSize());
		IPage<ConstructionLedger> pages;
		if(vo.getSiteStartTime() != null && vo.getSiteEndTime() != null){
			pages = this.constructionLedgerService.page(Condition.getPage(query), Condition.getQueryWrapper(ledger).lambda().in(ConstructionLedger::getWbsId, vo.getWbsIds()).between(ConstructionLedger::getSiteStartTime, ledger.getSiteStartTime(), ledger.getSiteEndTime()));
		} else {
			pages = this.constructionLedgerService.page(Condition.getPage(query), Condition.getQueryWrapper(ledger).lambda().in(ConstructionLedger::getWbsId, vo.getWbsIds()));
		}
		return R.data(ConstructionLedgerWrapper.build().pageVO(pages));
	}

	/**
	 * 新增 
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增（不需要）", notes = "传入constructionLedger")
	public R<Boolean> save(@Valid @RequestBody ConstructionLedger constructionLedger) {
		setUserData(constructionLedger, true);
		return R.status(this.constructionLedgerService.save(constructionLedger));
	}

	/**
	 * 修改 
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入constructionLedger")
	public R<Boolean> update(@Valid @RequestBody ConstructionLedgerVO constructionLedger) {
		//施工起止时间
		if(StringUtils.isNotEmpty(constructionLedger.getSiteTimeStr()) && constructionLedger.getSiteTimeStr().contains("~")){
			String[] time = constructionLedger.getSiteTimeStr().split("~");
			constructionLedger.setSiteStartTime(DateUtil.toLocalDateTime(org.springblade.core.tool.utils.DateUtil.parse(time[0], "yyyy-MM-dd")));
			constructionLedger.setSiteEndTime(DateUtil.toLocalDateTime(org.springblade.core.tool.utils.DateUtil.parse(time[1], "yyyy-MM-dd")));
		}

		//检测起止时间
		if(StringUtils.isNotEmpty(constructionLedger.getDetectionTimeStr()) && constructionLedger.getDetectionTimeStr().contains("~")){
			String[] time = constructionLedger.getDetectionTimeStr().split("~");
			constructionLedger.setDetectionStartTime(DateUtil.toLocalDateTime(org.springblade.core.tool.utils.DateUtil.parse(time[0], "yyyy-MM-dd")));
			constructionLedger.setDetectionEndTime(DateUtil.toLocalDateTime(org.springblade.core.tool.utils.DateUtil.parse(time[1], "yyyy-MM-dd")));
		}
		setUserData(constructionLedger, false);
		return R.status(this.constructionLedgerService.updateById(constructionLedger));
	}

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

	//设置登录用户信息
	private void setUserData(ConstructionLedger constructionLedger, boolean isCreate){
		//获取当前登录人
		BladeUser user = AuthUtil.getUser();
		//记录操作人信息
		if(isCreate){
			constructionLedger.setCreateUser(user.getUserId());
			constructionLedger.setCreateDept(Long.parseLong(user.getDeptId()));
		} else {
			constructionLedger.setUpdateUser(user.getUserId());
			constructionLedger.setUpdateTime(new Date());
		}
	}



}
