package com.sysu.admin.support.system.organ;

import com.querydsl.core.types.Predicate;
import com.sysu.admin.support.base.BaseService;
import com.sysu.admin.utils.ChineseCharacterUtil;
import com.xiesx.fastboot.core.jpa.JpaPlusRepository;
import com.sysu.admin.support.system.role.SRole;
import com.sysu.admin.support.system.user.User;
import com.sysu.admin.support.system.user_role.PKUR;
import com.sysu.admin.support.system.user_role.UserRole;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author shu hao
 * @description:
 * @date 2022/5/16 17:40
 */
@Service
public class OrganService extends BaseService<Organ, Long> {

    @Autowired
    public OrganRepository mOrganRepository;

    @Override
    public JpaPlusRepository<Organ, Long> r() {
        return mOrganRepository;
    }

    public List<Long> findIdByParentId(Long parentId){
        return mOrganRepository.findIdByParentId(parentId);
    }

    public void batchTestUser(Integer isBureau){
        Predicate predicate = QOrgan.organ.isBureau.eq(isBureau);
        List<Organ> list = mOrganRepository.findAll(predicate);
        list.stream().forEach(organ -> {
            User user = new User();

            String usernameHz = isBureau == 1
                    ? organ.getCityName().substring(0,2)
                    : organ.getCityName().substring(0,2) + organ.getCompany().substring(0,2);

            String username = ChineseCharacterUtil.convertHanzi2Pinyin(usernameHz,false)
                    + "_001";

            if(serviceContext.mUserService.findByUsername(username) != null){
                return;
            }

            user.setOrganId(organ.getId());
            user.setUsername(username);
            user.setCode(username);
            String pwd = DigestUtils.md5Hex(username + username);
            user.setPassword(pwd);
            user.setNickname(username);
            serviceContext.mUserService.saveAndFlush(user);

            UserRole userRole = new UserRole().setPk(new PKUR().users(user.getId())
                    .roles(organ.getIsBureau() == 1 ?
                            (long)SRole.RoleEnum.xjzf.ordinal() :
                            (long)SRole.RoleEnum.zjxc.ordinal()));
            mUserRoleRepository.save(userRole);
        });
    }
}
