package cn.estsh.i3plus.core.apiservice.serviceimpl.busi;

import cn.estsh.i3plus.platform.common.tool.EncryptTool;
import cn.estsh.i3plus.pojo.platform.bean.*;
import cn.estsh.i3plus.pojo.platform.repository.*;
import com.alibaba.fastjson.JSON;
import io.swagger.models.auth.In;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 系统数据初始化
 */
public class TestExcelPermission extends TestBase {
//public class TestExcelPermission {

    public static final Logger LOGGER = LoggerFactory.getLogger(TestExcelPermission.class);

    // 文件路径
    public static final String PATH_NAME = "init/permission.xlsx";
    // 权限Sheet 名称
    public static final String SHEET_NAME_MENU = "menu";
    public static final String SHEET_NAME_ROLE = "role";
    public static final String SHEET_NAME_USER_INFO = "user-info";
    public static final String SHEET_NAME_USER = "user";

    @Autowired
    private SysUserRepository sysUserRdao;

    @Autowired
    private SysUserInfoRepository userInfoRDao;

    @Autowired
    private SysMenuRepository menuRdao;

    @Autowired
    private SysRoleRepository roleRDao;

    @Autowired
    private SysRefRoleMenuRepository refRoleMenuRDao;

    @Test
    public void testInit() throws Exception {
        XSSFWorkbook workbook = getWorkbook(PATH_NAME);
        if(workbook != null){
            XSSFSheet sheetMenu = workbook.getSheet(SHEET_NAME_MENU);
            XSSFSheet sheetRole = workbook.getSheet(SHEET_NAME_ROLE);
            XSSFSheet sheetUserInfo = workbook.getSheet(SHEET_NAME_USER_INFO);
            XSSFSheet sheetUser = workbook.getSheet(SHEET_NAME_USER);

            List<SysMenu> menus = getSysMenu(sheetMenu);
            List<SysRole> roles = getSysRole(sheetRole);
            List<SysUserInfo> userInfos = getSysUserInfo(sheetUserInfo);
            List<SysUser> users = getSysUser(sheetUser);

            List<SysRefRoleMenu> refRoleMenu = getRefRoleMenu(menus, roles);

            LOGGER.info("System Init SysMenu Size:{}",menus.size());
            LOGGER.info("System Init SysRole Size:{}",roles.size());
            LOGGER.info("System Init SysUserInfo Size:{}",userInfos.size());
            LOGGER.info("System Init SysUser Size:{}",users.size());
            LOGGER.info("System Init SysRefRoleMenu Size:{}",refRoleMenu.size());

            sysUserRdao.saveAll(users);
            userInfoRDao.saveAll(userInfos);
            menuRdao.saveAll(menus);
            roleRDao.saveAll(roles);
            refRoleMenuRDao.saveAll(refRoleMenu);
        }
    }

    public List<SysRefUserRole> getRefUserRole(List<SysUser> users,List<SysRole> roles){
        List<SysRefUserRole> result = new ArrayList<>();
        if(users != null && roles != null){
            SysRefUserRole ref = null;
            for (SysUser user : users) {
                for (SysRole role : roles) {
                    ref = new SysRefUserRole();
                    ref.setRoleId(role.getId());
                    ref.setRoleNameRdd(role.getName());
                    ref.setUserId(user.getId());
                    ref.setUserNameRdd(user.getUserName());
                    result.add(ref);
                }
            }
        }
        return result;
    }

    public List<SysRefRoleMenu> getRefRoleMenu(List<SysMenu> menus,List<SysRole> roles){
        List<SysRefRoleMenu> result = new ArrayList<>();
        if(menus != null && roles != null){
            SysRefRoleMenu ref = null;
            for (SysMenu menu : menus) {
                for (SysRole role : roles) {
                    ref = new SysRefRoleMenu();
                    ref.setRoleId(role.getId());
                    ref.setRoleNameRdd(role.getName());
                    ref.setMenuId(menu.getId());
                    ref.setMenuNameRdd(menu.getName());
                    ref.setMenuTypeRdd(menu.getMenuType());
                    result.add(ref);
                }
            }
        }
        return result;
    }

    public List<SysUser> getSysUser(XSSFSheet sheet){
        List<SysUser> result = new ArrayList<>();
        if(sheet != null){
            if(sheet.getLastRowNum() >= 1){
                SysUser obj = null;
                for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                    try {
                        Row row = sheet.getRow(i);//获取索引为i的行，以0开始
                        if(row.getCell(0).toString().trim().length() > 0){
                            obj = new SysUser();
                            String md5 = EncryptTool.hexMD5(row.getCell(2).toString());
                            obj.setId(Long.parseLong(row.getCell(0).getStringCellValue()));
                            obj.setUserLoginName(row.getCell(1).getStringCellValue());
                            obj.setUserLoginPassword(md5);
                            obj.setUserEmail(row.getCell(3).getStringCellValue());
                            obj.setUserPhone(row.getCell(4).getStringCellValue());
                            obj.setUserInfoId(Long.parseLong(row.getCell(5).getStringCellValue()));
                            obj.setUserName(row.getCell(6).getStringCellValue());
                            obj.setIsValid(1);
                            obj.setUserStatus(1);
                            obj.setUserType(1);
                            obj.setUserLoginNum(0);

                            result.add(obj);
                        }
                    }catch (Exception e){
                        LOGGER.error("Excel Sheet Name :{} Index:{} DataType Error", sheet.getSheetName(), i);
                    }
                }
            }
        }
        return result;
    }

    public List<SysUserInfo> getSysUserInfo(XSSFSheet sheet){
        List<SysUserInfo> result = new ArrayList<>();
        if(sheet != null){
            if(sheet.getLastRowNum() >= 1){
                SysUserInfo obj = null;
                for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                    try {
                        Row row = sheet.getRow(i);//获取索引为i的行，以0开始
                        if(row.getCell(0).toString().trim().length() > 0){
                            obj = new SysUserInfo();
                            obj.setId(Long.parseLong(row.getCell(0).getStringCellValue()));
                            obj.setName(row.getCell(1).getStringCellValue());
                            obj.setUserEmpNo(row.getCell(2).getStringCellValue());
                            obj.setUserLoginNum(0);
                            obj.setIsValid(1);
                            obj.setUserInfoStatus(1);

                            result.add(obj);
                        }
                    }catch (Exception e){
                        LOGGER.error("Excel Sheet Name :{} Index:{} DataType Error", sheet.getSheetName(), i);
                    }
                }
            }
        }
        return result;
    }

    public List<SysRole> getSysRole(XSSFSheet sheet){
        List<SysRole> result = new ArrayList<>();
        if(sheet != null){
            if(sheet.getLastRowNum() >= 1){
                SysRole role = null;
                for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                    try {
                        Row row = sheet.getRow(i);//获取索引为i的行，以0开始
                        if(row.getCell(0).toString().trim().length() > 0){
                            role = new SysRole();
                            role.setId(Long.parseLong(row.getCell(0).getStringCellValue()));
                            role.setName(row.getCell(1).getStringCellValue());
                            role.setRoleDescription(row.getCell(2).getStringCellValue());
                            role.setRoleStatus(1);
                            role.setIsValid(1);

                            result.add(role);
                        }
                    }catch (Exception e){
                        LOGGER.error("Excel Sheet Name :{} Index:{} DataType Error", sheet.getSheetName(), i);
                    }
                }
            }
        }
        return result;
    }

    public List<SysMenu> getSysMenu(XSSFSheet sheet){
        List<SysMenu> result = new ArrayList<>();
        if(sheet != null){
            if(sheet.getLastRowNum() >= 1){
                SysMenu menu = null;
                for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                    try {
                        Row row = sheet.getRow(i);//获取索引为i的行，以0开始
                        if(row.getCell(0).toString().trim().length() > 0){
                            menu = new SysMenu();
                            menu.setId(Long.parseLong(row.getCell(0).getStringCellValue()));
                            menu.setMenuType(Integer.parseInt(row.getCell(1).getStringCellValue()));
                            menu.setMenuCode(row.getCell(2).getStringCellValue());
                            menu.setName(row.getCell(3).getStringCellValue());
                            menu.setParentId(Long.parseLong(row.getCell(4).getStringCellValue()));
                            menu.setParentNameRdd(row.getCell(5).getStringCellValue());
                            menu.setMenuDescription(row.getCell(6).getStringCellValue());
                            menu.setMenuStatus(Integer.parseInt(row.getCell(7).getStringCellValue()));
                            menu.setCreateUser("System Init");
                            menu.setMenuUrl(row.getCell(9).getStringCellValue());
                            menu.setMenuCss(row.getCell(10).getStringCellValue());
                            menu.setMenuIcon(row.getCell(11).getStringCellValue());

                            result.add(menu);
                        }
                    }catch (Exception e){
                        LOGGER.error("Excel Sheet Name :{} Index:{} DataType Error", sheet.getSheetName(), i);
                    }
                }
            }
        }
        return result;
    }

    public XSSFWorkbook getWorkbook(String pathName){
        try {
            InputStream in = TestExcelPermission.class.getClassLoader().getResourceAsStream(pathName);
            XSSFWorkbook workbook = new XSSFWorkbook(in);
            return workbook;
        }catch (Exception e){
            LOGGER.error(" System Init Sys Data Excel Error file path {} error message :{}",pathName,e.getMessage());
            e.getMessage();
            return null;
        }
    }

}
