package com.crm.manager.service.impl;

import com.crm.manager.dao.mapper.SalesCommissionManualMapper;
import com.crm.manager.service.SalesCommissionManualService;
import com.crm.manager.service.SalesCommissionRecordService;
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.SalesCommissionManualDto;
import com.crm.rely.backend.core.dto.sales.SalesCommissionManualSalaryTypeDto;
import com.crm.rely.backend.core.entity.sales.SalesCommissionManualAddEntity;
import com.crm.rely.backend.core.entity.sales.SalesCommissionManualListEntity;
import com.crm.rely.backend.core.entity.sales.SalesCommissionManualUpdateEntity;
import com.crm.rely.backend.core.enums.SalesCommissionManualType;
import com.crm.rely.backend.core.pojo.table.SalesCommissionManualTable;
import com.crm.rely.backend.core.pojo.table.SalesCommissionRecordTable;
import com.crm.rely.backend.core.pojo.table.UserInfoTable;
import com.crm.rely.backend.exception.ServiceException;
import com.crm.rely.backend.util.BeanUtilPlus;
import com.crm.rely.backend.util.FormatPage;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.util.CollectionUtils;

import java.util.List;
import java.util.Optional;

@Service
public class SalesCommissionManualServiceImpl implements SalesCommissionManualService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SalesCommissionManualMapper salesCommissionManualMapper;
    @Autowired
    private UserInfoService userInfoService;

    @Override
    public List<SalesCommissionManualSalaryTypeDto> getSalesCommissionManualSalaryTypes() throws ServiceException {

        List<SalesCommissionManualSalaryTypeDto> dtos = Lists.newArrayList();
        for (SalesCommissionManualType value : SalesCommissionManualType.values()) {
            SalesCommissionManualSalaryTypeDto dto = new SalesCommissionManualSalaryTypeDto();
            dto.setId(value.getCode());
            dto.setName(value.getDesc());
            dtos.add(dto);
        }

        return dtos;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveForm(SalesCommissionManualAddEntity entity) throws ServiceException {
        try {
            UserInfoTable userInfoTable = userInfoService.getDataById(entity.getSalesId());
            if (userInfoTable == null) {
                throw new ServiceException(Constants.INFO_NOT_FOUND);
            }

            Integer count = Optional.ofNullable(salesCommissionManualMapper.countBySalesIdAndYm(entity.getSalesId(), entity.getYm())).orElse(0);
            if (count >= 1) {
                throw new ServiceException(Constants.RECORD_EXISTS);
            }
            /*
                保存信息
             */
            SalesCommissionManualTable table = SalesCommissionManualTable.getInstance();
            BeanUtilPlus.copyPropertiesIgnoreNull(entity, table);
            table.setSalesNo(userInfoTable.getIbNo());
            salesCommissionManualMapper.save(table);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw ServiceException.exception(e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateForm(SalesCommissionManualUpdateEntity entity) throws ServiceException {
        try {
            //获取原数据
            SalesCommissionManualTable oldTable = salesCommissionManualMapper.findOne(entity.getId());
            if (oldTable == null) {
                throw new ServiceException(Constants.INFO_NOT_FOUND);
            }

            if (!oldTable.getSalesId().equals(entity.getSalesId())) {
                Integer count = Optional.ofNullable(salesCommissionManualMapper.countBySalesIdAndYm(entity.getSalesId(), entity.getYm())).orElse(0);
                if (count >= 1) {
                    throw new ServiceException(Constants.RECORD_EXISTS);
                }
            }

            //获取销售信息
            UserInfoTable userInfoTable = userInfoService.getDataById(entity.getSalesId());
            if (userInfoTable == null) {
                throw new ServiceException(Constants.INFO_NOT_FOUND);
            }
            //保存记录
            BeanUtilPlus.copyPropertiesIgnoreNull(entity, oldTable);
            oldTable.setSalesNo(userInfoTable.getIbNo());
            salesCommissionManualMapper.updateById(oldTable);

        } catch (Exception e) {
            logger.error(e.getMessage());
            throw ServiceException.exception(e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(Long id) throws ServiceException {
        try {
            //获取原数据
            SalesCommissionManualTable oldTable = salesCommissionManualMapper.findOne(id);
            if (oldTable == null) {
                throw new ServiceException(Constants.INFO_NOT_FOUND);
            }
            //删除记录
            salesCommissionManualMapper.removeById(oldTable.getId());

        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            throw ServiceException.exception(e.getMessage());
        }
    }

    @Override
    public SalesCommissionManualDto searchSingle(Long id) throws ServiceException {
        try {
            //获取原数据
            SalesCommissionManualTable oldTable = salesCommissionManualMapper.findOne(id);
            if (oldTable == null) {
                throw new ServiceException(Constants.INFO_NOT_FOUND);
            }
            return convertToDto(oldTable);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw ServiceException.exception(e.getMessage());
        }
    }

    @Override
    public BaseResultWithPagerDto<List<SalesCommissionManualDto>> searchList(SalesCommissionManualListEntity entity) throws ServiceException {
        try {
            Integer count = salesCommissionManualMapper.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<SalesCommissionManualDto> dtos = convertToDtoList(salesCommissionManualMapper.listSearch(entity));
            return new BaseResultWithPagerDto<>(Constants.SUCCESS_CODE, Constants.SEARCH_SUCCESS, pageDto, dtos);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw ServiceException.exception(e.getMessage());
        }
    }

    private SalesCommissionManualDto convertToDto(SalesCommissionManualTable salesCommissionManualTable) {
        SalesCommissionManualDto dto = new SalesCommissionManualDto();
        BeanUtils.copyProperties(salesCommissionManualTable, dto);
        return dto;
    }

    private List<SalesCommissionManualDto> convertToDtoList(List<SalesCommissionManualTable> salesCommissionManualTables) {
        if (CollectionUtils.isEmpty(salesCommissionManualTables)) return Lists.newArrayList();
        List<SalesCommissionManualDto> dtos = Lists.newArrayList();
        for (SalesCommissionManualTable table : salesCommissionManualTables) {
            SalesCommissionManualDto dto = convertToDto(table);
            dtos.add(dto);
        }
        return dtos;
    }
}
