package com.ghy.goods.service.impl;

import com.ghy.common.constant.UserConstants;
import com.ghy.common.core.domain.AjaxResult;
import com.ghy.common.core.domain.Ztree;
import com.ghy.common.core.text.Convert;
import com.ghy.common.utils.StringUtils;
import com.ghy.common.utils.bean.BeanUtils;
import com.ghy.customer.domain.Customer;
import com.ghy.customer.domain.CustomerSelection;
import com.ghy.customer.service.CustomerService;
import com.ghy.customer.service.ICustomerSelectionService;
import com.ghy.goods.domain.DeptGoodsCategory;
import com.ghy.goods.domain.GoodsCategory;
import com.ghy.goods.domain.GoodsImgs;
import com.ghy.goods.mapper.DeptGoodsCategoryMapper;
import com.ghy.goods.service.DeptGoodsCategoryService;
import com.ghy.goods.service.GoodsCategoryService;
import com.ghy.goods.service.GoodsImgsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

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

/**
 * @author clunt
 * 分公司使用类目
 */
@Slf4j
@Service
public class DeptGoodsCategoryServiceImpl implements DeptGoodsCategoryService {

    @Resource
    private GoodsCategoryService goodsCategoryService;
    @Resource
    private DeptGoodsCategoryMapper deptGoodsCategoryMapper;
    @Resource
    private GoodsImgsService goodsImgsService;
    @Resource
    private CustomerService customerService;
    @Resource
    private ICustomerSelectionService customerSelectionService;


    @Override
    public List<DeptGoodsCategory> list(DeptGoodsCategory category) {
        return deptGoodsCategoryMapper.selectList(category);
    }

    @Override
    public int add(DeptGoodsCategory deptGoodsCategory) {
        return deptGoodsCategoryMapper.insertDeptGoodsCategory(deptGoodsCategory);
    }

    @Override
    public int edit(DeptGoodsCategory deptGoodsCategory) {
        if(StringUtils.isNotEmpty(deptGoodsCategory.getCategoryUrl())){
            String[] split = deptGoodsCategory.getCategoryUrl().split(",");
            List<GoodsImgs> list = new ArrayList<>();
            for (String url : split){
                GoodsImgs goodsImgs = new GoodsImgs();
                goodsImgs.setGoodsId(0L);
                goodsImgs.setImgUrl(url);
                goodsImgs.setImgType(3);
                goodsImgs.setRemark(String.valueOf(deptGoodsCategory.getDeptGoodsCategoryId()));
                list.add(goodsImgs);
            }
            goodsImgsService.batchInsert(list);
        }
        return deptGoodsCategoryMapper.updateDeptGoodsCategory(deptGoodsCategory);
    }

    @Override
    public int delete(Collection<Long> ids) {
        return deptGoodsCategoryMapper.deleteDeptGoodsCategoryByIds(ids);
    }

    @Override
    public DeptGoodsCategory get(long id) {
        return deptGoodsCategoryMapper.selectById(id);
    }

    @Override
    public List<Ztree> tree(Long parentId) {
        DeptGoodsCategory category = new DeptGoodsCategory();
        category.setDeptId(parentId);
        List<DeptGoodsCategory> list = list(category);
        return initZtree(list);
    }

    @Override
    public List<DeptGoodsCategory> appList(DeptGoodsCategory deptGoodsCategory) {
        Customer customer= customerService.selectByCustomerId(deptGoodsCategory.getCustomerId());
        List<DeptGoodsCategory> goodsCategoryList = new ArrayList<>();
        if (customer == null) {
            log.warn("未找到客户，customerId: {}", deptGoodsCategory.getCustomerId());
            // 返回全部类目或默认类目
            goodsCategoryList = deptGoodsCategoryMapper.appList(deptGoodsCategory);
        } else {
            Long customerId = customer.getCustomerPlace();
            if (customer.getPlaceStatus() == 2) {
                customerId = customer.getCustomerId();
            }
            CustomerSelection customerSelection = new CustomerSelection();
            customerSelection.setCustomerId(customerId);
            List<CustomerSelection> customerSelections = customerSelectionService.selectCustomerSelectionList(customerSelection);
            log.info("用户id{}获取到的类目列表{}", customerId, customerSelections);
            if (deptGoodsCategory.getIsSetting() == 1) {
                goodsCategoryList = deptGoodsCategoryMapper.appList(deptGoodsCategory);
            } else {
                for (CustomerSelection customerSelection1 : customerSelections) {
                    DeptGoodsCategory deptGoodsCategory1 = deptGoodsCategoryMapper.selectOneByGoodsCategoryId(customerSelection1.getDeptCategoryId());
                    if (customerSelection1.getSelectionType() == 1) {
                        goodsCategoryList.add(deptGoodsCategory1);
                    }
                }
            }
        }
        log.info("筛选完的类目列表{}",goodsCategoryList);
        // 第二层
        this.fillChild(goodsCategoryList);
        // 第三层
        for (DeptGoodsCategory category : goodsCategoryList) {
            if (StringUtils.isNotNull(category.getChild())) {
                this.fillChild(category.getChild());
            }
        }
        // 第四层
        for (DeptGoodsCategory category : goodsCategoryList) {
            if (StringUtils.isNotNull(category.getChild())) {
                for (DeptGoodsCategory result : category.getChild()) {
                    if (StringUtils.isNotNull(result.getChild())) {
                        this.fillChild(result.getChild());
                    }
                }
            }
        }
        return goodsCategoryList;
    }

    @Override
    public List<DeptGoodsCategory> listByStep(DeptGoodsCategory deptGoodsCategory) {
        return deptGoodsCategoryMapper.appList(deptGoodsCategory);
    }

    @Override
    public int delete(String ids) {
        Long[] array = Convert.toLongArray(ids);
        return delete(Arrays.asList(array));
    }

    @Override
    public DeptGoodsCategory selectOneByGoodsCategoryId(Long goodsCategoryId) {
        return deptGoodsCategoryMapper.selectOneByGoodsCategoryId(goodsCategoryId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult batchAdd(Long parentId, Long[] checked) {
        GoodsCategory goodsCategory = goodsCategoryService.selectById(checked[0]);
        Assert.notNull(goodsCategory, "不存在该类目: " + checked[0]);
        List<DeptGoodsCategory> oldList = deptGoodsCategoryMapper.selectByDeptId(parentId);
        
        Map<Long, Long> oldMap = oldList.stream()
                .filter(x -> x.getType() != null && goodsCategory.getType() != null && x.getType().equals(goodsCategory.getType()))
                .collect(Collectors.toMap(DeptGoodsCategory::getGoodsCategoryId, DeptGoodsCategory::getDeptGoodsCategoryId));
                
        HashSet<Long> newSet = new HashSet<>(Arrays.asList(checked));
        Set<Long> intersection = oldList.stream().map(DeptGoodsCategory::getGoodsCategoryId).collect(Collectors.toSet());
        intersection.addAll(Arrays.asList(checked));
        for (Long id : intersection) {
            if (newSet.contains(id)) {
                if (!oldMap.containsKey(id)) {
                    DeptGoodsCategory category = new DeptGoodsCategory();
                    category.setDeptId(parentId);
                    category.setGoodsCategoryId(id);
                    deptGoodsCategoryMapper.insertDeptGoodsCategory(category);
                }
            } else if (oldMap.containsKey(id)) {
                deptGoodsCategoryMapper.deleteById(oldMap.get(id));
            }
        }
        return AjaxResult.success();
    }

    private void fillChild(List<DeptGoodsCategory> goodsCategoryList) {
        List<DeptGoodsCategory> childList;
        for (DeptGoodsCategory deptGoodsCategory : goodsCategoryList) {
            DeptGoodsCategory param = new DeptGoodsCategory();
            BeanUtils.copyProperties(deptGoodsCategory, param);
            param.setDeptGoodsCategoryId(null);
            childList = deptGoodsCategoryMapper.appList(param);
            if (childList.size() > 0) {
                deptGoodsCategory.setChild(childList);
            }
        }
    }

    public List<Ztree> initZtree(List<DeptGoodsCategory> list) {
        List<Ztree> ztrees = new ArrayList<>();
        for (GoodsCategory goodsCategory : list) {
            if (UserConstants.CATEGORY_NORMAL.equals(goodsCategory.getStatus())) {
                Ztree ztree = new Ztree();
                ztree.setId(goodsCategory.getGoodsCategoryId());
                ztree.setpId(goodsCategory.getParentCategoryId());
                ztree.setName(goodsCategory.getGoodsCategoryName());
                ztree.setTitle(goodsCategory.getGoodsCategoryName());
                ztrees.add(ztree);
            }
        }
        return ztrees;
    }

    @Override
    public Integer findCountdownHoursRecursively(Long deptGoodsCategoryId) {
        if (deptGoodsCategoryId == null) {
            log.warn("分公司类目ID为空，无法查找倒计时小时数");
            return null;
        }
        
        // 查询当前类目
        DeptGoodsCategory currentCategory = deptGoodsCategoryMapper.selectById(deptGoodsCategoryId);
        if (currentCategory == null) {
            log.warn("未找到分公司类目，ID: {}", deptGoodsCategoryId);
            return null;
        }
        
        // 如果当前类目有设置倒计时小时数，直接返回
        if (currentCategory.getCountdownHours() != null) {
            log.info("找到类目[{}]的倒计时小时数: {}", currentCategory.getGoodsCategoryName(), currentCategory.getCountdownHours());
            return currentCategory.getCountdownHours();
        }
        
        // 如果当前类目没有设置，查找上级类目
        if (currentCategory.getParentCategoryId() != null) {
            log.info("类目[{}]未设置倒计时小时数，查找上级类目ID: {}", currentCategory.getGoodsCategoryName(), currentCategory.getParentCategoryId());
            
            // 通过商品类目ID查找对应的分公司类目
            DeptGoodsCategory parentDeptCategory = deptGoodsCategoryMapper.selectOneByGoodsCategoryId(currentCategory.getParentCategoryId());
            if (parentDeptCategory != null) {
                return findCountdownHoursRecursively(parentDeptCategory.getDeptGoodsCategoryId());
            } else {
                log.warn("未找到上级类目对应的分公司类目，商品类目ID: {}", currentCategory.getParentCategoryId());
            }
        } else {
            log.info("类目[{}]已是顶级类目，无上级类目可查找", currentCategory.getGoodsCategoryName());
        }
        
        return null;
    }
}
