package com.crm.manager.service.impl;

import com.crm.manager.dao.mapper.MarketExtensionMapper;
import com.crm.manager.dao.repository.MarketExtensionRepository;
import com.crm.manager.service.MarketExtensionLinkService;
import com.crm.manager.service.MarketExtensionService;
import com.crm.manager.service.impl.base.BaseUploadServiceImpl;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.constant.CustomConstant;
import com.crm.rely.backend.core.dto.base.PageDto;
import com.crm.rely.backend.core.dto.base.ResultWithPagerDto;
import com.crm.rely.backend.core.dto.market.extension.MarketExtensionDto;
import com.crm.rely.backend.core.dto.market.extension.link.MarketExtensionLinkDto;
import com.crm.rely.backend.core.entity.market.extension.MarketExtensionAddEntity;
import com.crm.rely.backend.core.entity.market.extension.MarketExtensionDeleteEntity;
import com.crm.rely.backend.core.entity.market.extension.MarketExtensionSearchPageEntity;
import com.crm.rely.backend.core.entity.market.extension.MarketExtensionUpdateEntity;
import com.crm.rely.backend.core.pojo.table.MarketExtensionLinkTable;
import com.crm.rely.backend.core.pojo.table.MarketExtensionTable;
import com.crm.rely.backend.exception.ServiceException;
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 MarketExtensionServiceImpl extends BaseUploadServiceImpl implements MarketExtensionService {

    @Autowired
    private MarketExtensionRepository repository;

    @Autowired
    private MarketExtensionLinkService linkService;

    @Autowired
    private MarketExtensionMapper mapper;

    @Override
    public MarketExtensionTable getById(Long id) throws ServiceException {

        MarketExtensionTable table = repository.getFirstById(id);
        if (table == null) {
            throw new ServiceException(CustomConstant.ACTIVITY_NOT_EXIST_ERROR);
        }
        return table;
    }

    @Override
    public MarketExtensionDto searchSingle(Long id) throws ServiceException {
        MarketExtensionTable MarketExtensionTable = getById(id);

        if (MarketExtensionTable == null) {

            throw new ServiceException(Constants.SYSTEM_ERROR);
        }

        MarketExtensionDto marketExtensionDto = new MarketExtensionDto();
        BeanUtils.copyProperties(MarketExtensionTable, marketExtensionDto);

        List<MarketExtensionLinkDto> linkDtos = linkService.getByExtensionId(id);
        marketExtensionDto.setLinkDtos(linkDtos);

        return marketExtensionDto;
    }

    @Override
    public ResultWithPagerDto<MarketExtensionDto> pageSearchList(MarketExtensionSearchPageEntity entity) throws ServiceException {
        Integer count = mapper.countList(entity);
        PageDto pageDto = PageDto.format(entity, count);
        if (count == null || count <= 0) {
            return ResultWithPagerDto.success(pageDto);
        }
        List<MarketExtensionTable> tables = mapper.pageList(entity);

        if (tables == null || tables.size() <= 0) {

            throw new ServiceException(Constants.SYSTEM_ERROR);
        }
        List<MarketExtensionDto> dtos = new ArrayList<>(tables.size());
        List<Long> ids = new ArrayList<>(tables.size());
        for (MarketExtensionTable table : tables) {
            MarketExtensionDto MarketExtensionDto = new MarketExtensionDto();
            BeanUtils.copyProperties(table, MarketExtensionDto);
            dtos.add(MarketExtensionDto);
            ids.add(table.getId());
        }

        setLinks(dtos, ids);
        return ResultWithPagerDto.success(pageDto, dtos);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(MarketExtensionAddEntity entity) throws ServiceException {

        MarketExtensionTable table = new MarketExtensionTable();
        BeanUtils.copyProperties(entity, table);
        repository.save(table);

        linkService.save(entity.getDetail(), table);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(MarketExtensionUpdateEntity entity) throws ServiceException {
        MarketExtensionTable table = repository.findFirstById(entity.getId());
        if (table == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }

        BeanUtils.copyProperties(entity, table);

        repository.save(table);

        linkService.save(entity.getDetail(), table);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(MarketExtensionDeleteEntity entity) throws ServiceException {
        List<MarketExtensionTable> MarketExtensionRepositoryAllByIdIn = repository.findAllByIdIn(entity.getIds());
        if (MarketExtensionRepositoryAllByIdIn == null) {
            throw ServiceException.exception(Constants.INFO_NOT_FOUND);
        }

        repository.delete(MarketExtensionRepositoryAllByIdIn);

        linkService.delete(entity.getIds());
    }

    @Override
    public String uploadFile(MultipartFile file) throws Exception {
        String middlePath = "/market/extension";
        String path = saveFile(middlePath, file);

        return path;
    }


    private void setLinks(List<MarketExtensionDto> dtos, List<Long> extensionId) throws ServiceException {
        if (dtos == null || dtos.size() <= 0 || extensionId == null || extensionId.size() <= 0) {
            return;
        }
        List<MarketExtensionLinkTable> tables = linkService.getByExtensionIdIn(extensionId);
        if (tables == null || tables.size() <= 0) {
            return;
        }
        for (MarketExtensionDto marketExtensionDto : dtos) {

            int size = tables.size();
            List<MarketExtensionLinkDto> linkDtos = new ArrayList<>();
            for (int i = 0; i < size; ) {
                MarketExtensionLinkTable MarketExtensionTagTable = tables.get(i);
                if (marketExtensionDto.getId() != null && marketExtensionDto.getId().equals(MarketExtensionTagTable.getExtensionId())) {
                    MarketExtensionLinkDto dto = new MarketExtensionLinkDto();
                    dto.setId(MarketExtensionTagTable.getId());
                    dto.setLink(MarketExtensionTagTable.getLink());
                    dto.setSourceNameEn(MarketExtensionTagTable.getSourceNameEn());
                    dto.setSourceName(MarketExtensionTagTable.getSourceName());
                    dto.setSourceCode(MarketExtensionTagTable.getSourceCode());
                    dto.setExtensionId(MarketExtensionTagTable.getExtensionId());

                    linkDtos.add(dto);
                    size--;
                    tables.remove(MarketExtensionTagTable);
                } else {
                    i++;
                }
            }
            if (linkDtos != null && linkDtos.size() > 0) {
                marketExtensionDto.setLinkDtos(linkDtos);
            }
        }
    }
}
