package com.jwipc.sys.logic.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.jwipc.exception.DaoException;
import com.jwipc.prop.SysProp;
import com.jwipc.supplier.clent.dto.SupplierDTO;
import com.jwipc.supplier.client.SupplierClient;
import com.jwipc.sys.constant.SupplierRoleType;
import com.jwipc.sys.constant.UserStatus;
import com.jwipc.sys.constant.UserType;
import com.jwipc.sys.entity.Role;
import com.jwipc.sys.entity.User;
import com.jwipc.sys.entity.UserRole;
import com.jwipc.sys.logic.SupplierChildUserInitLogic;
import com.jwipc.sys.service.IRoleService;
import com.jwipc.sys.service.IUserRoleService;
import com.jwipc.sys.service.IUserService;
import com.jwipc.util.PasswordUtilSHA256;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * <p> </p>
 *
 * @author BOGON
 * @version 1.0
 * @since JDK 1.8
 */
@Service
@RequiredArgsConstructor
public class SupplierChildUserInitLogicImpl implements SupplierChildUserInitLogic {
    private final IRoleService roleService;
    private final SupplierClient supplierClient;
    private final IUserService userService;
    private final SysProp sysProp;
    private final IUserRoleService userRoleService;


    @Override
    public void initSupplierChildUser() {
        final SupplierRoleType[] values = SupplierRoleType.values();
        //供应商账号名称和对应的角色权限，账号规则供应商编码 + 后缀
        final Map<String, Long> accountMap = new HashMap<>();
        for (SupplierRoleType value : values) {
            if(!value.getCode().equals("supplier_role")){
                final Role role = roleService.getOne(new LambdaQueryWrapper<Role>().eq(Role::getRolekey, value.getCode()));
                if (Objects.isNull(role)) {
                    throw new DaoException(StrUtil.format("您尚未配置供应{}!", value.getName()));
                }
                accountMap.put(value.getSuffix(), role.getId());
            }

        }

        final List<SupplierDTO> filteredList = supplierClient.getAllSupplier();

        List<SupplierDTO> supplierList = filteredList.stream()
                .filter(supplier -> !supplier.getSupplierCode().contains("SRM"))
                .collect(Collectors.toList());

        final List<UserRole> spRoleList = Lists.newArrayList();

        final LocalDateTime createTime = LocalDateTime.now();

        if (CollUtil.isNotEmpty(supplierList)) {
            for (SupplierDTO e : supplierList) {
                //查找供应商编码、供应商id、供应商主账号
                final String supplierCode = e.getSupplierCode();
                final String supplierName = e.getSupplierName();
                final Long supplierId = e.getId();
                final User userParent = userService.getOne(
                        new LambdaQueryWrapper<User>().eq(User::getAccountName, supplierCode));
                if (Objects.isNull(userParent)) {
                    continue;
                }
                final Long parentId = userParent.getId();

                for (String key : accountMap.keySet()) {
                    final String accountName = supplierCode + key;
                    final User spUserRepeat = new User();
                    spUserRepeat.setAccountName(accountName);
                    spUserRepeat.setDeleteStatus(0L);

                    //如果供应商用户已存在，那么不再新增，执行下一条
                    User spUser = userService.getOne(
                            new LambdaQueryWrapper<User>().eq(User::getAccountName, accountName));
                    if (spUser != null) {
                        continue;
                    }

                    final User spUserInsert = new User();
                    spUserInsert.setAccountName(accountName);
                    spUserInsert.setUserType(UserType.SUPPLIER.getType());
                    spUserInsert.setSupplierId(supplierId);
                    spUserInsert.setUsername(supplierName);
                    spUserInsert.setParentId(parentId);
                    spUserInsert.setStatus(UserStatus.ENABLE.getStatus());
                    spUserInsert.setCreateDate(createTime);
                    String md5Password = sysProp.getDefaultPassword();
                    setPassword(spUserInsert, md5Password);
                    //新增供应商用户
                    userService.save(spUserInsert);
                    //新增供应商角色
                    final UserRole spUserRole = new UserRole();
                    spUserRole.setUserId(spUserInsert.getId());
                    spUserRole.setRoleId(accountMap.get(key));
                    spRoleList.add(spUserRole);
                }
            }
            if (CollUtil.isNotEmpty(spRoleList)) {
                userRoleService.saveBatch(spRoleList, 300);
            }
        }
    }

    private void setPassword(User user, String md5Password) {
        final String randomSalt = RandomUtil.randomString(16).toUpperCase();
        final byte[] bytes = randomSalt.getBytes();
        //生成随机字节
        String password = PasswordUtilSHA256.password(bytes, md5Password);
        //将字节编码成字符串设为盐值
        user.setPassword(password);
        user.setCredentialsSalt(randomSalt);
    }
}