package com.mortals.xhx.module.demo.service.impl;
import org.springframework.stereotype.Service;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.xhx.module.demo.dao.DemoDao;
import com.mortals.xhx.module.demo.model.DemoEntity;
import com.mortals.xhx.module.demo.service.DemoService;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import org.springframework.beans.factory.annotation.Autowired;
import com.mortals.xhx.module.demo.detail.model.DemoDetailEntity;
import com.mortals.xhx.module.demo.detail.model.DemoDetailQuery;
import com.mortals.xhx.module.demo.detail.service.DemoDetailService;
import org.springframework.util.ObjectUtils;
import java.util.Date;
import cn.hutool.core.util.IdUtil;



/**
 * DemoService
 * 测试demo service实现
 *
 * @author zxfei
 * @date 2021-10-22
 */
@Service("demoService")
public class DemoServiceImpl extends AbstractCRUDServiceImpl<DemoDao, DemoEntity, String> implements DemoService {
    @Autowired
    private DemoDetailService demoDetailService;

    @Override
    protected void saveBefore(DemoEntity entity, Context context) throws AppException {
        //非系统自增，需这里设置主键
        entity.setId(IdUtil.fastSimpleUUID());
        super.saveBefore(entity, context);
    }


    @Override
    protected void saveAfter(DemoEntity entity, Context context) throws AppException {
        if(!ObjectUtils.isEmpty(entity.getDemoDetailList())){
            entity.getDemoDetailList().stream().peek(item->{
                item.setDemoId(entity.getId());
                item.setCreateUser(context.getUser().getLoginName());
                item.setCreateUserId(context.getUser().getId());
                item.setCreateTime(new Date());
            }).count();
            demoDetailService.save(entity.getDemoDetailList());
        }
        super.saveAfter(entity, context);
    }

    @Override
    protected void updateAfter(DemoEntity entity, Context context) throws AppException {
        if(!ObjectUtils.isEmpty(entity.getDemoDetailList())){
            Long[] demoDetailIds = demoDetailService.find(new DemoDetailQuery().demoId(entity.getId())).stream().map(DemoDetailEntity::getId).toArray(Long[]::new);
            demoDetailService.remove(demoDetailIds,context);
            entity.getDemoDetailList().stream().peek(item ->{
                item.setDemoId(entity.getId());
                item.setCreateUser(context.getUser().getLoginName());
                item.setCreateUserId(context.getUser().getId());
                item.setCreateTime(new Date());
                item.setUpdateUser(context.getUser().getLoginName());
                item.setUpdateUserId(context.getUser().getId());
                item.setUpdateTime(new Date());
            }).count();
            demoDetailService.save(entity.getDemoDetailList());
        }
        super.updateAfter(entity, context);
    }
}