package com.qmth.distributed.print;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.*;
import com.qmth.teachcloud.common.enums.RoleTypeEnum;
import com.qmth.teachcloud.common.service.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
import org.junit.platform.commons.util.StringUtils;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 用户数据导入、课程导入、组织机构导入
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class BasicDataImportTest {
    @Autowired
    private BasicCourseService basicCourseService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysOrgService sysOrgService;
    @Autowired
    private BasicUserCourseService basicUserCourseService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysRolePrivilegeService sysRolePrivilegeService;

    // 学校Id
    private Long schoolId = 1l;

    // 用户数据文件
    String userFile = "D:\\20210508140918-1.xlsx";
    // 课程数据文件
    String courseFile = "D:\\20210508140918-2.xlsx";


    @Test
    public void importBasicCourse() throws Exception {
        List<BasicCourse> courses = readCourseFile();
        for (BasicCourse cours : courses) {
            QueryWrapper<BasicCourse> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(BasicCourse::getCode, cours.getCode());
            BasicCourse basicCourse = basicCourseService.getOne(queryWrapper);
            if (basicCourse != null) {
                if (basicCourse.getName().equals(cours.getName())) {
                    continue;
                } else {
                    throw new Exception(String.format("s%代码已存在，名称不一致，数据库：s%，文件中：s%", cours.getCode(), basicCourse.getName(), cours.getName()));
                }
            }

            cours.setId(SystemConstant.getDbUuid());
            cours.setSchoolId(schoolId);
            basicCourseService.save(cours);
        }
    }

    @Test
//    @Transactional
    public void importBasicUser() throws Exception {
        List<Map<String, String>> users = readUserFile();
        for (Map<String, String> userMap : users) {
            // sys_org
            String orgCode = userMap.get("orgCode");
            String orgName = userMap.get("orgName");
            QueryWrapper<SysOrg> orgQueryWrapper = new QueryWrapper<>();
            orgQueryWrapper.lambda().eq(SysOrg::getSchoolId, schoolId).eq(SysOrg::getCode, orgCode);
            SysOrg sysOrg = sysOrgService.getOne(orgQueryWrapper);
            if (sysOrg != null) {
                if (!sysOrg.getName().equals(orgName)) {
                    throw new Exception(String.format("s%代码已存在，名称不一致，数据库：s%，文件中：s%", orgCode, sysOrg.getName(), orgName));
                }
            } else {
                sysOrg = new SysOrg();
                sysOrg.setId(SystemConstant.getDbUuid());
                sysOrg.setSchoolId(schoolId);
                sysOrg.setCode(orgCode);
                sysOrg.setName(orgName);
                sysOrg.setParentId(100l);
                sysOrgService.save(sysOrg);
            }

            // sys_user
            String loginName = userMap.get("loginName");
            String realName = userMap.get("realName");
            String mobileNumber = userMap.get("mobileNumber");
            String password = userMap.get("password");
            QueryWrapper<SysUser> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.lambda().eq(SysUser::getSchoolId, schoolId).eq(SysUser::getLoginName, loginName);
            SysUser sysUser = sysUserService.getOne(userQueryWrapper);
            if (sysUser == null) {
                sysUser = new SysUser();
                sysUser.setId(SystemConstant.getDbUuid());
                sysUser.setSchoolId(schoolId);
                sysUser.setLoginName(loginName);
                sysUser.setRealName(realName);
                sysUser.setPassword(password);
                sysUser.setMobileNumber(mobileNumber);
                sysUser.setOrgId(sysOrg.getId());
                sysUserService.save(sysUser);
            }

            // sys_user_role
            String roleType = userMap.get("roleType");
            QueryWrapper<SysRole> roleQueryWrapper = new QueryWrapper<>();
            roleQueryWrapper.lambda().eq(SysRole::getType, roleType);
            SysRole sysRole = sysRoleService.getOne(roleQueryWrapper);
            if (sysRole == null) {
                throw new Exception("角色不存在");
            }
            QueryWrapper<SysRolePrivilege> rolePrivilegeQueryWrapper = new QueryWrapper<>();
            rolePrivilegeQueryWrapper.lambda().eq(SysRolePrivilege::getRoleId, sysRole.getId()).eq(SysRolePrivilege::getEnable, true);
            List<SysRolePrivilege> rolePrivileges = sysRolePrivilegeService.list(rolePrivilegeQueryWrapper);
            List<SysUserRole> userRoles = new ArrayList<>();
            for (SysRolePrivilege rolePrivilege : rolePrivileges) {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setId(SystemConstant.getDbUuid());
                sysUserRole.setUserId(sysUser.getId());
                sysUserRole.setRoleId(rolePrivilege.getRoleId());
                sysUserRole.setPrivilegeId(rolePrivilege.getPrivilegeId());
                sysUserRole.setEnable(true);
                userRoles.add(sysUserRole);
            }
            sysUserRoleService.saveBatch(userRoles);

            // sys_user_course
            String courseCodeses = userMap.get("courseCode");
            if (roleType.equals(RoleTypeEnum.QUESTION_TEACHER.name())) {
                if (StringUtils.isBlank(courseCodeses)) {
                    throw new Exception("命题老师课程不能为空");
                }

                List<BasicUserCourse> userCourses = new ArrayList<>();
                String[] courseCodes = courseCodeses.split(",");
                for (String courseCode : courseCodes) {
                    String[] coursees = courseCode.split("/");
                    QueryWrapper<BasicCourse> basicCourseQueryWrapper = new QueryWrapper<>();
                    basicCourseQueryWrapper.lambda().eq(BasicCourse::getSchoolId, schoolId).eq(BasicCourse::getCode, coursees[0]);
                    BasicCourse basicCourse = basicCourseService.getOne(basicCourseQueryWrapper);
                    if (basicCourse == null) {
                        throw new Exception("命题老师对应课程不存在");
                    }
                    BasicUserCourse basicUserCourse = new BasicUserCourse();
                    basicUserCourse.setId(SystemConstant.getDbUuid());
                    basicUserCourse.setUserId(sysUser.getId());
                    basicUserCourse.setCourseId(basicCourse.getId());
                    userCourses.add(basicUserCourse);
                }
                basicUserCourseService.saveBatch(userCourses);
            }
        }
    }

    /**
     * 读取课程数据文件
     *
     * @return
     * @throws Exception
     */
    private List<BasicCourse> readCourseFile() throws Exception {
        File file = new File(courseFile);
        if (!file.exists()) {
            throw new Exception("课程数据文件不存在");
        }
        FileInputStream fileInputStream = new FileInputStream(file);
        XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);
        XSSFSheet sheet = workbook.getSheetAt(0);

        List<BasicCourse> courseList = new ArrayList<>();
        for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
            BasicCourse basicCourse = new BasicCourse();
            Row row = sheet.getRow(i);
            // 用户名
            Cell cell0 = row.getCell(0);
            basicCourse.setCode(cell0 == null ? null : cell0.getStringCellValue());
            // 姓名
            Cell cell1 = row.getCell(1);
            basicCourse.setName(cell1 == null ? null : cell1.getStringCellValue());
            courseList.add(basicCourse);
        }
        return courseList;
    }

    /**
     * 读取用户数据文件
     *
     * @return
     * @throws Exception
     */
    private List<Map<String, String>> readUserFile() throws Exception {
        File file = new File(userFile);
        if (!file.exists()) {
            throw new Exception("用户数据文件不存在");
        }
        FileInputStream fileInputStream = new FileInputStream(file);
        XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);
        XSSFSheet sheet = workbook.getSheetAt(0);

        List<Map<String, String>> userList = new ArrayList<>();
        for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
            Map<String, String> map = new HashMap<>();
            Row row = sheet.getRow(i);
            // 用户名
            Cell cell0 = row.getCell(0);
            map.put("loginName", cell0 == null ? null : cell0.getStringCellValue());
            // 姓名
            Cell cell1 = row.getCell(1);
            map.put("realName", cell1 == null ? null : cell1.getStringCellValue());
            // 手机号
            Cell cell2 = row.getCell(2);
            map.put("mobileNumber", cell2 == null ? null : cell2.getStringCellValue());
            // 密码
            Cell cell4 = row.getCell(4);
            map.put("password", cell4 == null ? null : cell4.getStringCellValue());
            // 角色Code
            Cell cell5 = row.getCell(5);
            map.put("roleType", cell5 == null ? null : cell5.getStringCellValue());
            // 机构code
            Cell cell8 = row.getCell(8);
            map.put("orgCode", cell8 == null ? null : cell8.getStringCellValue());
            // 机构名称
            Cell cell9 = row.getCell(9);
            map.put("orgName", cell9 == null ? null : cell9.getStringCellValue());
            // 命题老师可操作课程代码
            Cell cell10 = row.getCell(10);
            map.put("courseCode", cell10 == null ? null : cell10.getStringCellValue());
            userList.add(map);
        }

        return userList;
    }

    @Test
    public void createCourse() {
        List<BasicCourse> courses = basicCourseService.list();
        for (BasicCourse cours : courses) {
            String a = "INSERT INTO `basic_course` VALUES (%s,1,'%s','%s',124882698949885952,1620464769921,NULL,1620464769921);";
            System.out.println(String.format(a, SystemConstant.getDbUuid(), cours.getCode(), cours.getName()));
        }
    }

}
