package com.testor.module.ZLOA.sysUserOA.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.testor.biz.auth.service.AuthService;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.biz.sys.post.model.domain.TSysPost;
import com.testor.biz.sys.post.service.TSysPostService;
import com.testor.biz.sys.role.model.domain.SysRole;
import com.testor.biz.sys.role.service.SysRoleService;
import com.testor.biz.sys.user.UserHelper;
import com.testor.biz.sys.user.model.domain.SysUser;
import com.testor.biz.sys.user.service.SysUserService;
import com.testor.biz.sys.userRole.model.domain.SysUserRole;
import com.testor.biz.sys.userRole.service.SysUserRoleService;
import com.testor.module.ZLOA.sysUserOA.dao.TSysUserOaDao;
import com.testor.module.ZLOA.sysUserOA.model.domain.TSysUserOa;
import com.testor.module.ZLOA.sysUserOA.service.TSysUserOaService;
import com.testor.module.video.model.domain.TSysUserImport;
import com.testor.module.video.model.domain.TSysUserImports;
import com.testor.module.video.model.domain.TSysUserImpotParam;
import com.testor.module.video.model.domain.TVideoEquipmentInfo;
import com.testor.module.video.service.TVideoEquipmentInfoService;
import com.testor.module.video.util.Beans;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.models.sys.UserInfo;
import com.tongtech.tfw.backend.core.helper.IdHelper;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.*;
import org.springframework.stereotype.Service;
import com.tongtech.tfw.backend.common.models.supers.SuperServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 用户 (OA)Service业务层处理
 * 
 * @author testor-framework
 * @date 2022-09-29 15:49:08
 */
@Service
public class TSysUserOaServiceImpl extends SuperServiceImpl<TSysUserOaDao, TSysUserOa> implements TSysUserOaService
{
    @Autowired(required = false)
    private TSysUserOaDao tSysUserOaDao;

    @Autowired
    private AuthService authService;

    @Autowired
    private TSysPostService tSysPostService;

    @Autowired
    private TVideoEquipmentInfoService infoService;

    @Autowired
    private SysOrgService sysOrgService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysUserRoleService userRoleService;

    @Override
    @Transactional
    public void imports(HttpServletRequest request, HttpServletResponse response, MultipartFile file) throws Exception{

        UserInfo loginUser = ContextUtils.getLoginUser();
        SysOrg sysOrg = sysOrgService.getById(loginUser.getOrgId());
        Workbook workbook = null;
        InputStream inputStream = null;
        inputStream = file.getInputStream();
        //todo 未导入
        List<TSysUserImpotParam> nolist=new ArrayList<>();
        List<TSysUserImport> tSysUserImports = processExcel(inputStream);
        List<SysUserRole> sysUserRoles=new ArrayList<>();
        List<SysUser> sysUsers=new ArrayList<>();
        for (TSysUserImport tSysUserImport : tSysUserImports) {
            System.out.println(tSysUserImport.getOrgName());
            SysOrg orgName = sysOrgService.getOne(new QueryWrapper<SysOrg>().eq("is_dept","0").eq("org_name", tSysUserImport.getOrgName()).ne("status","1"));
            int loginName = sysUserService.count(new QueryWrapper<SysUser>().eq("login_name", tSysUserImport.getAccount()).ne("status","1"));
            if (loginName>0) {
                TSysUserImpotParam tSysUserImpotParam = Beans.objectToBean(tSysUserImport, TSysUserImpotParam.class);
                tSysUserImpotParam.setType("已存在相同账号");
                nolist.add(tSysUserImpotParam);
                continue;
            }
            if (orgName==null) {
                TSysUserImpotParam tSysUserImpotParam = Beans.objectToBean(tSysUserImport, TSysUserImpotParam.class);
                tSysUserImpotParam.setType("机构名称不存在");
                nolist.add(tSysUserImpotParam);
                continue;
            }

            SysUser sysUser = new SysUser();
            String id32bit = IdHelper.getId32bit();
            sysUser.setUserId(id32bit);
            sysUser.setOrgId(orgName.getOrgId());
            sysUser.setLoginName(tSysUserImport.getAccount());
            sysUser.setLoginPwd(UserHelper.userPassword("123456"));
            sysUser.setUserName(tSysUserImport.getUserName());
            sysUser.setPwdSecurityLevel("2");
            sysUser.setSex("0");
            sysUser.setAge(18);
            sysUser.setOrgName(orgName.getOrgName());
            sysUser.setStatus("0");
            //查询部门
            List<SysOrg> list = this.sysOrgService.list((Wrapper)((QueryWrapper)((QueryWrapper)(new QueryWrapper())
                    .eq("parent_id", orgName.getOrgId())).eq("is_dept", "1")).ne("status", "1"));
            for (SysOrg org : list) {
                if ("安全环保部".equals(org.getOrgName())) {
                    sysUser.setDeptId(org.getOrgId());
                }
            }

            SysRole one = roleService.getOne(new QueryWrapper<SysRole>()
                    .like("role_name", tSysUserImport.getRoleName()).ne("status", "1"));

            SysUserRole sysUserRole=new SysUserRole();
            sysUserRole.setUserId(id32bit);
            sysUserRole.setRoleId(one.getRoleId());
            sysUserRoles.add(sysUserRole);
            sysUsers.add(sysUser);
        }

        //存账号信息
        boolean b = sysUserService.saveBatch(sysUsers);
        if (b) {
            //存角色信息
            userRoleService.saveBatch(sysUserRoles);
        }
        response.setContentType("application/vnd.ms-excel");
        // 对响应进行重新编码
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("测试", "utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        response.addHeader("Pargam", "no-cache");
        response.addHeader("Cache-Control", "no-cache");
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).head(TSysUserImpotParam.class).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        // 直接写入数据
        excelWriter.write(nolist, writeSheet);
        // 写入list之前的数据
        excelWriter.finish();
    }

    @Override
    @Transactional
    public void sysVideoImport(HttpServletRequest request, HttpServletResponse response, MultipartFile file) {
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();

        //todo 未导入
        List<TSysUserImport> tSysUserImports = processExcel(inputStream);
            List<TVideoEquipmentInfo>list=new ArrayList<>();
            for (TSysUserImport bean : tSysUserImports) {
                TVideoEquipmentInfo t=new TVideoEquipmentInfo();
                String id32bit = IdHelper.getId32bit();
                t.setId(id32bit);
                t.setOrgId(bean.getAccount());
                t.setOrgName(bean.getUserName());
                t.setEquipmentName(bean.getRoleName());
                t.setDeviceId(bean.getOrgName());
                t.setIsEye(0);
                t.setStatus("0");
                list.add(t);
            }
            infoService.saveBatch(list);
            System.out.println(list);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    @Transactional
    public List<TSysUserImpotParam> sysUserImports(HttpServletRequest request, HttpServletResponse response, MultipartFile file) throws Exception{
        UserInfo loginUser = ContextUtils.getLoginUser();
        InputStream inputStream = null;
        inputStream = file.getInputStream();
        //todo 未导入
        List<TSysUserImpotParam> nolist=new ArrayList<>();
        List<TSysUserImports> tSysUserImports = processExcels(inputStream);
        List<SysUserRole> sysUserRoles=new ArrayList<>();
        List<SysUser> sysUsers=new ArrayList<>();
        for (TSysUserImports tSysUserImport : tSysUserImports) {
            System.out.println(tSysUserImport.getOrgName());
            SysOrg orgName =new SysOrg();
            //ToDo 查询机构
            if (!"北良公司".equals(tSysUserImport.getOrgName())) {
                SysOrg beiliang = sysOrgService.getOne(new QueryWrapper<SysOrg>().eq("is_dept","0")
                        .eq("org_name", "北良公司").ne("status","1"));
                orgName = sysOrgService.getOne(new QueryWrapper<SysOrg>().eq("is_dept","0")
                        .eq("org_name", tSysUserImport.getOrgName()).ne("status","1")
                        .and(qr->
                                qr.eq("parent_id",beiliang.getOrgId())
                                        .or()
                                        .like("parent_ids",beiliang.getOrgId())));
            }else {
                orgName = sysOrgService.getOne(new QueryWrapper<SysOrg>().eq("is_dept","0")
                        .eq("org_name", tSysUserImport.getOrgName()).ne("status","1"));
            }


            int loginName = sysUserService.count(new QueryWrapper<SysUser>().eq("login_name", tSysUserImport.getAccount()).ne("status","1"));
            if (loginName>0) {
                TSysUserImpotParam tSysUserImpotParam = Beans.objectToBean(tSysUserImport, TSysUserImpotParam.class);
                tSysUserImpotParam.setType("已存在相同账号");
                nolist.add(tSysUserImpotParam);
                continue;
            }
            if (orgName==null) {
                TSysUserImpotParam tSysUserImpotParam = Beans.objectToBean(tSysUserImport, TSysUserImpotParam.class);
                tSysUserImpotParam.setType("机构名称不存在");
                nolist.add(tSysUserImpotParam);
                continue;
            }
            //ToDo  查询部门
            SysOrg department =sysOrgService.getOne(new QueryWrapper<SysOrg>().eq("is_dept","1").eq("parent_id",orgName.getOrgId())
                    .eq("org_name", tSysUserImport.getDepartment()).ne("status","1"));
            TSysPost one1 =new TSysPost();
            if (department==null) {
                String id32bi = IdHelper.getId32bit();
                SysOrg sysOrg=new SysOrg();
                sysOrg.setOrgId(id32bi);
                sysOrg.setParentId(orgName.getOrgId());
                sysOrg.setParentIds(orgName.getParentIds()+orgName.getOrgId());
                sysOrg.setOrgName(tSysUserImport.getDepartment());
                sysOrg.setIsDept("1");
                sysOrg.setStatus("0");
                boolean b = sysOrgService.save(sysOrg);
                if (b) {
                    TSysPost tSysPost=new TSysPost();
                    String id32bis = IdHelper.getId32bit();
                    tSysPost.setId(id32bis);
                    tSysPost.setDeptId(sysOrg.getOrgId());
                    tSysPost.setOrgId(sysOrg.getParentId());
                    tSysPost.setPostName(tSysUserImport.getPost());
                    tSysPost.setStatus("0");
                    tSysPostService.save(tSysPost);
                    department=sysOrg;
                }
            }else {
                //todo 查询岗位
                 one1 = tSysPostService.getOne(new QueryWrapper<TSysPost>().eq("post_name", tSysUserImport.getPost())
                        .eq("org_id",orgName.getOrgId())
                        .eq("dept_id", department.getOrgId()).ne("status", "1"));
                if (one1==null) {
                    TSysPost tSysPost=new TSysPost();
                    String idss = IdHelper.getId32bit();
                    tSysPost.setId(idss);
                    tSysPost.setDeptId(department.getOrgId());
                    tSysPost.setOrgId(department.getParentId());
                    tSysPost.setPostName(tSysUserImport.getPost());
                    tSysPost.setStatus("0");
                    tSysPostService.save(tSysPost);
                    one1=tSysPost;
                }
            }



            SysUser sysUser = new SysUser();
            String id32bit = IdHelper.getId32bit();
            sysUser.setUserId(id32bit);
            sysUser.setOrgId(orgName.getOrgId());
            sysUser.setLoginName(tSysUserImport.getAccount());
            sysUser.setLoginPwd(UserHelper.userPassword("123456"));
            sysUser.setUserName(tSysUserImport.getUserName());
            sysUser.setPwdSecurityLevel("2");
            sysUser.setSex("0");
            sysUser.setAge(18);
            sysUser.setOrgName(orgName.getOrgName());
            sysUser.setStatus("0");
            sysUser.setDeptId(department.getOrgId());
            sysUser.setPostId(one1.getId());
            sysUser.setPostName(one1.getPostName());
            sysUser.setPhoneNo(tSysUserImport.getPhone());

            SysRole one = roleService.getOne(new QueryWrapper<SysRole>()
                    .like("role_name", tSysUserImport.getRoleName()).ne("status", "1"));

            SysUserRole sysUserRole=new SysUserRole();
            sysUserRole.setUserId(id32bit);
            sysUserRole.setRoleId(one.getRoleId());
            sysUserRoles.add(sysUserRole);
            sysUsers.add(sysUser);
        }

        //存账号信息
        boolean b = sysUserService.saveBatch(sysUsers);
        if (b) {
            //存角色信息
            userRoleService.saveBatch(sysUserRoles);
        }
//        response.setContentType("application/vnd.ms-excel");
//        // 对响应进行重新编码
//        response.setCharacterEncoding("utf-8");
//        String fileName = URLEncoder.encode("测试", "utf-8");
//        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
//        response.addHeader("Pargam", "no-cache");
//        response.addHeader("Cache-Control", "no-cache");
//        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).head(TSysUserImpotParam.class).build();
//        WriteSheet writeSheet = EasyExcel.writerSheet().build();
//        // 直接写入数据
//        excelWriter.write(nolist, writeSheet);
//        // 写入list之前的数据
//        excelWriter.finish();
        return nolist;
    }

    private List<TSysUserImport> processExcel(InputStream inputStream) throws Exception {
        List<TSysUserImport> forlanStudentList = new ArrayList<>();

        Integer maxRows = 10000;
        // 导入模板表头
        List<String> chineseHeader = Arrays.asList("姓名", "登录名","所属机构","角色类型");
        // 0是表头
        final int headerRows = 0;

        try (Workbook workbook = WorkbookFactory.create(inputStream)) {
            Sheet sheet = workbook.getSheetAt(0);
            int totalRow = sheet.getLastRowNum();
            if (totalRow == 0) {
                throw new Exception("文件内容为空");
            } else if (totalRow - headerRows > maxRows) {
                throw new Exception(String.format("单次导入数据不能超过%s条", maxRows));
            }


            // 遍历每行
            for (int rowIndex = 1; rowIndex <= totalRow; rowIndex++) {
                Row currentRow = sheet.getRow(rowIndex);
                if (currentRow == null) {
                    continue;
                }
                // 读取数据行
                List<String> cellList = new ArrayList<>();
                for (int columnIndex = 0; columnIndex <= 3; columnIndex++) {
                    Cell currentCell = currentRow.getCell(columnIndex);
                    cellList.add(formatCellValue(currentCell));
                }

//                // 校验模板是否正确
//                if (rowIndex <= headerRows) {
//                    if (rowIndex == 0 && !cellList.equals(chineseHeader)) {
//                        throw new Exception("文件模板错误");
//                    }
//                    continue;
//                }

                if (null != cellList && !cellList.isEmpty()) {
                    TSysUserImport forlanStudent = new TSysUserImport();
                    forlanStudent.setUserName(cellList.get(0));
                    forlanStudent.setAccount(cellList.get(1));
                    forlanStudent.setOrgName(cellList.get(2));
                    forlanStudent.setRoleName(cellList.get(3));
                    forlanStudentList.add(forlanStudent);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception(e.getMessage());
        }finally {
            inputStream.close();

        }

        return forlanStudentList;
    }

    public static String formatCellValue(Cell cell) {

        if (cell == null) {
            return "";
        }
        if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {

            if (HSSFDateUtil.isCellDateFormatted(cell)) {
                double d = cell.getNumericCellValue();
                Date date = HSSFDateUtil.getJavaDate(d);
                return new SimpleDateFormat("yyyy/MM/dd HH:mm:ss\"").format(date);
            } else {
                // 强制将数字转字符串
                DecimalFormat format = new DecimalFormat("0.00");
                Number value = cell.getNumericCellValue();
                String phone = format.format(value).replace(".00", "");
                return String.valueOf(phone);
            }
        } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            return String.valueOf(cell.getNumericCellValue());
        } else {
            try {
                return cell.getStringCellValue() == null ? "" : cell.getStringCellValue().trim();
            } catch (Exception e) {
                return cell.toString() == null ? "" : cell.toString().trim();
            }
        }
    }

    private List<TSysUserImports> processExcels(InputStream inputStream) throws Exception {
        List<TSysUserImports> forlanStudentList = new ArrayList<>();

        Integer maxRows = 10000;
        // 导入模板表头
        List<String> chineseHeader = Arrays.asList("姓名", "登录名","所属机构","角色类型");
        // 0是表头
        final int headerRows = 0;

        try (Workbook workbook = WorkbookFactory.create(inputStream)) {
            Sheet sheet = workbook.getSheetAt(0);
            int totalRow = sheet.getLastRowNum();
            if (totalRow == 0) {
                throw new Exception("文件内容为空");
            } else if (totalRow - headerRows > maxRows) {
                throw new Exception(String.format("单次导入数据不能超过%s条", maxRows));
            }


            // 遍历每行
            for (int rowIndex = 1; rowIndex <= totalRow; rowIndex++) {
                Row currentRow = sheet.getRow(rowIndex);
                if (currentRow == null) {
                    continue;
                }
                // 读取数据行
                List<String> cellList = new ArrayList<>();
                for (int columnIndex = 0; columnIndex <= 6; columnIndex++) {
                    Cell currentCell = currentRow.getCell(columnIndex);
                    cellList.add(formatCellValue(currentCell));
                }

//                // 校验模板是否正确
//                if (rowIndex <= headerRows) {
//                    if (rowIndex == 0 && !cellList.equals(chineseHeader)) {
//                        throw new Exception("文件模板错误");
//                    }
//                    continue;
//                }

                if (null != cellList && !cellList.isEmpty()) {
                    TSysUserImports forlanStudent = new TSysUserImports();
                    forlanStudent.setOrgName(cellList.get(0));
                    forlanStudent.setDepartment(cellList.get(1));
                    forlanStudent.setUserName(cellList.get(2));
                    forlanStudent.setAccount(cellList.get(3));
                    forlanStudent.setPost(cellList.get(4));
                    forlanStudent.setPhone(cellList.get(5));
                    forlanStudent.setRoleName(cellList.get(6));
                    forlanStudentList.add(forlanStudent);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception(e.getMessage());
        }finally {
            inputStream.close();

        }

        return forlanStudentList;
    }



}
