/*
 *    Copyright (c) 2018-2025, hnqz 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 pig4cloud.com 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: hnqz
 */

package com.qunzhixinxi.hnqz.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qunzhixinxi.hnqz.admin.api.entity.SysDept;
import com.qunzhixinxi.hnqz.admin.entity.WmDaAgent;
import com.qunzhixinxi.hnqz.admin.entity.WmDaDrugEnt;
import com.qunzhixinxi.hnqz.admin.entity.WmTaskTypeEntRef;
import com.qunzhixinxi.hnqz.admin.entity.output.WmTaskTypeDeptOutput;
import com.qunzhixinxi.hnqz.admin.service.*;
import com.qunzhixinxi.hnqz.common.core.util.R;
import com.qunzhixinxi.hnqz.common.log.annotation.SysLog;
import com.qunzhixinxi.hnqz.admin.entity.WmTaskType;
import com.qunzhixinxi.hnqz.common.security.util.SecurityUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;


/**
 * 任务类型打分表
 *
 * @author gaoyang
 * @date 2020-07-01 20:20:05
 */
@RestController
@AllArgsConstructor
@RequestMapping("/wmtasktype")
@Api(value = "wmtasktype", tags = "任务类型打分表管理")
public class WmTaskTypeController {

	private final WmTaskTypeService wmTaskTypeService;
	private final SysDeptService sysDeptService;
	private final WmDaDrugEntService wmDaDrugEntService;
	private final WmDaAgentService wmDaAgentService;
	private final WmTaskTypeEntRefService wmTaskTypeEntRefService;


	/**
	 * 分页查询
	 *
	 * @return
	 */
	@ApiOperation(value = "分页查询", notes = "分页查询")
	@GetMapping("/getTaskTypeDeptList")
	public R getTaskTypeDeptList() {

		Integer deptId = SecurityUtils.getUser().getDeptId();
		WmTaskType query = new WmTaskType();
		query.setDeptId(deptId + "");
		List<WmTaskTypeDeptOutput> deptOutputList = wmTaskTypeService.getTaskTypeDeptList(query);

		if(CollectionUtils.isEmpty(deptOutputList)){
			return R.ok();
		}

		List<Map<String,String>>  resultList = new ArrayList<>();
		List<Map<String,String>>  resultList2 = new ArrayList<>();

		for (WmTaskTypeDeptOutput output : deptOutputList) {
			if(StringUtils.isNotEmpty(output.getDurgentId())){
				WmDaDrugEnt drugEnt = wmDaDrugEntService.getById(output.getDurgentId());
				if(null !=drugEnt){
					Map<String,String> map = new HashMap<>();
					map.put("value",output.getRuleId());
					map.put("label",drugEnt.getEntname());
					if(drugEnt.getDeptId().equals(deptId + "")){
						resultList2.add(map);
					}else {
						resultList.add(map);
					}

				}
				continue;
			}
			if(StringUtils.isNotEmpty(output.getLevel1Id())){
				WmDaAgent daAgent = wmDaAgentService.getById(output.getLevel1Id());
				if(null !=daAgent){
					Map<String,String> map = new HashMap<>();
					map.put("value",output.getRuleId());
					map.put("label",daAgent.getGsmc());
					if(daAgent.getDeptId().equals(deptId + "")){
						resultList2.add(map);
					}else {
						resultList.add(map);
					}
				}
			}
		}
		resultList2.addAll(resultList);

		return R.ok(resultList2);
	}


	/**
	 * 分页查询
	 *
	 * @param page       分页对象
	 * @param wmTaskType 任务类型打分表
	 * @return
	 */
	@ApiOperation(value = "分页查询", notes = "分页查询")
	@GetMapping("/page")
	public R getWmTaskTypePage(Page page, WmTaskType wmTaskType) {
		LambdaQueryWrapper<WmTaskType> queryWrapper ;
		if (wmTaskType.getRuleId() != null){
			List<String> noDisplayTaskTypeNameList = Arrays.asList("专家咨询", "受试者管理", "医学撰写", "受试者招募", "数据管理",
					"统计分析", "临床监察", "通用", "患者教育");
			queryWrapper = Wrappers.<WmTaskType>lambdaQuery()
					.eq(WmTaskType::getRuleId, wmTaskType.getRuleId())
					.notIn(WmTaskType::getTaskTypeName, noDisplayTaskTypeNameList);
		} else {
			queryWrapper = Wrappers.lambdaQuery(wmTaskType);
		}

		return R.ok(wmTaskTypeService.page(page, queryWrapper));
	}

	/**
	 * 分页查询
	 *
	 * @param page       分页对象
	 * @param wmTaskType 任务类型打分表
	 * @return
	 */
	@ApiOperation(value = "分页查询", notes = "分页查询")
	@GetMapping("/pages")
	public R getWmTaskTypePages(Page page, WmTaskType wmTaskType) {

		List<WmTaskTypeEntRef> wmTaskTypeEntRefList = wmTaskTypeEntRefService.selectByAgentId(wmTaskType.getLevel1Id());
		if (wmTaskTypeEntRefList.size() > 0) {
			for (WmTaskTypeEntRef wmTaskTypeEntRef1 : wmTaskTypeEntRefList) {
				//cso新增   药企id空   AgentId 有
					if (null!=wmTaskTypeEntRef1.getAgentId()&&null!=wmTaskTypeEntRef1.getDrugentId()&&!"".equals(wmTaskTypeEntRef1.getAgentId())
							&& !"".equals(wmTaskTypeEntRef1.getDrugentId())
					) {
					wmTaskType.setLevel1Id(wmTaskTypeEntRef1.getAgentId());
					List<WmTaskType> wmTaskTypeList = wmTaskTypeService.selectByRuleId(wmTaskType);
					for (WmTaskType wmTaskType1 : wmTaskTypeList) {

						if (wmTaskType1.getDurgentId()==null && "".equals(wmTaskType1.getDurgentId()) &&
								null!=wmTaskType1.getLevel1Id() && "".equals(wmTaskType1.getLevel1Id())) {
							wmTaskType.setRuleId(wmTaskType1.getRuleId());
						}
					}
					//药企新增  两个都是药企id
				} else if (wmTaskTypeEntRef1.getAgentId().equals(wmTaskTypeEntRef1.getDrugentId())) {
					wmTaskType.setRuleId(wmTaskTypeEntRef1.getAgentId());
					//药企给cso新增   两个都有值  药企和cso
					} else if (null!=wmTaskTypeEntRef1.getAgentId()&&null!=wmTaskTypeEntRef1.getDrugentId()
							&&!"".equals(wmTaskTypeEntRef1.getAgentId())&&!"".equals(wmTaskTypeEntRef1.getDrugentId())
					) {
					wmTaskType.setRuleId(wmTaskTypeEntRef1.getDrugentId() + wmTaskTypeEntRef1.getAgentId());
					List<WmTaskType> wmTaskTypeList = wmTaskTypeService.selectByRuleId(wmTaskType);
					for (WmTaskType wmTaskType1 : wmTaskTypeList) {
						if (null!=wmTaskType1.getDurgentId()&&null!=wmTaskType1.getLevel1Id()
								&&!"".equals(wmTaskType1.getDurgentId())&&!"".equals(wmTaskType1.getLevel1Id())) {
							wmTaskType.setRuleId(wmTaskType1.getRuleId());

						}
					}
				}
			}
		}

		LambdaQueryWrapper<WmTaskType> queryWrapper = Wrappers.lambdaQuery(wmTaskType);
		List<String> noDisplayTaskTypeNameList = Arrays.asList("专家咨询", "受试者管理", "医学撰写", "受试者招募", "数据管理",
				"统计分析", "临床监察", "通用", "患者教育");
		queryWrapper.notIn(WmTaskType::getTaskTypeName,noDisplayTaskTypeNameList);

		return R.ok(wmTaskTypeService.page(page, queryWrapper));
	}


	/**
	 * 通过id查询任务类型打分表
	 *
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "通过id查询", notes = "通过id查询")
	@GetMapping("/{id}")
	public R getById(@PathVariable("id") Integer id) {
		return R.ok(wmTaskTypeService.getById(id));
	}

	/**
	 * 新增任务类型打分表
	 *
	 * @param wmTaskType 任务类型打分表
	 * @return R
	 */
	@ApiOperation(value = "新增任务类型打分表", notes = "新增任务类型打分表")
	@SysLog("新增任务类型打分表")
	@PostMapping
	public R save(@RequestBody WmTaskType wmTaskType) {
		wmTaskType.setCreateTime(LocalDateTime.now());
		if (SecurityUtils.getRoles().contains(2)) {
			wmTaskType.setStatus("0");
		} else {
			wmTaskType.setStatus("1");
		}
		return R.ok(wmTaskTypeService.save(wmTaskType));
	}

	/**
	 * 修改任务类型打分表
	 *
	 * @param wmTaskType 任务类型打分表
	 * @return R
	 */
	@ApiOperation(value = "修改任务类型打分表", notes = "修改任务类型打分表")
	@SysLog("修改任务类型打分表")
	@PutMapping
	public R updateById(@RequestBody WmTaskType wmTaskType) {
		String baseId = wmTaskType.getId();
		if (SecurityUtils.getRoles().contains(2)) {
			if (null != wmTaskType.getId() && "1".equals(wmTaskType.getStatus())) {
				wmTaskTypeService.updateById(wmTaskType);
			} else {
				WmTaskType wmTaskRule1 = wmTaskType;
				wmTaskRule1.setId(null);
				wmTaskRule1.setStatus("1");
				wmTaskRule1.setBaseId(baseId);
				wmTaskTypeService.save(wmTaskRule1);
			}

		} else {
			wmTaskTypeService.updateById(wmTaskType);
		}
		return R.ok();
	}

	/**
	 * 通过id删除任务类型打分表
	 *
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "通过id删除任务类型打分表", notes = "通过id删除任务类型打分表")
	@SysLog("通过id删除任务类型打分表")
	@DeleteMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('admin_wmtasktype_del')")
	public R removeById(@PathVariable Integer id) {
		return R.ok(wmTaskTypeService.removeById(id));
	}

	/**
	 * 获取药企列表
	 *
	 * @return 角色列表
	 */
	@GetMapping("/list")
	public R listWmScorePackage() {
		WmTaskType wmDaDrugEnt = new WmTaskType();
		wmDaDrugEnt.setDelFlag("0");
		wmDaDrugEnt.setEnableFlag("0");
		wmDaDrugEnt.setTaskTypeLevel("1");
		return R.ok(wmTaskTypeService.list(Wrappers.query(wmDaDrugEnt)));
	}

	/**
	 * 获取药企列表
	 *
	 * @return 角色列表
	 */
	@GetMapping("/getTaskTree")
	public R getTaskTree(String description) {
		return R.ok(wmTaskTypeService.getTaskTree(description));
	}

	/**
	 * 有效任务类型树
	 * @return 角色列表
	 */
	@GetMapping("/getTaskTypeTree")
	public R getTaskTypeTree(String description) {

		return wmTaskTypeService.getTaskTypeTree(description);
	}
}
