<template>
  <div class="app-container">
    <el-card shadow="hover" style="max-width: 1000px; margin: 0 auto;">
      <div slot="header" class="clearfix">
        <span>上传MES地址维护</span>
      </div>

      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="mt-4">
        <el-form-item label="MES地址" prop="mesAddress">
          <el-input
            v-model="form.msg"
            placeholder="请输入上传MES地址"
            style="width:700px"
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="handleSave"
            :loading="loading"
          >
            <i class="el-icon-check"></i> 保存设置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getUploadMesAddress, updateUploadMesAddress } from "@/api/system/config";

export default {
  name: "MesAddressConfig",
  data() {
    return {
      // 加载状态
      loading: false,
      // 表单数据
      form: {
        msg: ""
      },
      // 表单校验规则
      rules: {
        msg: [
          { required: true, message: "MES地址不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (value && !this.isValidUrl(value)) {
                callback(new Error("请输入有效的URL地址"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ]
      }
    };
  },
  created() {
    // 初始化时加载数据
    this.fetchData();
  },
  methods: {
    /**
     * URL格式验证
     */
    isValidUrl(url) {
      try {
        new URL(url);
        return true;
      } catch (e) {
        return false;
      }
    },

    /**
     * 加载MES地址数据
     */
    fetchData() {
      this.loading = true;
      getUploadMesAddress().then(response => {
        if (response.msg) {
          this.form = { ...response };
        }
      }).catch(error => {
        this.$message.error("加载MES地址失败: " + (error.message || "未知错误"));
      }).finally(() => {
        this.loading = false;
      });
    },

    /**
     * 保存设置
     */
    handleSave() {
      this.$refs["formRef"].validate(valid => {
        if (valid) {
          this.loading = true;
          let obj = {
            configValue: this.form.msg
          };
          updateUploadMesAddress(obj).then(response => {
            this.$message.success("保存成功");
          }).catch(error => {
            this.$message.error("保存失败: " + (error.message || "未知错误"));
          }).finally(() => {
            this.loading = false;
          });
        }
      });
    },
  }
};
</script>

<style scoped>
.el-card {
  border-radius: 12px;
  border: 1px solid #ebeef5;
}

.el-card__header {
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
}

.el-form-item {
  margin-bottom: 20px;
}

.w-80 {
  width: 240px;
}

.mt-4 {
  margin-top: 16px;
}
</style>
