package com.jeequan.jeepay.agent.ctrl.sysuser;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeequan.jeepay.agent.ctrl.CommonCtrl;
import com.jeequan.jeepay.core.aop.MethodLog;
import com.jeequan.jeepay.core.constants.ApiCodeEnum;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.jwt.JWTPayload;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.core.utils.DateKit;
import com.jeequan.jeepay.db.entity.SysUserEntity;
import com.jeequan.jeepay.db.entity.SysUserTeam;
import com.jeequan.jeepay.service.impl.SysUserService;
import com.jeequan.jeepay.service.impl.SysUserTeamService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

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

/**
* 操作员列表
*
* @author zx
*
* @date 2022/3/17 17:13
*/
@RestController
@RequestMapping("/api/userTeams")
public class SysUserTeamController extends CommonCtrl {

	@Autowired private SysUserTeamService sysUserTeamService;
	@Autowired private SysUserService sysUserService;

	/** list */
	@PreAuthorize("hasAuthority( 'ENT_UR_TEAM_LIST' )")
	@RequestMapping(value="", method = RequestMethod.GET)
	public ApiRes list() {

		// 是否app登录
		String loginType = getCurrentUser().getLoginType();
		boolean isApp = StringUtils.isNotBlank(loginType) && (loginType.equals(JWTPayload.LOGIN_PAGE_TYPE.APP) || loginType.equals(JWTPayload.LOGIN_PAGE_TYPE.LITE));

		SysUserTeam queryObject = getObject(SysUserTeam.class);
		queryObject.setSysType(CS.SYS_ROLE_TYPE.AGENT);
		queryObject.setBelongInfoId(getCurrentAgentNo());

		// 团队列表
		IPage<SysUserTeam> iPage = sysUserTeamService.selectPage(getIPage(true), queryObject);

		// 1、查询全部团队列表，直接返回
		int pageSize = getValIntegerRequired("pageSize");
		if (pageSize == -1) {
			return ApiRes.page(iPage);
		}

		// 2、web端，仅返回团队列表
		if (!isApp) {
			return ApiRes.page(iPage);
		}

		if (iPage.getTotal() <= 0) {
			return ApiRes.page(new Page());
		}

		// 3、app端，返回团队列表 包含团队成员信息
		// 当前分页团队ID集合
		List<Long> teamIdList = new LinkedList<>();
		iPage.getRecords().forEach(record -> teamIdList.add(record.getTeamId()));

		// 查询团队id下的用户
		List<JSONObject> list = sysUserTeamService.selectList(teamIdList, null, null);
		if (CollUtil.isEmpty(list)) {
			return ApiRes.page(iPage);
		}

		// 外层：循环团队     内层：团队成员数据
		for (SysUserTeam sysUserTeam : iPage.getRecords()) {

			// 用户列表
			List<JSONObject> userList = new LinkedList<>();

			// 团队总商户数
			Long totalMchCount = 0L;

			// 团队总交易额
			Long totalOrderAmount = 0L;

			for (JSONObject json : list) {
				if (sysUserTeam.getTeamId().equals(json.getLong("teamId"))) {

					userList.add(json);

					if (json.getLong("mchCount") != null) {
						totalMchCount += json.getLong("mchCount");
					}

					if (json.getLong("orderAmount") != null) {
						totalOrderAmount += json.getLong("orderAmount");
					}
				}
			}

			sysUserTeam.addExt("userList", userList);
			sysUserTeam.addExt("totalMchCount", totalMchCount);
			sysUserTeam.addExt("totalOrderAmount", totalOrderAmount);
		}

		return ApiRes.page(iPage);
	}

	/** web端  团队详情下的拓展员信息 */
	@PreAuthorize("hasAuthority( 'ENT_UR_USER_VIEW' )")
	@RequestMapping(value="/userList/{recordId}", method = RequestMethod.GET)
	public ApiRes userList(@PathVariable("recordId") Long recordId) {

		IPage<SysUserEntity> iPage = sysUserService.page(getIPage(), SysUserEntity.gw().eq(SysUserEntity::getTeamId, recordId));
		if (iPage.getTotal() <= 0) {
			return ApiRes.page(new Page());
		}

		// 查询团队id下的用户
		String dateRange = getValStringRequired("queryDateRange");
		// 获取查询时间请求参数  [开始时间,  结束时间]
		Date[] queryDateRangeArray = DateKit.getQueryDateRange(dateRange);

		String createdStart = DateUtil.formatDateTime(queryDateRangeArray[0]);
		String createdEnd = DateUtil.formatDateTime(queryDateRangeArray[1]);


		List<JSONObject> list = sysUserTeamService.selectList(Arrays.asList(recordId), createdStart, createdEnd);
		if (CollUtil.isEmpty(list)) {
			return ApiRes.page(iPage);
		}

		// 用户列表
		List<JSONObject> userList = new LinkedList<>();

		for (SysUserEntity sysUserEntity : iPage.getRecords()) {
			for (JSONObject json : list) {
				if (sysUserEntity.getSysUserId().equals(json.getLong("sysUserId"))) {
					userList.add(json);
				}
			}
		}

		return ApiRes.page(getIPage(), userList, iPage.getTotal());
	}


	/** detail */
	@PreAuthorize("hasAuthority( 'ENT_UR_USER_EDIT' )")
	@RequestMapping(value="/{recordId}", method = RequestMethod.GET)
	public ApiRes detail(@PathVariable("recordId") Integer recordId) {
		return ApiRes.ok(sysUserTeamService.getById(recordId));
	}

	/** add */
	@PreAuthorize("hasAuthority( 'ENT_UR_TEAM_ADD' )")
	@MethodLog(remark = "添加团队")
	@RequestMapping(value="", method = RequestMethod.POST)
	public ApiRes add() {
		SysUserTeam sysUserTeam = getObject(SysUserTeam.class);
		sysUserTeam.setSysType(CS.SYS_ROLE_TYPE.AGENT);
		sysUserTeam.setBelongInfoId(getCurrentAgentNo());

		long count = sysUserTeamService.count(SysUserTeam.gw().eq(SysUserTeam::getTeamName, sysUserTeam.getTeamName()));
		if (count > 0) {
			throw new BizException("团队名已存在");
		}

		boolean result = sysUserTeamService.save(sysUserTeam);
		if (!result) {
			return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_CREATE);
		}

		return ApiRes.ok();
	}


	/** update */
	@PreAuthorize("hasAuthority( 'ENT_UR_TEAM_EDIT' )")
	@RequestMapping(value="/{recordId}", method = RequestMethod.PUT)
	@MethodLog(remark = "修改团队信息")
	public ApiRes update(@PathVariable("recordId") Long recordId) {
		SysUserTeam sysUserTeam = getObject(SysUserTeam.class);
		sysUserTeam.setTeamId(recordId);

		long count = sysUserTeamService.count(SysUserTeam.gw()
				.eq(SysUserTeam::getTeamName, sysUserTeam.getTeamName())
				.ne(SysUserTeam::getTeamId, recordId)
		);
		if (count > 0) {
			throw new BizException("团队名已存在");
		}

		boolean result = sysUserTeamService.updateById(sysUserTeam);
		if (!result) {
			return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_UPDATE);
		}

		return ApiRes.ok();
	}

	/** delete */
	@PreAuthorize("hasAuthority( 'ENT_UR_TEAM_DELETE' )")
	@RequestMapping(value="/{recordId}", method = RequestMethod.DELETE)
	@MethodLog(remark = "删除团队")
	public ApiRes delete(@PathVariable("recordId") Long recordId) {

		// 删除团队
		boolean result = sysUserTeamService.removeById(recordId);
		if (!result) {
			return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_DELETE);
		}

		return ApiRes.ok();
	}

}
