package com.ghy.web.controller.worker;

import com.ghy.common.constant.Constants;
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.common.utils.StringUtils;
import com.ghy.goods.domain.GoodsCategory;
import com.ghy.goods.service.GoodsCategoryService;
import com.ghy.worker.domain.WorkerArea;
import com.ghy.worker.domain.WorkerGoodsCategory;
import com.ghy.worker.request.WorkerGoodsCategorySaveRequest;
import com.ghy.worker.service.WorkerGoodsCategoryService;
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;

/**
 * 师傅服务类目Controller
 *
 * @author HH 2022/6/7
 */
@Slf4j
@Controller
@RequestMapping("worker/goods/category")
public class WorkerGoodsCategoryController extends BaseController {

    @Resource
    private WorkerGoodsCategoryService workerGoodsCategoryService;

    @Autowired
    private GoodsCategoryService goodsCategoryService;


    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(WorkerGoodsCategory workerGoodsCategory) {
        startPage();
        List<WorkerGoodsCategory> list = workerGoodsCategoryService.getByWorker(workerGoodsCategory.getWorkerId());
        for (WorkerGoodsCategory item: list) {
            List<String> nameList = new ArrayList<String>();
            // 查询所有父级服务类目，拼接服务名称
            GoodsCategory goodsCategory = goodsCategoryService.selectById(item.getGoodsCategoryId());
            while (goodsCategory.getParentCategoryId() != null) {
                nameList.add(goodsCategory.getGoodsCategoryName());
                goodsCategory = goodsCategoryService.selectById(goodsCategory.getParentCategoryId());
            }
            Collections.reverse(nameList);
            item.setMergeName(StringUtils.join(nameList, Constants.JOIN_SYMBOL));
        }
        return getDataTable(list);
    }

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

    /**
     * 查询某个师傅的所有服务类目
     *
     * @param workerId 师傅ID
     * @param serviceType 服务类型：1=服务, 2=商品，不传则查询所有
     */
    @GetMapping("worker")
    @ResponseBody
    public AjaxResult getByWorker(Long workerId, Integer serviceType) {
        List<WorkerGoodsCategory> list;
        if (serviceType != null) {
            // 根据服务类型查询
            list = workerGoodsCategoryService.getByWorkerIdAndType(workerId, serviceType);
        } else {
            // 查询所有类目（保持向后兼容）
            list = workerGoodsCategoryService.getByWorker(workerId);
        }
        
        for (WorkerGoodsCategory item: list) {
            List<String> nameList = new ArrayList<String>();
            // 查询所有父级服务类目，拼接服务名称
            GoodsCategory goodsCategory = goodsCategoryService.selectById(item.getGoodsCategoryId());
            while (goodsCategory.getParentCategoryId() != null) {
                nameList.add(goodsCategory.getGoodsCategoryName());
                goodsCategory = goodsCategoryService.selectById(goodsCategory.getParentCategoryId());
            }
            Collections.reverse(nameList);
            item.setMergeName(StringUtils.join(nameList, Constants.JOIN_SYMBOL));
        }
        return AjaxResult.success(list);
    }

    /**
     * 查询某个师傅的服务类目（类型1）
     *
     * @param workerId 师傅ID
     */
    @GetMapping("worker/service")
    @ResponseBody
    public AjaxResult getServiceCategoriesByWorker(Long workerId) {
        List<WorkerGoodsCategory> list = workerGoodsCategoryService.getByWorkerIdAndType(workerId, 1);
        for (WorkerGoodsCategory item: list) {
            List<String> nameList = new ArrayList<String>();
            // 查询所有父级服务类目，拼接服务名称
            GoodsCategory goodsCategory = goodsCategoryService.selectById(item.getGoodsCategoryId());
            while (goodsCategory.getParentCategoryId() != null) {
                nameList.add(goodsCategory.getGoodsCategoryName());
                goodsCategory = goodsCategoryService.selectById(goodsCategory.getParentCategoryId());
            }
            Collections.reverse(nameList);
            item.setMergeName(StringUtils.join(nameList, Constants.JOIN_SYMBOL));
        }
        return AjaxResult.success(list);
    }

    /**
     * 查询某个师傅的商品类目（类型2）
     *
     * @param workerId 师傅ID
     */
    @GetMapping("worker/goods")
    @ResponseBody
    public AjaxResult getGoodsCategoriesByWorker(Long workerId) {
        List<WorkerGoodsCategory> list = workerGoodsCategoryService.getByWorkerIdAndType(workerId, 2);
        for (WorkerGoodsCategory item: list) {
            List<String> nameList = new ArrayList<String>();
            // 查询所有父级服务类目，拼接服务名称
            GoodsCategory goodsCategory = goodsCategoryService.selectById(item.getGoodsCategoryId());
            while (goodsCategory.getParentCategoryId() != null) {
                nameList.add(goodsCategory.getGoodsCategoryName());
                goodsCategory = goodsCategoryService.selectById(goodsCategory.getParentCategoryId());
            }
            Collections.reverse(nameList);
            item.setMergeName(StringUtils.join(nameList, Constants.JOIN_SYMBOL));
        }
        return AjaxResult.success(list);
    }

    @GetMapping("worker/edit")
    @ResponseBody
    public AjaxResult getEditWorker(Long workerId, Integer type) {
        Map<Long, List<String>> twoMap = new HashMap<>();
        
        // 根据类型查询对应的商品分类数据
        List<WorkerGoodsCategory> list;
        if (Integer.valueOf(1).equals(type)) {
            // 服务类型：查询服务商品分类
            list = workerGoodsCategoryService.getByWorkerIdAndType(workerId, 1);
        } else if (Integer.valueOf(2).equals(type)) {
            // 商品类型：查询商品分类
            list = workerGoodsCategoryService.getByWorkerIdAndType(workerId, 2);
        } else {
            // 不传类型：查询所有商品分类
            list = workerGoodsCategoryService.getByWorker(workerId);
        }
        
        if(CollectionUtils.isEmpty(list)){
            return AjaxResult.success();
        }
        
        for (WorkerGoodsCategory item: list) {
            List<String> ids;
            GoodsCategory goodsCategory = goodsCategoryService.selectById(item.getGoodsCategoryId());
            if(twoMap.containsKey(goodsCategory.getParentCategoryId())){
                ids = twoMap.get(goodsCategory.getParentCategoryId());
            }else {
                ids = new ArrayList<>();
            }
            ids.add(String.valueOf(goodsCategory.getGoodsCategoryId()));
            twoMap.put(goodsCategory.getParentCategoryId(), ids);
        }
        
        List<WorkerGoodsCategory> result =  new ArrayList<>();
        for (Map.Entry<Long, List<String>> longListEntry : twoMap.entrySet()) {
            WorkerGoodsCategory model = new WorkerGoodsCategory();
            GoodsCategory goodsCategory = goodsCategoryService.selectById(longListEntry.getKey());
            model.setTwoGoodsCategory(goodsCategory);
            model.setOneGoodsCategory(goodsCategoryService.selectById(goodsCategory.getParentCategoryId()));
            model.setCategoryIds(longListEntry.getValue());
            result.add(model);
        }
        return AjaxResult.success(result);
    }


    @PostMapping("save")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult save(@RequestBody WorkerGoodsCategorySaveRequest request) {
        Set<Long> goodsCategoryIds = request.getGoodsCategoryIds();
        // 数据库中已存在的商品类目ID
        Set<Long> existingId = workerGoodsCategoryService.getByWorker(request.getWorkerId()).stream()
                .map(WorkerGoodsCategory::getGoodsCategoryId).collect(Collectors.toSet());
        goodsCategoryIds.removeIf(existingId::contains);
        if (CollectionUtils.isEmpty(goodsCategoryIds)) {
            // 如果去重后ID集合为空 则结束
            return AjaxResult.success();
        }
        for (Long goodsCategoryId : existingId) {
            WorkerGoodsCategory wgc = new WorkerGoodsCategory();
            wgc.setWorkerId(request.getWorkerId());
            wgc.setGoodsCategoryId(goodsCategoryId);
            workerGoodsCategoryService.insert(wgc);
        }
        return AjaxResult.success();
    }

    /**
     * 删除某个师傅的所有服务类目
     *
     * @param workerId 师傅ID
     */
    @DeleteMapping("worker")
    @ResponseBody
    public AjaxResult deleteByWorker(Long workerId) {
        workerGoodsCategoryService.deleteByWorker(workerId);
        return AjaxResult.success();
    }

    /**
     * 通过主键删除
     *
     * @param ids 师傅服务类目表主键
     */
    @DeleteMapping
    @ResponseBody
    public AjaxResult deleteByWorkerAreaId(String ids) {
        Long[] idArray = Convert.toLongArray(ids);
        workerGoodsCategoryService.delete(idArray);
        return AjaxResult.success();
    }
}
