<template>
  <view class="app-content">
    <form @submit="formSubmit" @reset="formReset">
      <view class="module-com input-line-wrap">

        <tui-list-cell class="line-cell" :hover="false">
            <view class="tui-title required">标题</view>
            <input v-model="form.title" type="text" placeholder-class="phcolor" placeholder-style="color:#CCCCCC" placeholder="请输入" class="tui-input" name="title" />
        </tui-list-cell>

        <view class="editor-container">
          <rich-media-editor 
            ref="richEditor"
            v-model="form.imageTextVos" 
            @change="onContentChange"
            :action="getLoginInfo.imgUploadApi"
          />
        </view>

        <view class="confirm-btn">
          <button class="admin-button-com big" @click="previewContent">预览</button>
          <button class="admin-button-com big blue" formType="submit">确认</button>
        </view>
      </view>
    </form>
  </view>
</template>

<script>
import TuiListCell from "@/components/plugin/list-cell";
import RichMediaEditor from "@/components/RichMediaEditor/index.vue";
const form = require("@/utils/formValidation.js");
import { getPicText, createPicText, updatePicText } from "@/api/pic-text";

export default {
  name: "picTextAdd",
  components: {
    TuiListCell,
    RichMediaEditor
  },
  data() {
    return {
      form: {
        title: '',
        imageTextVos: [] // 新增图文内容数组
      },
      isEdit: false
    };
  },
  onLoad(option) {
    if (option.id) {
      this.isEdit = true;
      // 设置页面标题
      uni.setNavigationBarTitle({
        title: '编辑图文'
      })
      this._getDet();
    } else {
      uni.setNavigationBarTitle({
        title: '新增图文'
      })
    }
  },
  methods: {
    init(){
    },
    // 获取详情
    _getDet() {
      getPicText({ id: this.option.id }).then(res => {
        if (this.$util.isEmpty(res.data)) return;
        
        // 确保将字符串转换成数组
        let content = [];
        if (typeof res.data.content === 'string') {
          try {
            content = JSON.parse(res.data.content);
          } catch (e) {
            console.error('解析图文内容失败:', e);
            content = [];
          }
        } else if (Array.isArray(res.data.content)) {
          content = res.data.content;
        }
        
        // 处理内容数据，确保每个项目都有正确的格式
        content = content.map(item => {
          // 确保每个项目都有type和content属性
          return {
            type: item.type || 3, // 默认为文本类型
            content: item.content || ''
          };
        });
        
        this.form = {
          title: res.data.title || '',
          imageTextVos: content
        };
        
        // 触发富文本编辑器内容更新
        this.$nextTick(() => {
          // 确保组件已经更新数据后再触发更新
          setTimeout(() => {
            if (this.$refs.richEditor) {
              console.log('更新编辑器内容');
              this.$refs.richEditor.updateContent(this.form.imageTextVos);
            } else {
              console.error('找不到richEditor引用');
            }
          }, 100);
        });
      });
    },
    // 图文内容变化处理
    onContentChange(content) {
      this.form.imageTextVos = content;
    },
    
    // 预览内容
    previewContent() {
      console.log('点击了预览按钮');
      console.log('当前图文内容:', this.form.imageTextVos);
      
      if (this.form.imageTextVos.length === 0) {
        // console.log('内容为空，使用示例数据进行预览');
        // 如果没有内容，使用示例数据进行预览
        this.form.imageTextVos = [
          {
            type: 3,
            content: "这是一个预览示例，因为当前没有添加任何内容。"
          }
        ];
      }
      
      // 准备预览数据
      const previewData = {
        title: this.form.title || '未命名图文',
        content: this.form.imageTextVos
      };
      
      console.log('准备预览数据:', previewData);
      
      // 通过全局数据传递
      const app = getApp();
      app.globalData = app.globalData || {};
      app.globalData.previewData = previewData;
      
      console.log('全局数据已设置:', app.globalData.previewData);
      
      // 跳转到预览页面
      uni.navigateTo({
        url: './preview',
        success: (res) => {
          console.log('跳转成功:', res);
        },
        fail: (err) => {
          console.error('跳转失败:', err);
          this.$msg('页面跳转失败，请检查路由配置');
        }
      });
    },
    // 提交
    confirmFn() {
      uni.showLoading({mask: true});
      let that = this;
      let apiCall = this.isEdit ? updatePicText : createPicText;
      
      // 准备提交参数
      let params = {
        title: this.form.title,
        content: JSON.stringify(this.form.imageTextVos),
        type: this.option.type
      };
      
      // 编辑模式需要添加ID
      if (this.isEdit) {
        params.id = this.option.id;
      }
      
      
      apiCall(params).then(res => {
        uni.hideLoading();
        if(res.code == 1){
          uni.$emit('refreshListPage');
          that.$msg(this.isEdit ? '修改成功' : '添加成功');
          uni.navigateBack({
            delta: 1
          });
        } else {
          that.$msg(res.message || '操作失败');
        }
      }).catch(err => {
        uni.hideLoading();
        console.error('提交失败:', err);
        that.$msg('提交失败，请稍后重试');
      });
    },
    formSubmit(e) {
      let rules = [
        { name: "title", rule: ["required", "notEmpty"], msg: ["请输入标题"] },
        //{ name: "imageTextVos", rule: ["notEmpty"], msg: ["请添加图文内容"] }
      ];
      let formData = e.detail.value;
      // 将图文内容添加到表单数据中进行验证
      // formData.imageTextVos = this.form.imageTextVos;
      let checkRes = form.validation(formData, rules);
      
      // 检查图文内容
      if (this.form.imageTextVos.length === 0) {
        this.$msg("请添加至少一项图文内容");
        return;
      }
      
      if (!checkRes) {
        this.confirmFn();
      } else {
        this.$msg(checkRes);
      }
    },
    formReset() {
      this.form = {
        title: '',
        imageTextVos: []
      };
    }
  }
};
</script>

<style lang="scss" scoped>
.app-content {
  min-height: calc(100vh - 20upx);
  padding-top: 20upx;
  padding: 12upx;
  background-color: #f5f5f5;
}

.module-com {
  margin-bottom: 20upx;
}

.confirm-btn {
  display: flex;
  gap: 30rpx;
  margin: 40rpx 30rpx 20rpx;
  .admin-button-com {
    flex: 1;
  }
}

.editor-container {
  margin-bottom: 20rpx;
}
</style>