package com.mortals.xhx.module.platform.service.impl;

import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.xhx.common.code.PlatformStatus;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.common.pdu.api.ApiRespPdu;
import com.mortals.xhx.feign.flowable.IApiFlowDefinitionFeign;
import com.mortals.xhx.flowable.FlowDefSaveReq;
import com.mortals.xhx.tools.uid.ISeqGeneratorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.xhx.module.platform.dao.PlatformModelinfoDao;
import com.mortals.xhx.module.platform.model.PlatformModelinfoEntity;
import com.mortals.xhx.module.platform.service.PlatformModelinfoService;

/**
 * <p>Title: 平台用户模型关系表</p>
 * <p>Description: PlatformModelinfoService service接口 </p>
 * <p>Copyright: Copyright &reg;  </p>
 *
 * @version 1.0.0
 */
@Service("platformModelinfoService")
public class PlatformModelinfoServiceImpl extends AbstractCRUDServiceImpl<PlatformModelinfoDao, PlatformModelinfoEntity, Long> implements PlatformModelinfoService {

    @Autowired
    private ISeqGeneratorService seqGeneratorService;
    @Autowired
    private IApiFlowDefinitionFeign apiFlowDefinitionFeign;


    @Override
    protected void saveBefore(PlatformModelinfoEntity entity, Context context) throws AppException {
        long num = seqGeneratorService.nextOrderId(0);
        entity.setModelId(num + "");
        entity.setModelKey(num + "_" + entity.getName());

        super.saveBefore(entity, context);
    }

    @Override
    public String deployFlowByXml(Long id, Context context) {
        PlatformModelinfoEntity entity = this.get(id);

        FlowDefSaveReq req = new FlowDefSaveReq();
        req.setName(entity.getName());
        req.setCategory(entity.getCategoryName());
        req.setBpmnXml(entity.getBpmnXml());
        req.setTenantId(entity.getPlatformSn());

        try {
            ApiRespPdu<String> resp = apiFlowDefinitionFeign.save(req);
            if (YesNoEnum.NO.getValue() == resp.getCode()) {
                log.error("流程部署异常：" + resp.getMsg());
                throw new AppException(resp.getMsg());
            }
            entity.setDeployId(resp.getData());
            entity.setStatus(PlatformStatus.PUBLISH.getValue());
            this.update(entity);
            return resp.getData();

        } catch (Exception e) {
            log.error("流程部署异常", e);
            throw new AppException(e.getMessage());
        }

    }
}