package com.ghy.web.controller.worker;

import com.ghy.common.core.controller.BaseController;
import com.ghy.common.core.domain.AjaxResult;
import com.ghy.common.core.page.TableDataInfo;
import com.ghy.common.core.text.Convert;
import com.ghy.order.domain.OrderGoods;
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.ui.ModelMap;
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 extends BaseController {

    @Resource
    private WorkerAreaService workerAreaService;

    @Autowired
    private ISysAreaService sysAreaService;

    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(WorkerArea workerArea) {
        startPage();
        List<WorkerArea> list = workerAreaService.getWorkerAreaList(workerArea);
        return getDataTable(list);
    }

    @GetMapping()
    public String area(Long workerId, ModelMap mmap)
    {
        mmap.put("workerId", workerId);
        return "worker/areaDetail";
    }

    /**
     * 查询某个师傅的所有接单地区
     *
     * @param workerId 师傅ID
     * @param serviceType 服务类型：1=服务, 2=商品，不传则查询所有
     */
    @GetMapping("worker")
    @ResponseBody
    public AjaxResult getByWorker(Long workerId, Integer serviceType) {
        if (serviceType != null) {
            // 根据服务类型查询
            return AjaxResult.success(workerAreaService.getByWorkerIdAndType(workerId, serviceType));
        } else {
            // 查询所有区域（保持向后兼容）
            return AjaxResult.success(workerAreaService.getByWorker(workerId));
        }
    }

    /**
     * 查询某个师傅的服务区域（类型1）
     *
     * @param workerId 师傅ID
     */
    @GetMapping("worker/service")
    @ResponseBody
    public AjaxResult getServiceAreasByWorker(Long workerId) {
        return AjaxResult.success(workerAreaService.getByWorkerIdAndType(workerId, 1));
    }

    /**
     * 查询某个师傅的商品区域（类型2）
     *
     * @param workerId 师傅ID
     */
    @GetMapping("worker/goods")
    @ResponseBody
    public AjaxResult getGoodsAreasByWorker(Long workerId) {
        return AjaxResult.success(workerAreaService.getByWorkerIdAndType(workerId, 2));
    }

    @GetMapping("worker/edit")
    @ResponseBody
    public AjaxResult getEditWorker(Long workerId, Integer type){
        Map<Long, List<String>> countryMap = new HashMap<>();
        
        // 需求1：根据类型查询对应的区域数据
        List<WorkerArea> byWorker;
        if (Integer.valueOf(1).equals(type)) {
            // 服务类型：查询服务区域
            byWorker = workerAreaService.getByWorkerIdAndType(workerId, 1);
        } else if (Integer.valueOf(2).equals(type)) {
            // 商品类型：查询商品区域
            byWorker = workerAreaService.getByWorkerIdAndType(workerId, 2);
        } else {
            // 不传类型：查询所有区域
            byWorker = workerAreaService.getByWorker(workerId);
        }
        
        // 收集只有cityId没有districtId的城市ID集合（用于单独处理）
        Set<Long> cityOnlyIds = new HashSet<>();
        // 按districtId分组收集cityIds
        Map<Long, Set<Long>> districtCityMap = new HashMap<>();
        
        for (WorkerArea area : byWorker){
           Long districtId = area.getDistrictId();
           
           // 如果有districtId，按districtId分组处理
           if (districtId != null) {
               List<String> ids;
               if(countryMap.containsKey(districtId)){
                   ids = countryMap.get(districtId);
               } else {
                   ids = new ArrayList<>();
               }
               
               // 收集该district下的城市ID
               if (area.getCityId() != null) {
                   districtCityMap.computeIfAbsent(districtId, k -> new HashSet<>()).add(area.getCityId());
               }
               
               // 添加街道ID
               if (area.getStreetId() != null) {
                   ids.add(String.valueOf(area.getStreetId()));
               }
               
               countryMap.put(districtId, ids);
           } else {
               // 如果只有cityId没有districtId，收集到cityOnlyIds
               if (area.getCityId() != null) {
                   cityOnlyIds.add(area.getCityId());
               }
           }
        }
        
        List<WorkerArea> result = new ArrayList<>();
        
        // 处理有districtId的情况（正常流程）
        for (Map.Entry<Long, List<String>> longListEntry : countryMap.entrySet()) {
            WorkerArea model = new WorkerArea();
            Long districtId = longListEntry.getKey();
            SysArea countryArea = sysAreaService.selectById(districtId);
            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);
            
            // 设置该district下的cityIds
            Set<Long> districtCityIds = districtCityMap.getOrDefault(districtId, new HashSet<>());
            List<Long> cityIdList = new ArrayList<>(districtCityIds);
            model.setCityIds(cityIdList);
            
            // 设置街道ID列表
            model.setStreetIds(longListEntry.getValue());
            
            result.add(model);
        }
        
        // 处理只有cityId没有districtId的情况（只返回省市信息）
        for (Long cityId : cityOnlyIds) {
            WorkerArea model = new WorkerArea();
            SysArea cityArea = sysAreaService.selectById(cityId);
            model.setCityArea(cityArea);
            // 获取省份信息
            SysArea provinceArea = sysAreaService.selectById(Long.valueOf(cityArea.getParentCode()));
            model.setProvinceArea(provinceArea);
            
            // 只设置城市ID列表
            List<Long> cityIdList = new ArrayList<>();
            cityIdList.add(cityId);
            model.setCityIds(cityIdList);
            
            // 不设置district和street信息
            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();
    }
}
