package com.yeejoin.amos.api.openapi.face.service;


import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yeejoin.amos.api.openapi.face.model.TmCylinderInspectionModel;
import com.yeejoin.amos.api.openapi.face.orm.dao.TmCylinderInspectionMapper;
import com.yeejoin.amos.api.openapi.face.orm.entity.TmCylinderInspection;
import com.yeejoin.amos.api.openapi.service.MyBaseServiceImpl;
import com.yeejoin.amos.api.openapi.util.MultiFieldKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import java.util.Date;
import java.util.List;

/**
 * <pre>
 * 气瓶检验信息 服务类
 * </pre>
 *
 * @author gwb
 * @version $Id: ElevatorService.java, v 0.1 2021年9月30日 下午3:28:55 gwb Exp $
 */
@Component
public class TmCylinderInspectionService extends MyBaseServiceImpl<TmCylinderInspectionModel, TmCylinderInspection, TmCylinderInspectionMapper> {

    @Autowired
    private SyncCylinderDataService syncCylinderDataService;

    @DSTransactional
    @Transactional(rollbackFor = {java.lang.Exception.class})
    public String createCylinderInspection(List<TmCylinderInspectionModel> model) {
        if (ValidationUtil.isEmpty(model)) throw new BadRequest("气瓶检验信息为空.");
        String appId = getAppId();
        Date now = new Date();
        for (TmCylinderInspectionModel cylinderInspectionModel : model) {
            cylinderInspectionModel.setSequenceNbr(null);
            cylinderInspectionModel.setRecDate(now);
            cylinderInspectionModel.setAppId(appId);
        }
        List<TmCylinderInspection> tmCylinderInspectionList = Bean.toModels(model, TmCylinderInspection.class);

        syncCylinderInspectionModel(model);

        this.saveOrUpdateBatchByUniqueFields(
                tmCylinderInspectionList,
                entity -> new LambdaQueryWrapper<TmCylinderInspection>()
                        .eq(TmCylinderInspection::getAppId, entity.getAppId())
                        .eq(TmCylinderInspection::getSequenceCode, entity.getSequenceCode())
                        .eq(TmCylinderInspection::getInspectionDate, entity.getInspectionDate()),
                entity -> new MultiFieldKey(entity.getAppId(), entity.getSequenceCode(), entity.getInspectionDate()),
                "appId", "sequenceCode", "inspectionDate");
        return "OK";
    }

    /**
     * 同步气瓶检验信息至气瓶服务
     *
     * @param model
     */
    private void syncCylinderInspectionModel(List<TmCylinderInspectionModel> model) {
        syncCylinderDataService.syncCylinderInspection(model);
    }
}
