<template>
  <view class="app-content">
    <form @submit="formSubmit">
      <view class="module-com">
        <view class="editor-container">
          <rich-media-editor
            ref="richEditor"
            v-model="form.imageTextVos"
            @change="onContentChange"
            @collect-delete="onCollectDelete"
            :action="getLoginInfo.imgUploadApi"
            :deferDelete="isEdit"
          />
        </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 { getItemDesc, createItemDesc, updateItemDesc } from '@/api/item/picText.js';
export default {
  name: 'picTextAdd',
  components: {
    TuiListCell,
    RichMediaEditor
  },
  data() {
    return {
      form: {
        title: '',
        imageTextVos: [] // 图文内容数组
      },
      isEdit: false,
      descId: null, // 图文简介ID
      itemId: null, // 花材ID
      // 编辑模式下，暂存删除的图片路径（短路径）
      delImgQueue: []
    };
  },
  async onLoad(option) {
    try {
      if (option && option.itemId) {
        this.itemId = option.itemId;
        const res = await this.getDetDesc();
        if (res === 'create') {
          this.isEdit = false;
          uni.setNavigationBarTitle({
            title: '创建简介'
          });
        } else {
          this.isEdit = true;
          uni.setNavigationBarTitle({
            title: '修改简介'
          });
        }
      } else {
        this.$msg('缺少商品ID参数');
        uni.navigateBack();
      }
    } catch (error) {
      console.error('页面加载错误:', error);
      this.isEdit = false;
      uni.setNavigationBarTitle({
        title: '创建简介'
      });
      this.$msg('页面加载失败，请重试');
    }
  },
  methods: {
    init() {},
    // 获取描述
    async getDetDesc() {
      try {
        const res = await getItemDesc({ itemId: this.itemId });
        
        if (res.code == 0 || this.$util.isEmpty(res.data)) {
          return 'create';
        }

        if(res.code == 1 && res.data == 'not_exist'){
          return 'create';
        }

        this.descId = res.data.id;

        // 确保将字符串转换成数组
        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) => {
          return {
            type: item.type || 3, // 默认为文本类型
            content: item.content || ''
          };
        });

        this.form = {
          title: res.data.title || '',
          imageTextVos: content
        };

        // 触发富文本编辑器内容更新
        this.$nextTick(() => {
          setTimeout(() => {
            if (this.$refs.richEditor) {
              this.$refs.richEditor.updateContent(this.form.imageTextVos);
            }
          }, 50);
        });
        
        return 'edit';
      } catch (error) {
        console.error('获取描述失败:', error);
        return 'create';
      }
    },
    // 图文内容变化处理
    onContentChange(content) {
      this.form.imageTextVos = content;
    },

    // 预览内容
    previewContent() {
      if (this.form.imageTextVos.length === 0) {
        this.form.imageTextVos = [
          {
            type: 3,
            content: '这是一个预览示例，因为当前没有添加任何内容。'
          }
        ];
      }

      // 准备预览数据
      const previewData = {
        title: this.form.title || '未命名图文',
        content: this.form.imageTextVos
      };

      // 通过全局数据传递
      const app = getApp();
      app.globalData = app.globalData || {};
      app.globalData.previewData = previewData;

      // 跳转到预览页面
      uni.navigateTo({
        url: '/admin/picText/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 ? updateItemDesc : createItemDesc;

      // 准备提交参数
      let params = {
        title: this.form.title,
        content: JSON.stringify(this.form.imageTextVos)
      };

      // 编辑模式需要添加简介ID，创建模式需要关联商品ID
      if (this.isEdit) {
        params.id = this.descId;
        params.itemId = this.option.itemId;
      } else {
        params.itemId = this.option.itemId;
      }

      apiCall(params)
        .then((res) => {
          uni.hideLoading();
          if (res.code == 1) {
            uni.$emit('refreshListPage');
            that.$msg(this.isEdit ? '修改成功' : '添加成功');
            // 编辑模式下，如存在待删图片，统一调用批量删除
            if (this.isEdit && this.delImgQueue.length > 0) {
              const { delImages } = require('@/api/pic-text');
              const filePaths = Array.from(new Set(this.delImgQueue))
              delImages({ filePaths }).then(() => {
                this.delImgQueue = []
              }).catch(() => {})
            }
            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);
      }
    },
    // 收集编辑模式下的删除图片
    onCollectDelete(payload){
      if (!this.isEdit) return;
      if (!payload || !Array.isArray(payload.filePaths)) return;
      payload.filePaths.forEach(p => {
        if (p && !this.delImgQueue.includes(p)) this.delImgQueue.push(p)
      })
    },
  }
};
</script>

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

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

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

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