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

import com.ruoyi.bst.agreement.domain.AgreementQuery;
import com.ruoyi.bst.agreement.domain.AgreementVO;
import com.ruoyi.bst.agreement.mapper.AgreementMapper;
import com.ruoyi.bst.agreement.service.AgreementValidator;
import com.ruoyi.bst.area.domain.AreaVO;
import com.ruoyi.bst.area.service.AreaService;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.collection.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Service
public class AgreementValidatorImpl implements AgreementValidator {

    @Autowired
    private AgreementMapper agreementMapper;
    @Autowired
    private AreaService areaService;

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

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

    // 是否可以操作运营区
    private boolean canOperate(List<Long> agreementIds) {

        if (SecurityUtils.isSysAdmin()) {
            return true;
        }
        if (CollectionUtils.isEmptyElement(agreementIds)) {
            return true;
        }
        // 查询协议
        AgreementQuery query = new AgreementQuery();
        query.setIds(agreementIds);
        query.setScope(true);
        List<AgreementVO> agreementList = agreementMapper.selectAgreementList(query);
        Long userId = SecurityUtils.getUserId();

        // 判断是否可以操作协议
        for (Long agreementId : agreementIds) {
            AgreementVO agreement = agreementList.stream()
                    .filter(item -> item.getId().equals(agreementId))
                    .findFirst().orElse(null);

            if (agreement == null) {
                return false;
            }
            boolean canOperate = isMch(agreement, userId) || isAgent(agreement,userId);
            if (!canOperate) {
                return false;
            }
        }

        return true;
    }


    private boolean isAgent(AgreementVO agreement, Long userId) {
        return agreement != null && agreement.getAgentId() != null && agreement.getAgentId().equals(userId);
    }

    private boolean isMch(AgreementVO agreement, Long userId) {
        return agreement != null && agreement.getStoreId() != null && agreement.getStoreId().equals(userId);
    }

}
