package com.qunzhixinxi.hnqz.admin.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qunzhixinxi.hnqz.admin.entity.WmProject;
import com.qunzhixinxi.hnqz.admin.entity.WmScorePackage;
import com.qunzhixinxi.hnqz.admin.entity.base.BaseEntity;
import com.qunzhixinxi.hnqz.admin.enums.PackageTypeEnum;
import com.qunzhixinxi.hnqz.admin.service.WmProjectService;
import com.qunzhixinxi.hnqz.admin.service.WmScorePackageService;
import com.qunzhixinxi.hnqz.common.core.util.R;
import com.qunzhixinxi.hnqz.common.security.service.HnqzUser;
import com.qunzhixinxi.hnqz.common.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * CRO关联的项目管理
 *
 * @author lixuesong
 * @date 2021年06月21日 13:20
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/wmProject")
@Api(value = "wmProject", tags = "CRO关联的项目管理")
public class WmProjectController {

	private final WmProjectService wmProjectService;

	private final WmScorePackageService wmScorePackageService;

	/**
	 * 查询项目列表
	 *
	 * @return 项目列表
	 */
	@GetMapping("/list")
	@ApiOperation(value = "查询项目列表", notes = "查询项目列表")
	public R list() {
		try {
			// 查询当前用户所属部门下的项目
			Wrapper<WmProject> queryWrapper = Wrappers.<WmProject>lambdaQuery()
					.eq(WmProject::getDeptId, SecurityUtils.getUser().getDeptId())
					.orderByDesc(WmProject::getCreateTime);
			List<WmProject> list = wmProjectService.list(queryWrapper);
			return R.ok(list);
		} catch (Exception e) {
			log.error("查询项目列表失败", e);
		}
		return R.failed("查询项目列表失败");
	}

	/**
	 * 分页查询项目
	 *
	 * @param page 分页对象
	 * @param projectName 项目名称
	 * @param delegate 委托方
	 * @return 项目分页列表
	 */
	@GetMapping("/page")
	@ApiOperation(value = "分页查询项目", notes = "分页查询项目")
	public R page(Page page, String projectName, String delegate) {
		try {
			Integer deptId = SecurityUtils.getUser().getDeptId();
			IPage<WmProject> pageResult = wmProjectService.listProjectPage(page, deptId, projectName, delegate);
			List<WmProject> records = pageResult.getRecords();

			if (CollectionUtil.isNotEmpty(records)) {
				records.forEach(project -> {
					// 判断项目编号projectNumber是不是只读
					if (project != null && StringUtils.isNotBlank(project.getProjectNumber())) {
						// 查询上传证据链的积分包，是否已经关联了这个项目编号
						Wrapper<WmScorePackage> query = Wrappers.<WmScorePackage>lambdaQuery()
								.eq(WmScorePackage::getSendPackageDeptId, SecurityUtils.getUser().getDeptId())
								.eq(WmScorePackage::getPackageType1, PackageTypeEnum.TYPE1_SETTLE_PACKAGE.val())
								.eq(WmScorePackage::getPackageType2, PackageTypeEnum.TYPE2_SETTLE_PACKAGE.val())
								.in(WmScorePackage::getTypeid, "3", "4")
								.eq(WmScorePackage::getProjectNum, project.getProjectNumber());
						int extCount = wmScorePackageService.count(query);
						if (extCount > 0) {
							project.setReadOnlyFlag(1);
						} else {
							project.setReadOnlyFlag(0);
						}
					}
				});
			}
			return R.ok(pageResult);
		} catch (Exception e) {
			log.error("分页查询项目失败", e);
		}
		return R.failed("分页查询项目失败");
	}

	/**
	 * 根据id查询
	 *
	 * @param projectId 主键id
	 * @return 项目对象
	 */
	@GetMapping("/{projectId}")
	@ApiOperation(value = "根据id查询", notes = "根据id查询")
	public R getById(@PathVariable("projectId") Integer projectId) {
		try {
			WmProject wmProject = wmProjectService.getProjectById(projectId);
			// 判断项目编号projectNumber是不是只读
			if (wmProject != null && StringUtils.isNotBlank(wmProject.getProjectNumber())) {
				// 查询上传证据链的积分包，是否已经关联了这个项目编号
				Wrapper<WmScorePackage> queryWrapper = Wrappers.<WmScorePackage>lambdaQuery()
						.eq(WmScorePackage::getSendPackageDeptId, SecurityUtils.getUser().getDeptId())
						.eq(WmScorePackage::getPackageType1, PackageTypeEnum.TYPE1_SETTLE_PACKAGE.val())
						.eq(WmScorePackage::getPackageType2, PackageTypeEnum.TYPE2_SETTLE_PACKAGE.val())
						.in(WmScorePackage::getTypeid, "3", "4")
						.eq(WmScorePackage::getProjectNum, wmProject.getProjectNumber());
				int extCount = wmScorePackageService.count(queryWrapper);
				if (extCount > 0) {
					wmProject.setReadOnlyFlag(1);
				} else {
					wmProject.setReadOnlyFlag(0);
				}
			}
			return R.ok(wmProject);
		} catch (Exception e) {
			log.error("根据id查询失败", e);
		}
		return R.failed("根据id查询失败");
	}

	/**
	 * 新增项目
	 *
	 * @param wmProject 项目对象
	 * @return 是否成功
	 */
	@PostMapping
	@ApiOperation(value = "新增项目", notes = "新增项目")
	public R save(@RequestBody @Validated({BaseEntity.Create.class}) WmProject wmProject, BindingResult bindingResult) {
		try {
			// 判断校验结果
			if (bindingResult.hasErrors()) {
				return R.failed(bindingResult.getFieldError().getDefaultMessage());
			}
			HnqzUser user = SecurityUtils.getUser();
			// 当前部门
			Integer deptId = user.getDeptId();
			// 判断项目编号、项目名称是否重复
			int projectNumberCount = wmProjectService.count(Wrappers.<WmProject>lambdaQuery()
					.eq(WmProject::getDeptId, deptId)
					.eq(WmProject::getProjectNumber, wmProject.getProjectNumber()));
			int projectNameCount = wmProjectService.count(Wrappers.<WmProject>lambdaQuery()
					.eq(WmProject::getDeptId, deptId)
					.eq(WmProject::getProjectName, wmProject.getProjectName()));
			if (projectNumberCount > 0) {
				return R.failed("项目编号已存在");
			}
			if (projectNameCount > 0) {
				return R.failed("项目名称已存在");
			}
			wmProjectService.saveProject(wmProject);
			return R.ok();
		} catch (Exception e) {
			log.error("新增项目失败", e);
		}
		return R.failed("新增项目失败");
	}

	/**
	 * 更新项目
	 *
	 * @param wmProject 项目对象
	 * @return 是否成功
	 */
	@PutMapping
	@ApiOperation(value = "更新项目", notes = "更新项目")
	public R updateById(@RequestBody @Validated({BaseEntity.Update.class}) WmProject wmProject, BindingResult bindingResult) {
		try {
			// 判断校验结果
			if (bindingResult.hasErrors()) {
				return R.failed(bindingResult.getFieldError().getDefaultMessage());
			}
			HnqzUser user = SecurityUtils.getUser();
			// 当前部门
			Integer deptId = user.getDeptId();
			// 判断项目编号、项目名称是否重复
			int projectNumberCount = wmProjectService.count(Wrappers.<WmProject>lambdaQuery()
					.eq(WmProject::getDeptId, deptId)
					.eq(WmProject::getProjectNumber, wmProject.getProjectNumber())
					.ne(WmProject::getId, wmProject.getId()));
			int projectNameCount = wmProjectService.count(Wrappers.<WmProject>lambdaQuery()
					.eq(WmProject::getDeptId, deptId)
					.eq(WmProject::getProjectName, wmProject.getProjectName())
					.ne(WmProject::getId, wmProject.getId()));
			if (projectNumberCount > 0) {
				return R.failed("项目编号已存在");
			}
			if (projectNameCount > 0) {
				return R.failed("项目名称已存在");
			}
			// 判断项目编号projectNumber是不是只读，如果只读则不可修改
			if (StringUtils.isNotBlank(wmProject.getProjectNumber())) {
				// 查询上传证据链的积分包，是否已经关联了这个项目编号
				Wrapper<WmScorePackage> queryWrapper = Wrappers.<WmScorePackage>lambdaQuery()
						.eq(WmScorePackage::getSendPackageDeptId, SecurityUtils.getUser().getDeptId())
						.eq(WmScorePackage::getPackageType1, PackageTypeEnum.TYPE1_SETTLE_PACKAGE.val())
						.eq(WmScorePackage::getPackageType2, PackageTypeEnum.TYPE2_SETTLE_PACKAGE.val())
						.in(WmScorePackage::getTypeid, "3", "4")
						.eq(WmScorePackage::getProjectNum, wmProject.getProjectNumber());
				int extProjectNumCount = wmScorePackageService.count(queryWrapper);
				if (extProjectNumCount > 0) {
					return R.failed("项目编号已关联积分包，不能修改");
				}
			}
			wmProjectService.updateProjectById(wmProject);
			return R.ok();
		} catch (Exception e) {
			log.error("更新项目失败", e);
		}
		return R.failed("更新项目失败");
	}

	/**
	 * 删除项目
	 *
	 * @param projectId
	 * @return 是否成功
	 */
	@DeleteMapping("/{projectId}")
	@ApiOperation(value = "删除项目", notes = "删除项目")
	public R deleteById(@PathVariable("projectId") Integer projectId) {
		try {
			if (projectId == null) {
				return R.failed("id不能为空");
			}
			// 判断项目编号projectNumber是不是只读
			WmProject project = wmProjectService.getById(projectId);
			if (project != null && StringUtils.isNotBlank(project.getProjectNumber())) {
				// 查询上传证据链的积分包，是否已经关联了这个项目编号
				Wrapper<WmScorePackage> query = Wrappers.<WmScorePackage>lambdaQuery()
						.eq(WmScorePackage::getSendPackageDeptId, SecurityUtils.getUser().getDeptId())
						.eq(WmScorePackage::getPackageType1, PackageTypeEnum.TYPE1_SETTLE_PACKAGE.val())
						.eq(WmScorePackage::getPackageType2, PackageTypeEnum.TYPE2_SETTLE_PACKAGE.val())
						.in(WmScorePackage::getTypeid, "3", "4")
						.eq(WmScorePackage::getProjectNum, project.getProjectNumber());
				int extCount = wmScorePackageService.count(query);
				if (extCount > 0) {
					return R.failed("项目编号已关联积分包，不能删除");
				}
			}
			wmProjectService.removeProjectById(projectId);
			return R.ok();
		} catch (Exception e) {
			log.error("删除项目失败", e);
		}
		return R.failed("删除项目失败");
	}
}
