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

import cn.hutool.core.lang.Pair;
import cn.hutool.extra.spring.SpringUtil;
import cn.iocoder.foodnexus.framework.common.enums.CommonStatusEnum;
import cn.iocoder.foodnexus.framework.common.enums.CustomerTypeEnum;
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.framework.common.util.spring.SpringUtils;
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.api.vo.customer.DeptSimpleDTO;
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.dal.redis.RedisKeyConstants;
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.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
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.*;

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, List<Long> warehouseAreaIds) {
        this.validateCustomer(id);
        for (Long warehouseAreaId : warehouseAreaIds) {
            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, null);

            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, List<Long> warehouseAreaIds) {
        this.validateCustomer(id);
        customerWarehouseService.deleteByCustomerId(id, warehouseAreaIds);
    }

    /**
     * 根据客户id返回对应绑定的库区id
     *
     * @param id
     * @return
     */
    @Override
    public List<Long> queryWarehouseAreaIdByCustomerId(Long id) {
        return CommonUtil.listConvert(customerWarehouseService.getCustomerWarehouseByCustomerId(id), CustomerWarehouseDO::getWarehouseAreaId);
    }

    @Override
    @Cacheable(cacheNames = RedisKeyConstants.USER_TO_CUSTOMER, key = "#userId")
    public ErpCustomerDO getCustomerByUserId(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;
    }


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

    @Override
    @CacheEvict(cacheNames = RedisKeyConstants.USER_TO_CUSTOMER, allEntries = true)
    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
    @CacheEvict(cacheNames = RedisKeyConstants.USER_TO_CUSTOMER, allEntries = true)
    public void deleteByDept(Long deptId) {
        customerMapper.delete(ErpCustomerDO::getSystemDeptId, deptId);
    }

    @Override
    //@Cacheable(cacheNames = RedisKeyConstants.USER_TO_CUSTOMER, key = "#userId")
    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());
        }*/
        ErpCustomerServiceImpl bean = SpringUtil.getBean(getClass());
        return Optional.ofNullable(bean.getCustomerByUserId(userId)).map(ErpCustomerDO::getId).orElse(null);
    }

    @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);
    }

    @Override
    public String queryNameStrById(Long customerId) {
        return Optional.ofNullable(customerMapper.selectById(customerId)).map(ErpCustomerDO::getName).orElse("");
    }

    @Override
    public Integer queryCustomerTypeByUserId(Long userId) {
        AdminUserDO user = userService.getUser(userId);
        if (!UserSystemEnum.CUSTOMER.getKey().equals(user.getUserSystem())) {
            return null;
        }
        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());
        }

        DeptDO dept = deptService.getDept(user.getDeptId());
        if (DeptDO.PARENT_ID_ROOT.equals(dept.getParentId())) {
            return CustomerTypeEnum.CUSTOMER.getKey();
        }
        return CustomerTypeEnum.CHIEF.getKey();
    }

    @Override
    public Set<Long> queryCustomerDeptIdsByUserId(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());
        }

        Set<Long> deptIds = deptService.getChildDeptIdListFromCache(user.getDeptId());
        deptIds.add(user.getDeptId());
        return deptIds;
    }

    @Override
    public Pair<Boolean, Set<Long>> queryCustomerOrUserByUserId(Long userId) {
        AdminUserDO user = userService.getUser(userId);
        if (!UserSystemEnum.CUSTOMER.getKey().equals(user.getUserSystem())) {
            throw exception(ERROR_CUSTOMER_USER);
        }
        DeptDO userDept = deptService.getDept(user.getDeptId());
        if (Objects.equals(userDept.getParentId(), DeptDO.PARENT_ID_ROOT)) {
            Set<Long> deptIds = deptService.getChildDeptIdListFromCache(user.getDeptId());
            deptIds.add(user.getDeptId());
            return new Pair<>(Boolean.TRUE, deptIds);
        }

        return new Pair<>(Boolean.FALSE, null);
    }

    @Override
    public List<DeptSimpleDTO> querySubDeptByUserId(Long userId) {
        AdminUserDO user = userService.getUser(userId);
        if (!UserSystemEnum.CUSTOMER.getKey().equals(user.getUserSystem())) {
            throw exception(ERROR_CUSTOMER_USER);
        }
        DeptDO userDept = deptService.getDept(user.getDeptId());
        if (Objects.equals(userDept.getParentId(), DeptDO.PARENT_ID_ROOT)) {
            return CommonUtil.listConvert(deptService.getChildDeptList(user.getDeptId()), item->{
                DeptSimpleDTO dto = new DeptSimpleDTO();
                dto.setCustomerDeptId(item.getId());
                dto.setName(item.getName());
                return dto;
            });
        }

        return new ArrayList<>();
    }
}
