package com.jeeplus.centerservice.utils;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeeplus.centerservice.dto.ReimbursementAmountInfo;
import com.jeeplus.centerservice.dto.ReimbursementDetailInfo;
import com.jeeplus.centerservice.dto.SaveInfoDto;
import com.jeeplus.centerservice.dto.WorkAttachmentDto;
import com.jeeplus.flowable.vo.HisTaskVo;
import com.jeeplus.flowable.vo.ProcessVo;
import com.jeeplus.flowable.vo.TaskVo;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.utils.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;

public class ConvertServiceUtil {

    /**
     * 批量将ccpm系统待办返回的字段转换为当前系统待办需要的字段
     * @param res
     * @return
     */
    public static List<ProcessVo> convertProcessVoList(List<ProcessVo> res) throws Exception {
        ArrayList<ProcessVo> processVoList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(res)) {
            List<ProcessVo> processVos = res;
            String ccpm_task = Global.getConfig("CCPM_TASK"); // 获取ccpm可查看的待办数据
            for (ProcessVo item : processVos) {
                if ("cpa".equals(item.getBelongProject())) {
                    processVoList.add(item);
                } else if ("ccpm".equals(item.getBelongProject())) {
                    TaskVo task = item.getTask();
                    Map vars = item.getVars();
                    if (Objects.nonNull(task) && Objects.nonNull(vars) && (vars.get("remarks").toString().contains("待审批") || vars.get("remarks").toString().contains("重新申请"))) {
                        if(StringUtils.isNotBlank(ccpm_task)) {
                            String[] split = ccpm_task.split(",");
                            List<String> taskAliasList = Arrays.asList(split);
                            if (taskAliasList.contains(task.getProcessDefKey())) {
                                processVoList.add(item);
                            }
                        }
                    }
                }
            }
        }

        return processVoList;
    }
    /**
     * 批量将ccpm系统待办返回的字段转换为当前系统已办
     * @param res
     * @return
     */
    public static List<HisTaskVo> convertHisTaskVoList(List<HisTaskVo> res) throws Exception {
        List<HisTaskVo> hisTaskVoList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(res)) {
            List<HisTaskVo> hisTaskVos = res;
            String ccpm_task = Global.getConfig("CCPM_TASK"); // 获取ccpm可查看的待办数据
            for (HisTaskVo item : hisTaskVos) {
                if ("cpa".equals(item.getBelongProject())) {
                    hisTaskVoList.add(item);
                } else if ("ccpm".equals(item.getBelongProject())) {
                    if(StringUtils.isNotBlank(ccpm_task)) {
                        String[] split = ccpm_task.split(",");
                        List<String> taskAliasList = Arrays.asList(split);
                        if (taskAliasList.contains(item.getProcessDefKey())) {
                            hisTaskVoList.add(item);
                        }
                    }
                }
            }
        }
        return hisTaskVoList;
    }

    /**
     * ccpm系统待办返回的字段转换为当前系统待办需要的字段
     * @param map
     * @return
     */
    public static ProcessVo convertProcessVo(Map<String, Object> map) throws Exception {
        ProcessVo processVo = new ProcessVo();
        Map<String, String> vars = new HashMap();
        TaskVo task = new TaskVo();
        if (CollectionUtil.isNotEmpty(map)) {
            // 标题
            if (Objects.nonNull(map.get("title"))){
                vars.put("title", map.get("title").toString());
            }
            // 流程名称
            if (Objects.nonNull(map.get("typeLabel"))){
                processVo.setProcessDefinitionName(map.get("typeLabel").toString());
            }
            // 当前环节
            if (Objects.nonNull(map.get("notifyRole"))){
                task.setName(map.get("notifyRole").toString());
            }
            // 流程发起人
            if (Objects.nonNull(map.get("createUserName"))){
                vars.put("userName", map.get("createUserName").toString());
            }
            // 创建时间
            if (Objects.nonNull(map.get("createDate"))){
                task.setCreateTime((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).parse(map.get("createDate").toString()));
            }
            // 流程id
            if (Objects.nonNull(map.get("id"))){
                task.setId(map.get("id").toString());
            }
            // 数据id
            if (Objects.nonNull(map.get("notifyId"))){
                vars.put("notifyId", map.get("notifyId").toString());
            }
            // 审批状态
            if (Objects.nonNull(map.get("remarks"))){
                vars.put("remarks", map.get("remarks").toString());
            }
        }
        processVo.setVars(vars);
        processVo.setTask(task);
        processVo.setBelongProject("ccpm");
        processVo.setStatus ("todo");
        return processVo;
    }

    /**
     * 将结果排序后分页(已办)
     * 由于是根据数据中的creaTime字段来进行排序，所以此字段不可以为空，否则会报空指针
     * @param page
     * @param list
     * @return
     */
    public static Page getSortAndPagingHisTask(Page page, List<HisTaskVo> list) {
        // 将数据按照creaTime倒序排序
        CollectionUtil.sort(list, new Comparator<HisTaskVo>() {
            @Override
            public int compare(HisTaskVo o1, HisTaskVo o2) {
                return o2.getCreateTime().compareTo(o1.getCreateTime());
            }
        });
        // 将数据分页
        page.setTotal(list.size());
        List<HisTaskVo> records = new ArrayList<>();
        int startIndex = (int) ((page.getCurrent() - 1) * page.getSize());
        if (startIndex > list.size()) {
            startIndex = 0;
            page.setCurrent(1);
        }
        for (int i = 0; i < page.getSize() ; i ++) {
            if (startIndex == list.size() || ObjectUtil.isEmpty(list.get(startIndex))) {
                break;
            }
            records.add(list.get(startIndex));
            startIndex++;
        }
        page.setRecords(records);
        return page;
    }

    /**
     * 将结果排序后分页(待办)
     * 由于是根据数据中的creaTime字段来进行排序，所以此字段不可以为空，否则会报空指针
     * @param page
     * @param list
     * @return
     */
    public static Page getSortAndPaging(Page page, List<ProcessVo> list) {
        // 将数据按照creaTime倒序排序
        CollectionUtil.sort(list, new Comparator<ProcessVo>() {
            @Override
            public int compare(ProcessVo o1, ProcessVo o2) {
                return o2.getTask().getCreateTime().compareTo(o1.getTask().getCreateTime());
            }
        });
        // 将数据分页
        page.setTotal(list.size());
        List<ProcessVo> records = new ArrayList<>();
        int startIndex = (int) ((page.getCurrent() - 1) * page.getSize());
        if (startIndex > list.size()) {
            startIndex = 0;
            page.setCurrent(1);
        }
        for (int i = 0; i < page.getSize() ; i ++) {
            if (startIndex == list.size() || ObjectUtil.isEmpty(list.get(startIndex))) {
                break;
            }
            records.add(list.get(startIndex));
            startIndex++;
        }
        page.setRecords(records);
        return page;
    }

    /**
     * ccpm报销转换
     * @param response
     * @return
     */
    public static SaveInfoDto convertReim(Object response) {
        SaveInfoDto result = new SaveInfoDto();
        if (Objects.nonNull(response)) {
            Map<String, Object> resp = JSONObject.parseObject(JSON.toJSONString(response));
            if (CollectionUtil.isNotEmpty(resp)) {
                // processInstanceId
                if (ObjectUtil.isNotEmpty(resp.get("processInstanceId"))) {
                    result.setProcInsId(resp.get("processInstanceId").toString());
                }
                // 经办人
                if (ObjectUtil.isNotEmpty(resp.get("submitterName"))) { // 报销人
                    result.setUserName(resp.get("submitterName").toString());
                }
                // 报销编号
                if (ObjectUtil.isNotEmpty(resp.get("number"))) { // 报销编号
                    result.setNo(resp.get("number").toString());
                }
                // 所属部门
                if (ObjectUtil.isNotEmpty(resp.get("officeName"))) { // 所属部门
                    result.setDepartmentName(resp.get("officeName").toString());
                }
                // 报销日期
                if (ObjectUtil.isNotEmpty(resp.get("createDate"))) { // 报销日期、创建时间
                    result.setReimDate(DateUtil.parse(resp.get("createDate").toString()));
                }
                // 备注
                if (ObjectUtil.isNotEmpty(resp.get("remarks"))) { // 备注
                    result.setRemarks(resp.get("remarks").toString());
                }
                // 附件
                if (ObjectUtil.isNotEmpty(resp.get("workAttachments"))) {
                    String jsonString = JSON.toJSONString(resp.get("workAttachments"));
                    List<Object> attachmentList = JSON.parseArray(jsonString, Object.class);
                    List<WorkAttachmentDto> attachments = new ArrayList<>();
                    if (CollectionUtil.isNotEmpty(attachmentList)) {
                        attachmentList.stream().forEach(attachment -> {
                            WorkAttachmentDto attachmentDto = new WorkAttachmentDto();
                            UserDTO userDTO = new UserDTO();
                            Map<String, Object> fileMap = JSONObject.parseObject(JSON.toJSONString(attachment));
                            if (ObjectUtil.isNotEmpty(fileMap.get("attachmentName"))) { // 附件名称
                                attachmentDto.setName(fileMap.get("attachmentName").toString());
                            }
                            if (ObjectUtil.isNotEmpty(fileMap.get("createName"))) { // 创建人
                                userDTO.setName(fileMap.get("createName").toString());
                            }
                            if (ObjectUtil.isNotEmpty(fileMap.get("createDate"))) { // 创建时间
                                attachmentDto.setCreateTime(DateUtil.parse(fileMap.get("createDate").toString()));
                            }
                            if (ObjectUtil.isNotEmpty(fileMap.get("url"))) { // 文件地址
                                attachmentDto.setUrl(fileMap.get("url").toString());
                            }
                            if (ObjectUtil.isNotEmpty(fileMap.get("temporaryUrl"))) { // 文件临时地址
                                attachmentDto.setLsUrl(fileMap.get("temporaryUrl").toString());
                            }
                            attachmentDto.setCreateBy(userDTO);
                            attachments.add(attachmentDto);
                        });
                    }
                    result.setFiles(attachments);
                }
                // 专用发票信息
                if (ObjectUtil.isNotEmpty(resp.get("reimbursementVATTaxes"))) {
                    String jsonString = JSON.toJSONString(resp.get("reimbursementVATTaxes"));
                    List<Object> reimVATTaxeList = JSON.parseArray(jsonString, Object.class);
                    List<ReimbursementAmountInfo> reimbursementAmountInfoList = new ArrayList<>();
                    if (CollectionUtil.isNotEmpty(reimVATTaxeList)) {
                        reimVATTaxeList.stream().forEach(reim -> {
                            ReimbursementAmountInfo reimbursementAmountInfo = new ReimbursementAmountInfo();
                            Map<String, Object> vaTaxeMap = JSONObject.parseObject(JSON.toJSONString(reim));
                            if (ObjectUtil.isNotEmpty(vaTaxeMap.get("invoiceCode"))) { // 发票代码
                                reimbursementAmountInfo.setCode(vaTaxeMap.get("invoiceCode").toString());
                            }
                            if (ObjectUtil.isNotEmpty(vaTaxeMap.get("invoiceNumber"))) { // 发票号
                                reimbursementAmountInfo.setNumber(vaTaxeMap.get("invoiceNumber").toString());
                            }
                            if (ObjectUtil.isNotEmpty(vaTaxeMap.get("money"))) { // 金额
                                reimbursementAmountInfo.setAmount(vaTaxeMap.get("money").toString());
                            }
                            if (ObjectUtil.isNotEmpty(vaTaxeMap.get("taxAmount"))) { // 税额
                                reimbursementAmountInfo.setTaxAmount(vaTaxeMap.get("taxAmount").toString());
                            }
                            if (ObjectUtil.isNotEmpty(vaTaxeMap.get("sumMoney"))) { // 价税合计
                                reimbursementAmountInfo.setCount(vaTaxeMap.get("sumMoney").toString());
                            }
                            reimbursementAmountInfoList.add(reimbursementAmountInfo);
                        });
                    }
                    result.setAmountInfos(reimbursementAmountInfoList);
                }
                // 报销详情
                if (ObjectUtil.isNotEmpty(resp.get("workAccountList"))) {
                    String jsonString = JSON.toJSONString(resp.get("workAccountList"));
                    List<Object> workAccountList = JSON.parseArray(jsonString, Object.class);
                    List<ReimbursementDetailInfo> reimbursementDetailInfos = new ArrayList<>();
                    if (CollectionUtil.isNotEmpty(workAccountList)) {
                        workAccountList.stream().forEach(detail -> {
                            Map<String, Object> detailMap = JSONObject.parseObject(JSON.toJSONString(detail));
                            ReimbursementDetailInfo detailInfo = new ReimbursementDetailInfo();
                            if (ObjectUtil.isNotEmpty(detailMap.get("reimbursementName"))) { // 报销人
                                detailInfo.setUserName(detailMap.get("reimbursementName").toString());
                            }
                            if (ObjectUtil.isNotEmpty(detailMap.get("officeId"))) { // 报销部门
                                detailInfo.setDeptName(detailMap.get("officeId").toString());
                            }
                            if (ObjectUtil.isNotEmpty(detailMap.get("typeName"))) { // 报销类别
                                detailInfo.setTypeName(detailMap.get("typeName").toString());
                            }
                            if (ObjectUtil.isNotEmpty(detailMap.get("project"))) { // 报销项目
                                Map<String, Object> projectMap = JSONObject.parseObject(JSON.toJSONString(detailMap.get("project")));
                                if (ObjectUtil.isNotEmpty(projectMap.get("projectName"))) {
                                    detailInfo.setProjectName(projectMap.get("projectName").toString());
                                }
                            }
                            if (ObjectUtil.isNotEmpty(detailMap.get("projectReportNumber"))) { // 报告号
                                detailInfo.setReportNumber(detailMap.get("projectReportNumber").toString());
                            }
                            if (ObjectUtil.isNotEmpty(detailMap.get("money"))) { // 费用（元）
                                detailInfo.setNumber(detailMap.get("money").toString());
                            }
                            if (ObjectUtil.isNotEmpty(detailMap.get("bills"))) { // 收据张数
                                detailInfo.setReceiptNumbers(detailMap.get("bills").toString());
                            }
                            if (ObjectUtil.isNotEmpty(detailMap.get("evectionNumber"))) { // 出差天数
                                detailInfo.setEvectionNumber(detailMap.get("evectionNumber").toString());
                            }
                            if (ObjectUtil.isNotEmpty(detailMap.get("remarks"))) { // 内容
                                detailInfo.setContent(detailMap.get("remarks").toString());
                            }
                            reimbursementDetailInfos.add(detailInfo);
                        });
                    }
                    result.setDetailInfos(reimbursementDetailInfos);
                }
            }
        }
        return result;
    }

    /**
     * ccpm流程历史转换
     * @param list
     * @return
     */
    public static List<Map<String, Object>> convertHisFlowList(List<Map<String, Object>> list) {
        if (CollectionUtil.isNotEmpty(list)) {
            list.stream().forEach(item -> {
                // beginDate日期格式化后重新赋值
                if (Objects.nonNull(item.get("beginDate"))) {
                    Long beginDate = Long.valueOf(String.valueOf(item.get("beginDate")));
                    item.remove("beginDate");
                    item.put("beginDate",formatLongDate(beginDate));
                }
                // endDate日期格式化后重新赋值
                if (Objects.nonNull(item.get("endDate"))) {
                    Long beginDate = Long.valueOf(String.valueOf(item.get("endDate")));
                    item.remove("endDate");
                    item.put("endDate",formatLongDate(beginDate));
                }
            });
        }
        return list;
    }

    /**
     * 将Long类型时间转换为String时间格式
     * @param date
     * @return
     */
    public static String formatLongDate (Long date) {
        Date dt=new Date(date);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String format = sdf.format(dt);
        return format;
    }

    /**
     * 当前系统待办数据转换为ccpm待办 批量转换
     * @param processVoList
     * @return
     */
    public static List<Map<String, Object>> copyNotifyListToCcpm(List<ProcessVo> processVoList) throws Exception {
        List<Map<String, Object>> res = new ArrayList<>();
        for (ProcessVo processVo : processVoList) {
            Map<String, Object> respMap = copyNotifyToCcpm(processVo);
            if (MapUtil.isNotEmpty(respMap)) {
                res.add(respMap);
            }
        }
        return res;
    }

    /**
     * 当前系统待办数据转换为ccpm待办
     * @param processVo
     * @return
     * @throws Exception
     */
    public static Map<String, Object> copyNotifyToCcpm(ProcessVo processVo) throws Exception {
        Map<String, Object> res = new HashMap<>();
        Map<String, Object> vars = processVo.getVars();
        TaskVo task = processVo.getTask();
        // 只查询待审批状态的数据
        // vars.get("agree") 的值为false时，此流程为驳回状态。值为null或其他时，此流程为待审批状态
        if (Objects.nonNull(vars) && (Objects.isNull(vars.get("agree")) || Boolean.parseBoolean(vars.get("agree").toString()))) {
            res.put("belongProject",processVo.getBelongProject());
            // 流程名称
            if (StringUtils.isNotBlank(processVo.getProcessDefinitionName())){
                res.put("typeLabel", processVo.getProcessDefinitionName());
            }
            // 标题
            if (Objects.nonNull(vars.get("title"))){
                res.put("title", "cpa " + vars.get("title").toString()); // 标题
                res.put("content", vars.get("title").toString()); // 内容
            }
            // 流程发起人
            if (Objects.nonNull(vars.get("userName"))){
                res.put("createUserName",vars.get("userName").toString());
            }
            // 数据id
            if (Objects.nonNull(vars.get("id"))){
                res.put("notifyId",vars.get("id").toString());
            }
            // 审批状态
            res.put("remarks","待审批");
            if (Objects.nonNull(vars.get("agree"))) {
                if (!Boolean.parseBoolean(vars.get("agree").toString())) {
                    res.put("remarks","重新发起"); // vars.get("agree")的值为false时，此流程为驳回状态，其他值为待审批状态
                }
            }
            if (Objects.nonNull(task)) {
                // 流程类型
                if (StringUtils.isNotBlank(task.getProcessDefKey())){
                    // Process_1665383385070 评估-报销审批
//                    if ("Process_1665383385070".equals(task.getProcessDefKey())) {
//                        res.put("type", "13");
//                    }
                    res.put("type", task.getProcessDefKey());
                }
                // 当前环节
                if (Objects.nonNull(task.getName())){
                    res.put("notifyRole", task.getName());
                }
                // 创建时间
                if (Objects.nonNull(task.getCreateTime())){
                    res.put("createDate", task.getCreateTime());
                }
                // 流程id
                if (Objects.nonNull(task.getId())){
                    res.put("id",task.getId());
                }
                // 审核人
                if (Objects.nonNull(task.getAssignee())){
                    res.put("auditUserName",task.getAssignee());
                }
            }
        }
        return res;
    }

    /**
     * 当前系统待办数据转换为ccpm已办 批量转换
     * @param hisTaskVoList
     * @return
     */
    public static List<Map<String, Object>> copyHisTaskListToCcpm(List<HisTaskVo> hisTaskVoList) throws Exception {
        List<Map<String, Object>> res = new ArrayList<>();
        for (HisTaskVo hisTaskVo : hisTaskVoList) {
            Map<String, Object> respMap = copyHisTaskToCcpm(hisTaskVo);
            if (MapUtil.isNotEmpty(respMap)) {
                res.add(respMap);
            }
        }
        return res;
    }

    /**
     * 当前系统待办数据转换为ccpm已办
     * @param hisTaskVo
     * @return
     * @throws Exception
     */
    public static Map<String, Object> copyHisTaskToCcpm(HisTaskVo hisTaskVo) throws Exception {
        Map<String, Object> res = new HashMap<>();
        Map<String, Object> vars = hisTaskVo.getVars();
        res.put("belongProject",hisTaskVo.getBelongProject());
        // 流程名称
        if (StringUtils.isNotBlank(hisTaskVo.getProcessDefinitionName())){
            res.put("typeLabel", hisTaskVo.getProcessDefinitionName());
        }
        // 标题
        if (Objects.nonNull(vars.get("title"))){
            res.put("title", "cpa " + vars.get("title").toString()); // 标题
            res.put("content", vars.get("title").toString()); // 内容
        }
        // 流程发起人
        if (Objects.nonNull(vars.get("userName"))){
            res.put("createUserName",vars.get("userName").toString());
        }
        // 数据id
        if (Objects.nonNull(hisTaskVo.getBusinessId())){
            res.put("notifyId",hisTaskVo.getBusinessId());
        }
        // 审批状态
        if (Objects.nonNull(hisTaskVo.getStatus())){
            res.put("remarks",hisTaskVo.getStatus());
        }
        // 流程类型
        if (StringUtils.isNotBlank(hisTaskVo.getProcessDefKey())){
            res.put("type", hisTaskVo.getProcessDefKey());
        }
        // 当前环节
        if (Objects.nonNull(hisTaskVo.getName())){
            res.put("notifyRole", hisTaskVo.getName());
        }
        // 创建时间
        if (Objects.nonNull(hisTaskVo.getCreateTime())){
            res.put("createDate", hisTaskVo.getCreateTime());
        }
        // 流程id
        if (Objects.nonNull(hisTaskVo.getExecutionId())){
            res.put("id",hisTaskVo.getExecutionId());
        }
        return res;
    }
}
