package com.persagy.dmp.rwd.demand.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.persagy.dmp.common.constant.ValidEnum;
import com.persagy.dmp.common.lang.PsDate;
import com.persagy.dmp.common.lang.PsDateTime;
import com.persagy.dmp.rwd.demand.constant.DemandBillState;
import com.persagy.dmp.rwd.demand.dao.DictionaryDemandMapper;
import com.persagy.dmp.rwd.demand.entity.DictionaryDemand;
import com.persagy.dmp.rwd.demand.service.IDictionaryDemandService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 字典需求 实现类
 * @author Charlie Yu
 * @date 2021-09-16
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class DictionaryDemandServiceImpl extends ServiceImpl<DictionaryDemandMapper, DictionaryDemand> implements IDictionaryDemandService {

    @Override
    public DictionaryDemand saveOrSubmit(DictionaryDemand vo, Boolean submitFlag) {
        // 提交
        if(BooleanUtil.isTrue(submitFlag)) {
            vo.setBillState(DemandBillState.SUBMITTED.getIndex());
            vo.setSubmitTime(new PsDateTime());
        } else if(vo.getBillState() == null) {
            vo.setBillState(DemandBillState.SAVING.getIndex());
        }
        vo.setValid(ValidEnum.TRUE.getType());
        saveOrUpdate(vo);
        // 首次提交后，生成编码
        if(BooleanUtil.isTrue(submitFlag)) {
            // 保存后，更新编码（有值就不再更新了)
            getBaseMapper().updateMaxCode(vo.getId());
        }
        return getById(vo.getId());
    }

    @Override
    public void deleteByIds(List<String> ids) {
        if(CollUtil.isEmpty(ids)) {
            return;
        }
        // 查询
        List<DictionaryDemand> vos = listByIds(ids);
        if(CollUtil.isEmpty(vos)) {
            return;
        }
        vos.forEach(p -> p.setValid(ValidEnum.FALSE.getType()));
        updateBatchById(vos);
    }

    @Override
    public List<DictionaryDemand> answer(List<String> ids, Integer state, String respondent, String reply, PsDate date) {
        if(CollUtil.isEmpty(ids) || state == null) {
            return null;
        }
        // 查询
        List<DictionaryDemand> vos = listByIds(ids);
        // 赋值
        PsDateTime now = new PsDateTime();
        for(DictionaryDemand vo:vos) {
            vo.setBillState(state);
            vo.setRespondent(respondent);
            vo.setReply(reply);
            vo.setAnswerTime(now);
            // 论证中的，需要填写预计回复日期
            if(DemandBillState.PROOFING.getIndex().equals(state)) {
                vo.setEstimateTime(date);
            }
        }
        updateBatchById(vos);
        return vos;
    }
}
