package com.yc.ship.module.resource.service.company;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.yc.ship.framework.common.pojo.PageResult;
import com.yc.ship.framework.common.util.object.BeanUtils;
import com.yc.ship.module.resource.controller.admin.company.vo.CompanyPageReqVO;
import com.yc.ship.module.resource.controller.admin.company.vo.CompanySaveReqVO;
import com.yc.ship.module.resource.controller.admin.vo.SimpleListReqVO;
import com.yc.ship.module.resource.dal.dataobject.company.CompanyDO;
import com.yc.ship.module.resource.dal.mysql.company.CompanyMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;

import static com.yc.ship.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.yc.ship.module.resource.enums.ErrorCodeConstants.COMPANY_NOT_EXISTS;


/**
 * 供应商 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class CompanyServiceImpl implements CompanyService {

    @Resource
    private CompanyMapper companyMapper;


    @Override
    public String createCompany(CompanySaveReqVO createReqVO) {
        // 插入
        CompanyDO company = BeanUtils.toBean(createReqVO, CompanyDO.class);
        String id = IdWorker.getIdStr(company);
        company.setId(id);
        company.setDeleted(false);
        companyMapper.insert(company);
        // 返回
        return company.getId();
    }

    @Override
    @Transactional
    public void updateCompany(CompanySaveReqVO updateReqVO) {
        // 校验存在
        validateCompanyExists(updateReqVO.getId());
        // 更新
        CompanyDO updateObj = BeanUtils.toBean(updateReqVO, CompanyDO.class);
        companyMapper.updateById(updateObj);
    }

    @Override
    @Transactional
    public void deleteCompany(String id) {
        // 校验存在
        validateCompanyExists(id);
        // 删除
        companyMapper.deleteById(id);
    }

    private void validateCompanyExists(String id) {
        if (companyMapper.selectById(id) == null) {
            throw exception(COMPANY_NOT_EXISTS);
        }
    }

    @Override
    public CompanyDO getCompany(String id) {
        return companyMapper.selectById(id);
    }

    @Override
    public PageResult<CompanyDO> getCompanyPage(CompanyPageReqVO pageReqVO) {
        return companyMapper.selectPage(pageReqVO);
    }

    @Override
    public List<CompanyDO> getCompanyList(SimpleListReqVO listReqVO) {
        List<CompanyDO> list = companyMapper.selectList(listReqVO);
        list.sort(Comparator.comparing(CompanyDO::getUpdateTime));
        return list;
    }

}