<template>
    <div class="ele-body">
        <el-card shadow="never">
            <el-tabs v-model="tabValue" type="card" @tab-click="handleTabClick">
                <el-tab-pane label="范文信息" name="1">
                    <el-form
                        :model="formData"
                        ref="form"
                        label-width="110px"
                        :rules="rules"
                        style="margin-top: 20px;"
                    >
                        <el-row :gutter="24">
                            <el-col :span="6">
                                <el-form-item label="范文编号" prop="code">
                                    <el-input
                                        placeholder="系统自动编号"
                                        disabled
                                        v-model="formData.code"
                                    >
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="范文名称" prop="name">
                                    <el-input
                                        placeholder="请输入范文名称"
                                        v-model="formData.name"
                                        :disabled="disabled"
                                    >
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="状态" prop="status">
                                    <el-switch
                                        v-model="formData.status"
                                        :disabled="disabled"
                                        active-text="启用"
                                        inactive-text="停用">
                                    </el-switch>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </el-tab-pane>
                <el-tab-pane label="稿纸信息" name="2">
                    <MainBodyTemplate ref="mainBodyTemplate" :type="routerQuery.type"></MainBodyTemplate>
                </el-tab-pane>
                <el-tab-pane label="正文" name="3">
                     <tinymce-editor :disabled="disabled" v-model="formData.content" :init="{ height: 525 }" />
                </el-tab-pane>
            </el-tabs>
            <div v-if="!disabled" class="footer">
                <el-button type="primary" @click="save" v-click-once>保存</el-button>
                <el-button @click="cancel">取消</el-button>
            </div>
        </el-card>
    </div>
</template>
<script>
import MainBodyTemplate from './mainBodyTemplate.vue'
import TinymceEditor from '@/components/TinymceEditor/index.vue';
import { createDoc, docTplTemplateById, updateDoc } from '@/api/documents/doc-manage';

export default {
  components: {
    MainBodyTemplate,
    TinymceEditor
  },

  data() {
    return {
      tabValue: '1',
      formData: {
        code: '',
        name: '',
        status: true,
        content: '',
        fields: [],
        directoryId: ''
      },
      rules: {
        // code: [{ required: true, message: '请输入范文编号', trigger: 'blur' }],
        name: [{ required: true, message: '请输入范文名称', trigger: 'blur' }],
        status: [{ required: true, message: '请选择状态', trigger: 'blur' }],
      },
    }
  },
  created() {
    console.log('created~~~~');
    this.routerQuery = this.$route.query || {};
    this.formData.directoryId = this.routerQuery.treeId || '';
    if(this.routerQuery.type != 'add') {
      this.getDetail();
    }
  },
  computed: {
    disabled() {
      return this.routerQuery.type == 'detail';
    }
  },
  methods: {
    async getDetail() {
      console.log('getDetail~~~~');
      let res = await docTplTemplateById(this.routerQuery.id);
      res.status = res.status == 1 ? true : false;
      this.formData = res;
      this.$refs.mainBodyTemplate.setData(this.formData.fields);
    },
    handleTabClick(tab) {
      this.tabValue = tab.name;
    },
    async save() {
      try {
        // 先校验范文信息表单
        const formValid = await this.$refs.form.validate().catch(() => false);
        if (!formValid) {
          this.$message.warning('请完善范文信息');
          return;
        }

        // 校验子组件 mainBodyTemplate 的必填项
        const mainBodyValid = await this.$refs.mainBodyTemplate.$refs.form.validate().catch(() => false);
        if (!mainBodyValid) {
          this.$message.warning('请完善稿纸信息的必填项');
          return;
        }

        // 获取自定义字段数据
        const customFields = this.$refs.mainBodyTemplate.generateCustomFields();

        // 将 customFields 放到 formData 字段
        this.formData.fields = customFields;

        this.formData.status = this.formData.status ? 1 : 0;

        console.log('提交数据:', this.formData);

        // 提交到后端
        const loading = this.$loading({ lock: true });
        const requestUrl = this.routerQuery.type == 'edit' ? updateDoc : createDoc;
        requestUrl(this.formData)
          .then((res) => {
            loading.close();
            this.$message.success('保存成功');
            this.$router.go(-1);
          })
          .catch((e) => {
            loading.close();
            console.error('保存失败:', e);
          });

      } catch (error) {
        console.error('保存异常:', error);
      }
    },

    cancel() {
      this.$router.go(-1);
    },
  }
}
</script>
<style scoped>
.el-card {
  min-height: 600px;
}
.footer {
  text-align: center;
}
</style>
