package cn.iocoder.foodnexus.module.erp.service.sale;

import cn.iocoder.foodnexus.framework.common.enums.CommonStatusEnum;
import cn.iocoder.foodnexus.framework.common.exception.ServiceException;
import cn.iocoder.foodnexus.framework.common.pojo.PageResult;
import cn.iocoder.foodnexus.framework.common.util.CommonUtil;
import cn.iocoder.foodnexus.framework.common.util.object.BeanUtils;
import cn.iocoder.foodnexus.module.erp.api.service.ErpCustomerApi;
import cn.iocoder.foodnexus.module.erp.api.vo.customer.CustomerAddReqVO;
import cn.iocoder.foodnexus.module.erp.controller.admin.customerwarehouse.vo.CustomerWarehouseSaveReqVO;
import cn.iocoder.foodnexus.module.erp.controller.admin.sale.vo.customer.ErpCustomerPageReqVO;
import cn.iocoder.foodnexus.module.erp.controller.admin.sale.vo.customer.ErpCustomerSaveReqVO;
import cn.iocoder.foodnexus.module.erp.dal.dataobject.customerwarehouse.CustomerWarehouseDO;
import cn.iocoder.foodnexus.module.erp.dal.dataobject.sale.ErpCustomerDO;
import cn.iocoder.foodnexus.module.erp.dal.dataobject.stock.ErpWarehouseDO;
import cn.iocoder.foodnexus.module.erp.dal.mysql.sale.ErpCustomerMapper;
import cn.iocoder.foodnexus.module.erp.service.customerwarehouse.CustomerWarehouseService;
import cn.iocoder.foodnexus.module.erp.service.stock.ErpWarehouseService;
import cn.iocoder.foodnexus.module.system.dal.dataobject.dept.DeptDO;
import cn.iocoder.foodnexus.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.foodnexus.framework.common.enums.UserSystemEnum;
import cn.iocoder.foodnexus.module.system.service.dept.DeptService;
import cn.iocoder.foodnexus.module.system.service.user.AdminUserService;
import com.google.common.collect.Maps;
import jakarta.annotation.Resource;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import static cn.iocoder.foodnexus.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.foodnexus.module.erp.enums.ErrorCodeConstants.*;

/**
 * ERP 客户 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class ErpCustomerServiceImpl implements ErpCustomerService, ErpCustomerApi {

    @Resource
    private ErpCustomerMapper customerMapper;

    @Autowired
    private ErpWarehouseService warehouseService;

    @Autowired
    private CustomerWarehouseService customerWarehouseService;

    @Autowired
    @Lazy
    private AdminUserService userService;

    @Autowired
    @Lazy
    private DeptService deptService;

    @Override
    public Long createCustomer(ErpCustomerSaveReqVO createReqVO) {
        // 插入
        ErpCustomerDO customer = BeanUtils.toBean(createReqVO, ErpCustomerDO.class);
        customerMapper.insert(customer);
        // 返回
        return customer.getId();
    }

    @Override
    public void updateCustomer(ErpCustomerSaveReqVO updateReqVO) {
        // 校验存在
        validateCustomerExists(updateReqVO.getId());
        // 更新
        ErpCustomerDO updateObj = BeanUtils.toBean(updateReqVO, ErpCustomerDO.class);
        customerMapper.updateById(updateObj);
    }

    @Override
    public void deleteCustomer(Long id) {
        // 校验存在
        validateCustomerExists(id);
        // 删除
        customerMapper.deleteById(id);
    }

    private void validateCustomerExists(Long id) {
        if (customerMapper.selectById(id) == null) {
            throw exception(CUSTOMER_NOT_EXISTS);
        }
    }

    @Override
    public ErpCustomerDO getCustomer(Long id) {
        return customerMapper.selectById(id);
    }

    @Override
    public ErpCustomerDO validateCustomer(Long id) {
        ErpCustomerDO customer = customerMapper.selectById(id);
        if (customer == null) {
            throw exception(CUSTOMER_NOT_EXISTS);
        }
        if (CommonStatusEnum.isDisable(customer.getStatus())) {
            throw exception(CUSTOMER_NOT_ENABLE, customer.getName());
        }
        return customer;
    }

    @Override
    public List<ErpCustomerDO> getCustomerList(Collection<Long> ids) {
        if (CommonUtil.isEmpty(ids)) {
            return Lists.newArrayList();
        }
        return customerMapper.selectByIds(ids);
    }

    @Override
    public PageResult<ErpCustomerDO> getCustomerPage(ErpCustomerPageReqVO pageReqVO) {
        return customerMapper.selectPage(pageReqVO);
    }

    @Override
    public List<ErpCustomerDO> getCustomerListByStatus(Integer status) {
        return customerMapper.selectListByStatus(status);
    }

    /**
     * 客户绑定仓库(库区)
     *
     * @param id
     * @param warehouseAreaId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void bindWarehouse(Long id, Long warehouseAreaId) {
        this.validateCustomer(id);
        ErpWarehouseDO warehouseArea = warehouseService.getWarehouse(warehouseAreaId);
        Optional.ofNullable(warehouseArea).orElseThrow(() -> new ServiceException(WAREHOUSE_NOT_EXISTS));
        ErpWarehouseDO warehouse = warehouseService.getWarehouse(warehouseArea.getParentId());
        Optional.ofNullable(warehouse).orElseThrow(() -> new ServiceException(WAREHOUSE_NOT_EXISTS));

        customerWarehouseService.deleteByCustomerId(id);

        CustomerWarehouseSaveReqVO saveReqVO = new CustomerWarehouseSaveReqVO();
        saveReqVO.setCustomerId(id);
        saveReqVO.setWarehouseId(warehouse.getId());
        saveReqVO.setWarehouseAreaId(warehouseArea.getId());
        customerWarehouseService.createCustomerWarehouse(saveReqVO);
    }

    /**
     * 客户解绑仓库
     *
     * @param id
     */
    @Override
    public void bindWarehouseRelease(Long id) {
        this.validateCustomer(id);
        customerWarehouseService.deleteByCustomerId(id);
    }

    /**
     * 根据客户id返回对应绑定的库区id
     *
     * @param id
     * @return
     */
    @Override
    public Long queryWarehouseAreaIdByCustomerId(Long id) {
        return Optional.ofNullable(customerWarehouseService.getCustomerWarehouseByCustomerId(id)).map(CustomerWarehouseDO::getWarehouseAreaId).orElse(null);
    }


    /* --------------- api --------------- */
    @Override
    public void createByDept(Long deptId, CustomerAddReqVO customerAddReqVO) {
        this.createCustomer(BeanUtils.toBean(customerAddReqVO, ErpCustomerSaveReqVO.class, item ->
                item.setSystemDeptId(deptId)));
    }

    @Override
    public void updateByDept(Long deptId, CustomerAddReqVO customerAddReqVO) {
        ErpCustomerDO customer = customerMapper.selectOne(ErpCustomerDO::getSystemDeptId, deptId);
        if (CommonUtil.isEmpty(customer)) {
            this.createCustomer(BeanUtils.toBean(customerAddReqVO, ErpCustomerSaveReqVO.class, item ->
                    item.setSystemDeptId(deptId)));
        } else {
            this.updateCustomer(BeanUtils.toBean(customerAddReqVO, ErpCustomerSaveReqVO.class, item ->{
                item.setSystemDeptId(deptId);
                item.setId(customer.getId());
            }));
        }
    }

    @Override
    public void deleteByDept(Long deptId) {
        customerMapper.delete(ErpCustomerDO::getSystemDeptId, deptId);
    }

    @Override
    public Long queryCustomerIdByUserId(Long userId) {
        AdminUserDO user = userService.getUser(userId);
        if (!UserSystemEnum.CUSTOMER.getKey().equals(user.getUserSystem())) {
            throw exception(ERROR_CUSTOMER_USER);
        }
        DeptDO topDept = deptService.getTopDept(user.getDeptId());
        ErpCustomerDO customer = customerMapper.selectOne(ErpCustomerDO::getSystemDeptId, topDept.getId());
        if (CommonUtil.isEmpty(customer)) {
            throw exception(CUSTOMER_NOT_EXISTS);
        }
        if (CommonStatusEnum.isDisable(customer.getStatus())) {
            throw exception(CUSTOMER_NOT_ENABLE, customer.getName());
        }
        return customer.getId();
    }

    @Override
    public Map<Long, String> queryNameMapByIds(Collection<Long> collection) {
        if (CommonUtil.isEmpty(collection)) {
            return Maps.newHashMap();
        }
        List<ErpCustomerDO> customers = customerMapper.selectByIds(collection);
        return CommonUtil.listConvertMap(customers, ErpCustomerDO::getId, ErpCustomerDO::getName);
    }
}
