package com.jeeplus.business.monthly.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeeplus.business.goOut.mapper.GoOutMapper;
import com.jeeplus.business.monthly.domain.JyProcess;
import com.jeeplus.business.monthly.domain.Monthly;
import com.jeeplus.business.monthly.mapper.JyProcessMapper;
import com.jeeplus.business.monthly.mapper.MonthlyMapper;
import com.jeeplus.business.monthly.service.dto.MonthlyDTO;
import com.jeeplus.business.project.service.JyProjectService;
import com.jeeplus.business.project.service.dto.JyProjectDTO;
import com.jeeplus.business.useSeal.domain.Signet;
import com.jeeplus.business.useSeal.mapper.SignetMapper;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.flowable.feign.IFlowableApi;
import com.jeeplus.sys.domain.WorkAttachmentInfo;
import com.jeeplus.sys.feign.IOfficeApi;
import com.jeeplus.sys.feign.IPostApi;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.feign.IWorkAttachmentApi;
import com.jeeplus.sys.service.dto.FlowCopy;
import com.jeeplus.sys.service.dto.PostDTO;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service
public class MonthlyService {

    @Resource
    private MonthlyMapper monthlyMapper;

    @Resource
    private JyProjectService jyProjectService;

    @Resource
    private GoOutMapper goOutMapper;

    @Resource
    private JyProcessMapper jyProcessMapper;

    @Autowired
    private SignetMapper signetMapper;


    /**
     * 列表展示
     * @param monthlyDTO
     * @param page
     * @return
     */
    public IPage<MonthlyDTO> findPageList(MonthlyDTO monthlyDTO, Page<MonthlyDTO> page) throws Exception {
        QueryWrapper<MonthlyDTO> queryWrapper = QueryWrapperGenerator.buildQueryCondition(monthlyDTO, MonthlyDTO.class);
        queryWrapper.eq("a.del_flag",0);
        //申请人
        if (StringUtils.isNotBlank(monthlyDTO.getCreateById())){
            queryWrapper.eq("a.create_by_id",monthlyDTO.getCreateById());
        }
        //申请人部门
        if (StringUtils.isNotBlank(monthlyDTO.getOfficeId())){
            queryWrapper.eq("so.id",monthlyDTO.getOfficeId());
        }
        //申请时间
        if (monthlyDTO.getCreateDates() != null && monthlyDTO.getCreateDates().length > 0) {
            queryWrapper.between("a.create_time", monthlyDTO.getCreateDates()[0], monthlyDTO.getCreateDates()[1]);
        }
        IPage<MonthlyDTO> pageList=monthlyMapper.findPageList(queryWrapper,page);

        pageList.getRecords().stream().forEach(item->{
            //生成月报年月
            String date=item.getYear()+"年"+item.getMonth()+"月";
            item.setMonthDate(date);
        });

        return pageList;

    }

    /**
     * 根据id查找信息
     * @param id
     * @return
     */
    public MonthlyDTO findById(String id) {
        MonthlyDTO monthlyDTO = new MonthlyDTO();
        if (StringUtils.isNotBlank(id)){
            MonthlyDTO dto=monthlyMapper.findById(id);
            BeanUtils.copyProperties(dto,monthlyDTO);
            // 查询附件信息
            List<WorkAttachmentInfo> files = goOutMapper.findDtos(id);
            if (CollectionUtils.isNotEmpty(files)) {
                for (WorkAttachmentInfo i : files) {
                    i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                }
                monthlyDTO.setFiles(files);
            }
        }
        //根据月报表id查询项目进度
//        List<JyProcess> processList=jyProcessMapper.findByMonthId(id);
//        if (ObjectUtils.isNotEmpty(processList)){
//            monthlyDTO.setProcessList(processList);
//        }else {
            String mid = UUID.randomUUID().toString().replace("-", "");
            //先往月报表中添加一条数据
//            Monthly monthly = new Monthly();
//            monthly.setId(mid);
//            monthly.setIfsubmit("0");
//            monthlyMapper.insert(monthly);

            monthlyDTO.setId(mid);
            //获取当前登录人信息
            UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
            //获取当前登陆人未归档的项目信息
            List<JyProjectDTO> jyProjectDTO=jyProjectService.getByIdNoArchive(userDTO.getId());
            List<JyProjectDTO> arrayList = new ArrayList<>();
            if (ObjectUtils.isNotEmpty(jyProjectDTO)){
                for (JyProjectDTO item : jyProjectDTO) {
                    //项目进度信息
                    if (!item.getFirstInstanceStatus().equals("5") && StringUtils.isNotBlank(item.getFirstInstanceStatus())){
                        item.setProcess("登记完成");
                        item.setProcessTime(item.getUpdateTime());
                        continue;
                    }else {
                        item.setProcess("一级校审完成");
                        item.setProcessTime(item.getAudit1UpdateTime());
                    }
                    if (!item.getSecondInstanceStatus().equals("5") && StringUtils.isNotBlank(item.getSecondInstanceStatus())){
                        item.setProcess("一级校审完成");
                        item.setProcessTime(item.getAudit1UpdateTime());
                        continue;
                    }else {
                        item.setProcess("二级校审完成");
                        item.setProcessTime(item.getAudit2UpdateTime());
                    }
                    if (!item.getThirdInstanceStatus().equals("5") && StringUtils.isNotBlank(item.getThirdInstanceStatus())){
                        item.setProcess("二级校审完成");
                        item.setProcessTime(item.getAudit2UpdateTime());
                        continue;
                    }else {
                        item.setProcess("三级校审完成");
                        item.setProcessTime(item.getAudit3UpdateTime());
                    }
                    if ((StringUtils.isNotBlank(item.getReportStatus()) && !item.getReportStatus().equals("5")) || StringUtils.isBlank(item.getReportStatus())){
                        item.setProcess("三级校审完成");
                        item.setProcessTime(item.getAudit3UpdateTime());
                        continue;
                    }else {
                        item.setProcess("报告签发完成");
                        item.setProcessTime(item.getReportTime());
                    }
                    if (StringUtils.isNotBlank(item.getOutInstance()) && !item.getOutInstance().equals("5")){
                        item.setProcess("报告签发完成");
                        item.setProcessTime(item.getReportTime());
                        continue;
                    }else {
                        item.setProcess("外审完成");
                        item.setProcessTime(item.getOutTime());
                    }
                    if ((StringUtils.isNotBlank(item.getReportsStatus()) && !item.getReportsStatus().equals("5")) || StringUtils.isBlank(item.getReportsStatus())){
                        item.setProcess("外审完成");
                        item.setProcessTime(item.getOutTime());
                        continue;
                    }else {
                        item.setProcess("报批签发完成");
                        item.setProcessTime(item.getReportsTime());
                    }
                };
                arrayList.addAll(jyProjectDTO);
            }
            List<JyProcess> jyProcessList = saveProcess(arrayList, mid);
            monthlyDTO.setProcessList(jyProcessList);
//        }
        return monthlyDTO;
    }

    /**
     * 往进度表中添加数据
     */
    public List<JyProcess> saveProcess(List<JyProjectDTO> projectDTOS,String monthId){
        ArrayList<JyProcess> jyProcesses = new ArrayList<>();

        //获取用印id
        QueryWrapper<Signet> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag",'0');
        queryWrapper.orderByDesc("create_time");
        List<Signet> signets = signetMapper.selectList(queryWrapper);
        projectDTOS.stream().forEach(item ->{
            for (Signet signet : signets) {
                if (org.apache.commons.lang3.StringUtils.isNotBlank(signet.getProjectId())){
                    String[] split = signet.getProjectId().split(",");
                    for (String s : split) {
                        if (org.apache.commons.lang3.StringUtils.isNotBlank(s)){
                            if (org.apache.commons.lang3.StringUtils.isNotBlank(signet.getTypeStatus())){
                                //用印类型为报告,则获取报告签发
                                if ( s.equals(item.getId()) && signet.getTypeStatus().equals("1") ){
                                    item.setReportStatus(signet.getStatus());
                                    item.setReportTime(signet.getUpdateTime());
                                }
                                if (s.equals(item.getId()) && signet.getTypeStatus().equals("2")){
                                    //用印类型为报批,则设置报批签发所需信息
                                    item.setReportsTime(signet.getUpdateTime());
                                    item.setReportsStatus(signet.getStatus());
                                }
                            }
                        }
                    }
                }

                if (org.apache.commons.lang3.StringUtils.isNotBlank(signet.getProjectId())){
                    String[] split = signet.getProjectId().split(",");
                    for (String s : split) {
                        if (org.apache.commons.lang3.StringUtils.isNotBlank(s)){
                            if (org.apache.commons.lang3.StringUtils.isNotBlank(signet.getTypeStatus())){
                                //用印类型为报告,则获取报告签发
                                if ( s.equals(item.getId()) && signet.getTypeStatus().equals("1") ){
                                    item.setSealId(signet.getId());
                                    item.setProcInsReportIssuance(signet.getProcInsId());
                                    item.setReportIssuance(signet.getStatus());
                                }
                                if (s.equals(item.getId()) && signet.getTypeStatus().equals("2")){
                                    //用印类型为报批,则设置报批签发所需信息
                                    item.setReportsSubmitId(signet.getId());
                                    item.setProcInsIdReports(signet.getProcInsId());
                                    item.setReportsSubmit(signet.getStatus());
                                }
                            }
                        }
                    }
                }
            }
        });



        projectDTOS.stream().forEach(item->{
            JyProcess jyProcess = new JyProcess();
            String id = UUID.randomUUID().toString().replace("-", "");
            jyProcess.setId(id);
            jyProcess.setProjectId(item.getId());
            jyProcess.setOfficeName(item.getOfficeName());//部门
            jyProcess.setProjectName(item.getName());//项目名称
            jyProcess.setNo(item.getNo());//报告号
            jyProcess.setProjectLeader(item.getProjectLeader());//项目负责人
            jyProcess.setProcessTime(item.getProcessTime());//进度完成时间
            jyProcess.setProcess(item.getProcess());//进度
            jyProcess.setMonthlyId(monthId);//月报id

            jyProcess.setAuditId1(item.getAuditId1());
            jyProcess.setAuditId2(item.getAuditId2());
            jyProcess.setAuditId3(item.getAuditId3());
            jyProcess.setSealId(item.getSealId());
            jyProcess.setOutInstanceId(item.getOutInstanceId());
            jyProcess.setReportsSubmitId(item.getReportsSubmitId());
            jyProcess.setArchiveId(item.getArchiveId());
            jyProcess.setArchiveId(item.getArchiveId());
            jyProcess.setEiaId(item.getEiaId());

            jyProcessMapper.insert(jyProcess);
            jyProcesses.add(jyProcess);
        });
        return jyProcesses;
    }





    /**
     * 修改或保存
     * @param monthlyDTO
     */
    public void saveForm(MonthlyDTO monthlyDTO) {
        //获取当前登陆人信息
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        Monthly monthly = new Monthly();
        if (StringUtils.isNotBlank(monthlyDTO.getId())){
            monthly.setUpdateById(userDTO.getId());
            monthly.setUpdateTime(new Date());
            monthly.setProjectStatus(monthlyDTO.getProjectStatus()); //项目情况
            monthly.setRemarks(monthlyDTO.getRemarks()); //备注
            monthly.setId(monthlyDTO.getId());
            monthly.setIfsubmit("1");
            //切割月报时间
            String[] split = monthlyDTO.getMonthDate().split("-");
            monthly.setYear(split[0]);
            monthly.setMonth(split[1]);
            //月报名称
            String name=userDTO.getName()+split[0]+"年"+split[1]+"月月报";
            monthly.setName(name);
            monthlyMapper.insert(monthly);

            //修改附件
            List<WorkAttachmentInfo> files = monthlyDTO.getFiles();
            updateFiles(files, userDTO, monthlyDTO.getId());
        }else {
            //切割月报时间
            String[] split = monthlyDTO.getMonthDate().split("-");
            monthly.setYear(split[0]);
            monthly.setMonth(split[1]);

            String id = UUID.randomUUID().toString().replace("-", "");
            monthly.setId(id);
            monthly.setCreateById(userDTO.getId());
            monthly.setCreateTime(new Date());
            monthly.setUpdateById(userDTO.getId());
            monthly.setUpdateTime(new Date());
            monthly.setProjectStatus(monthlyDTO.getProjectStatus()); //项目情况
            monthly.setIfsubmit("1");
            monthly.setRemarks(monthlyDTO.getRemarks()); //备注
            //月报名称
            String name=userDTO.getName()+split[0]+"年"+split[1]+"月月报";
            monthly.setName(name);
            monthlyMapper.insert(monthly);
            //保存附件
            List<WorkAttachmentInfo> files = monthlyDTO.getFiles();
            if (CollectionUtil.isNotEmpty(files)) {
                saveFiles(files, userDTO, id);
            }

            //给办公室和部门主任抄送
            ArrayList<UserDTO> userDTOS = new ArrayList<>();
            PostDTO postDTOByName = SpringUtil.getBean(IPostApi.class).getPostDTOByName("办公室(嘉溢)");
            List<UserDTO> officeId = SpringUtil.getBean(IUserApi.class).findListByOfficeId(userDTO.getOfficeDTO().getId());
            List<UserDTO> listByPostId = SpringUtil.getBean(IUserApi.class).findListByPostId(postDTOByName.getId());
            for (UserDTO dto : officeId) {
                if (StringUtils.isNotBlank(dto.getManageOfficeIds())){
                    userDTOS.add(dto);
                }
            }
            listByPostId.stream().forEach(item->{
                userDTOS.add(item);
            });
            for (UserDTO dto : userDTOS) {
                String id1 = UUID.randomUUID().toString().replace("-", "");
                FlowCopy flowCopy = new FlowCopy();
                flowCopy.setCreateById(userDTO.getId());
                flowCopy.setCreateTime(new Date());
                flowCopy.setUpdateById(userDTO.getId());
                flowCopy.setUpdateTime(new Date());
                flowCopy.setProcInsName(name);
                flowCopy.setUserId(dto.getId());
                flowCopy.setId(id1);
                flowCopy.setDelFlag(0);
                SpringUtil.getBean(IFlowableApi.class).add(flowCopy);
            }



        }
    }
    /**
     * 保存附件信息
     * @param list 待保存的附件列表
     * @param userDTO 当前登录用户
     * @param id 关联id
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveFiles(List<WorkAttachmentInfo> list, UserDTO userDTO, String id) {
        int j = 1;
        for (WorkAttachmentInfo dto : list) {
            WorkAttachmentInfo i = new WorkAttachmentInfo();
            //包含了url、size、name
            i.setId(UUID.randomUUID().toString().replace("-", ""));
//            i.getCreateBy().setId(userDTO.getId());
            i.setCreateTime(new Date());
//            i.getUpdateBy().setId(userDTO.getId());
            i.setUpdateTime(new Date());
            i.setDelFlag(0);
            i.setUrl(dto.getUrl());
            //文件类型处理
            List<String> strings = Arrays.asList(dto.getName().split("\\."));
            if (CollectionUtil.isNotEmpty(strings)) {
                i.setType(strings.get(1));
            }
            i.setAttachmentId(id);
            i.setAttachmentName(dto.getName());
            i.setAttachmentFlag("monthly");
            i.setFileSize(dto.getSize());
            i.setSort(j);
            Map<String,String> map = new HashMap<>();
            String workAttachment = JSON.toJSONString((i));
            String userDTOInfo = JSON.toJSONString((userDTO));
            map.put("workAttachment",workAttachment);
            map.put("userDTO",userDTOInfo);
            SpringUtil.getBean ( IWorkAttachmentApi.class ).insertWorkAttachment(map);
            j++;
        }
    }

    /**
     * 修改附件信息
     * @param list 待修改的附件列表
     * @param userDTO 当前登录用户
     * @param id 关联id
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateFiles(List<WorkAttachmentInfo> list, UserDTO userDTO, String id) {
        int j = 1;
        String names = new String();
        //表中存在，但是传过来不存在，说明已删除，表中数据也要删除
        for (WorkAttachmentInfo dto : list) {
            names = names + "," +dto.getUrl();
        }
        //查询保存的附件信息
        List<WorkAttachmentInfo> infoList = goOutMapper.findList(id);
        if (CollectionUtil.isNotEmpty(infoList)) {
            for (WorkAttachmentInfo i : infoList) {
                if (!names.contains(i.getUrl())) {
                    SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteById(i.getId());
                }
            }
        }
        //保存信息
        for (WorkAttachmentInfo dto : list) {
            //判断是否存在
            Integer isExit = goOutMapper.findIsExit(id, dto.getName());
            if (isExit == 0) {
                WorkAttachmentInfo i = new WorkAttachmentInfo();
                //包含了url、size、name
                i.setId(UUID.randomUUID().toString().replace("-", ""));
//                i.getCreateBy().setId(userDTO.getId());
                i.setCreateTime(new Date());
//                i.getUpdateBy().setId(userDTO.getId());
                i.setUpdateTime(new Date());
                i.setDelFlag(0);
                i.setUrl(dto.getUrl());
                //文件类型处理
                List<String> strings = Arrays.asList(dto.getName().split("\\."));
                if (CollectionUtil.isNotEmpty(strings)) {
                    i.setType(strings.get(1));
                }
                i.setAttachmentId(id);
                i.setAttachmentName(dto.getName());
                i.setAttachmentFlag("monthly");
                i.setFileSize(dto.getSize());
                i.setSort(j);
                Map<String,String> map = new HashMap<>();
                String workAttachment = JSON.toJSONString((i));
                String userDTOInfo = JSON.toJSONString((userDTO));
                map.put("workAttachment",workAttachment);
                map.put("userDTO",userDTOInfo);
                SpringUtil.getBean ( IWorkAttachmentApi.class ).insertWorkAttachment(map);
                j++;
            }
        }
    }

    /*
    根据id进行删除
     */
    public void delete(String id) {
        monthlyMapper.deleteById(id);
    }

    /**
     * 列表
     * @param monthlyDTO
     * @return
     */
    public List<MonthlyDTO> getList() {
        List<MonthlyDTO> list= monthlyMapper.getList();
        return list;
    }
}
