package cn.ysk.cashier.service.impl.productimpl;

import cn.ysk.cashier.dto.product.TbProductSortCriteria;
import cn.ysk.cashier.exception.BadRequestException;
import cn.ysk.cashier.pojo.product.TbProduct;
import cn.ysk.cashier.repository.product.TbProductRepository;
import cn.ysk.cashier.pojo.product.TbProductGroup;
import cn.ysk.cashier.utils.*;
import cn.ysk.cashier.vo.AddProduct;
import cn.ysk.cashier.repository.product.TbProductGroupRepository;
import cn.ysk.cashier.dto.product.TbProductGroupDto;
import cn.ysk.cashier.dto.product.TbProductGroupQueryCriteria;
import cn.ysk.cashier.config.security.service.OnlineUserService;
import cn.ysk.cashier.config.security.service.dto.OnlineUserDto;
import lombok.RequiredArgsConstructor;
import cn.ysk.cashier.service.product.TbProductGroupService;
import cn.ysk.cashier.mapper.product.TbProductGroupMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.util.CollectionUtils;

import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author lyf
* @date 2023-12-16
**/
@Service
@RequiredArgsConstructor
public class TbProductGroupServiceImpl implements TbProductGroupService {

    private final TbProductGroupRepository tbProductGroupRepository;
    private final TbProductGroupMapper tbProductGroupMapper;
    private final TbProductRepository tbProductRepository;
    private final WxMsgUtils wxMsgUtils;

    @Resource
    private OnlineUserService onlineUserService;

    @Override
    public Map<String,Object> queryAll(TbProductGroupQueryCriteria criteria, Pageable pageable){
        PageRequest sort = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), Sort.by("sort"));
        Page<TbProductGroup> page = tbProductGroupRepository.findAll((root, criteriaQuery, criteriaBuilder) ->
                QueryHelp.getPredicate(root,criteria,criteriaBuilder),sort);
        return PageUtil.toPage(page.map(tbProductGroupMapper::toDto));
    }

    @Override
    public List<TbProductGroupDto> queryAll(TbProductGroupQueryCriteria criteria){
        return tbProductGroupMapper.toDto(tbProductGroupRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    public List<TbProduct> findByIdProduct(Integer productGroup) {
        TbProductGroup tbProductGroup = tbProductGroupRepository.findById(productGroup).orElseGet(TbProductGroup::new);
        TbProductGroupDto dto = tbProductGroupMapper.toDto(tbProductGroup);
        if (!CollectionUtils.isEmpty(dto.getProductIds())){
            return tbProductRepository.findByIds(dto.getProductIds());
        }
        return new ArrayList<>();
    }

    @Override
    @Transactional
    public TbProductGroupDto findById(Integer id) {
        TbProductGroup tbProductGroup = tbProductGroupRepository.findById(id).orElseGet(TbProductGroup::new);
        ValidationUtil.isNull(tbProductGroup.getId(),"TbProductGroup","id",id);
        return tbProductGroupMapper.toDto(tbProductGroup);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TbProductGroupDto create(TbProductGroup resources) {
        if (resources.getUseTime() == 1) {
            if (StringUtils.isBlank(resources.getSaleStartTime()) || StringUtils.isBlank(resources.getSaleEndTime()))
                throw new BadRequestException("可售时间不可为空");
        }
        resources.setCreatedAt(Instant.now().toEpochMilli());
        resources.setUpdatedAt(Instant.now().toEpochMilli());
        TbProductGroup save = tbProductGroupRepository.save(resources);
        resources.setSort(save.getId());
        return tbProductGroupMapper.toDto(tbProductGroupRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(TbProductGroup resources) {
        if (resources.getUseTime() == 1) {
            if (StringUtils.isBlank(resources.getSaleStartTime()) || StringUtils.isBlank(resources.getSaleEndTime()))
                throw new BadRequestException("可售时间不可为空");
        }
        TbProductGroup tbProductGroup = tbProductGroupRepository.findById(resources.getId()).orElseGet(TbProductGroup::new);
//        TbProductGroup byName = tbProductGroupRepository.findByName(resources.getName(), resources.getShopId());
//        if (byName != null){
//            throw new BadRequestException("名称重复");
//        }
        // 推送微信操作消息
        if (!tbProductGroup.getIsShow().equals(resources.getIsShow())) {
            wxMsgUtils.aboardOperationMsg((resources.getIsShow() == 0 ? "关闭分组: " : "开启分组: ") + tbProductGroup.getName(), resources.getShopId());
        }
        tbProductGroup.setUpdatedAt(Instant.now().toEpochMilli());
        ValidationUtil.isNull( tbProductGroup.getId(),"TbProductGroup","id",resources.getId());
        tbProductGroup.copy(resources);
        tbProductGroupRepository.save(tbProductGroup);


    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void upSort(TbProductSortCriteria param) {
        Integer strSort = tbProductGroupRepository.findById(param.getStrId()).get().getSort();
        Integer endSort = tbProductGroupRepository.findById(param.getEndId()).get().getSort();
        List<TbProductGroup> list = tbProductGroupRepository.findByIds(param.getIds());
        Integer sort = 0;
        Integer strIndex = -1;
        if(strSort<endSort){
            for (int i = list.size() - 1; i >= 0; i--) {
                TbProductGroup product = list.get(i);
                if(product.getId().equals(param.getEndId())) {
                    sort=product.getSort();
                    strIndex=i;
                }
                if(!strIndex.equals(-1)){
                    if (product.getId().equals(param.getStrId())){
                        product.setSort(sort);
                        tbProductGroupRepository.save(product);
                        break;
                    }
                    TbProductGroup product1 = list.get(i - 1);
                    product.setSort(product1.getSort());
                    tbProductGroupRepository.save(product);
                }
            }
        }else {
            for (int i = 0; i < list.size(); i++) {
                TbProductGroup product = list.get(i);
                if(product.getId().equals(param.getEndId())) {
                    sort=product.getSort();
                    strIndex=i;
                }
                if(!strIndex.equals(-1)){
                    if (product.getId().equals(param.getStrId())){
                        product.setSort(sort);
                        tbProductGroupRepository.save(product);
                        break;
                    }
                    Integer nextIndex= i + 1;
                    TbProductGroup product1 = list.get(nextIndex);
                    product.setSort(product1.getSort());
                    tbProductGroupRepository.save(product);
                }
            }
        }
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            tbProductGroupRepository.deleteById(id);
        }
    }
    @Override
    public void download(List<TbProductGroupDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (TbProductGroupDto tbProductGroup : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("分组名称", tbProductGroup.getName());
            map.put("商户Id", tbProductGroup.getMerchantId());
            map.put("店铺Id", tbProductGroup.getShopId());
            map.put("图标", tbProductGroup.getPic());
            map.put("是否显示", tbProductGroup.getIsShow());
            map.put("分类描述", tbProductGroup.getDetail());
            map.put(" style",  tbProductGroup.getStyle());
            map.put("排序", tbProductGroup.getSort());
            map.put("商品列表", tbProductGroup.getProductIds());
            map.put(" createdAt",  tbProductGroup.getCreatedAt());
            map.put(" updatedAt",  tbProductGroup.getUpdatedAt());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public ResponseEntity<Object> updateProductIds(AddProduct addProduct, String userName) {
//        OnlineUserDto onlineUser = onlineUserService.getOne(addProduct.getKey());

        if (addProduct.getIds().size()<1){
            return new ResponseEntity<>("错误", HttpStatus.NOT_ACCEPTABLE);
        }
        TbProductGroupDto productGroup = this.findById(addProduct.getGroupId());

        if (productGroup == null){
            return new ResponseEntity<>("没有找到改分类", HttpStatus.NOT_ACCEPTABLE);
        }
        TbProductGroup tbProductGroup = new TbProductGroup();
        StringBuilder sb = new StringBuilder();
//        //如果没有
        if (productGroup.getProductIds() == null || "".equals(productGroup.getProductIds())) {
            for (String s : addProduct.getIds()) {
                sb.append(s);
                sb.append(",");
            }

            tbProductGroup.setProductIds(sb.toString());
            tbProductGroup.setId(addProduct.getGroupId());
            this.update(tbProductGroup);
        }else {
            //如果有
            for (String s : addProduct.getIds()) {
                sb.append(s);
                sb.append(",");
            }
            sb.append(productGroup.getProductIds());

            tbProductGroup.setProductIds(sb.toString());
            tbProductGroup.setId(addProduct.getGroupId());
            this.update(tbProductGroup);
        }

        return new ResponseEntity<>(HttpStatus.OK);

    }



}
