package thyyxxk.webserver.service.lc.purchasePlan;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import thyyxxk.webserver.dao.his.lc.purchasePlan.LcPurchasePlanDao;
import thyyxxk.webserver.dao.his.lc.purchasePlan.LcPurchasePlanDetailDao;
import thyyxxk.webserver.entity.lc.project.LcProject;
import thyyxxk.webserver.entity.lc.purchasePlan.LcPurchasePlan;
import thyyxxk.webserver.entity.lc.purchasePlan.LcPurchasePlanDetail;
import thyyxxk.webserver.entity.lc.purchasePlan.LcPurchasePlanParam;

import java.util.Collections;
import java.util.UUID;

import static com.baomidou.mybatisplus.extension.toolkit.Db.save;

@Slf4j
@Service
public class LcPurchasePlanService {

    @Autowired
    private LcPurchasePlanDao dao;

    @Autowired
    private LcPurchasePlanDetailDao detailDao;

    @Transactional(rollbackFor = Exception.class)
    public boolean savePlanWithDetails(LcPurchasePlan plan) {
        if(StringUtils.isNotBlank(plan.getId())) {
            dao.updateById(plan);
            if (plan.getDetails() != null && !plan.getDetails().isEmpty()) {
                for (LcPurchasePlanDetail detail : plan.getDetails()) {
                    detailDao.updateById(detail);
                }
            }
        } else {
            plan.setId(UUID.randomUUID().toString().replace("-", ""));
            int insert = dao.insert(plan);
            if (insert > 0 && plan.getDetails() != null && !plan.getDetails().isEmpty()) {
                for (LcPurchasePlanDetail detail : plan.getDetails()) {
                    detail.setLcPurchasePlanId(plan.getId());
                    detailDao.insert(detail);
                }
            }
        }

        return true;
    }

    public Page<LcPurchasePlan> getLcPurchasePlanList(LcPurchasePlanParam lcPurchasePlanParam) {
        Page<LcPurchasePlan> page = new Page<>(lcPurchasePlanParam.getPageNumber(), lcPurchasePlanParam.getPageSize());

        LambdaQueryWrapper<LcPurchasePlan> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(lcPurchasePlanParam.getDeptCode())) {
            queryWrapper.eq(LcPurchasePlan::getDeptCode, lcPurchasePlanParam.getDeptCode());
        }
        if (StringUtils.isNotBlank(lcPurchasePlanParam.getLcPurchasePlanCode())) {
            queryWrapper.like(LcPurchasePlan::getLcPurchasePlanCode, lcPurchasePlanParam.getLcPurchasePlanCode());
        }

        return dao.selectPage(page, queryWrapper);
    }

}
