package com.ruoyi.system.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.Apply;
import com.ruoyi.system.domain.ApplyChild;
import com.ruoyi.system.mapper.ApplyChildMapper;
import com.ruoyi.system.mapper.ApplyMapper;
import com.ruoyi.system.service.IApplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 开通申请Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-10-26
 */
@Service
public class ApplyServiceImpl implements IApplyService
{
    @Autowired
    private ApplyMapper applyMapper;
    @Autowired
    private ApplyChildMapper childMapper;

    /**
     * 查询开通申请
     * 
     * @param applyId 开通申请ID
     * @return 开通申请
     */
    @Override
    public Apply selectApplyById(Long applyId)
    {
        return applyMapper.selectApplyById(applyId);
    }

    /**
     * 查询开通申请列表
     * 
     * @param apply 开通申请
     * @return 开通申请
     */
    @Override
    public List<Apply> selectApplyList(Apply apply)
    {
        return applyMapper.selectApplyList(apply);
    }

    /**
     * 新增开通申请
     * 
     * @param apply 开通申请
     * @return 结果
     */
    @Override
    @Transactional
    public int insertApply(Apply apply)
    {
        apply.setApplyTime(DateUtils.getNowDate());
        apply.setCreateTime(DateUtils.getNowDate());
        apply.setDealStatus("1");
        int result = applyMapper.insertApply(apply);
        if(result>0){
            if(StringUtils.isNotEmpty(apply.getChildDatas())){
                //保存到子系统表
                String jsonStr = apply.getChildDatas();
                List<ApplyChild> childList = JSONArray.parseArray(jsonStr, ApplyChild.class);
                if(null!=childList && childList.size()>0){
                    for(ApplyChild child: childList){
                        child.setApplyId(apply.getApplyId());
                        child.setStatus("0");
                    }
                }
                childMapper.batchChildInfo(childList);
            }
        }
        return result;
    }

    /**
     * 修改开通申请
     * 
     * @param apply 开通申请
     * @return 结果
     */
    @Override
    public int updateApply(Apply apply)
    {
        apply.setUpdateTime(DateUtils.getNowDate());
        return applyMapper.updateApply(apply);
    }

    /**
     * 删除开通申请对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteApplyByIds(String ids)
    {
        return applyMapper.deleteApplyByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除开通申请信息
     * 
     * @param applyId 开通申请ID
     * @return 结果
     */
    @Override
    public int deleteApplyById(Long applyId)
    {
        return applyMapper.deleteApplyById(applyId);
    }
}
