package cn.cslg.report.service;

import cn.cslg.report.common.core.base.Constants;
import cn.cslg.report.common.model.dto.TaskWebSocketDTO;
import cn.cslg.report.common.model.dto.UploadFileDTO;
import cn.cslg.report.common.model.vo.LoginVO;
import cn.cslg.report.common.model.vo.PersonnelVO;
import cn.cslg.report.common.model.vo.TaskParams;
import cn.cslg.report.common.utils.*;
import cn.cslg.report.common.utils.SecurityUtils.LoginUtils;
import cn.cslg.report.entity.ImportTask;
import cn.hutool.core.collection.IterUtil;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

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

@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
public class BaseService {
    private final OutInterfaceService outInterfaceService;
    private final FileUtils fileUtils;
    private final LoginUtils loginUtils;
    private final CacheUtils cacheUtils;
    /**
     * @return 1.生成验证码的base64转码 2.生成的UUID 与Redis里面的验证码KEY值一致
     * @title 获取验证码
     * @author 沈永艺
     */
    public String verifyCode() {
        try {
            String resBody = outInterfaceService.getVerifyCodeFromPCS();
            JSONObject data = (JSONObject) JSONObject.parseObject(resBody).get("data");
            Map<String, String> result = new HashMap<>();
            result.put("captcha", data.get("captcha").toString());
            result.put("uuid", data.get("uuid").toString());
            return Response.success(result);
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("权限系统获取验证码失败,错误信息:" + LogExceptionUtil.getMessage(ex));
            return Response.error(Constants.NET_ERROR);
        }
    }

    /**
     * @return 成功返回Token 失败返回错误信息
     * @title 登录接口
     * @author 沈永艺
     */
    public String login(LoginVO loginVO) throws IOException {
        String resBody = outInterfaceService.loginFromPCS(loginVO);
        JSONObject jsonObject = JSONObject.parseObject(resBody);
        //判断请求返回是否为200，不是的话则返回报错信息
        if (!jsonObject.get("code").equals(200)) {
            log.error("权限系统登录失败,错误信息:" + jsonObject.get("message").toString());
            return Response.error(Constants.NET_ERROR);
        } else {
            PersonnelVO personnelVO = com.alibaba.fastjson2.JSONObject.parseObject(jsonObject.get("data").toString(), PersonnelVO.class);
            return Response.success(personnelVO.getToken());
        }
    }

    /**
     * @return 成功返回用户信息 失败返回错误信息
     * @title 获取登录人信息
     * @author 沈永艺
     */
    public String getUserInfo() {
        try {
            String resBody = outInterfaceService.userInfoFromPCS();
            JSONObject jsonObject = JSONObject.parseObject(resBody);
            PersonnelVO personnelVO = com.alibaba.fastjson2.JSONObject.parseObject(jsonObject.get("data").toString(), PersonnelVO.class);
            return Response.success(personnelVO);
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("权限系统获取用户信息失败,错误信息:" + LogExceptionUtil.getMessage(ex));
            return Response.error(Constants.NET_ERROR);
        }
    }

    /**
     * @return 成功返回Map类型字典项信息 失败返回错误信息
     * @title 获取字典项信息
     * @author 沈永艺
     */
    public String getDictMessage() {
        try {
            Map<String, Object> map = outInterfaceService.dictMessageFromPCS();
            return Response.success(map);
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("权限系统获取字典项信息失败,错误信息:" + LogExceptionUtil.getMessage(ex));
            return Response.error(Constants.NET_ERROR);
        }
    }

    /**
     * @return 成功返回权限列表信息 失败返回错误信息
     * @title 获取权限列表
     * @author 沈永艺
     */
    public String getPermissionList(String code) {
        try {
            String resBody = outInterfaceService.getPermissionListFromPCS(code);
            JSONObject jsonObject = JSONObject.parseObject(resBody);
            return Response.success(jsonObject.get("data"));
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("权限系统获取权限列表失败,错误信息:" + LogExceptionUtil.getMessage(ex));
            return Response.error(Constants.NET_ERROR);
        }
    }

    /**
     * @return 成功返回部门列表信息 失败返回错误信息
     * @title 获取所有部门
     * @author 沈永艺
     */
    public String getAllDepartment() {
        try {
            String resBody = outInterfaceService.getAllDepartmentFromPCS();
            JSONObject jsonObject = JSONObject.parseObject(resBody);
            return Response.success(jsonObject.get("data"));
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("权限系统获取部门列表失败,错误信息:" + LogExceptionUtil.getMessage(ex));
            return Response.error(Constants.NET_ERROR);
        }
    }

    /**
     * @return 成功返回部门列表信息 失败返回错误信息
     * @title 获取部分部门
     * @author 沈永艺
     */
    public String getPartDepartment() {
        try {
            String resBody = outInterfaceService.getPartDepartmentFromPCS();
            JSONObject jsonObject = JSONObject.parseObject(resBody);
            return Response.success(jsonObject.get("data"));
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("权限系统获取部门列表失败,错误信息:" + LogExceptionUtil.getMessage(ex));
            return Response.error(Constants.NET_ERROR);
        }
    }

    /**
     * @return 成功返回人员列表信息 失败返回错误信息
     * @title 获取全部人员
     * @author 沈永艺
     */
    public String getAllPersonnel() {
        try {
            String resBody = outInterfaceService.getAllPersonnelFromPCS();
            JSONObject jsonObject = JSONObject.parseObject(resBody);
            return Response.success(jsonObject.get("data"));
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("权限系统获取人员列表失败,错误信息:" + LogExceptionUtil.getMessage(ex));
            return Response.error(Constants.NET_ERROR);
        }
    }

    /**
     * @return 成功返回人员列表信息 失败返回错误信息
     * @title 获取部分人员
     * @author 沈永艺
     */
    public String getPartPersonnel(PersonnelVO personnelVO) {
        try {
            String resBody = outInterfaceService.getPartPersonnelFromPCS(personnelVO);
            return resBody;
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("权限系统获取人员列表失败,错误信息:" + LogExceptionUtil.getMessage(ex));
            return Response.error(Constants.NET_ERROR);
        }
    }
    public String getPartPersonnelID(Integer id) {
        try {
            String resBody = outInterfaceService.getPartPersonnelID(id);
            return resBody;
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("权限系统获取人员列表失败,错误信息:" + LogExceptionUtil.getMessage(ex));
            return Response.error(Constants.NET_ERROR);
        }
    }


    /**
     * @return 成功返回客户列表信息 失败返回错误信息
     * @title 获取所有客户
     * @author 沈永艺
     */
    public String getAllClient() {
        try {
            String resBody = outInterfaceService.getAllClientFromPCS();
            JSONObject jsonObject = JSONObject.parseObject(resBody);
            return Response.success(jsonObject.get("data"));
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("权限系统获取客户列表失败,错误信息:" + LogExceptionUtil.getMessage(ex));
            return Response.error(Constants.NET_ERROR);
        }
    }

    /**
     * @return 成功返回客户列表信息 失败返回错误信息
     * @title 获取部分客户
     * @author 沈永艺
     */
    public String getPartClient() {
        try {
            String resBody = outInterfaceService.getPartClientFromPCS();
            JSONObject jsonObject = JSONObject.parseObject(resBody);
            return Response.success(jsonObject.get("data"));
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("权限系统获取客户列表失败,错误信息:" + LogExceptionUtil.getMessage(ex));
            return Response.error(Constants.NET_ERROR);
        }
    }

    //获得
    @Transactional(rollbackFor = Exception.class)
    public TaskParams getImportPatentTaskParamsBro(MultipartFile file,Integer reportId) throws IOException {
        //上传文档
        UploadFileDTO fileDTO = fileUtils.uploadFile(file);
        //获得文档保存的路径
        String path = fileUtils.getPath(fileDTO.getPath());

        File file1 = new File(path);
        String fileName = file1.getName();
        Workbook workbook = null;
        FileInputStream fileInputStream = new FileInputStream(file1);
        // excel类型
        if (fileName.endsWith(".xls")) {
            workbook = new HSSFWorkbook(fileInputStream);
        } else if (fileName.endsWith(".xlsx")) {
            workbook = new XSSFWorkbook(fileInputStream);
        }
        Sheet sheet1 = workbook.getSheetAt(0); // excel文件的工作簿的名称
        // 不作处理时获取的行数
        int total = sheet1.getLastRowNum();
        ImportTask importTask =new ImportTask();
        importTask.setImportCount(total);
        importTask.setReportId(reportId);
        importTask.insert();
        List<List<Object>> fileHead =new ArrayList<>();
        //解析excel文件并保存进map里
        ExcelUtil.readBySax(path, -1, (sheetIndex, rowIndex, row) ->
                { if(rowIndex==0)
                { fileHead.add(row);}
                    else {
                        List<Map<Object, Object>> mapList = new ArrayList<>();
                        mapList.add(IterUtil.toMap(fileHead.get(0),row));
                    TaskParams taskParams = new TaskParams();
                    taskParams.setPath(path);
                    taskParams.setTaskType(1);
                    taskParams.setRowList(mapList);
                    taskParams.setUserId(String.valueOf(loginUtils.getId()));
                    taskParams.setOldName(file.getOriginalFilename());
                    taskParams.setTotal(total);
                    taskParams.setIndex((int) rowIndex);
                    taskParams.setTaskId(importTask.getId());
                    try {
                    outInterfaceService.importPatents(taskParams);
                        WebSocketServer.sendInfo(Response.websocket(new TaskWebSocketDTO()
                                .setTaskId(taskParams.getTaskId())
                                .setComplete(true)
                                .setIndex((int) rowIndex)
                                .setTaskType(Constants.TASK_IMPORT_PATENT)
                                .setPercentage(100L)
                                .setFileName("")
                                .setOldName(taskParams.getOldName())
                                .setUrl("")
                                .setTotal(total), ResponseEnum.PATENT_IMPORT_TASK_SUCCESS), taskParams.getUserId());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                }



               );
        TaskParams taskParams =new TaskParams();
        return taskParams;
    }

}
