package com.qunzhixinxi.hnqz.admin.controller;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qunzhixinxi.hnqz.admin.api.entity.SysUser;
import com.qunzhixinxi.hnqz.admin.entity.SysDeptSub;
import com.qunzhixinxi.hnqz.admin.entity.SysUserSub;
import com.qunzhixinxi.hnqz.admin.enums.GigChannelEnum;
import com.qunzhixinxi.hnqz.admin.enums.GigTypeEnum;
import com.qunzhixinxi.hnqz.admin.service.SysDeptService;
import com.qunzhixinxi.hnqz.admin.service.SysDeptSubService;
import com.qunzhixinxi.hnqz.admin.service.SysUserService;
import com.qunzhixinxi.hnqz.admin.service.SysUserSubService;
import com.qunzhixinxi.hnqz.common.core.util.R;
import com.qunzhixinxi.hnqz.common.security.annotation.Inner;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 初始化控制器
 *
 * @author jimmy
 * @date 2022/05/07 12:59
 */
@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping(value = "/init", produces = MediaType.APPLICATION_JSON_VALUE)
public class InitController {

	private final SysDeptService deptService;
	private final SysDeptSubService deptSubService;
	private final SysUserService userService;
	private final SysUserSubService userSubService;

	@Inner(value = false)
	@PostMapping(value = "/user-sub")
	@Transactional(rollbackFor = Exception.class)
	public R<Boolean> doUserSubInit() {

		// 获取企业的结算通道
		List<SysDeptSub> deptSubList = deptSubService.list(Wrappers.<SysDeptSub>lambdaQuery().eq(SysDeptSub::getEnableFlag, "1"));

		// 按照企业id分组
		Map<Integer, List<SysDeptSub>> deptSubMap = deptSubList.stream().collect(Collectors.groupingBy(SysDeptSub::getDeptId));

		// 获取所有可用的用户
		List<SysUser> userList = userService.list(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getDelFlag, "0").eq(SysUser::getLockFlag, "0"));

		// 按照企业分组
		Map<Integer, List<SysUser>> deptUserMap = userList.stream().collect(Collectors.groupingBy(SysUser::getDeptId));

		List<SysUserSub> initUserSubList = new ArrayList<>();

		// 封装初始化数据
		for (Map.Entry<Integer, List<SysDeptSub>> entry : deptSubMap.entrySet()) {
			// 获取部门id
			int deptId = entry.getKey();
			// 获取企业结算
			List<SysDeptSub> deptSubs = entry.getValue();
			// 无结算渠道自动跳过
			if (CollUtil.isEmpty(deptSubs)) {
				continue;
			}
			// 获取企业的员工
			List<SysUser> deptUsers = deptUserMap.get(deptId);

			// 无结算员工自动跳过
			if (CollUtil.isEmpty(deptUsers)) {
				continue;
			}

			// 封装初始化数据
			deptSubs.stream()
					// 过滤出税邦云和人力家结算渠道
					.filter(deptSub -> "0".equals(deptSub.getSubjectType()) || "1".equals(deptSub.getSubjectType()))
					.forEach(deptSub -> {

						int subjectType = Integer.parseInt(deptSub.getSubjectType());

						GigTypeEnum gigTypeEnum = GigTypeEnum.resolve(subjectType);

						Integer subjectChannel = deptSub.getSubjectChannel();

						if (subjectChannel != null && GigTypeEnum.TAX_HELPOR.equals(gigTypeEnum)) {
							// 税邦云原0-中金、1-平安，转换为新1-中金、2-平安
							subjectChannel = subjectChannel == 0 ? 1 : subjectChannel == 1 ? 2 : 0;
						} else {
							subjectChannel = 0;
						}
						GigChannelEnum gigChannelEnum = GigChannelEnum.resolve(subjectChannel);

						if (gigChannelEnum == null) {
							log.warn("结算通道不存在");
							return;
						}

						List<SysUserSub> userSubs = deptUsers.stream()
								// 过滤出没有状态的
								.filter(sysUser -> {
									if (GigTypeEnum.REN_LI_JIA.equals(gigTypeEnum)) {
										return sysUser.getRljCertStatus() != null;
									} else {
										return sysUser.getCertStatus() != null;
									}
								}).map(sysUser -> {
									SysUserSub userSub = new SysUserSub();
									userSub.setUserId(sysUser.getUserId());
									userSub.setDeptId(sysUser.getDeptId());
									userSub.setBankCardNumber(sysUser.getBankCardNumber());
									userSub.setCertStatus(GigTypeEnum.REN_LI_JIA.equals(gigTypeEnum) ? sysUser.getRljCertStatus() : sysUser.getCertStatus());
									userSub.setGigType(gigTypeEnum);
									userSub.setGigChannel(gigChannelEnum);
									userSub.setCertRemark("init from sys_user");
									return userSub;

								}).collect(Collectors.toList());

						initUserSubList.addAll(userSubs);

					});
		}

		// 消除
		List<SysUserSub> currSub = userSubService.list();
		Set<Integer> currIds = currSub.stream().mapToInt(SysUserSub::getUserId).boxed().collect(Collectors.toSet());
		List<SysUserSub> pureNew = initUserSubList.stream().filter(sysUserSub -> !currIds.contains(sysUserSub.getUserId())).collect(Collectors.toList());
		pureNew.sort(Comparator.comparing(SysUserSub::getUserId));


		// 初始化user_sub
		userSubService.saveBatch(pureNew);


		return R.ok(Boolean.TRUE);
	}


}
