/**
 * Copyright (c) 2018-2099, Chill Zhuang 庄骞 (bladejava@qq.com).
 * <p>
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.xiaoniu.subsystem.business.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.xiaoniu.common.core.constant.Constants;
import com.xiaoniu.common.core.result.R;
import com.xiaoniu.common.core.utils.BeanUtil;
import com.xiaoniu.subsystem.business.domain.Demand;
import com.xiaoniu.subsystem.business.domain.DemandSignUp;
import com.xiaoniu.subsystem.business.domain.DemandTotal;
import com.xiaoniu.subsystem.business.domain.WaitDone;
import com.xiaoniu.subsystem.business.domain.dto.DemandSignUpDTO;
import com.xiaoniu.subsystem.business.domain.vo.DemandSignUpVO;
import com.xiaoniu.subsystem.business.service.IDemandService;
import com.xiaoniu.subsystem.business.service.IDemandSignUpService;
import com.xiaoniu.subsystem.business.service.IDemandTotalService;
import com.xiaoniu.subsystem.business.service.IWaitDoneService;
import com.xiaoniu.subsystem.system.domain.Unit;
import com.xiaoniu.subsystem.system.service.IUnitService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import static com.xiaoniu.common.security.utils.SecurityUtils.getUnitId;
import static com.xiaoniu.common.security.utils.SecurityUtils.getUserId;

/**
 * 需求报名表 控制器
 *
 * @author sst
 * @since 2024-11-26
 */
@RestController
@AllArgsConstructor
@RequestMapping("/demandsignup")
@Tag(name = "需求报名表", description = "需求报名表接口")
public class DemandSignUpController  {

	private IDemandSignUpService demandSignUpService;
	private IDemandService demandService;
	private final IWaitDoneService waitDoneService;
	private final IUnitService unitService;
	private IDemandTotalService demandTotalService;


	/**
	 * 新增 需求报名表
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 1)
	@Operation(summary = "新增", description = "传入demandSignUp")
	public R save(@Valid @RequestBody DemandSignUpDTO dto) {
		long l = demandService.count(new LambdaQueryWrapper<Demand>()
				.eq(Demand::getDemandId, dto.getDemandId())
				.eq(Demand::getIsReport, 1)
				.ne(Demand::getStatus, 0));
		if (l != 0) {
            return R.fail("该需求已经上报或审核");
        }
		long count = demandSignUpService.count(new LambdaQueryWrapper<DemandSignUp>()
				.eq(DemandSignUp::getDemandId, dto.getDemandId()));
		if (count == 0) {
			Demand demand = demandService.getById(dto.getDemandId());
			demandService.updateById(demand
					.setStatus(1)
					.setIsReport("1")
					.setUpdateUser(getUserId())
					.setUpdateTime(new Date()));
			demandSignUpService.save(dto
					.setStatus(1)
					.setCreateDept(getUnitId())
					.setCreateUser(getUserId())
					.setCreateTime(new Date()));
			Unit unit = unitService.getById(getUnitId());
			DemandTotal demandTotal = demandTotalService.getOne(new LambdaQueryWrapper<DemandTotal>()
					.eq(DemandTotal::getDemandId, dto.getDemandId())
					.eq(DemandTotal::getUnitId, unit.getUnitId()));
			if (demandTotal == null) {
				demandTotalService.save(new DemandTotal()
						.setDemandId(dto.getDemandId())
						.setUnitId(unit.getUnitId())
						.setUnitName(unit.getUnitName())
						.setContactPerson(unit.getContactPerson())
						.setPhone(unit.getPhone())
						.setPeopleNum(Integer.valueOf(dto.getForecastAttendance())));
			} else {
				demandTotalService.updateById(demandTotal
						.setPeopleNum(demandTotal.getPeopleNum()
								+ Integer.parseInt(dto.getForecastAttendance())));
			}
			setDemandTotal(demand.getParentId(),unit.getParentId(),
					Integer.valueOf(dto.getForecastAttendance()));

			Demand one = getDemand(demand.getParentId());
			List<Demand> list = listDemand(one);
			List<Demand> demands = list.stream().filter(d -> StringUtils.equals("0", d.getIsReport())).toList();
			if (CollectionUtils.isEmpty(demands)){
				demandService.updateById(one.setIsReport("1"));
			}
			return R.status(waitDoneService.save(new WaitDone()
					.setWaitDoneUnit(demand.getMainUnitId())
					.setFlightId(dto.getFlightId())
					.setFlightName(dto.getFlightName())
					.setType("1")
					.setWaitDoneMessage("需求上报待办提示,点击跳转需求类表（机关）审核列表，审核过后修改状态")
					.setSkip("")
					.setBusinessId(one.getDemandId())
					.setCreateDept(getUnitId())
					.setStatus(Constants.ZERO)));
		}
		return R.fail("该需求已经报名");
	}


	private Demand getDemand(Long parentId){
		Demand one = demandService.getOne(new LambdaQueryWrapper<Demand>()
				.eq(Demand::getDemandId, parentId));
		if (0 == one.getParentId()) {
			return one;
		}
		return getDemand(one.getParentId());
	}

	private List<Demand> listDemand(Demand demand){
		List<Demand> demandList = new ArrayList<>();
		List<Demand> list1 = demandService.list(new LambdaQueryWrapper<Demand>()
				.eq(Demand::getParentId, demand.getDemandId()));
		if (CollectionUtils.isEmpty(list1)) {
			return demandList;
		}
		demandList.addAll(list1);
		listDemand(list1,demandList);
		List<Demand> demandList1 = new ArrayList<>();
		for (Demand d : demandList) {
			List<Demand> list2 = demandService.list(new LambdaQueryWrapper<Demand>()
					.eq(Demand::getParentId, d.getDemandId()));
			if (CollectionUtils.isNotEmpty(list2)) {
				demandList1.add(d);
			}
		}
		demandList.removeAll(demandList1);
		return demandList;
	}

	private void listDemand(List<Demand> list, List<Demand> demandList){
		List<Demand> list1 = demandService.list(new LambdaQueryWrapper<Demand>()
				.in(Demand::getParentId, list.stream().map(Demand::getDemandId).toList()));
		if (CollectionUtils.isNotEmpty(list1)) {
			demandList.addAll(list1);
			listDemand(list1,demandList);
		}
	}


	/**
	 * 修改 需求报名表
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 2)
	@Operation(summary = "修改", description = "传入demandSignUp")
	public R update(@Valid @RequestBody DemandSignUpDTO dto) {
		long l = demandService.count(new LambdaQueryWrapper<Demand>()
				.eq(Demand::getDemandId, dto.getDemandId())
				.eq(Demand::getIsReport, 1)
				.eq(Demand::getStatus, 1));
		if (l != 0) {
			return R.fail("该需求已经审核通过");
		}
		demandSignUpService.updateById(
				dto.setStatus(1).setUpdateUser(getUserId()).setUpdateTime(new Date()));
		Demand byId = demandService.getById(dto.getDemandId());
		demandService.update(new LambdaUpdateWrapper<Demand>()
				.set(Demand::getIsReport,1)
				.set(Demand::getStatus,1)
				.set(Demand::getUpdateUser,getUserId())
				.set(Demand::getUpdateTime,new Date())
				.eq(Demand::getDemandId,dto.getDemandId()));
		if (0 == byId.getStatus()){
			return R.status(true);
		}
		Unit unit = unitService.getById(getUnitId());
		return R.status(waitDoneService.save(new WaitDone().setWaitDoneUnit(unit.getParentId())
				.setFlightId(dto.getFlightId())
				.setFlightName(dto.getFlightName())
				.setType("1")
				.setWaitDoneMessage("需求上报待办提示,点击跳转需求类表（机关）审核列表，审核过后修改状态")
				.setSkip("")
				.setBusinessId(dto.getDemandId())
				.setCreateDept(getUnitId())
				.setStatus(Constants.ZERO)));
	}

	/**
	 * 删除 需求报名表
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 3)
	@Operation(summary = "删除", description = "传入ids")
	public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String demandSignUpIds) {
		return R.status(demandSignUpService.removeByIds(Arrays.stream(demandSignUpIds.split(",")).toList()));
	}
	/**
	 * 根据需求ID查询详情
	 */
	@GetMapping("/detailByDemandId")
	@ApiOperationSupport(order = 4)
	@Operation(summary = "根据需求ID查询详情", description = "传入demandId")
	public R<DemandSignUpVO> detailByDemandId(@Parameter(description = "需求主键", required = true)
												  @RequestParam Long demandId) {
		DemandSignUp detail = demandSignUpService.getOne(new LambdaQueryWrapper<DemandSignUp>()
				.eq(DemandSignUp::getDemandId,demandId));
		return R.data(BeanUtil.copy(detail, DemandSignUpVO.class));
	}

	/**
	 * 根据需求ID集合删除 需求报名表
	 */
	@PostMapping("/removeByDemandIds")
	@ApiOperationSupport(order = 5)
	@Operation(summary = "根据需求ID集合删除", description = "传入ids")
	public R removeByDemandIds(@Parameter(description = "需求主键主键集合", required = true)
								   @RequestParam String demandIds) {
		return R.status(demandSignUpService.remove(new LambdaQueryWrapper<DemandSignUp>()
				.in(DemandSignUp::getDemandId,Arrays.stream(demandIds.split(",")).toList())));
	}


	private void setDemandTotal(Long demandId,Long unitId,Integer forecastAttendance) {
		if(0 != demandId){
			Unit unit = unitService.getById(unitId);
			Demand demand = demandService.getById(demandId);
			DemandTotal demandTotal = demandTotalService.getOne(new LambdaQueryWrapper<DemandTotal>()
					.eq(DemandTotal::getDemandId, demand.getDemandId())
					.eq(DemandTotal::getUnitId, unit.getUnitId()));
			if (demandTotal == null) {
				demandTotalService.save(new DemandTotal()
						.setDemandId(demand.getDemandId())
						.setUnitId(unit.getUnitId())
						.setUnitName(unit.getUnitName())
						.setContactPerson(unit.getContactPerson())
						.setPhone(unit.getPhone())
						.setPeopleNum(forecastAttendance));
			} else {
				demandTotalService.updateById(demandTotal
						.setPeopleNum(demandTotal.getPeopleNum()
								+ forecastAttendance));
			}
			setDemandTotal(demand.getParentId(),unit.getParentId(),forecastAttendance);
		}
	}
	
}
