package cn.estsh.i3plus.ext.mes.apiservice.serviceimpl.base.bu;

import cn.estsh.i3plus.ext.mes.api.base.IFileManageService;
import cn.estsh.i3plus.ext.mes.api.busi.bu.IMesTeamManagementIntroduceService;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesTeamManagementIntroduce;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesTeamManagementIntroduceExt;
import cn.estsh.i3plus.ext.mes.pojo.model.bu.MesTeamManagementIntroduceVo;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesTeamManagementIntroduceExtRepository;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesTeamManagementIntroduceRepository;
import cn.estsh.i3plus.ext.mes.pojo.sqlpack.MesExtHqlPack;
import cn.estsh.i3plus.ext.mes.pojo.util.ConvertBeanExt;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtConstWords;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.exception.ImppExceptionEnum;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.pojo.base.bean.DdlPackBean;
import cn.estsh.i3plus.pojo.base.bean.ListPager;
import cn.estsh.i3plus.pojo.base.common.Pager;
import cn.estsh.i3plus.pojo.base.common.PagerHelper;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.tool.DdlPreparedPack;
import cn.estsh.i3plus.pojo.mes.bean.MesFile;
import cn.estsh.i3plus.pojo.mes.repository.MesFileRepository;
import cn.estsh.i3plus.pojo.platform.bean.SysFile;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

@Slf4j
@Service
public class MesTeamManagementIntroduceService implements IMesTeamManagementIntroduceService {

    @Autowired
    private IFileManageService fileManageService;

    @Autowired
    private MesTeamManagementIntroduceRepository teamManagementIntroduceRepository;

    @Autowired
    private MesTeamManagementIntroduceExtRepository teamManagementIntroduceExtRepository;

    @Autowired
    private MesFileRepository fileRepository;

    /**
     * 团队管理介绍分页查询
     * @param teamManagementIntroduce
     * @param pager
     * @param organizeCode
     * @return
     */
    @Override
    public ListPager getTeamManagementIntroducePage(MesTeamManagementIntroduce teamManagementIntroduce, Pager pager, String organizeCode) {
        if (null == teamManagementIntroduce) {
            pager = PagerHelper.getPager(pager, teamManagementIntroduceExtRepository.listCount());
            return new ListPager(teamManagementIntroduceExtRepository.listPager(pager), pager);
        } else {
            DdlPackBean packBean = MesExtHqlPack.getTeamManagementIntroduceSelectQuery(teamManagementIntroduce, organizeCode);

            int count = teamManagementIntroduceExtRepository.findByHqlWhereCount(packBean);
            pager = PagerHelper.getPager(pager, count);
            DdlPreparedPack.getOrderByPack(new Object[]{CommonEnumUtil.ASC_OR_DESC.DESC.getValue()}, new String[]{MesExtConstWords.MODIFY_DATE_TIME}, packBean);
            List<MesTeamManagementIntroduceExt> teamManagementIntroduceList = teamManagementIntroduceExtRepository.findByHqlWherePage(packBean, pager);

            List<MesTeamManagementIntroduceVo> resultList = new ArrayList<>();

            teamManagementIntroduceList.forEach(t -> {
                MesTeamManagementIntroduceVo mesTeamManagementIntroduceVo = new MesTeamManagementIntroduceVo();
                mesTeamManagementIntroduceVo.setShiftPhotoUrl(t.getUrlShift());
                mesTeamManagementIntroduceVo.setTeamPhotoUrl(t.getUrlTeam());
                BeanUtils.copyProperties(t,mesTeamManagementIntroduceVo);
                resultList.add(mesTeamManagementIntroduceVo);
            });

            /*Map<String, List<MesTeamManagementIntroduceExt>> collect = teamManagementIntroduceList.stream().collect(Collectors.groupingBy(MesTeamManagementIntroduceExt::getWorkCenterCode));
            collect.forEach((k,v) -> {
                MesTeamManagementIntroduceVo mesTeamManagementIntroduceVo = new MesTeamManagementIntroduceVo();
                mesTeamManagementIntroduceVo.setWorkCenterCode(v.get(0).getWorkCenterCode());
                mesTeamManagementIntroduceVo.setTeamSlogan(v.get(0).getTeamSlogan());
                mesTeamManagementIntroduceVo.setTeamYearTarget(v.get(0).getTeamYearTarget());
                DdlPackBean packBeanPid = DdlPackBean.getDdlPackBean(organizeCode);
                DdlPreparedPack.getStringEqualPack(v.get(0).getWorkCenterCode(), MesExtConstWords.WORK_CENTER_CODE, packBeanPid);
                MesTeamManagementIntroduce byProperty = teamManagementIntroduceRepository.getByProperty(packBeanPid);
                mesTeamManagementIntroduceVo.setId(byProperty.getId());
                v.forEach(t -> {
                    if (t.getPhotoType().equals(MesExtEnumUtil.TEAM_MANAGEMENT_INTRODUCE_PHOTO_TYPE.SHIFT_PHOTO.getValue())){
                        mesTeamManagementIntroduceVo.setShiftPhotoUrl(t.getUrl());
                    }else if (t.getPhotoType().equals(MesExtEnumUtil.TEAM_MANAGEMENT_INTRODUCE_PHOTO_TYPE.TEAM_PHOTO.getValue())){
                        mesTeamManagementIntroduceVo.setTeamPhotoUrl(t.getUrl());
                    }
                });
                mesTeamManagementIntroduceVo.setCreateUser(v.get(0).getCreateUser());
                mesTeamManagementIntroduceVo.setCreateDatetime(v.get(0).getCreateDatetime());
                mesTeamManagementIntroduceVo.setModifyUser(v.get(0).getModifyUser());
                mesTeamManagementIntroduceVo.setModifyDatetime(v.get(0).getModifyDatetime());
                resultList.add(mesTeamManagementIntroduceVo);
            });*/

            resultList.sort(Comparator.comparing(MesTeamManagementIntroduceVo::getModifyDatetime, Comparator.nullsLast(Comparator.reverseOrder())));

            return new ListPager(resultList, pager);
        }
    }

    /**
     * 新增团队管理介绍
     * @param teamManagementIntroduce
     * @param organizeCode
     * @param userName
     */
    @Override
    public void insertTeamManagementIntroduce(MesTeamManagementIntroduce teamManagementIntroduce, MultipartFile file1, MultipartFile file2, String organizeCode, String userName) {

        checkRepeat(teamManagementIntroduce, organizeCode);

        MesTeamManagementIntroduceExt mesTeamManagementIntroduceExt1 = new MesTeamManagementIntroduceExt();
        mesTeamManagementIntroduceExt1.setWorkCenterCode(teamManagementIntroduce.getWorkCenterCode());
        mesTeamManagementIntroduceExt1.setTeamSlogan(teamManagementIntroduce.getTeamSlogan());
        mesTeamManagementIntroduceExt1.setTeamYearTarget(teamManagementIntroduce.getTeamYearTarget());

        if (null != file1){
            SysFile sysFile1 = fileManageService.uploadFile(file1);
            if (sysFile1.getFileTypeId() == null) {
                log.error("FastDFS上传文件出错：{}", "未在字典中定义该文件类型，无法上传成功，请先添加file_type字典");
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.IO_EXCEPTION_FILE.getCode())
                        .setErrorDetail("未在字典中定义该文件类型，无法上传成功，请先添加file_type字典")
                        .build();
            }

            MesFile f1 = new MesFile();
            f1.setOrganizeCode(organizeCode);
            f1.setFileName(sysFile1.getDfsFileName());
            f1.setFileUrl(sysFile1.getFilePath());
            f1.setFileSize(String.valueOf(sysFile1.getFileSize()));
            f1.setFileType(String.valueOf(sysFile1.getFileTypeName()));
            f1.setFileOriginName(sysFile1.getFileOriginalName());
            f1.setGroupName(sysFile1.getDfsGroupName());
            f1.setSyncTag(0);
            ConvertBean.serviceModelInitialize(f1, userName);
            MesFile fileInsert1 = fileRepository.insert(f1);
            mesTeamManagementIntroduceExt1.setFileIdShift(fileInsert1.getId());
            mesTeamManagementIntroduceExt1.setUrlShift(fileInsert1.getFileUrl());
            mesTeamManagementIntroduceExt1.setFileOriginNameShift(file1.getOriginalFilename());
            mesTeamManagementIntroduceExt1.setUploadDatetimeShift(TimeTool.getNowTime("yyyy-MM-dd HH:mm"));
        }
        if (null!= file2){
            SysFile sysFile2 = fileManageService.uploadFile(file2);
            if (sysFile2.getFileTypeId() == null) {
                log.error("FastDFS上传文件出错：{}", "未在字典中定义该文件类型，无法上传成功，请先添加file_type字典");
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.IO_EXCEPTION_FILE.getCode())
                        .setErrorDetail("未在字典中定义该文件类型，无法上传成功，请先添加file_type字典")
                        .build();
            }

            MesFile f2 = new MesFile();
            f2.setOrganizeCode(organizeCode);
            f2.setFileName(sysFile2.getDfsFileName());
            f2.setFileUrl(sysFile2.getFilePath());
            f2.setFileSize(String.valueOf(sysFile2.getFileSize()));
            f2.setFileType(String.valueOf(sysFile2.getFileTypeName()));
            f2.setFileOriginName(sysFile2.getFileOriginalName());
            f2.setGroupName(sysFile2.getDfsGroupName());
            f2.setSyncTag(0);
            ConvertBean.serviceModelInitialize(f2, userName);
            MesFile fileInsert2 = fileRepository.insert(f2);
            mesTeamManagementIntroduceExt1.setFileIdTeam(fileInsert2.getId());
            mesTeamManagementIntroduceExt1.setUrlTeam(fileInsert2.getFileUrl());
            mesTeamManagementIntroduceExt1.setFileOriginNameTeam(file2.getOriginalFilename());
            mesTeamManagementIntroduceExt1.setUploadDatetimeTeam(TimeTool.getNowTime("yyyy-MM-dd HH:mm"));
        }

        /*MesTeamManagementIntroduceExt mesTeamManagementIntroduceExt2 = new MesTeamManagementIntroduceExt();
        mesTeamManagementIntroduceExt2.setWorkCenterCode(teamManagementIntroduce.getWorkCenterCode());
        mesTeamManagementIntroduceExt2.setTeamSlogan(teamManagementIntroduce.getTeamSlogan());
        mesTeamManagementIntroduceExt2.setTeamYearTarget(teamManagementIntroduce.getTeamYearTarget());*/


        /*mesTeamManagementIntroduceExt2.setFileId(fileInsert2.getId());
        mesTeamManagementIntroduceExt2.setUrl(fileInsert2.getFileUrl());
        mesTeamManagementIntroduceExt2.setFileOriginName(file2.getOriginalFilename());
        mesTeamManagementIntroduceExt2.setPhotoType(MesExtEnumUtil.TEAM_MANAGEMENT_INTRODUCE_PHOTO_TYPE.TEAM_PHOTO.getValue());
        mesTeamManagementIntroduceExt2.setUploadDatetime(userName);
        mesTeamManagementIntroduceExt2.setOrganizeCode(organizeCode);
        mesTeamManagementIntroduceExt2.setId(insert.getId());
        ConvertBean.serviceModelInitialize(mesTeamManagementIntroduceExt2, userName);
        teamManagementIntroduceExtRepository.insert(mesTeamManagementIntroduceExt2);*/

        mesTeamManagementIntroduceExt1.setOrganizeCode(organizeCode);
        ConvertBean.serviceModelInitialize(mesTeamManagementIntroduceExt1, userName);
        new ConvertBeanExt(mesTeamManagementIntroduceExt1).convertBean(mesTeamManagementIntroduceExt1);
        teamManagementIntroduceExtRepository.insert(mesTeamManagementIntroduceExt1);
    }

    /**
     * 更新团队管理介绍
     * @param teamManagementIntroduce
     * @param organizeCode
     * @param userName
     */
    @Override
    public void updateTeamManagementIntroduce(MesTeamManagementIntroduce teamManagementIntroduce, MultipartFile file1, MultipartFile file2, String organizeCode, String userName) {

        DdlPackBean packBean = MesExtHqlPack.getTeamManagementIntroduceSelectQuery(teamManagementIntroduce, organizeCode);
        MesTeamManagementIntroduceExt teamManagementIntroduceExt = teamManagementIntroduceExtRepository.getByProperty(packBean);

        if (null != teamManagementIntroduceExt){

            teamManagementIntroduceExt.setTeamSlogan(teamManagementIntroduce.getTeamSlogan());
            teamManagementIntroduceExt.setTeamYearTarget(teamManagementIntroduce.getTeamYearTarget());
            ConvertBean.serviceModelUpdate(teamManagementIntroduceExt, userName);
            new ConvertBeanExt(teamManagementIntroduceExt).convertBean(teamManagementIntroduceExt);

            if (null != file1){
                SysFile sysFile1 = fileManageService.uploadFile(file1);
                if (sysFile1.getFileTypeId() == null) {
                    log.error("FastDFS上传文件出错：{}", "未在字典中定义该文件类型，无法上传成功，请先添加file_type字典");
                    throw ImppExceptionBuilder.newInstance()
                            .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                            .setErrorCode(ImppExceptionEnum.IO_EXCEPTION_FILE.getCode())
                            .setErrorDetail("未在字典中定义该文件类型，无法上传成功，请先添加file_type字典")
                            .build();
                }

                DdlPackBean packBeanFile = DdlPackBean.getDdlPackBean(organizeCode);
                DdlPreparedPack.getNumEqualPack(teamManagementIntroduceExt.getFileIdShift(),"id",packBeanFile);
                MesFile f1 = fileRepository.getByProperty(packBeanFile);

                f1.setOrganizeCode(organizeCode);
                f1.setFileName(sysFile1.getDfsFileName());
                f1.setFileUrl(sysFile1.getFilePath());
                f1.setFileSize(String.valueOf(sysFile1.getFileSize()));
                f1.setFileType(String.valueOf(sysFile1.getFileTypeName()));
                f1.setFileOriginName(sysFile1.getFileOriginalName());
                f1.setGroupName(sysFile1.getDfsGroupName());
                f1.setSyncTag(0);
                ConvertBean.serviceModelUpdate(f1, userName);
                fileRepository.update(f1);

                teamManagementIntroduceExt.setFileIdShift(f1.getId());
                teamManagementIntroduceExt.setUrlShift(f1.getFileUrl());
                teamManagementIntroduceExt.setFileOriginNameShift(file1.getOriginalFilename());
                teamManagementIntroduceExt.setUploadDatetimeShift(TimeTool.getNowTime("yyyy-MM-dd HH:mm"));

            }

            if (null != file2){
                SysFile sysFile2 = fileManageService.uploadFile(file2);
                if (sysFile2.getFileTypeId() == null) {
                    log.error("FastDFS上传文件出错：{}", "未在字典中定义该文件类型，无法上传成功，请先添加file_type字典");
                    throw ImppExceptionBuilder.newInstance()
                            .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                            .setErrorCode(ImppExceptionEnum.IO_EXCEPTION_FILE.getCode())
                            .setErrorDetail("未在字典中定义该文件类型，无法上传成功，请先添加file_type字典")
                            .build();
                }

                DdlPackBean packBeanFile = DdlPackBean.getDdlPackBean(organizeCode);
                DdlPreparedPack.getNumEqualPack(teamManagementIntroduceExt.getFileIdTeam(),"id",packBeanFile);
                MesFile f2 = fileRepository.getByProperty(packBeanFile);

                f2.setOrganizeCode(organizeCode);
                f2.setFileName(sysFile2.getDfsFileName());
                f2.setFileUrl(sysFile2.getFilePath());
                f2.setFileSize(String.valueOf(sysFile2.getFileSize()));
                f2.setFileType(String.valueOf(sysFile2.getFileTypeName()));
                f2.setFileOriginName(sysFile2.getFileOriginalName());
                f2.setGroupName(sysFile2.getDfsGroupName());
                f2.setSyncTag(0);
                ConvertBean.serviceModelUpdate(f2, userName);
                fileRepository.update(f2);

                teamManagementIntroduceExt.setFileIdTeam(f2.getId());
                teamManagementIntroduceExt.setUrlTeam(f2.getFileUrl());
                teamManagementIntroduceExt.setFileOriginNameTeam(file2.getOriginalFilename());
                teamManagementIntroduceExt.setUploadDatetimeTeam(TimeTool.getNowTime("yyyy-MM-dd HH:mm"));
            }

            teamManagementIntroduceExtRepository.update(teamManagementIntroduceExt);

        }


        /*teamManagementIntroduceExtList.forEach(t -> {
            if (t.getPhotoType().equals(MesExtEnumUtil.TEAM_MANAGEMENT_INTRODUCE_PHOTO_TYPE.SHIFT_PHOTO.getValue())){

                t.setPhotoType(MesExtEnumUtil.TEAM_MANAGEMENT_INTRODUCE_PHOTO_TYPE.SHIFT_PHOTO.getValue());
                t.setUploadDatetime(userName);
                t.setTeamSlogan(teamManagementIntroduce.getTeamSlogan());
                t.setTeamYearTarget(teamManagementIntroduce.getTeamYearTarget());
                ConvertBean.serviceModelUpdate(t, userName);

                if (null != file1){
                    SysFile sysFile1 = fileManageService.uploadFile(file1);
                    if (sysFile1.getFileTypeId() == null) {
                        log.error("FastDFS上传文件出错：{}", "未在字典中定义该文件类型，无法上传成功，请先添加file_type字典");
                        throw ImppExceptionBuilder.newInstance()
                                .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                                .setErrorCode(ImppExceptionEnum.IO_EXCEPTION_FILE.getCode())
                                .setErrorDetail("未在字典中定义该文件类型，无法上传成功，请先添加file_type字典")
                                .build();
                    }

                    DdlPackBean packBeanFile = DdlPackBean.getDdlPackBean(organizeCode);
                    DdlPreparedPack.getNumEqualPack(t.getFileId(),"id",packBeanFile);
                    MesFile f1 = fileRepository.getByProperty(packBeanFile);

                    f1.setOrganizeCode(organizeCode);
                    f1.setFileName(sysFile1.getDfsFileName());
                    f1.setFileUrl(sysFile1.getFilePath());
                    f1.setFileSize(String.valueOf(sysFile1.getFileSize()));
                    f1.setFileType(String.valueOf(sysFile1.getFileTypeName()));
                    f1.setFileOriginName(sysFile1.getFileOriginalName());
                    f1.setGroupName(sysFile1.getDfsGroupName());
                    f1.setSyncTag(0);
                    ConvertBean.serviceModelUpdate(f1, userName);
                    fileRepository.update(f1);

                    t.setFileId(f1.getId());
                    t.setUrl(f1.getFileUrl());
                    t.setFileOriginName(file1.getOriginalFilename());

                }
                teamManagementIntroduceExtRepository.update(t);

            }else if (t.getPhotoType().equals(MesExtEnumUtil.TEAM_MANAGEMENT_INTRODUCE_PHOTO_TYPE.TEAM_PHOTO.getValue())){

                t.setPhotoType(MesExtEnumUtil.TEAM_MANAGEMENT_INTRODUCE_PHOTO_TYPE.TEAM_PHOTO.getValue());
                t.setUploadDatetime(userName);
                t.setTeamSlogan(teamManagementIntroduce.getTeamSlogan());
                t.setTeamYearTarget(teamManagementIntroduce.getTeamYearTarget());
                ConvertBean.serviceModelUpdate(t, userName);

                if (null != file2){
                    SysFile sysFile2 = fileManageService.uploadFile(file2);
                    if (sysFile2.getFileTypeId() == null) {
                        log.error("FastDFS上传文件出错：{}", "未在字典中定义该文件类型，无法上传成功，请先添加file_type字典");
                        throw ImppExceptionBuilder.newInstance()
                                .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                                .setErrorCode(ImppExceptionEnum.IO_EXCEPTION_FILE.getCode())
                                .setErrorDetail("未在字典中定义该文件类型，无法上传成功，请先添加file_type字典")
                                .build();
                    }

                    DdlPackBean packBeanFile = DdlPackBean.getDdlPackBean(organizeCode);
                    DdlPreparedPack.getNumEqualPack(t.getFileId(),"id",packBeanFile);
                    MesFile f2 = fileRepository.getByProperty(packBeanFile);

                    f2.setOrganizeCode(organizeCode);
                    f2.setFileName(sysFile2.getDfsFileName());
                    f2.setFileUrl(sysFile2.getFilePath());
                    f2.setFileSize(String.valueOf(sysFile2.getFileSize()));
                    f2.setFileType(String.valueOf(sysFile2.getFileTypeName()));
                    f2.setFileOriginName(sysFile2.getFileOriginalName());
                    f2.setGroupName(sysFile2.getDfsGroupName());
                    f2.setSyncTag(0);
                    ConvertBean.serviceModelUpdate(f2, userName);
                    fileRepository.update(f2);

                    t.setFileId(f2.getId());
                    t.setUrl(f2.getFileUrl());
                    t.setFileOriginName(file2.getOriginalFilename());
                }

                teamManagementIntroduceExtRepository.update(t);
            }
        });*/
    }

    @Override
    public void updateTeamManagementIntroduceValid(MesTeamManagementIntroduce teamManagementIntroduce, String organizeCode, String userName) {
        teamManagementIntroduceRepository.updateValidStatusById(teamManagementIntroduce.getId(),teamManagementIntroduce.getIsValid(),userName);
    }

    private void checkRepeat(MesTeamManagementIntroduce teamManagementIntroduce, String organizeCode) {
        DdlPackBean packBean = MesExtHqlPack.getTeamManagementIntroduceSelectQuery(teamManagementIntroduce, organizeCode);
        MesTeamManagementIntroduce teamManagementIntroduceCheck = teamManagementIntroduceRepository.getByProperty(packBean);

        if (null != teamManagementIntroduceCheck) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("已存在相同团队管理介绍")
                    .build();
        }

        teamManagementIntroduce.setOrganizeCode(organizeCode);
    }

}
