package com.ruoyi.worktecket.service.impl;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.constant.DeletedEnum;
import com.ruoyi.common.constant.WorkTicketSignOptionUserTypeEnum;
import com.ruoyi.common.core.domain.model.SysUserSimple;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.mapper.SysPostMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.worktecket.domain.*;
import com.ruoyi.worktecket.dto.SysPostSimpleDTO;
import com.ruoyi.worktecket.dto.WorkTicketSignOptionDTO;
import com.ruoyi.worktecket.dto.WorkTicketSignatureTemplateDTO;
import com.ruoyi.worktecket.dto.WorkTicketSmOptionDTO;
import com.ruoyi.worktecket.mapper.WorkTicketSignOptionMapper;
import com.ruoyi.worktecket.mapper.WorkTicketSignOptionUserMapper;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import com.ruoyi.worktecket.mapper.WorkTicketSignatureTemplateMapper;
import com.ruoyi.worktecket.service.IWorkTicketSignatureTemplateService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * 作业票签字模板Service业务层处理
 *
 * @author ruoyi
 * @date 2023-08-04
 */
@Service
public class WorkTicketSignatureTemplateServiceImpl implements IWorkTicketSignatureTemplateService {
    @Autowired
    private WorkTicketSignatureTemplateMapper workTicketSignatureTemplateMapper;

    @Autowired
    private WorkTicketSignOptionUserMapper workTicketSignOptionUserMapper;

    @Autowired
    private WorkTicketSignOptionMapper workTicketSignOptionMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysPostMapper sysPostMapper;

    /**
     * 查询作业票签字模板
     *
     * @param id 作业票签字模板主键
     * @return 作业票签字模板
     */
    @Override
    public WorkTicketSignatureTemplateDTO selectWorkTicketSignatureTemplateById(String id) {
        WorkTicketSignatureTemplate workTicketSignatureTemplate = workTicketSignatureTemplateMapper.selectById(id);
        if (Objects.isNull(workTicketSignatureTemplate)) {
            return null;
        }
        Integer isDel = workTicketSignatureTemplate.getIsDel();
        //排除无效状态的签字模板
        if (isDel == null || isDel != DeletedEnum.VALID.getValue()) {
            return null;
        }

        WorkTicketSignatureTemplateDTO workTicketSignatureTemplateDTO = new WorkTicketSignatureTemplateDTO();
        BeanUtils.copyProperties(workTicketSignatureTemplate, workTicketSignatureTemplateDTO);
        //查询签字项列表
        LambdaQueryWrapper<WorkTicketSignOption> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WorkTicketSignOption::getWorkTicketStId, id);
        queryWrapper.eq(WorkTicketSignOption::getIsDel, DeletedEnum.VALID.getValue());
        queryWrapper.orderByDesc(WorkTicketSignOption::getCreateDate);
        List<WorkTicketSignOption> workTicketSignOptions = workTicketSignOptionMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(workTicketSignOptions)) {
            List<WorkTicketSignOptionDTO> workTicketSignOptionDTOList = new ArrayList<>();
            //签字范围是人员类型的签字项
            List<String> userSignOptionIdList = new ArrayList<>();
            //签字范围是岗位类型的签字项
            List<String> postSignOptionIdList = new ArrayList<>();
            workTicketSignOptions.forEach(workTicketSignOption -> {
                //按人员
                if (workTicketSignOption.getWorkTicketSignType().equals(WorkTicketSignOptionUserTypeEnum.USER.getValue())) {
                    userSignOptionIdList.add(workTicketSignOption.getId());
                }
                //按岗位
                else {
                    postSignOptionIdList.add(workTicketSignOption.getId());
                }
            });

            //签字项对应的用户信息
            Map<String, List<Long>> signOptionUserMap = new HashMap<>();
            if (!CollectionUtils.isEmpty(userSignOptionIdList)) {
                List<SysUserSimple> sysUserSimples = workTicketSignOptionMapper.selectWorkTicketSignOptionUserBySignOptionIdList(userSignOptionIdList);
                if (!CollectionUtils.isEmpty(sysUserSimples)) {
                    signOptionUserMap = sysUserSimples.stream().collect(Collectors.groupingBy(SysUserSimple::getWorkSignOptionId, Collectors.mapping(SysUserSimple::getUserId, Collectors.toList())));
                }
            }

            //签字项对应的岗位信息
            Map<String, List<Long>> signOptionPostMap = new HashMap<>();
            if (!CollectionUtils.isEmpty(postSignOptionIdList)) {
                List<SysPostSimpleDTO> sysPostSimples = workTicketSignOptionMapper.selectWorkTicketSignOptionPostBySignOptionIdList(postSignOptionIdList);
                if (!CollectionUtils.isEmpty(sysPostSimples)) {
                    signOptionPostMap = sysPostSimples.stream().collect(Collectors.groupingBy(SysPostSimpleDTO::getWorkSignOptionId, Collectors.mapping(SysPostSimpleDTO::getPostId, Collectors.toList())));
                }
            }

            //签字项填充人员ID/岗位ID
            for (WorkTicketSignOption workTicketSignOption : workTicketSignOptions) {
                WorkTicketSignOptionDTO workTicketSignOptionDTO = new WorkTicketSignOptionDTO();
                BeanUtils.copyProperties(workTicketSignOption, workTicketSignOptionDTO);
                //填充签字项对应人员或岗位信息
                if (workTicketSignOption.getWorkTicketSignType().equals(WorkTicketSignOptionUserTypeEnum.USER.getValue())) {
                    workTicketSignOptionDTO.setWorkTicketSignUserIdList(signOptionUserMap.get(workTicketSignOption.getId()));
                } else {
                    workTicketSignOptionDTO.setWorkTicketSignUserIdList(signOptionPostMap.get(workTicketSignOption.getId()));
                }
                workTicketSignOptionDTOList.add(workTicketSignOptionDTO);
            }

            workTicketSignatureTemplateDTO.setWorkTicketSignOptionDTOList(workTicketSignOptionDTOList);
        }
        return workTicketSignatureTemplateDTO;
    }

    /**
     * 查询作业票签字模板列表
     *
     * @param workTicketSignatureTemplateDTO 作业票签字模板
     * @return 作业票签字模板
     */
    @Override
    public List<WorkTicketSignatureTemplate> selectList(WorkTicketSignatureTemplateDTO workTicketSignatureTemplateDTO) {
        WorkTicketSignatureTemplate workTicketSignatureTemplate = new WorkTicketSignatureTemplate();
        BeanUtils.copyProperties(workTicketSignatureTemplateDTO, workTicketSignatureTemplate);
        workTicketSignatureTemplate.setIsDel(DeletedEnum.VALID.getValue());
        List<WorkTicketSignatureTemplate> workTicketSignatureTemplates = workTicketSignatureTemplateMapper.selectWorkTicketSignatureTemplateList(workTicketSignatureTemplate);

        if (!CollectionUtils.isEmpty(workTicketSignatureTemplates)) {
//            List<WorkTicketSignatureTemplateDTO> workTicketSignatureTemplateDTOS = new ArrayList<>();
//            for(WorkTicketSignatureTemplate workTicketSignatureTemplate1 : workTicketSignatureTemplates){
//                WorkTicketSignatureTemplateDTO workTicketSignatureTemplateDTO1 = new WorkTicketSignatureTemplateDTO();
//                BeanUtils.copyProperties(workTicketSignatureTemplate1,workTicketSignatureTemplateDTO1);
//                workTicketSignatureTemplateDTOS.add(workTicketSignatureTemplateDTO1);
//            }
//            return workTicketSignatureTemplateDTOS;
            return workTicketSignatureTemplates;
        }
        return Lists.newArrayList();
    }

    /**
     * 查询作业票签字模板列表
     *
     * @param workTicketSignatureTemplateDTO 作业票签字模板
     * @return 作业票签字模板
     */
    @Override
    public List<WorkTicketSignatureTemplateDTO> selectWorkTicketSignatureTemplateList(WorkTicketSignatureTemplateDTO workTicketSignatureTemplateDTO) {
        WorkTicketSignatureTemplate workTicketSignatureTemplate = new WorkTicketSignatureTemplate();
        BeanUtils.copyProperties(workTicketSignatureTemplateDTO, workTicketSignatureTemplate);
        workTicketSignatureTemplate.setIsDel(DeletedEnum.VALID.getValue());
        //查询：作业票签字模板
        List<WorkTicketSignatureTemplate> workTicketSignatureTemplates = workTicketSignatureTemplateMapper.selectWorkTicketSignatureTemplateList(workTicketSignatureTemplate);
        if (!CollectionUtils.isEmpty(workTicketSignatureTemplates)) {
            List<WorkTicketSignatureTemplateDTO> workTicketSignatureTemplateDTOS = new ArrayList<>();
            for (WorkTicketSignatureTemplate workTicketSignatureTemplate1 : workTicketSignatureTemplates) {
                WorkTicketSignatureTemplateDTO workTicketSignatureTemplateDTO1 = new WorkTicketSignatureTemplateDTO();
                BeanUtils.copyProperties(workTicketSignatureTemplate1, workTicketSignatureTemplateDTO1);
                workTicketSignatureTemplateDTOS.add(workTicketSignatureTemplateDTO1);
            }
            return workTicketSignatureTemplateDTOS;
        }
        return Lists.newArrayList();
    }

    /**
     * 新增作业票签字模板
     *
     * @param workTicketSignatureTemplateDTO 作业票签字模板
     * @return 结果
     */
    @Override
    @Transactional
    public int insertWorkTicketSignatureTemplate(WorkTicketSignatureTemplateDTO workTicketSignatureTemplateDTO) {
        WorkTicketSignatureTemplate workTicketSignatureTemplate = new WorkTicketSignatureTemplate();
        BeanUtils.copyProperties(workTicketSignatureTemplateDTO, workTicketSignatureTemplate);
        workTicketSignatureTemplate.setCreateDefault();
        int count = workTicketSignatureTemplateMapper.insert(workTicketSignatureTemplate);
        List<WorkTicketSignOptionDTO> workTicketSignOptionDTOList = workTicketSignatureTemplateDTO.getWorkTicketSignOptionDTOList();
        if (!CollectionUtils.isEmpty(workTicketSignOptionDTOList)) {
            for (WorkTicketSignOptionDTO workTicketSignOptionDTO : workTicketSignOptionDTOList) {
                WorkTicketSignOption workTicketSignOption = new WorkTicketSignOption();
                BeanUtils.copyProperties(workTicketSignOptionDTO, workTicketSignOption);
                workTicketSignOption.setCreateDefault();
                workTicketSignOption.setWorkTicketStId(workTicketSignatureTemplate.getId());
                workTicketSignOptionMapper.insert(workTicketSignOption);
                List<Long> workTicketSignUserIdList = workTicketSignOptionDTO.getWorkTicketSignUserIdList();
                if (!CollectionUtils.isEmpty(workTicketSignUserIdList)) {
                    for (Long userId : workTicketSignUserIdList) {
                        WorkTicketSignOptionUser workTicketSignOptionUser = new WorkTicketSignOptionUser();
                        workTicketSignOptionUser.setWorkSignOptionId(workTicketSignOption.getId());
                        if (WorkTicketSignOptionUserTypeEnum.POST.getValue().equals(workTicketSignOptionDTO.getWorkTicketSignType())) {
                            workTicketSignOptionUser.setWorkSignOptionPostId(userId);
                        } else {
                            workTicketSignOptionUser.setWorkSignOptionUserId(userId);
                        }
                        workTicketSignOptionUser.setCreateDefault();
                        workTicketSignOptionUserMapper.insert(workTicketSignOptionUser);
                    }
                }
            }
        }
        return count;
    }

    /**
     * 修改作业票签字模板
     *
     * @param workTicketSignatureTemplateDTO 作业票签字模板
     * @return 结果
     */
    @Override
    public int updateWorkTicketSignatureTemplate(WorkTicketSignatureTemplateDTO workTicketSignatureTemplateDTO) {
        WorkTicketSignatureTemplate workTicketSignatureTemplate = new WorkTicketSignatureTemplate();
        BeanUtils.copyProperties(workTicketSignatureTemplateDTO, workTicketSignatureTemplate);
        workTicketSignatureTemplate.setUpdateDefault();
        int count = workTicketSignatureTemplateMapper.updateById(workTicketSignatureTemplate);
        List<WorkTicketSignOptionDTO> workTicketSignOptionDTOList = workTicketSignatureTemplateDTO.getWorkTicketSignOptionDTOList();
        if (!CollectionUtils.isEmpty(workTicketSignOptionDTOList)) {
            //先删除签字项
            WorkTicketSignOption updateSmOption = new WorkTicketSignOption();
            updateSmOption.setUpdateDefault();
            updateSmOption.setIsDel(DeletedEnum.INVALID.getValue());
            QueryWrapper<WorkTicketSignOption> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("work_ticket_st_id", workTicketSignatureTemplateDTO.getId());
            workTicketSignOptionMapper.update(updateSmOption, queryWrapper);

            for (WorkTicketSignOptionDTO workTicketSignOptionDTO : workTicketSignOptionDTOList) {
                WorkTicketSignOption workTicketSignOption = new WorkTicketSignOption();
                BeanUtils.copyProperties(workTicketSignOptionDTO, workTicketSignOption);
                workTicketSignOption.setCreateDefault();
                workTicketSignOption.setId(null);
                workTicketSignOption.setWorkTicketStId(workTicketSignatureTemplate.getId());
                workTicketSignOptionMapper.insert(workTicketSignOption);
                List<Long> workTicketSignUserIdList = workTicketSignOptionDTO.getWorkTicketSignUserIdList();
                if (!CollectionUtils.isEmpty(workTicketSignUserIdList)) {
                    for (Long userId : workTicketSignUserIdList) {
                        WorkTicketSignOptionUser workTicketSignOptionUser = new WorkTicketSignOptionUser();
                        workTicketSignOptionUser.setWorkSignOptionId(workTicketSignOption.getId());
                        if (WorkTicketSignOptionUserTypeEnum.POST.getValue().equals(workTicketSignOptionDTO.getWorkTicketSignType())) {
                            workTicketSignOptionUser.setWorkSignOptionPostId(userId);
                        } else {
                            workTicketSignOptionUser.setWorkSignOptionUserId(userId);
                        }
                        workTicketSignOptionUser.setCreateDefault();
                        workTicketSignOptionUserMapper.insert(workTicketSignOptionUser);
                    }
                }
            }
        }
        return count;
    }

    /**
     * 批量删除作业票签字模板
     *
     * @param ids 需要删除的作业票签字模板主键
     * @return 结果
     */
    @Override
    public int deleteWorkTicketSignatureTemplateByIds(Long[] ids) {
        //先删除模板数据
        WorkTicketSignatureTemplate workTicketSignatureTemplate = new WorkTicketSignatureTemplate();
        workTicketSignatureTemplate.setUpdateDefault();
        workTicketSignatureTemplate.setIsDel(DeletedEnum.INVALID.getValue());
        QueryWrapper<WorkTicketSignatureTemplate> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", ids);
        int count = workTicketSignatureTemplateMapper.update(workTicketSignatureTemplate, queryWrapper);
        //后删除签字项
        WorkTicketSignOption workTicketSignOption = new WorkTicketSignOption();
        workTicketSignOption.setUpdateDefault();
        workTicketSignOption.setIsDel(DeletedEnum.INVALID.getValue());
        QueryWrapper<WorkTicketSignOption> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.in("work_ticket_st_id", ids);
        workTicketSignOptionMapper.update(workTicketSignOption, queryWrapper2);
        return count;
    }


}
