/*
 *    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 cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
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.WmScorePackageStatusBatch;
import com.qunzhixinxi.hnqz.admin.entity.WmScorePackage;
import com.qunzhixinxi.hnqz.admin.entity.WmScorePackageStatus;
import com.qunzhixinxi.hnqz.admin.entity.WmTeam;
import com.qunzhixinxi.hnqz.admin.enums.DelEnum;
import com.qunzhixinxi.hnqz.admin.enums.EnableEnum;
import com.qunzhixinxi.hnqz.admin.enums.PackageTypeEnum;
import com.qunzhixinxi.hnqz.admin.service.WmScorePackageService;
import com.qunzhixinxi.hnqz.admin.service.WmScorePackageStatusService;
import com.qunzhixinxi.hnqz.admin.service.WmTaskService;
import com.qunzhixinxi.hnqz.admin.service.WmTeamService;
import com.qunzhixinxi.hnqz.common.core.util.R;
import com.qunzhixinxi.hnqz.common.log.annotation.SysLog;
import com.qunzhixinxi.hnqz.common.security.util.SecurityUtils;
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.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * 积分包状态
 *
 * @author pigx code generator
 * @date 2020-07-17 23:32:01
 */
@RestController
@AllArgsConstructor
@RequestMapping("/wmscorepackagestatus" )
@Api(value = "wmscorepackagestatus", tags = "积分包状态管理")
public class WmScorePackageStatusController {

    private final  WmScorePackageStatusService wmScorePackageStatusService;
	private final WmTaskService wmTaskService;
	private final WmScorePackageService wmScorePackageService;
	private final WmTeamService wmTeamService;

	/**
     * 分页查询
     * @param page 分页对象
     * @param wmScorePackageStatus 积分包状态
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page" )
    public R getWmScorePackageStatusPage(Page page, WmScorePackageStatus wmScorePackageStatus) {
		OrderItem orderItem=new OrderItem();
		orderItem.setColumn("create_time");
		orderItem.setAsc(false);
		page.addOrder(orderItem);
		Integer userId = SecurityUtils.getUser().getId();
		Integer deptId = SecurityUtils.getUser().getDeptId();
		wmScorePackageStatus.setUserId(String.valueOf(userId));
		// 判断当前用户是否配置了团队负责人
		List<WmTeam> teamList = wmTeamService.list(Wrappers.<WmTeam>lambdaQuery()
				.eq(WmTeam::getDeptId, deptId)
				.eq(WmTeam::getEnableFlag, EnableEnum.ENABLE.val())
				.eq(WmTeam::getDelFlag, DelEnum.NOT_DEL.val())
				.apply("FIND_IN_SET({0}, leader)", String.valueOf(userId)));
		if (CollectionUtil.isNotEmpty(teamList)) {
			// 如果配置了，则只查询所在团队下发的积分包
			List<String> teamIdList = teamList.stream().map(wmTeam -> String.valueOf(wmTeam.getId())).collect(Collectors.toList());
			wmScorePackageStatus.setTeamIdList(teamIdList);
		}
        return R.ok(wmScorePackageStatusService.getWmScorePackageStatusPage(page, wmScorePackageStatus));
    }


    /**
     * 通过id查询积分包状态
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}" )
    public R getById(@PathVariable("id" ) Integer id) {
        return R.ok(wmScorePackageStatusService.getById(id));
    }

    /**
     * 新增积分包状态
     * @param wmScorePackageStatus 积分包状态
     * @return R
     */
    @ApiOperation(value = "新增积分包状态", notes = "新增积分包状态")
    @SysLog("新增积分包状态" )
    @PostMapping
    public R save(@RequestBody WmScorePackageStatus wmScorePackageStatus) {
		wmScorePackageStatus.setCreateTime(LocalDateTime.now());
        return R.ok(wmScorePackageStatusService.save(wmScorePackageStatus));
    }

    /**
     * 修改积分包状态
     * @param wmScorePackageStatus 积分包状态
     * @return R
     */
    @ApiOperation(value = "修改积分包状态", notes = "修改积分包状态")
    @SysLog("修改积分包状态" )
    @PutMapping
    public R updateById(@RequestBody WmScorePackageStatus wmScorePackageStatus) {
			boolean answer=wmScorePackageStatusService.updateById(wmScorePackageStatus);
			if(answer)
			{
				WmScorePackage wmScorePackage=wmScorePackageService.getById(wmScorePackageStatus.getPackageId());
				if("2".equals(wmScorePackageStatus.getStatus())) {
					wmScorePackage.setZbId(wmScorePackageStatus.getUserId());
					wmScorePackage.setPackageStatus("2");
					wmScorePackage.setUpdateTime(LocalDateTime.now());
					wmScorePackage.setReceiveDate(LocalDateTime.now());
					wmScorePackage.setIsConduct("1");
				}else{
					wmScorePackage.setPackageStatus(null);
					wmScorePackage.setIsConduct(null);
				}
				wmScorePackageService.updateById(wmScorePackage);

			}
        return R.ok();
    }

    /**
     * 通过id删除积分包状态
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除积分包状态", notes = "通过id删除积分包状态")
    @SysLog("通过id删除积分包状态" )
    @DeleteMapping("/{id}" )
    public R removeById(@PathVariable Integer id) {
        return R.ok(wmScorePackageStatusService.removeById(id));
    }


	/**
	 * 接单审核--分页查询
	 * @param page 分页对象
	 * @param wmScorePackageStatus 积分包状态
	 * @return
	 */
	@ApiOperation(value = "分页查询", notes = "分页查询")
	@GetMapping("/getPage" )
	public R getPage(Page page, WmScorePackageStatus wmScorePackageStatus){
		if(StringUtil.isEmpty(wmScorePackageStatus.getPackageId())){
			return R.failed("未查询到积分包id");
		}
		return wmScorePackageStatusService.getPage(page, wmScorePackageStatus);
	}

	/**
	 * 接单审核--同意
	 * @param wmScorePackageStatus
	 * @return
	 */
	@PostMapping("/approvalStatus")
	public R approvalStatus(@RequestBody WmScorePackageStatus wmScorePackageStatus){
		if(wmScorePackageStatus.getId()==null){
			return R.failed("缺少参数ID");
		}
		if(StringUtil.isEmpty(wmScorePackageStatus.getStatus())){
			return R.failed("缺少参数:审批意见");
		}
		return wmScorePackageStatusService.approvalStatus( wmScorePackageStatus);
	}

	/**
	 * 批量接单审核
	 * @param statusBatch 批量审批信息
	 */
	@PutMapping("/approvalStatus/batch")
	public R approvalStatusBatch(@RequestBody WmScorePackageStatusBatch statusBatch){
		if(StrUtil.isEmpty(statusBatch.getBatchIds())){
			return R.failed("缺少参数ID");
		}
		if(statusBatch.getStatus() == null){
			return R.failed("缺少参数:审批意见");
		}
		return R.ok(wmScorePackageStatusService.approvalStatusBatch(statusBatch));
	}

	/**
	 * 获取批量审核的校验信息
	 * @param ids
	 * @return
	 */
	@GetMapping(value = "/approvalStatus/checkout")
	public R approvalStatusCheckout(@RequestParam(value = "ids") String ids){

		// 获取id
		List<String> idList = StrUtil.split(ids, StrUtil.COMMA);
		List<Integer> idListInt = idList.stream().mapToInt(Integer::valueOf).boxed().collect(Collectors.toList());

		// 获取待审核的记录
		List<WmScorePackageStatus> wmScorePackageStatuses = wmScorePackageStatusService.list(Wrappers.<WmScorePackageStatus>lambdaQuery()
				.in(WmScorePackageStatus::getId, idList));

		// 过滤出待审核的积分包id
		Set<String> packageIds = wmScorePackageStatuses.stream()
				.map(WmScorePackageStatus::getPackageId)
				.collect(Collectors.toSet());

		// 获取积分包信息,主要是为了获取接单对象
		List<WmScorePackage> packageList = wmScorePackageService.list(Wrappers.<WmScorePackage>lambdaQuery()
				.in(WmScorePackage::getId, packageIds));

		// 封装每个积分包对应的接单人数
		Map<String, Integer> userNumMap = packageList.stream()
				.collect(Collectors.toMap(WmScorePackage::getId, WmScorePackage::getUserNum));

		// 查询所有积分包的领包记录(过滤掉领包不通过的, 审核状态：1.审核中，2.审核通过，3.审核不通过), 只包含审核通过和待审核
		List<WmScorePackageStatus> packageStatuses = wmScorePackageStatusService.list(Wrappers.<WmScorePackageStatus>lambdaQuery()
				.in(WmScorePackageStatus::getPackageId, packageIds)).stream().filter(ps -> !StrUtil.equals("3", ps.getStatus())).collect(Collectors.toList());

		// 按照积分包id分组, 审核记录
		Map<String, List<WmScorePackageStatus>> map = packageStatuses.stream()
				.collect(Collectors.groupingBy(WmScorePackageStatus::getPackageId));

		int operation = 0;
		int remain = 0;
		for (Map.Entry<String,List<WmScorePackageStatus>>entry : map.entrySet()){

			String packageId = entry.getKey();
			Set<Integer> tempIds = entry.getValue().stream().mapToInt(WmScorePackageStatus::getId).boxed().collect(Collectors.toSet());
			Set<Integer> idSet = new HashSet<>(idListInt);
			tempIds.retainAll(idSet);
			Integer userNum = userNumMap.get(packageId) == null ? 1 : userNumMap.get(packageId);

			if (entry.getValue().size() <= userNum){

				operation += tempIds.size();

			} else {
				remain += tempIds.size();
			}
		}


		Map<String, Integer> result = new HashMap<>(2);
		result.put("operation", operation);
		result.put("remain",remain);

		return R.ok(result);

	}

	/**
	 * 终止接单--区分全部收回，和部分收回
	 *
	 * @param wmScorePackageStatus 终止接单
	 * enableType 1全部收回，2部分收回
	 * @return R
	 */
	@ApiOperation(value = "终止接单", notes = "终止接单")
	@SysLog("终止接单" )
	@GetMapping("updateZZ")
	public R updateZZ( WmScorePackageStatus wmScorePackageStatus) {
		if(StringUtil.isEmpty(wmScorePackageStatus.getId()+"")){
			return R.failed("缺少参数");
		}
		return wmScorePackageStatusService.updateZZ(wmScorePackageStatus);
	}

	/**
	 * 获取当前部门已接单人的列表
	 *
	 * @return 获取当前部门已接单人的列表
	 */
	@ApiOperation(value = "获取当前部门已接单人的列表", notes = "获取当前部门已接单人的列表")
	@GetMapping("/getDeptReceiveUserList")
	public R getDeptReceiveUserList() {
		Integer deptId = SecurityUtils.getUser().getDeptId();
		List<Map<String, String>> list = wmScorePackageStatusService.getDeptReceiveUserList(String.valueOf(deptId),
				PackageTypeEnum.TYPE1_HCP_PACKAGE.val(), PackageTypeEnum.TYPE2_SETTLE_PACKAGE.val());
		return R.ok(list);
	}
}
