package com.ghy.web.controller.worker;

import com.ghy.common.core.domain.AjaxResult;
import com.ghy.common.core.text.Convert;
import com.ghy.system.domain.SysArea;
import com.ghy.system.service.ISysAreaService;
import com.ghy.worker.domain.WorkerArea;
import com.ghy.worker.request.WorkerAreaSaveRequest;
import com.ghy.worker.service.WorkerAreaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 师傅接单区域
 *
 * @author HH 2022/6/7
 */
@Slf4j
@Controller
@RequestMapping("worker/area")
public class WorkerAreaController {

    @Resource
    private WorkerAreaService workerAreaService;

    @Autowired
    private ISysAreaService sysAreaService;

    /**
     * 查询某个师傅的所有接单地区
     *
     * @param workerId 师傅ID
     */
    @GetMapping("worker")
    @ResponseBody
    public AjaxResult getByWorker(Long workerId) {
        return AjaxResult.success(workerAreaService.getByWorker(workerId));
    }

    @GetMapping("worker/edit")
    @ResponseBody
    public AjaxResult getEditWorker(Long workerId){
        Map<Long, List<String>> countryMap = new HashMap<>();
        List<WorkerArea> byWorker = workerAreaService.getByWorker(workerId);
        for (WorkerArea area : byWorker){
           List<String> ids;
           if(countryMap.containsKey(area.getDistrictId())){
               ids = countryMap.get(area.getDistrictId());
           }else {
               ids = new ArrayList<>();
           }
            ids.add(String.valueOf(area.getStreetId()));
            countryMap.put(area.getDistrictId(), ids);
        }
        List<WorkerArea> result = new ArrayList<>();
        for (Map.Entry<Long, List<String>> longListEntry : countryMap.entrySet()) {
            WorkerArea model = new WorkerArea();
            SysArea countryArea = sysAreaService.selectById(longListEntry.getKey());
            model.setDistrictArea(countryArea);
            SysArea cityArea = sysAreaService.selectById(Long.valueOf(countryArea.getParentCode()));
            model.setCityArea(cityArea);
            SysArea provinceArea = sysAreaService.selectById(Long.valueOf(cityArea.getParentCode()));
            model.setProvinceArea(provinceArea);
            model.setStreetIds(longListEntry.getValue());
            result.add(model);
        }
        return AjaxResult.success(result);
    }

    @PostMapping("save")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult save(@RequestBody WorkerAreaSaveRequest request) {
        Set<WorkerArea> areas = request.getAreas();
        // 数据库中已存在的街道ID
        Set<Long> existingArea = workerAreaService.getByWorker(request.getWorkerId()).stream()
                .map(WorkerArea::getStreetId).collect(Collectors.toSet());
        // 去掉重复
        areas.removeIf(x -> existingArea.contains(x.getStreetId()));
        if (CollectionUtils.isEmpty(areas)) {
            // 如果去重后ID集合为空 则结束
            return AjaxResult.success();
        }
        for (WorkerArea area : areas) {
            area.setWorkerId(request.getWorkerId());
            workerAreaService.insert(area);
        }
        return AjaxResult.success();
    }

    /**
     * 删除某个师傅的所有接单地区
     *
     * @param workerId 师傅ID
     */
    @DeleteMapping("worker")
    @ResponseBody
    public AjaxResult deleteByWorker(Long workerId) {
        workerAreaService.deleteByWorker(workerId);
        return AjaxResult.success();
    }

    /**
     * 通过主键删除
     *
     * @param ids 接单地区表主键
     */
    @DeleteMapping
    @ResponseBody
    public AjaxResult deleteByWorkerAreaId(String ids) {
        Long[] idArray = Convert.toLongArray(ids);
        workerAreaService.delete(idArray);
        return AjaxResult.success();
    }
}
