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

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;

import javax.validation.Valid;

import org.springblade.core.secure.BladeUser;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.service.IDeptService;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.modules.hcrwb.entity.HcrwbEntity;
import org.springblade.modules.hcrwb.vo.HcrwbVO;
import org.springblade.modules.hcrwb.excel.HcrwbExcel;
import org.springblade.modules.hcrwb.wrapper.HcrwbWrapper;
import org.springblade.modules.hcrwb.service.IHcrwbService;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.excel.util.ExcelUtil;
import org.springblade.core.tool.constant.BladeConstant;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

/**
 * 核查任务表 控制器
 *
 * @author BladeX
 * @since 2024-01-29
 */
@RestController
@AllArgsConstructor
@RequestMapping("blade-hcrwb/hcrwb")
@Api(value = "核查任务表", tags = "核查任务表接口")
public class HcrwbController extends BladeController {

	private final IHcrwbService hcrwbService;
	private final IDeptService deptService;

	/**
	 * 核查任务表 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入hcrwb")
	public R<HcrwbVO> detail(HcrwbEntity hcrwb) {
		HcrwbEntity detail = hcrwbService.getOne(Condition.getQueryWrapper(hcrwb));
		return R.data(HcrwbWrapper.build().entityVO(detail));
	}

	/**
	 * 核查任务表 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入hcrwb")
	public R<IPage<HcrwbVO>> list(@ApiIgnore @RequestParam Map<String, Object> hcrwb, Query query) {
		IPage<HcrwbEntity> pages = hcrwbService.page(Condition.getPage(query), Condition.getQueryWrapper(hcrwb, HcrwbEntity.class));
		return R.data(HcrwbWrapper.build().pageVO(pages));
	}

	/**
	 * 核查任务表 自定义分页
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入hcrwb")
	public R<IPage<HcrwbVO>> page(HcrwbVO hcrwb, Query query) {
		IPage<HcrwbVO> pages = hcrwbService.selectHcrwbPage(Condition.getPage(query), hcrwb);
		return R.data(pages);
	}

	/**
	 * 核查任务表 新增
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入hcrwb")
	public R save(@Valid @RequestBody HcrwbEntity hcrwb) {
		return R.status(hcrwbService.save(hcrwb));
	}

	/**
	 * 核查任务表 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入hcrwb")
	public R update(@Valid @RequestBody HcrwbEntity hcrwb) {
		return R.status(hcrwbService.updateById(hcrwb));
	}

	/**
	 * 核查任务表 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入hcrwb")
	public R submit(@Valid @RequestBody HcrwbEntity hcrwb) {
		return R.status(hcrwbService.saveOrUpdate(hcrwb));
	}

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


	/**
	 * 导出数据
	 */
	@GetMapping("/export-hcrwb")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "导出数据", notes = "传入hcrwb")
	public void exportHcrwb(@ApiIgnore @RequestParam Map<String, Object> hcrwb, BladeUser bladeUser, HttpServletResponse response) {
		QueryWrapper<HcrwbEntity> queryWrapper = Condition.getQueryWrapper(hcrwb, HcrwbEntity.class);
		//if (!AuthUtil.isAdministrator()) {
		//	queryWrapper.lambda().eq(Hcrwb::getTenantId, bladeUser.getTenantId());
		//}
		queryWrapper.lambda().eq(HcrwbEntity::getIsDeleted, BladeConstant.DB_NOT_DELETED);
		List<HcrwbExcel> list = hcrwbService.exportHcrwb(queryWrapper);
		ExcelUtil.export(response, "核查任务表数据" + DateUtil.time(), "核查任务表数据表", list, HcrwbExcel.class);
	}

	/**
	 * 核查任务表 保存
	 */
	@PostMapping("/saveHcrw")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "核查任务保存", notes = "传入hcrwb")
	public R saveHcrw(@Valid @RequestBody HcrwbEntity hcrwb) {
		if (StringUtil.isBlank(hcrwb.getSid())
			|| StringUtil.isBlank(hcrwb.getInspectionBatch())
			|| StringUtil.isBlank(hcrwb.getExecutionUnit().toString())
		) {
			return R.fail("缺少核查任务主要信息！");
		}
		String[] shtyBmArr = hcrwb.getSid().split(",");
		int[] hcrwCnt = new int[2];

		List<HcrwbEntity> hcrwbEntityList = hcrwbService.list(Wrappers.<HcrwbEntity>query().lambda().eq(HcrwbEntity::getIsDeleted, BladeConstant.DB_NOT_DELETED)
			.in(HcrwbEntity::getSid, shtyBmArr).eq(HcrwbEntity::getInspectionBatch, hcrwb.getInspectionBatch()));
		Dept dept = deptService.getById(hcrwb.getExecutionUnit());

		if (hcrwbEntityList.size() > 0) {
			for (HcrwbEntity hcrwbEntity : hcrwbEntityList) {
				if (!hcrwbEntity.getInspectionStatus().equals("1")) {
					if (dept.getAncestors().contains(hcrwbEntity.getExecutionUnit().toString())) {
						hcrwbEntity.setExecutionUnit(hcrwb.getExecutionUnit());
						if(!hcrwbService.updateById(hcrwbEntity)){
							return R.fail("任务下发失败，请联系管理员！");
						}
						hcrwCnt[0]++;
					} else {
						return R.fail("核查任务不在您辖区内！");
					}
				} else {
					//已完成
					hcrwCnt[1]++;
				}
			}
		}
		List<HcrwbEntity> hcrwbEntityArrayList = new ArrayList<>();

		for (String shtyBm : shtyBmArr) {
			HcrwbEntity hcrwbEntity = new HcrwbEntity();
			hcrwbEntity.setSid(shtyBm);
			hcrwbEntity.setExecutionUnit(hcrwb.getExecutionUnit());
			hcrwbEntity.setInspectionBatch(hcrwb.getInspectionBatch());
			hcrwbEntity.setInspectionDeadline(hcrwb.getInspectionDeadline());
			hcrwbEntity.setInspectionDescription(hcrwb.getInspectionDescription());
			hcrwbEntity.setInspectionStatus("0");
			hcrwbEntityArrayList.add(hcrwbEntity);
		}
		Set<String> sidsInList1 = hcrwbEntityList.stream().map(HcrwbEntity::getSid).collect(Collectors.toSet());
		hcrwbEntityArrayList.removeIf(x -> sidsInList1.contains(x.getSid()));
		if (!hcrwbService.saveBatch(hcrwbEntityArrayList)) {
			return R.fail("任务下发失败，请联系管理员！");
		}

		return R.success("核查任务已下发，共计" + shtyBmArr.length
			+ "个，其中更新任务：" + hcrwCnt[0]
			+ "个，新增任务：" + hcrwbEntityArrayList.size()
			+ "个，有" + hcrwCnt[1] + "个核查已完成，无需下发。");
	}
}
