package com.ghy.worker.service.impl;

import com.ghy.worker.domain.WorkerArea;
import com.ghy.worker.mapper.WorkerAreaMapper;
import com.ghy.worker.service.WorkerAreaService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class WorkerAreaServiceImpl implements WorkerAreaService {

    @Resource
    private WorkerAreaMapper workerAreaMapper;

    @Override
    public int insert(WorkerArea workerArea) {
        return workerAreaMapper.insert(workerArea);
    }

    @Override
    public int delete(Long[] ids) {
        return workerAreaMapper.delete(ids);
    }

    @Override
    public int deleteByWorker(Long workerId) {
        return workerAreaMapper.deleteByWorker(workerId);
    }

    @Override
    public List<WorkerArea> getByWorker(Long workerId) {
        return workerAreaMapper.getByWorker(workerId);
    }

    @Override
    public void updateWorkerServArea(Long workerId, List<WorkerArea> areas) {
        List<WorkerArea> existAreas = getByWorker(workerId);
        Set<Long> existAreaIds = existAreas.stream().map(WorkerArea::getStreetId).collect(Collectors.toSet());
        Set<Long> areaIds = areas.stream().map(WorkerArea::getStreetId).collect(Collectors.toSet());

        // 新的区域-已存在区域的差集，为需要新加入的区域
        List<WorkerArea> areas2Insert = areas.stream().distinct().filter(x -> !existAreaIds.contains(x.getStreetId()))
            .collect(Collectors.toList());
        // 已存在区域-新的区域的差集，为需要删除的区域
        List<Long> id2DelList = existAreas.stream().filter(x -> !areaIds.contains(x.getStreetId()))
            .map(WorkerArea::getWorkerAreaId).collect(Collectors.toList());

        if (!CollectionUtils.isEmpty(areas2Insert)) {
            workerAreaMapper.batchInsert(areas2Insert);
        }
        if (!CollectionUtils.isEmpty(id2DelList)) {
            Long[] id2Del = new Long[]{};
            workerAreaMapper.delete(id2DelList.toArray(id2Del));
        }
    }

    @Override
    public void updateWorkerAreaByType(Long workerId, List<WorkerArea> areas, Integer serviceType) {
        if (areas == null || areas.isEmpty()) {
            return;
        }
        
        // 先删除该师傅该类型的旧区域
        workerAreaMapper.deleteByWorkerIdAndType(workerId, serviceType);
        
        // 插入新的区域，并设置类型
        for (WorkerArea area : areas) {
            area.setWorkerId(workerId);
            area.setServiceType(serviceType);  // 设置类型：1=服务, 2=商品
            workerAreaMapper.insert(area);
        }
    }

    @Override
    public List<WorkerArea> getByWorkerIdAndType(Long workerId, Integer serviceType) {
        return workerAreaMapper.getByWorkerIdAndType(workerId, serviceType);
    }

    @Override
    public List<WorkerArea> getWorkerAreaList(WorkerArea area) {
        return workerAreaMapper.getWorkerAreaList(area);
    }
}
