package com.pj.project.tb_business_sort;

import java.util.List;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pj.project.tb_costomer.TbCostomer;
import com.pj.project.tb_costomer.TbCostomerMapper;
import com.pj.project.tb_item_type.TbItemType;
import com.pj.project.tb_item_type.TbItemTypeService;
import com.pj.utils.so.SoMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * Service: tb_business_order -- 业务顺序
 *
 * @author qzy
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class TbBusinessSortService extends ServiceImpl<TbBusinessSortMapper, TbBusinessSort> implements IService<TbBusinessSort> {

    /**
     * 底层 Mapper 对象
     */
    @Autowired
    TbBusinessSortMapper tbBusinessOrderMapper;
    @Resource
    private TbItemTypeService tbItemTypeService;

    /**
     * 增
     */
    void add(String addJson) {
        remove(new QueryWrapper<>());
        List<AddBusinessSortBO> businessSortBOS = JSONUtil.toList(addJson, AddBusinessSortBO.class);
        int sort = 1;
        for (AddBusinessSortBO addBusinessSortBO : businessSortBOS) {
            TbBusinessSort tbBusinessSort = new TbBusinessSort();
            tbBusinessSort.setSingleIntervalTime(addBusinessSortBO.getSingleIntervalTime())
                    .setTypeId(addBusinessSortBO.getTypeId())
                    .setTypeName(addBusinessSortBO.getTypeName()).setSort(sort)
                    .setIntervalTime(addBusinessSortBO.getInterval());
            if (sort == 1) {
                tbBusinessSort.setIntervalTime(0);
            }
            this.save(tbBusinessSort);
            sort++;
        }
    }

    /**
     * 改
     */
    void update(TbBusinessSort t) {
        this.updateById(t);
    }

    /**
     * 查
     */
    TbBusinessSort getById(Long id) {
        return super.getById(id);
    }

    /**
     * 查集合 - 根据条件（参数为空时代表忽略指定条件）
     */
    public List<TbBusinessSort> getList(SoMap so) {
        return tbBusinessOrderMapper.getList(so);
    }


    public List<TbBusinessSort> findByGroupId(Long groupId) {
        QueryWrapper<TbBusinessSort> ew = new QueryWrapper<>();
        ew.eq("group_id", groupId);
        return list(ew);
    }

    public void removeByGroupId(Long groupId) {
        QueryWrapper<TbBusinessSort> ew = new QueryWrapper<>();
        ew.eq("group_id", groupId);
        this.remove(ew);
    }

    public TbBusinessSort findByItemTypeId(String typeId) {
        QueryWrapper<TbBusinessSort> ew = new QueryWrapper<>();
        ew.eq("type_id", typeId);
        List<TbBusinessSort>list=list(ew);
        return list.isEmpty()?null:list.get(0);
    }
}
