package cn.estsh.i3plus.ext.mes.pcn.apiservice.controller.busi;

import cn.estsh.i3plus.ext.mes.pcn.api.base.IMesTemplateService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.constant.MesCommonConstant;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.mes.pcn.api.iservice.base.IConfigService;
import cn.estsh.impp.framework.boot.exception.ImppBusiException;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import cn.estsh.impp.framework.boot.util.ResultBean;
import cn.estsh.impp.framework.boot.util.ValidatorBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@Api("获取系统配置的模版信息")
@RestController
@RequestMapping(MesCommonConstant.MES_YANFEN)
public class MesLabelTemplateExtController {

    @Autowired
    private IConfigService configService;

    @Autowired
    private IMesTemplateService mesTemplateService;

    @GetMapping("/label-template/by-module-or-template/get")
    @ApiOperation(value = "获取系统配置的模版信息")
    public ResultBean queryMesLabelTemplate(String organizeCode, String moduleCode, String templateCode) {
        try {
            ValidatorBean.checkNotNull(organizeCode, "工厂代码不能为空");
            if (StringUtils.isEmpty(moduleCode) && StringUtils.isEmpty(templateCode)) {
                ValidatorBean.checkNotNull(moduleCode, "模版配置代码不能为空");
            }
            if (!StringUtils.isEmpty(moduleCode)) {
                Map<String, String> configMap = configService.getConfigMapByCfgCode(moduleCode, organizeCode);
                String templateCustomHtml = configMap.get(MesPcnExtConstWords.TEMPLATE_CUSTOM_HTML);
                if (!StringUtils.isEmpty(templateCustomHtml)) return ResultBean.success("查询成功").setResultObject(templateCustomHtml);
                String templateCfg = configMap.get(moduleCode);
                if (!StringUtils.isEmpty(templateCfg)) templateCode = templateCfg;
            }
            ValidatorBean.checkNotNull(templateCode, "模版代码不能为空");
            return ResultBean.success("查询成功").setResultObject(mesTemplateService.getMesLabelTemplate(templateCode, organizeCode));

        } catch (ImppBusiException imppException) {
            return ResultBean.fail(imppException);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

}
