package org.jeecg.modules.ctop.service.impl;

import cn.com.ctop.common.module.utils.ResultMapUtils;
import cn.com.ctop.common.module.utils.StatusCode;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.modules.ctop.entity.DramaItemInfo;
import org.jeecg.modules.ctop.entity.DramaRoleInfo;
import org.jeecg.modules.ctop.mapper.DramaItemInfoMapper;
import org.jeecg.modules.ctop.service.IDramaItemInfoService;
import org.jeecg.modules.ctop.service.IDramaRoleInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 剧本内容信息
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2020-03-06
 */
@Service
public class DramaItemInfoServiceImpl extends ServiceImpl<DramaItemInfoMapper, DramaItemInfo> implements IDramaItemInfoService {

    @Autowired
    private IDramaRoleInfoService roleInfoService;

    @Override
    public List<DramaItemInfo> getByDramaId(Long dramaId) {
        QueryWrapper<DramaItemInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("drama_id", dramaId).eq("enabled", 1).orderByAsc("rank").orderByDesc("update_time");
        List<DramaItemInfo> infos = this.list(queryWrapper);
        List<DramaItemInfo> returnInfos = new ArrayList<>();
        if (null != infos && infos.size() > 0) {
            for (DramaItemInfo itemInfo : infos) {
                if (null != itemInfo.getRoleId()) {
                    DramaRoleInfo roleInfo = roleInfoService.getById(itemInfo.getRoleId());
                    itemInfo.setRoleName(roleInfo.getName());
                }
                returnInfos.add(itemInfo);
            }
        }
        return returnInfos;
    }

    @Override
    public int getMaxRankByDramaId(Long dramaId) {
        QueryWrapper<DramaItemInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("drama_id", dramaId);
        queryWrapper.orderByDesc("rank").last(" limit 1");
        DramaItemInfo itemInfo = this.getOne(queryWrapper);
        if (null == itemInfo) {
            return 1;
        } else {
            return itemInfo.getRank() + 1;
        }
    }

    @Override
    public Map<String, Object> delete(Long id) {
        Map<String, Object> result = new HashMap<>();
        DramaItemInfo info = this.getById(id);
        if (null == info) {
            ResultMapUtils.setResultMap(result, StatusCode.COMMON_DATA_NOT_EXIST);
            return result;
        }
        info.setEnabled(0);
        this.updateById(info);
        ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS);
        return result;
    }
}
