package com.ruoyi.bst.customerService.service.impl;

import com.ruoyi.bst.area.domain.AreaQuery;
import com.ruoyi.bst.area.domain.AreaVO;
import com.ruoyi.bst.area.service.AreaService;
import com.ruoyi.bst.customerService.domain.CustomerServiceQuery;
import com.ruoyi.bst.customerService.domain.CustomerServiceVO;
import com.ruoyi.bst.customerService.mapper.CustomerServiceMapper;
import com.ruoyi.bst.customerService.service.CustomerServiceValidator;
import com.ruoyi.common.core.domain.vo.UserVO;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.collection.CollectionUtils;
import com.ruoyi.system.user.domain.UserQuery;
import com.ruoyi.system.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;

@Service
public class CustomerServiceValidatorImpl implements CustomerServiceValidator {


    @Autowired
    private CustomerServiceMapper customerServiceMapper;

    @Autowired
    private UserService userService;

    @Override
    public boolean canEdit(Long customerId) {
        return canOperate(Arrays.asList(customerId));
    }

    @Override
    public boolean canDeleteAll(List<Long> ids) {
        return canOperate(ids);
    }


    // 是否可以操作客服
    private boolean canOperate(List<Long> customerIds) {

        if (SecurityUtils.isSysAdmin()) {
            return true;
        }
        if (CollectionUtils.isEmptyElement(customerIds)) {
            return true;
        }

        // 查询客服
        CustomerServiceQuery query = new CustomerServiceQuery();
        query.setIds(customerIds);
        query.setScope(true);
        List<CustomerServiceVO> customerServiceList = customerServiceMapper.selectCustomerServiceList(query);
        Long userId = SecurityUtils.getUserId();

        // 判断是否可以操作客服
        for (Long customerId : customerIds) {
            CustomerServiceVO customerService = customerServiceList.stream()
                    .filter(item -> item.getId().equals(customerId))
                    .findFirst().orElse(null);
            if (customerService == null) {
                return false;
            }

            boolean canOperate = isStore(customerService, userId) || isAgent(customerService, userId);
            if (!canOperate) {
                return false;
            }
        }
        return true;
    }


    private boolean isStore(CustomerServiceVO customerService, Long userId) {
        return customerService != null && customerService.getStoreId() != null && customerService.getStoreId().equals(userId);
    }


    private boolean isAgent(CustomerServiceVO customerService, Long userId) {
        UserVO user = userService.selectUserById(customerService.getStoreId());
        if (user == null) {
            return false;
        }
        return user.getAgentId() != null && user.getAgentId().equals(userId);


    }

}
