package com.crm.manager.service.impl;

import com.crm.manager.dao.mapper.SalesPerformanceInfoMapper;
import com.crm.manager.service.SalesPerformanceExcelService;
import com.crm.manager.service.SalesPerformanceInfoService;
import com.crm.manager.service.UserInfoService;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.dto.base.BaseResultWithPagerDto;
import com.crm.rely.backend.core.dto.base.PageDto;
import com.crm.rely.backend.core.dto.sales.SalesPerformanceInfoDto;
import com.crm.rely.backend.core.entity.custom.info.InfoEntity;
import com.crm.rely.backend.core.entity.sales.SalesPerformanceInfoSearchEntity;
import com.crm.rely.backend.core.enums.SalesType;
import com.crm.rely.backend.core.pojo.table.SalesPerformanceInfoTable;
import com.crm.rely.backend.core.pojo.table.UserInfoTable;
import com.crm.rely.backend.exception.ServiceException;
import com.crm.rely.backend.util.FileProcessUtil;
import com.crm.rely.backend.util.FormatPage;
import com.crm.rely.backend.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class SalesPerformanceInfoServiceImpl implements SalesPerformanceInfoService {

    @Value("${web.export-path}")
    private String exportPath;

    @Autowired
    private SalesPerformanceInfoMapper salesPerformanceInfoMapper;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private SalesPerformanceExcelService salesPerformanceExcelService;

    @Override
    public SalesPerformanceInfoDto searchById(Long id, InfoEntity infoEntity) throws ServiceException {
        SalesPerformanceInfoTable table = salesPerformanceInfoMapper.getById(id);
        if (table == null) throw ServiceException.exception(Constants.INFO_NOT_FOUND);

        UserInfoTable userInfoTable = userInfoService.getDataById(table.getSalesId());
        if (userInfoTable == null) throw ServiceException.exception(Constants.INFO_NOT_FOUND);

        if (!userInfoTable.getStamp().startsWith(infoEntity.getIbInfo().getStamp())) {
            throw ServiceException.exception(Constants.NOT_PERMIT);
        }

        return convertTableToDto(table);
    }

    @Override
    public BaseResultWithPagerDto<List<SalesPerformanceInfoDto>> searchList(SalesPerformanceInfoSearchEntity entity) throws ServiceException {
        Integer count = salesPerformanceInfoMapper.countSearch(entity);
        PageDto pageDto = FormatPage.format(entity.getPage(), count);
        if (count == null || count == 0) {
            return new BaseResultWithPagerDto(Constants.SUCCESS_CODE, Constants.SEARCH_SUCCESS, pageDto);
        }

        List<SalesPerformanceInfoTable> tables = salesPerformanceInfoMapper.listSearch(entity);
        List<SalesPerformanceInfoDto> dtos = convertTablesToDtos(tables);

        return new BaseResultWithPagerDto(Constants.SUCCESS_CODE, Constants.SEARCH_SUCCESS, pageDto, dtos);
    }

    @Override
    public String export(SalesPerformanceInfoSearchEntity entity) throws ServiceException {
        try {
            entity.setPage(null);
            List<SalesPerformanceInfoTable> tables = salesPerformanceInfoMapper.listSearch(entity);
            if (CollectionUtils.isEmpty(tables)) return null;
            List<String> exportFiles = Lists.newArrayList();
            for (SalesPerformanceInfoTable table : tables) {
                exportFiles.add(salesPerformanceExcelService.createExcelByPerformanceInfo(table));
            }

            //压缩文件
            String zipFileName = generateZipFileName(entity);
            String zipFilePath = exportPath + File.separator + zipFileName;
            FileProcessUtil.deleteFiles(Arrays.asList(zipFilePath));
            FileProcessUtil.zipFiles(exportPath, exportFiles, zipFilePath);
            //删除导出excel文件
            List<String> deleteFiles = Lists.newArrayList();
            for (String exportFile : exportFiles) {
                deleteFiles.add(exportPath + File.separator + exportFile);
            }
            FileProcessUtil.deleteFiles(deleteFiles);
            return zipFileName;
        } catch (Exception e) {
            log.error(e.getMessage());
            throw ServiceException.exception(e.getMessage());
        }
    }

    private String generateZipFileName(SalesPerformanceInfoSearchEntity entity) {
        StringBuffer sb = new StringBuffer();
        sb.append(new SimpleDateFormat("yyyyMMdd").format(new Date()));
        sb.append("_");
        sb.append(StringUtils.isEmpty(entity.getYm()) ? "" : entity.getYm());
        sb.append(StringUtils.isEmpty(entity.getSaleNo()) ? "" : entity.getSaleNo());
        sb.append(StringUtils.isEmpty(entity.getSalesName()) ? "" : entity.getSalesName());
        sb.append(entity.getSalesType() == null ? "" : String.valueOf(entity.getSalesType()));
        sb.append(".zip");
        return sb.toString();
    }


    private List<SalesPerformanceInfoDto> convertTablesToDtos(List<SalesPerformanceInfoTable> tables) {
        List<SalesPerformanceInfoDto> dtos = Lists.newArrayList();
        for (SalesPerformanceInfoTable table : tables) {
            dtos.add(convertTableToDto(table));
        }
        return dtos;
    }

    private SalesPerformanceInfoDto convertTableToDto(SalesPerformanceInfoTable table) {
        SalesPerformanceInfoDto dto = SalesPerformanceInfoDto.getInstance();
        BeanUtils.copyProperties(table, dto);
        dto.setSalesTypeName(SalesType.matchCode(dto.getSalesType()).getDesc());
        return dto;
    }
}
