package com.storlead.system.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.storlead.framework.common.ecode.PasswordEncoder;
import com.storlead.framework.common.result.Result;
import com.storlead.system.service.IUserRoleService;
import com.storlead.system.util.SystemConfigItemCacheUtil;
import com.storlead.user.pojo.entity.*;
import com.storlead.user.pojo.vo.WxExcelOrgVo;
import com.storlead.user.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import javax.annotation.Resource;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @program: sp-sales
 * @description:
 * @author: chenkq
 * @create: 2022-07-15 15:55
 */

@Api(tags = "系统: 角色管理")
@RestController
@RequestMapping("/sys/data/sync")
public class OrganizDataSyncApiController {

    @Resource
    private ICompanyService companyService;

    @Resource
    private ISubCompanyService subCompanyService;

    @Resource
    private IDepartService departService;

    @Resource
    private IUserService userService;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private IUserRoleService userRoleService;

    @Resource
    private IJobService jobService;

    @ApiOperation("导入企业微信数据")
    @RequestMapping(value = "/importWxData",method = {RequestMethod.POST},headers = "content-type=multipart/form-data")
    public Result importWxData(HttpServletRequest request, @ApiParam(value="文件",required=true)@RequestPart("file") MultipartFile file) throws Exception {
        if (file == null ) {
            return Result.error("请上传附件!");
        }
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // MultipartFile files = multipartRequest.getFile("filename");
        InputStream inputStream = file.getInputStream();
        List<WxExcelOrgVo> vols = excelWxExcelOrg(inputStream, file.getOriginalFilename());
        Result result = markData(vols);
        return result;
    }

    public List<WxExcelOrgVo> excelWxExcelOrg(InputStream in, String fileName) {
        List list = new ArrayList<>();
        try{
            //创建Excel工作薄
            Workbook work = this.getWorkbook(in, fileName);
            if (null == work) {
                return null;
            }
            //获得第一个shell
            Sheet sheet=work.getSheetAt(0);
            //获得Excel的行数
            int totalRows=sheet.getPhysicalNumberOfRows();
            // 获取总列数
            // int totalCells=sheet.getRow(0).getPhysicalNumberOfCells();
            // Cell cell = null;
            List<WxExcelOrgVo> orgVos = new ArrayList<>();
            for (int j = 10; j < totalRows; j++) {
                Row row = sheet.getRow(j);
                WxExcelOrgVo orgVo = new WxExcelOrgVo();
                if(row.getCell(0) != null) {
                    orgVo.setRealName(row.getCell(0).toString());
                }
                if(row.getCell(1) != null) {
                    orgVo.setXworkUserId(row.getCell(1).toString());
                }
                if(row.getCell(2) != null) {
                    orgVo.setNickName(row.getCell(2).toString());
                }
                if(row.getCell(3) != null) {
                    orgVo.setJobName(row.getCell(3).toString());
                }
                if(row.getCell(4) != null) {
                    orgVo.setDeptName(row.getCell(4).toString());
                }
                if(row.getCell(5) != null) {
                    orgVo.setSex(row.getCell(5).toString());
                }

                if(row.getCell(6) != null) {
                    orgVo.setMobile(row.getCell(6).toString());
                }
                if(row.getCell(10) != null) {
                    orgVo.setEmail(row.getCell(10).toString());
                }
                if(row.getCell(12) != null) {
                    String  enabledStr = row.getCell(12).toString();
                    orgVo.setEnabled("已激活".equals(enabledStr) ? true:false);
                }
                orgVos.add(orgVo);
            }
            work.close();
            return orgVos;
        }catch (Exception e){
            return null;
        }
    }

    /**
     * 判断文件格式
     *
     * @param inStr
     * @param fileName
     * @return
     * @throws Exception
     */
    public Workbook getWorkbook(InputStream inStr, String fileName) throws Exception {
        Workbook workbook = null;
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        if (".xls".equals(fileType)) {
            workbook = new HSSFWorkbook(inStr);
        } else if (".xlsx".equals(fileType)) {
            workbook = new XSSFWorkbook(inStr);
        } else {
            return null;
        }
        return workbook;
    }

    public Result markData(List<WxExcelOrgVo> vos) {

        /**
         * 岗位处理
         */
        Map<String, Long> jobMap = new HashMap<>();
        List<JobEntity> oldJob = jobService.list(new LambdaUpdateWrapper<JobEntity>().eq(JobEntity::getIsDelete,0));
        if (!CollectionUtils.isEmpty(oldJob)) {
            jobMap = oldJob.stream().collect(Collectors.toMap(JobEntity::getName, JobEntity::getId));
        }

        List<JobEntity> jobs = new ArrayList<>();
        for (WxExcelOrgVo vo : vos) {
            JobEntity job = oldJob.stream().filter(e ->vo.getJobName().equals(e.getName())).findFirst().orElse(null);
            if (Objects.isNull(job)) {
                job = new JobEntity();
                job.setName(vo.getJobName());
                jobs.add(job);
                if (StrUtil.isNotBlank(vo.getJobName())) {
                    jobService.saveOrUpdate(job);
                    oldJob.add(job);
                    jobMap.put(job.getName(),job.getId());
                }
            }
        }


        /**
         * 人员处理
         */
        List<DeptEntity> oldDeptls = departService.list(new LambdaUpdateWrapper<DeptEntity>().eq(DeptEntity::getIsDelete,0));

        Map<String,DeptEntity> deptMap = new HashMap();
        if (!CollectionUtils.isEmpty(oldDeptls)) {
            deptMap = oldDeptls.stream().collect(Collectors.toMap(DeptEntity::getDeptNameRoute, a -> a));
        }
        CompanyEntity company = new CompanyEntity();
        SubCompanyEntity subCompany = new SubCompanyEntity();

        /**
         * 处理组织数据
         */
        int i = 1;
        for (WxExcelOrgVo vo : vos) {
            String[] ds = vo.getDeptName().split(";");
            String[] deptstr = ds[0].split("/");
            if (i == 1) {
                company.setName(deptstr[0]);
                company.setRouteCode("100");
                company.setId(Long.valueOf(1));
                subCompany.setName(deptstr[0]);
                subCompany.setCompanyId(company.getId());
                subCompany.setRouteCode("100,100");
                subCompany.setId(Long.valueOf(1));
                companyService.truncateTable();
                companyService.save(company);

                subCompanyService.truncateTable();
                subCompanyService.save(subCompany);
                i++;
            }

            String routeStr = deptstr[0];
            for (int j = 1; j < deptstr.length; j++) {
                routeStr = routeStr + "/" + deptstr[j];
                String finalRouteStr = routeStr;
                DeptEntity dept = oldDeptls.stream().filter(e -> e.getDeptNameRoute().equals(finalRouteStr)).findFirst().orElse(null);
                if (Objects.isNull(dept)) {
                    String topRoute = finalRouteStr.substring(0, StrUtil.ordinalIndexOf(finalRouteStr, "/", j));
                    // 上一级
                    DeptEntity topDept = oldDeptls.stream().filter(e -> e.getDeptNameRoute().equals(topRoute)).findFirst().orElse(null);
                    DeptEntity newDept = new DeptEntity();
                    if (Objects.nonNull(topDept)) {
                        DeptEntity nextD = oldDeptls.stream().filter(e -> e.getDeptNameRoute().contains(topRoute) && !e.getDeptNameRoute().equals(topRoute)).collect(Collectors.toList()).stream().max(Comparator.comparing(s -> s.getRouteCode())).orElse(null);
                        if (Objects.isNull(nextD)) {
                            newDept.setRouteCode(topDept.getRouteCode() + ",100");
                        } else {
                            String[] routeCodes = nextD.getRouteCode().split(",");
                            String lastCode = routeCodes[routeCodes.length - 1];
                            lastCode = String.valueOf(Integer.valueOf(lastCode) + 1);
                            routeCodes[routeCodes.length - 1] = lastCode;
                            String routeCode = StringUtils.join(routeCodes, ",");
                            newDept.setRouteCode(routeCode);
                        }
                        newDept.setCompanyId(topDept.getCompanyId());
                        newDept.setSubCompanyId(topDept.getSubCompanyId());
                        newDept.setDeptNameRoute(routeStr);
                        newDept.setPid(topDept.getId());
                        newDept.setName(deptstr[j]);
                        departService.saveOrUpdate(newDept);
                        deptMap.put(newDept.getDeptNameRoute(), newDept);
                        oldDeptls.add(newDept);
                    } else {
                        newDept.setPid(Long.valueOf(0));
                        newDept.setRouteCode(subCompany.getRouteCode() + ",100");
                        newDept.setDeptNameRoute(subCompany.getName() + "/"+deptstr[j]);
                        newDept.setCompanyId(company.getId());
                        newDept.setSubCompanyId(subCompany.getId());
                        newDept.setName(deptstr[j]);
                        departService.saveOrUpdate(newDept);
                        deptMap.put(newDept.getDeptNameRoute(), newDept);
                        oldDeptls.add(newDept);

                    }

                }
            }
        }



        List<UserEntity> oldUsers = userService.list(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getIsDelete,0));
        List<UserEntity> users = new ArrayList<>();
        String defaultPassWord = SystemConfigItemCacheUtil.getDefaultPassWord();
        for (WxExcelOrgVo vo : vos) {
            UserEntity oldInfo = oldUsers.stream().filter(e ->e.getMobile().equals(vo.getMobile())).findFirst().orElse(null);
            if (Objects.nonNull(oldInfo)) {
                continue;
            }
            UserEntity user = new UserEntity();
            user.setUserName(vo.getRealName());
            user.setSex(vo.getSex());
            user.setNickName(vo.getNickName());
            user.setRealName(vo.getRealName());
            user.setXworkUserId(vo.getXworkUserId());
            user.setEmail(vo.getEmail());
            user.setPassword(passwordEncoder.encode(defaultPassWord));
            user.setJobId(jobMap.get(vo.getJobName()));
            user.setId(Long.valueOf(i));
            user.setStatus("1");
            String[] ds = vo.getDeptName().split(";");
            String deptRouteName = ds[0];
            DeptEntity wxVo = deptMap.get(deptRouteName);
            if (Objects.nonNull(wxVo)) {
                DeptEntity d = wxVo;
                user.setSubCompanyId(d.getSubCompanyId());
                user.setCompanyId(d.getCompanyId());
                user.setDeptId(d.getId());
                user.setOrgRouteCode(d.getRouteCode());
            }
            user.setMobile(vo.getMobile());
            users.add(user);
        }
        userService.saveBatch(users);
        userRoleService.initUserRole();

        return Result.ok();
    }
}
