package com.jeeplus.business.useSeal.service;

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.extension.plugins.pagination.Page;
import com.jeeplus.business.project.domain.JyProject;
import com.jeeplus.business.project.domain.JyProjectOutinstance;
import com.jeeplus.business.project.domain.JyProjectReportsSubmit;
import com.jeeplus.business.project.mapper.JyProjectMapper;
import com.jeeplus.business.project.mapper.JyProjectOutinstanceMapper;
import com.jeeplus.business.project.mapper.JyProjectReportsSubmitMapper;
import com.jeeplus.business.project.service.JyProjectService;
import com.jeeplus.business.project.service.dto.JyProjectDTO;
import com.jeeplus.business.workContractInfo.mapper.JyWorkContractInfoMapper;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.business.useSeal.domain.Signet;
import com.jeeplus.business.useSeal.mapper.SignetMapper;
import com.jeeplus.business.useSeal.service.dto.SignetDTO;
import com.jeeplus.sys.domain.WorkAttachmentInfo;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.feign.IWorkAttachmentApi;
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.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional
public class SignetService {

    @Autowired
    private SignetMapper signetMapper;


    @Autowired
    private JyProjectMapper jyProjectMapper;

    @Autowired
    private JyWorkContractInfoMapper jyWorkContractInfoMapper;

    @Autowired
    private JyProjectReportsSubmitMapper jyProjectReportsSubmitMapper;

    @Autowired
    private JyProjectOutinstanceMapper jyProjectOutinstanceMapper;



    /**
     * 列表查询
     * @param signetDTOPage
     * @param dto
     * @return
     * @throws Exception
     */
    public IPage<SignetDTO> findList(Page<SignetDTO> signetDTOPage, SignetDTO dto) throws Exception {
        QueryWrapper<SignetDTO> queryWrapper = QueryWrapperGenerator.buildQueryCondition(dto, SignetDTO.class);
        queryWrapper.eq("a.del_flag",0);
        //关联项目
        if (StringUtils.isNotBlank(dto.getProjectName())){
            queryWrapper.like("a.project_name",dto.getProjectName());
        }
        //用印类型
        if (null != dto.getTypes() && dto.getTypes().size()>0){
            if (dto.getTypes().size() ==1){
                queryWrapper.eq("a.first_type",dto.getTypes().get(0));
            }else {
                queryWrapper.eq("a.type",dto.getTypes().get(1));
            }
        }
        //申请人
        if (StringUtils.isNotBlank(dto.getCreateById())){
            queryWrapper.eq("a.create_by_id", dto.getCreateById());
        }
        //创建时间
        if (dto.getCreateDates() != null && dto.getCreateDates().length > 0) {
            queryWrapper.between("a.create_time", dto.getCreateDates()[0], dto.getCreateDates()[1]);
        }
        //申请人部门
        if (StringUtils.isNotBlank(dto.getOffice())){
            queryWrapper.eq("so.id",dto.getOffice());
        }
        IPage<SignetDTO> signetList=signetMapper.findPageList(signetDTOPage,queryWrapper);
        //报批签发信息
        List<JyProjectReportsSubmit> jyProjectReportsSubmits = jyProjectReportsSubmitMapper.selectList(new QueryWrapper<JyProjectReportsSubmit>());

        signetList.getRecords().stream().forEach(item->{
            if (StringUtils.isNotBlank(item.getProjectName())){
                String project=item.getProjectName().substring(0,item.getProjectName().lastIndexOf(","));
                item.setProjectName(project);
            }
            //用印类型
            if (StringUtils.isNotBlank(item.getType())){
                item.setType("项目-"+item.getType());
            }else {
                item.setType(item.getFirstType());
            }
            //关联项目
            if (StringUtils.isNotBlank(item.getProjectId())){
                String[] split = item.getProjectId().split(",");
                ArrayList<JyProject> jyProjects = new ArrayList<>();
                for (String s : split) {
                    JyProject byId = jyProjectMapper.getById(s);
                    byId.setSealId(item.getId());
                    //报批签发关联的项目
                    for (JyProjectReportsSubmit jyProjectReportsSubmit : jyProjectReportsSubmits) {
                        if (StringUtils.isNotBlank(jyProjectReportsSubmit.getProjectId())){
                            String[] split1 = jyProjectReportsSubmit.getProjectId().split(",");
                            //将用印关联的项目和报批签发关联的项目进行比较
                            for (String s1 : split1) {
                                if (s1.equals(s)){
                                    byId.setReportsSubmitId(jyProjectReportsSubmit.getId());
                                }
                            }
                        }
                    }
                    jyProjects.add(byId);
                }
                item.setProjectList(jyProjects);
            }
        });
        return signetList;

    }

    public String save(SignetDTO dto) throws Exception{
        // 获取当前登录人信息
//        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken (TokenProvider.getCurrentToken ( ));
        if (StringUtils.isNotEmpty(dto.getId())) {
            return update(dto, userDTO);
        } else {
            return add(dto, userDTO);
        }
    }

    public synchronized String add(SignetDTO dto, UserDTO userDTO) throws Exception{
        // 生成id
        String id = UUID.randomUUID().toString().replace("-", "");
        // 生成编号
        String no = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), dto.BIZ_CODE,TokenProvider.getCurrentToken());
        // 保存基础信息表信息
        Signet signet = new Signet();
        BeanUtils.copyProperties(dto, signet);
        signet.setId(id);
        signet.setNo(no);
        signet.setCreateById(userDTO.getId());
        signet.setCreateTime(new Date());
        signet.setUpdateById(userDTO.getId());
        signet.setUpdateTime(new Date());
        signet.setDelFlag(0);
        //保存关联项目信息
        String projectId="";
        String projectName="";
        if (ObjectUtil.isNotEmpty(dto.getProjectList())){
            for (JyProject jyProject : dto.getProjectList()) {
                //修改项目报告签发状态
                JyProject project = new JyProject();
                project.setReportIssuance(dto.getStatus());
                project.setId(jyProject.getId());
                jyProjectMapper.update(project,new QueryWrapper<JyProject>().lambda().eq(JyProject::getId,jyProject.getId()));

                projectId+=jyProject.getProjectId()+",";
                projectName+=jyProject.getName()+",";
            }
        }
        signet.setProjectId(projectId);
        signet.setProjectName(projectName);
        //保存用印类型
        if (null != dto.getTypes()&&dto.getTypes().size()>0){
            if (dto.getTypes().size()==1){
                signet.setFirstType(dto.getTypes().get(0));
            }else {
                signet.setFirstType(dto.getTypes().get(0));
                signet.setType(dto.getTypes().get(1));
            }
        }

        signet.setRemarks(dto.getRemarks());//说明
        signet.setStatus(dto.getStatus());//状态
        signet.setNumber(dto.getNumber()); //份数
        signetMapper.insert(signet);
        // 保存附件列表信息
        if (CollectionUtils.isNotEmpty(dto.getFiles())) {
            saveFiles(dto.getFiles(), userDTO, id);
        }
        //修改项目中的报告签发状态
        if (StringUtils.isNotBlank(projectId)){
            String[] split = projectId.split(",");
            for (String s : split) {
                if (StringUtils.isNotBlank(s)){
                    jyProjectMapper.updateReportIssuanceById(s,signet.getStatus());
                }

            }
        }

        return id;
    }

    public String update(SignetDTO dto, UserDTO userDTO) {
        Signet signet = new Signet();
        BeanUtils.copyProperties(dto, signet);
        signet.setUpdateTime(new Date());
        //保存关联项目信息
        String projectId="";
        String projectName="";
        if (ObjectUtil.isNotEmpty(dto.getProjectList())){
            for (JyProject jyProject : dto.getProjectList()) {
                //修改项目报告签发状态
                JyProject project = new JyProject();
                project.setReportIssuance(dto.getStatus());
                project.setId(jyProject.getId());
                jyProjectMapper.update(project,new QueryWrapper<JyProject>().lambda().eq(JyProject::getId,jyProject.getId()));

                projectId=jyProject.getId()+",";
                projectName=jyProject.getName()+",";
            }
        }
        signet.setProjectId(projectId);
        signet.setProjectName(projectName);
        //保存用印类型
        if (ObjectUtil.isNotEmpty(dto.getTypes())){
            if (StringUtils.isNotBlank(dto.getTypes().get(1))){
                signet.setType(dto.getTypes().get(1));
            }
            if (StringUtils.isNotBlank(dto.getTypes().get(0))){
                signet.setFirstType(dto.getTypes().get(0));
            }
        }
        signet.setRemarks(dto.getRemarks());//说明
        signet.setStatus(dto.getStatus());//状态
        signet.setNumber(dto.getNumber()); //份数
        signetMapper.updateById(signet);
        // 修改附件信息
        if (CollectionUtils.isNotEmpty(dto.getFiles())) {
            updateFiles(dto.getFiles(), userDTO, dto.getId());
        }
        //修改项目中的报告签发状态
        if (StringUtils.isNotBlank(projectId)){
            String[] split = projectId.split(",");
            for (String s : split) {
                if (StringUtils.isNotBlank(s)){
                    jyProjectMapper.updateReportIssuanceById(s,signet.getStatus());
                }

            }
        }
        return dto.getId();
    }

    /**
     * 保存附件信息
     * @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 (org.flowable.editor.language.json.converter.util.CollectionUtils.isNotEmpty(strings)) {
                i.setType(strings.get(1));
            }
            i.setAttachmentId(id);
            i.setAttachmentName(dto.getName());
            i.setAttachmentFlag("jySeal");
            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);
//            ossServiceMapper.insertWorkAttachment(i, userDTO);
            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 = signetMapper.findFileList(id);
        if (org.flowable.editor.language.json.converter.util.CollectionUtils.isNotEmpty(infoList)) {
            for (WorkAttachmentInfo i : infoList) {
                if (!names.contains(i.getUrl())) {
//                    ossServiceMapper.deleteById(i.getId());
                    SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteById(i.getId());
                }
            }
        }
        //保存信息
        for (WorkAttachmentInfo dto : list) {
            //判断是否存在
            Integer isExit = signetMapper.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 (org.flowable.editor.language.json.converter.util.CollectionUtils.isNotEmpty(strings)) {
                    i.setType(strings.get(1));
                }
                i.setAttachmentId(id);
                i.setAttachmentName(dto.getName());
                i.setAttachmentFlag("jySeal");
                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);
//                ossServiceMapper.insertWorkAttachment(i, userDTO);
                j++;
            }
        }
    }

    /**
     * 根据id查询用印
     * @param id
     * @return
     */
    public SignetDTO findById(String id) {
        SignetDTO signetDTO = new SignetDTO();
        SignetDTO dto = signetMapper.findById(id);
        BeanUtils.copyProperties(dto, signetDTO);
        //查询项目信息
        if (StringUtils.isNotBlank(dto.getProjectId())){
            String[] split = dto.getProjectId().split(",");
            ArrayList<JyProject> signetDTOS = new ArrayList<>();
            for (String s : split) {
                JyProject jyProject=jyProjectMapper.getById(s);
                signetDTOS.add(jyProject);
            }
            signetDTO.setProjectList(signetDTOS);
        }
        List<String> stringList = new ArrayList<>();
        if (StringUtils.isNotBlank(dto.getType())){
            stringList.add(dto.getFirstType());
            stringList.add(dto.getType());
        }else {
            stringList.add(dto.getFirstType());
        }
        signetDTO.setTypes(stringList);
        signetDTO.setCreateById(dto.getCreateById());
        // 查询附件信息
        List<WorkAttachmentInfo> files = jyWorkContractInfoMapper.findDtos(id);
        if (CollectionUtils.isNotEmpty(files)) {
            for (WorkAttachmentInfo i : files) {
                i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
            }
            signetDTO.setFiles(files);
        }
        return  signetDTO;
    }

    /**
     * 根据id修改状态
     * @param id
     * @param status
     */
    public void updateStatusById(String id,String status) {
        signetMapper.updateStatusById(id,status);
        SignetDTO signetDTO = signetMapper.findById(id);
        //修改项目中的报告签发状态
        if (StringUtils.isNotBlank(signetDTO.getProjectId())){
            String[] split = signetDTO.getProjectId().split(",");
            for (String s : split) {
                if (StringUtils.isNotBlank(s)){
                    jyProjectMapper.updateReportIssuanceById(s,signetDTO.getStatus());
                }

            }
        }
    }

    /**
     * 查询用印信息
     * @return
     */
    public List<Signet> findSeal() {
        //获取一个月前的时间
        //创建时间格式化对象
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取当前时间
        Date currentDate = new Date();
        //将当前时间转化为字符串
        String format = simpleDateFormat.format(currentDate);
        //创建calendar对象
        Calendar instance = Calendar.getInstance();
        //将日期设置为当前时间
        instance.setTime(currentDate);
        //将日期往前推两周
        instance.add(Calendar.DATE,-14);
        //获取推送后的日期
        Date newDate = instance.getTime();
        List<Signet> seal = signetMapper.findSeal(newDate);

        seal.stream().forEach(item->{
                String outId="";
                String[] split = item.getProjectId().split(",");
                for (String s : split) {
                    if (StringUtils.isNotBlank(s)){
                        JyProjectOutinstance jyProjectOutinstance=jyProjectOutinstanceMapper.findByProjectId(s);
                        if (ObjectUtil.isNotEmpty(jyProjectOutinstance)){
                            outId+=jyProjectOutinstance.getId()+",";
                        }

                    }

                }
                item.setOutInstanceId(outId);
        });
        return seal;
    }

    /**
     * 查询用印信息
     * @return
     */
    public List<Signet> findSealInTime() {
        //获取一个月前的时间
        //创建时间格式化对象
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取当前时间
        Date currentDate = new Date();
        //将当前时间转化为字符串
        String format = simpleDateFormat.format(currentDate);
        //创建calendar对象
        Calendar instance = Calendar.getInstance();
        //将日期设置为当前时间
        instance.setTime(currentDate);
        //将日期往前推两周
        instance.add(Calendar.DATE,-14);
        //获取推送后的日期
        Date newDate = instance.getTime();
        List<Signet> seal = signetMapper.findSealInTime(newDate);
        return seal;
    }

    /**
     * 修改外审逾期状态
     * @param id
     */
    public void updateOutInstanceStatus(String id,String status,String exceedTimeStatus) {
        jyProjectOutinstanceMapper.updateOutInstanceStatus(id,status,exceedTimeStatus);




    }

    /**
     * 根据id删除
     * @param id
     * @return
     */
    public String deleteById(String id) {
        signetMapper.deleteById(id);
        return "删除成功";
    }
}
