package com.crm.custom.service.impl;

import com.crm.custom.dao.repository.CustomFileRepository;
import com.crm.custom.service.CustomFileHistoryService;
import com.crm.custom.service.CustomFileService;
import com.crm.custom.service.CustomInfoService;
import com.crm.custom.service.impl.base.BaseUploadServiceImpl;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.constant.StatusConstants;
import com.crm.rely.backend.core.dto.custom.file.CustomFileDto;
import com.crm.rely.backend.core.pojo.table.CustomFileTable;
import com.crm.rely.backend.core.exception.ServiceException;
import com.crm.rely.backend.model.entity.custom.file.CustomFileAddAndUpdateEntity;
import com.crm.rely.backend.model.entity.custom.file.CustomFileAllEntity;
import com.crm.rely.backend.model.entity.custom.file.CustomFileApproveEntity;
import com.crm.rely.backend.model.entity.custom.file.CustomFileDeleteEntity;
import com.crm.rely.backend.model.entity.custom.file.history.CustomFileHistoryAddEntity;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

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

@Service
public class CustomFileServiceImpl extends BaseUploadServiceImpl implements CustomFileService {

    @Autowired
    private CustomFileRepository customFileRepository;
    @Autowired
    private CustomInfoService customInfoService;

    @Autowired
    private CustomFileHistoryService customFileHistoryService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public CustomFileDto save(CustomFileAddAndUpdateEntity entity, MultipartFile file) throws Exception {


        CustomFileTable customFileTable = null;
        if (entity.getId() != null) {
            customFileTable = customFileRepository.findFirstById(entity.getId());
            if (customFileTable == null) {
                throw new ServiceException(Constants.SELECT_ROW);
            }

        } else {
            if (!entity.getType().equals(10)) {
                customFileTable = customFileRepository.findFirstByCustomIdAndType(entity.getCustomId(), entity.getType());
            }
        }
        if (customFileTable != null) {
            if (!entity.getType().equals(customFileTable.getType())) {
                throw new ServiceException(Constants.SYSTEM_ERROR);
            }
            if (entity.getUploadUserType() == null || entity.getUploadUserType().equals(1)) {
                if (customFileTable.getStatus().equals(StatusConstants.PASSED_STATUS)) {
                    throw new ServiceException(Constants.NOT_PERMIT);
                }
            }
            customFileTable.setAddTime(entity.getTime());
            customFileTable.setModifyIp(entity.getIp());
            customFileTable.setModifyTime(entity.getTime());
            customFileTable.setModifyUser(entity.getUser());
        }
        String middlePath = (entity.getCustomId() == null ? "" : entity.getCustomId().toString()) + "/" + "info";
        String path = saveFile(middlePath, file);

        if (customFileTable == null) {
            customFileTable = new CustomFileTable();
            customFileTable.setAddIp(entity.getIp());
            customFileTable.setAddTime(entity.getTime());
            customFileTable.setAddUser(entity.getUser());
            customFileTable.setType(entity.getType());
            customFileTable.setCustomId(entity.getCustomId());
            if (entity.getUploadUserType() == null || entity.getUploadUserType().equals(1)) {
                customFileTable.setStatus(StatusConstants.APPLY_STATUS);
            } else {
                customFileTable.setStatus(StatusConstants.PASSED_STATUS);
            }

            customFileTable.setPath(path);
        } else {
            if (customFileTable.getStatus().equals(StatusConstants.UPLOAD_STATUS)) {
                customFileTable.setAgainPath(path);
            } else {
                customFileTable.setPath(path);
            }
        }

        customFileRepository.save(customFileTable);
        CustomFileDto customFileDto = new CustomFileDto();
        BeanUtils.copyProperties(customFileTable, customFileDto);

        //验证资料完整
//        customInfoService.checkAndSaveCompleteById(entity.getCustomId());

        return customFileDto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(CustomFileDeleteEntity entity) throws ServiceException {
        List<CustomFileTable> customFileTables = customFileRepository.findAllByIdInAndCustomId(entity.getIds(), entity.getCustomId());

        if (customFileTables == null || customFileTables.size() <= 0) {
            return;
        }
        for (CustomFileTable customFileTable : customFileTables) {
            //文件类型不是10 或者文件已经审核通过的 不允许删除
            if (!customFileTable.getType().equals(10) || StatusConstants.PASSED_STATUS.equals(customFileTable.getStatus())) {
                throw ServiceException.exception(Constants.NOT_PERMIT);
            }
        }
        customFileRepository.delete(customFileTables);
    }


    @Override
    public List<CustomFileDto> getAllFiles(CustomFileAllEntity entity) throws ServiceException {

        return getAllFiles(entity.getCustomId());
    }

    @Override
    public List<CustomFileDto> getAllFiles(Long customId) throws ServiceException {
        List<CustomFileTable> customFileTables = customFileRepository.getAllByCustomIdOrderByType(customId);

        if (customFileTables == null || customFileTables.size() <= 0) {
            return null;
        }

        List<CustomFileDto> customFileDtos = new ArrayList<>(customFileTables.size());
        for (CustomFileTable customFileTable : customFileTables) {
            CustomFileDto customFileDto = new CustomFileDto();
            BeanUtils.copyProperties(customFileTable, customFileDto);
//            if (customFileTable.getModifyTime() == null) {
//                customFileDto.setUploadTime(customFileTable.getAddTime());
//            } else {
//                customFileDto.setUploadTime(customFileTable.getModifyTime());
//            }
            customFileDto.setUploadTime(customFileTable.getAddTime());
            customFileDtos.add(customFileDto);
        }
        return customFileDtos;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void approve(CustomFileApproveEntity entity) throws ServiceException {
        CustomFileTable customFileTable = customFileRepository.findFirstByCustomIdAndId(entity.getCustomId(), entity.getId());

        if (customFileTable == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }
        if (!StatusConstants.UPLOAD_STATUS.equals(entity.getStatus())) {
            if (customFileTable.getStatus() != null && StatusConstants.PASSED_STATUS.equals(customFileTable.getStatus())) {
                throw ServiceException.exception(Constants.NOT_PERMIT);
            }
        }


        if (customFileTable.getStatus().equals(StatusConstants.UPLOAD_STATUS) && StatusConstants.PASSED_STATUS.equals(customFileTable.getStatus())) {
            customFileTable.setPath(customFileTable.getAgainPath());
            customFileTable.setAgainPath(null);
        }

        BeanUtils.copyProperties(entity, customFileTable);

        if (StatusConstants.PASSED_STATUS.equals(entity.getStatus())) {
            CustomFileHistoryAddEntity customFileHistoryAddEntity = new CustomFileHistoryAddEntity();

            BeanUtils.copyProperties(customFileTable, customFileHistoryAddEntity);
            customFileHistoryService.add(customFileHistoryAddEntity);
        }

        customFileRepository.save(customFileTable);
    }


}
