package com.malk.benteler.service;

import com.alibaba.fastjson.JSON;
import com.malk.benteler.config.BentelerYidaConf;
import com.malk.benteler.dto.EiamTestResult;
import com.malk.server.aliwork.YDAuth;
import com.malk.server.aliwork.YDConf;
import com.malk.server.common.McException;
import com.malk.service.aliwork.YDClient_Form;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 宜搭连接器测试实例的读取与回写服务。
 */
@Service
public class BentelerYidaTestService {

    private static final String SUCCESS_RESULT = "成功";

    private final YDClient_Form ydClientForm;
    private final YDConf ydConf;
    private final BentelerYidaConf conf;

    public BentelerYidaTestService(YDClient_Form ydClientForm, YDConf ydConf,
                                   BentelerYidaConf conf) {
        this.ydClientForm = ydClientForm;
        this.ydConf = ydConf;
        this.conf = conf;
    }

    /**
     * 读取测试表单的最终处理结果，并回写为成功。
     *
     * @param formInstanceId 宜搭表单实例 ID
     * @return 回写前后的字段值
     */
    public EiamTestResult markResultSuccess(String formInstanceId) {
        validateConfiguration(formInstanceId);
        Map<String, Object> instance = ydClientForm.getForm(auth(), formInstanceId, null);
        validateForm(instance);
        String originalResult = readResult(instance);
        writeSuccess(formInstanceId);
        return EiamTestResult.builder()
                .formInstanceId(formInstanceId)
                .originalResult(originalResult)
                .updatedResult(SUCCESS_RESULT)
                .build();
    }

    private void validateConfiguration(String formInstanceId) {
        if (StringUtils.isBlank(formInstanceId)) {
            throw new McException("YIDA_FORM_INSTANCE_ID_EMPTY", "formInstanceId 不能为空");
        }
        if (StringUtils.isBlank(conf.getTestFormUuid())
                || StringUtils.isBlank(conf.getTestResultFieldId())) {
            throw new McException("YIDA_TEST_CONFIG_EMPTY", "宜搭测试表单字段配置不能为空");
        }
    }

    private void validateForm(Map<String, Object> instance) {
        if (instance == null || instance.get("formData") == null) {
            throw new McException("YIDA_FORM_DATA_EMPTY", "宜搭实例数据为空");
        }
        Object modelUuid = instance.get("modelUuid");
        String actualFormUuid = modelUuid == null
                ? null
                : StringUtils.trimToNull(String.valueOf(modelUuid));
        if (StringUtils.isNotBlank(actualFormUuid)
                && !StringUtils.equals(conf.getTestFormUuid(), actualFormUuid)) {
            throw new McException("YIDA_FORM_MISMATCH", "宜搭实例与测试表单不匹配: expected="
                    + conf.getTestFormUuid() + ", actual=" + actualFormUuid);
        }
    }

    @SuppressWarnings("unchecked")
    private String readResult(Map<String, Object> instance) {
        Object value = instance.get("formData");
        Map<String, Object> formData = value instanceof Map
                ? (Map<String, Object>) value
                : JSON.parseObject(String.valueOf(value), Map.class);
        return formData == null ? null : StringUtils.trimToNull(
                String.valueOf(formData.get(conf.getTestResultFieldId())));
    }

    private void writeSuccess(String formInstanceId) {
        Map<String, Object> update = new HashMap<>();
        update.put(conf.getTestResultFieldId(), SUCCESS_RESULT);
        Map<String, Object> bodyExt = new HashMap<>();
        bodyExt.put("useLatestVersion", true);
        bodyExt.put("ignoreEmpty", false);
        ydClientForm.updateForm(auth(), formInstanceId, JSON.toJSONString(update), bodyExt);
    }

    private YDAuth auth() {
        return YDAuth.ofGlobal(ydConf);
    }
}
