<template>
  <div class="app-container agreement-page">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <!-- 基础信息：第一个 el-card -->
      <el-card v-loading="loading" shadow="never" class="info-card">
        <div slot="header" class="card-header">
          <span>商城入驻协议</span>
          <span class="header-tip">关闭启用后，C 端将无法提交新的商家入驻申请</span>
        </div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="协议标题" prop="agreementTitle">
              <el-input v-model="form.agreementTitle" placeholder="请输入协议标题" maxlength="128" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="协议版本号" prop="versionLabel">
              <el-input v-model="form.versionLabel" placeholder="如 v1.0（选填）" maxlength="32" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否启用" prop="enableFlag">
              <el-radio-group v-model="form.enableFlag">
                <el-radio label="1">是</el-radio>
                <el-radio label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最后更新">
              <span class="readonly-text">{{ form.updateBy || '—' }} / {{ parseTime(form.updateTime) || '—' }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 协议正文：第二个 el-card -->
      <el-card shadow="never" class="content-card">
        <div slot="header">
          <span>协议内容</span>
        </div>
        <el-form-item label="正文" prop="content" label-width="100px">
          <editor v-model="form.content" :min-height="280" />
        </el-form-item>
        <el-form-item label-width="100px">
          <el-button type="info" plain icon="el-icon-view" @click="previewOpen = true">预览</el-button>
          <el-button type="primary" @click="submitForm" v-hasPermi="['agri:merchantEntryAgreement:edit']">保 存</el-button>
        </el-form-item>
      </el-card>
    </el-form>

    <!-- 协议预览弹窗 -->
    <el-dialog title="协议预览" :visible.sync="previewOpen" width="800px" append-to-body>
      <h3 class="preview-title">{{ form.agreementTitle || '协议标题' }}</h3>
      <p v-if="form.versionLabel" class="preview-version">版本：{{ form.versionLabel }}</p>
      <div class="preview-content" v-html="form.content"></div>
    </el-dialog>
  </div>
</template>

<script>
import { getMerchantEntryAgreement, saveMerchantEntryAgreement } from "@/api/agri/merchantEntryAgreement"

export default {
  name: "MerchantEntryAgreement",
  data() {
    // 自定义校验：启用时协议内容不能为空
    const validateContent = (rule, value, callback) => {
      if (this.form.enableFlag === "1" && this.isBlankHtml(value)) {
        callback(new Error("启用状态下请填写协议内容"))
      } else {
        callback()
      }
    }
    return {
      // 页面加载遮罩
      loading: true,
      // 是否显示预览弹窗
      previewOpen: false,
      // 表单数据
      form: {
        configId: 1,
        agreementTitle: "",
        versionLabel: "",
        content: "",
        enableFlag: "0",
        updateBy: "",
        updateTime: ""
      },
      // 表单校验规则
      rules: {
        agreementTitle: [
          { required: true, message: "请输入协议标题", trigger: "blur" }
        ],
        enableFlag: [
          { required: true, message: "请选择是否启用", trigger: "change" }
        ],
        content: [
          { validator: validateContent, trigger: "blur" }
        ]
      }
    }
  },
  watch: {
    // 启用状态变化时重新校验正文
    "form.enableFlag"() {
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.validateField("content")
        }
      })
    }
  },
  created() {
    this.loadConfig()
  },
  methods: {
    /** 加载当前协议配置 */
    loadConfig() {
      this.loading = true
      getMerchantEntryAgreement().then(response => {
        this.form = Object.assign({}, this.form, response.data || {})
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    /** 判断富文本是否为空（去掉 HTML 标签后） */
    isBlankHtml(html) {
      if (!html) {
        return true
      }
      const text = html.replace(/<[^>]+>/g, "").replace(/&nbsp;/g, " ").trim()
      return !text
    },
    /** 保存协议配置 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return
        }
        saveMerchantEntryAgreement({
          agreementTitle: this.form.agreementTitle,
          versionLabel: this.form.versionLabel,
          content: this.form.content,
          enableFlag: this.form.enableFlag,
          remark: this.form.remark
        }).then(() => {
          this.$modal.msgSuccess("保存成功")
          this.loadConfig()
        })
      })
    }
  }
}
</script>

<style scoped>
.info-card {
  margin-bottom: 10px;
}
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.header-tip {
  color: #909399;
  font-size: 13px;
  font-weight: normal;
}
.readonly-text {
  color: #606266;
}
.preview-title {
  margin: 0 0 8px;
  text-align: center;
}
.preview-version {
  margin: 0 0 16px;
  text-align: center;
  color: #909399;
  font-size: 13px;
}
.preview-content {
  max-height: 60vh;
  overflow-y: auto;
  line-height: 1.8;
  padding: 0 12px;
}
</style>
