<template>
  <div class="mainBox">
    <div class="layerBox">
      <tableTitle :name="tableDivTitle" />
      <el-form :model="form" ref="form" :rules="formRules" label-position="left" label-width="120px">
        <div class="formDiv">
          <el-form-item label="发布类型" prop="type_id" class="custom-align-right">
            <el-radio-group v-model="form.type_id">
              <el-radio :label="1">供应商品</el-radio>
              <el-radio :label="2">求购商品</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="商品名称：" prop="name" class="custom-align-right">
            <template #label>
              <span class="askBox" v-if="form.type_id == 1">
                商品名称：
              </span>
              <span class="askBox" v-if="form.type_id == 2">
                标题：
              </span>
            </template>
            <el-input v-model="form.name" autocomplete="off" placeholder="请输入商品标题"></el-input>
          </el-form-item>
          <el-form-item label="发布地点：" prop="city_arr_id" class="custom-align-right">
            <el-cascader :key="cascaderKey" v-model="form.city_arr_id" placeholder="发布地区：" :props="cityData" filterable
              clearable></el-cascader>
          </el-form-item>
          <el-form-item label="网站：" prop="website_id" class="custom-align-right" v-if="userType != 10000">
            <el-select v-model="form.website_id" placeholder="请选择网站" filterable clearable>
              <el-option v-for="item in websiteOptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="导航池名称：" prop="cat_arr_id" class="custom-align-right">
            <el-cascader :key="parentKey" v-model="form.cat_arr_id" placeholder="请选择要绑定的导航池名称" :props="parentData"
              filterable clearable></el-cascader>
          </el-form-item>
          <div v-if="form.type_id == 1">
            <el-form-item label="商品单价：" prop="price" class="custom-align-right">
              <el-input type="number" v-model="form.price" autocomplete="off" placeholder="请输入商品单价">
                <template #suffix>
                  元
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="单位：" prop="unit" class="custom-align-right">
              <el-input v-model="form.unit" autocomplete="off" placeholder="请输入单位"></el-input>
            </el-form-item>

            <el-form-item label="最小定量：" prop="min" class="custom-align-right">
              <el-input v-model="form.min" autocomplete="off" placeholder="请输入最小定量"></el-input>
            </el-form-item>
            <el-form-item label="供货总量：" prop="max" class="custom-align-right">
              <el-input v-model="form.max" autocomplete="off" placeholder="请输入供货总量"></el-input>
            </el-form-item>
            <el-form-item label="有效期：" prop="validity" class="custom-align-right">
              <el-date-picker v-model="form.validity" type="date" placeholder="选择日期" :disabled="form.islong == 1">
              </el-date-picker>

              <el-checkbox v-model="form.islong">无期限</el-checkbox>
            </el-form-item>
          </div>
          <div v-if="form.type_id == 2">

            <el-form-item label="截止日期：" prop="validity" class="custom-align-right">
              <el-date-picker v-model="form.validity" type="date" placeholder="选择日期" :disabled="form.islong == 1">
              </el-date-picker>
              <el-checkbox v-model="form.islong">无期限</el-checkbox>
            </el-form-item>
          </div>

          <el-form-item label="商品图：" class="custom-align-right" prop="imgurl">
            <div class="uploaderBox">

              <span v-if="imgurl.length > 0" class="uploaded-images">
                <div v-for="(url, index) in imgurl" :key="index" style="display: inline;float: left; width: 150px;;">

                  <img :src="url" class="avatar" style="float: left; margin-right: 10px;">
                  <div style="position: relative;
                                transform: translate(-50%, -50%);
                                right: -120px;
                                top: -20px;
                                background-color: rgba(0, 0, 0, 0.5);
                                color: white;
                                border-radius: 50%;
                                width: 24px;
                                height: 24px;
                                display: flex;
                                align-items: center;
                                justify-content: center;
                                cursor: pointer;
                                z-index: 10;" @click="deleteImage(index)">
                    <i class="el-icon-delete"></i>
                  </div>
                </div>
              </span>
              <el-upload class="avatar-uploader1" action="#" :show-file-list="true" :before-upload="beforeAvatarUpload"
                style="display: inline;">
                <div style="width: 100px; display: inline-block;">
                  <img src="@/assets/public/upload/noImage.png">
                  <div>选择图片</div>
                </div>

              </el-upload>
            </div>

          </el-form-item>
          <div class="imgBox" style="margin-left: 100px ;margin-bottom: 20px; padding-top: -20px;">
            最多可上传5张，每张图片大小不能超过500K，推荐上传图片尺寸
            宽1000像素 高1000像素。(首张显示为商品头图)</div>
          <el-form-item label="商品关键词：" prop="keyword" class="custom-align-right">
            <el-input v-model="form.keyword" autocomplete="off" placeholder="请输入商品关键词"></el-input>
          </el-form-item>

          <el-form-item label="商品描述：" prop="description" class="custom-align-right">
            <el-input v-model="form.description" maxlength="300" autocomplete="off" placeholder="请输入商品描述"
              type="textarea" :rows="10"></el-input>
          </el-form-item>

          <div class="QuillTitle">
            <span>* </span> <span style="color: #606266" v-if="form.type_id == 1">商品详情：</span><span
              style="color: #606266" v-else>详情说明：</span>
            <div @click="toggleSourceMode" class="QuillModelBtn">
              {{ showHtml ? '切换到编辑模式' : '切换到源码模式' }}
            </div>
          </div>
          <el-form-item label="" prop="detail">
            <div class="editor-container">
              <div v-if="showHtml">
                <textarea v-model="editorHtml" style="width: 100%; height: 400px;"></textarea>
              </div>
              <div v-else>
                <quill-editor ref="quillEditor" v-model="form.detail" :options="editorOptions"
                  class="my-quill-editor" />
              </div>
              <!-- 多图上传隐藏的input -->
              <input type="file" ref="multiFileInput" @change="handleMultipleFiles" multiple hidden
                accept="image/jpeg, image/png" />
            </div>
          </el-form-item>
          <el-form-item label="浏览量：" prop="hits" class="custom-align-right">
            <el-input type="number" v-model="form.hits" autocomplete="off" placeholder="请输入浏览量"></el-input>
          </el-form-item>

          <el-form-item label="联系人：" prop="contact" class="custom-align-right">
            <el-input v-model="form.contact" autocomplete="off" placeholder="请输入联系人"></el-input>
          </el-form-item>

          <el-form-item label="联系电话：" prop="phone" class="custom-align-right">
            <el-input v-model="form.phone" autocomplete="off" placeholder="请输入联系电话"></el-input>
          </el-form-item>
          <el-form-item label="座机：" prop="landline" class="custom-align-right">
            <el-input v-model="form.landline" autocomplete="off" placeholder="请输入座机"></el-input>
          </el-form-item>

          <el-form-item label="电子邮箱：" prop="email" class="custom-align-right">
            <el-input type="email" v-model="form.email" autocomplete="off" placeholder="请输入电子邮件"></el-input>
          </el-form-item>

          <el-form-item label="邮政编码：" prop="postal" class="custom-align-right">
            <el-input type="number" v-model="form.postal" autocomplete="off" placeholder="请输入邮政编码"></el-input>
          </el-form-item>
          <el-form-item label="详细地址：" prop="address" class="custom-align-right">
            <el-input v-model="form.address" autocomplete="off" placeholder="请输入详细地址"></el-input>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="bottomBtnBox">
      <el-button type="info" @click="returnPage">返回</el-button>
      <el-button type="primary" @click="editToServe" v-if="editStatus == true">确定</el-button>
      <el-button type="primary" @click="addToServe" v-else>发布商品</el-button>
    </div>
  </div>
</template>

<script>
//表格标题
import tableTitle from './components/tableTitle';
//引入公用样式
import '@/styles/global.less';
import { quillEditor } from 'vue-quill-editor';
import 'quill/dist/quill.snow.css';
import ImageResize from 'quill-image-resize-module';
import Quill from 'quill';  // 引入 Quill
import Delta from 'quill-delta'; // 引入 Delta，用于手动修改文档
//格式化时间
import { formatLocalDate } from '@/utils/public';

// 注册 Image Resize 模块
Quill.register('modules/imageResize', ImageResize);
//解决富文本样式居中不显示
import 'quill/dist/quill.core.css';
export default {
  components: {
    quillEditor,
    tableTitle
  },
  data() {
    //0.全局操作 start ------------------------------------------------------------>
    //表单验证
    const validateNull = (rule, value, callback) => {
      console.log(value, '-------------------------------')
      if (value == '' || value == undefined || value == null) {
        callback(new Error('该项不能为空！'))
      } else {
        callback()
      }
    }
    const validateEmpty = (rule, value, callback) => {
      console.log(value, '-------------------------------')
      if (value.length == 0) {
        callback(new Error('该项不能为空！'))
      } else {
        callback()
      }
    }
    const validateArray = (rule, value, callback) => {
      if (value.length == 0) {
        callback(new Error('该项不能为空！'))
      } else {
        callback()
      }
    }
    let self = this;
    //0.全局操作 end ------------------------------------------------------------>
    return {
      userType: 0,
      websiteOptions: [],
      checked: false,
      formLabelWidth: '80px',//表单的长度
      //1.表单项 start ------------------------------------------------------------>
      editStatus: false,
      tableDivTitle: "添加商品",
      searchCascaderKey: 0, //列表缓存key
      // imgurl: ['http://192.168.1.127:9501/image/20250227/1740674706184955.jpg', 'http://192.168.1.127:9501/image/20250227/1740674706184955.jpg'],//图片路径
      website_id: 2,
      //提交表单
      form: {
        //1.1使用了外链
        name: '',//商品标题
        type_id: 1,//布类型：1：供应，2求购
        city_arr_id: [],//行政区划
        city_id: '',//城市id
        cat_arr_id: '',//导航池名称
        website_id: 2,
        catid: "",
        cat_arr_id: "",
        name: "",
        price: "",
        unit: "",
        min: null,
        max: null,
        islong: 0,
        validity: "",
        keyword: "",
        description: "",
        detail: "",
        hits: null,
        contact: '',
        phone: '',
        landline: '',
        email: '',
        postal: '',
        address: '',
        city_id: '',
        imgurl: [],//缩略图
      },
      // form: {
      //   //1.1使用了外链
      //   name: 'ceshi',//商品标题
      //   type_id:1,//布类型：1：供应，2求购
      //   city_arr_id: [1],//行政区划
      //   cat_arr_id:'',//导航池名称
      //   website_id: "2",
      //   catid: "1",
      //   cat_arr_id: [1],
      //   name:"商品",
      //   price:"100.00",
      //   unit:"元",
      //   min:"100",
      //   max:"1000",
      //   islong:"1",
      //   validity:"2034-11-08 10:49:47",
      //   // imgs: "",
      //   keyword: "关键词",
      //   description: "描述",
      //   detail: "细节",
      //   hits: "1",
      //   contact: '联系人',
      //   phone: '1800000000',
      //   landline: '0511-12345678',
      //   email: '123456@qq.com',
      //   postal: '123456',
      //   address: '详细地址',
      //   city_id :1,
      //   imgurl:['http://192.168.1.127:9501/image/20250227/1740674706184955.jpg','http://192.168.1.127:9501/image/20250227/1740674706184955.jpg'],//缩略图
      // },
      //1.2 表单验证规则
      formRules: {
        type_id: [{ required: true, trigger: 'blur', validator: validateEmpty }],
        //商品名称不能为空
        name: [{ required: true, trigger: 'blur', validator: validateEmpty }],
        city_arr_id: [{ required: true, trigger: 'blur', validator: validateArray }],
        // 导航池名称不能为空
        cat_arr_id: [{ required: true, trigger: 'blur', validator: validateArray }],
        imgurl: [{ required: true, trigger: 'blur', validator: validateArray }],
        website_id: [{ required: true, trigger: 'blur', validator: validateEmpty }],

        price: [{ required: true, trigger: 'blur', validator: validateEmpty }],
        unit: [{ required: true, trigger: 'blur', validator: validateEmpty }],
        validity: [{ required: true, trigger: 'blur', validator: validateNull }],
        description: [{ required: true, trigger: 'blur', validator: validateEmpty }],

        keyword: [{ required: true, trigger: 'blur', validator: validateEmpty }],
        contact: [{ required: true, trigger: 'blur', validator: validateEmpty }],
        phone: [{ required: true, trigger: 'blur', validator: validateEmpty }],
        address: [{ required: true, trigger: 'blur', validator: validateEmpty }],
      },
      //1.3富文本编辑器配置
      showHtml: false, //用于保存源码内容
      editorHtml: '',
      cascaderKey: 0,//弹窗用的key
      websiteData: {
        lazy: true,
        checkStrictly: true,
        async lazyLoad(node, resolve) {
          const { level, data } = node;
          if (data && data.children && data.children.length !== 0) {
            return resolve(node)
          }
          console.log(level)
          let parentId = level == 0 ? 0 : data.value
          let parames = {
            'page': 1,
            'pageSize': 1000,
          }
          self.$store.dispatch('news/websiteList', parames).then(res => {
            if (res.data) {
              const nodes = res.data.rows.map(item => ({
                value: item.id,
                label: item.website_name,
                leaf: level >= 3,
                children: []
              }))

              console.log(nodes, 'leaf')
              resolve(nodes)
            }
          })
        },
      },

      cityData: {
        checkStrictly: true,
        lazy: true,
        async lazyLoad(node, resolve) {
          const { level, data } = node;
          if (data && data.children && data.children.length !== 0) {
            return resolve(node)
          }
          console.log(level, '====level-----')
          let parentId = level == 0 ? 0 : data.value
          let parames = {
            'pid': parentId
          }
          self.$store.dispatch('pool/getcityList', parames).then(res => {
            if (res.data) {
              const nodes = res.data.map(item => ({
                value: item.id,
                label: item.name,
                leaf: level >= 3,
                children: []
              }))
              resolve(nodes)
            }
          })
        }
      },
      editorOptions: {
        placeholder: '请输入内容...',
        theme: 'snow',  // 主题样式
        modules: {
          toolbar: {
            container: [
              [{ 'font': [] }],                                // 字体
              [{ 'header': [1, 2, 3, 4, 5, 6, false] }],       // 标题
              [{ 'size': ['small', false, 'large', 'huge'] }],  // 字体大小
              ['bold', 'italic', 'underline', 'strike'],        // 加粗、斜体、下划线、删除线
              [{ 'color': [] }, { 'background': [] }],          // 文字颜色、背景颜色
              [{ 'script': 'sub' }, { 'script': 'super' }],     // 上标、下标
              [{ 'list': 'ordered' }, { 'list': 'bullet' }],     // 列表
              [{ 'indent': '-1' }, { 'indent': '+1' }],          // 缩进
              [{ 'align': [] }],                                // 对齐方式
              ['blockquote', 'code-block'],                     // 引用、代码块
              ['link', 'image', 'video'],                       // 链接、图片、视频
              ['clean'],
              [{ 'html': true }]  // 添加自定义按钮的占位符
            ],
            handlers: {
              image: () => {
                this.handleImageClick();
              },
              showHtml: function () {
                this.$emit('toggleSourceMode');
              }
            }
          },
          imageResize: {
            displayStyles: {
              backgroundColor: 'black',
              border: 'none',
              color: 'white'
            },
            modules: ['Resize', 'DisplaySize', 'Toolbar']  // 启用不同的调整方式
          }
        }
      },
      //1.4图片上传
      // imgurl: ['http://192.168.1.127:9501/image/20250227/1740674706184955.jpg', 'http://192.168.1.127:9501/image/20250227/1740674706184955.jpg'],
      imgurl: [],
      //获取父级导航池
      parentKey: 0,//获取父级导航
      parentData: {
        checkStrictly: true,
        lazy: true,
        async lazyLoad(node, resolve) {
          console.log(resolve, 'node')
          const { level, data } = node;
          if (data && data.children && data.children.length !== 0) {
            return resolve(node)
          }
          console.log(level, 'level--1--');
          let pid = level == 0 ? 0 : data.value
          let website_id = self.form.website_id == '' ? 2 : self.form.website_id;
          console.log(website_id, 'website_id--111-----');
          let parames = {
            'website_id': website_id,
            'pid': pid
          }
          self.$store.dispatch('news/getWebsiteNavList', parames).then(res => {
            if (res.data) {
              const nodes = res.data.map(item => ({
                value: item.category_id,
                label: item.name,
                leaf: level >= 3,
                children: []
              }))
              resolve(nodes)
            } else {
              //输出报错原因
              console.log(res.msg, 'getWebsiteNavList--1--');

            }
          })
        }
      },
      inputList: [
        { value: '' }
      ]
      //表单项 end ------------------------------------------------------------>
    };
  },
  methods: {
    async fetchWebsiteOptions() {
      try {
        const response = await this.$store.dispatch('news/websiteList', { page: 1, pageSize: 1000 });
        if (response && response.data) {
          this.websiteOptions = response.data.rows.map(item => ({
            value: item.id,
            label: item.website_name,
          }));
        }
      } catch (error) {
        console.error('获取网站列表失败:', error);
      }
    },
    //获取用户身份信息
    getUserInfo() {
      this.$store.dispatch('public/getInfo').then(res => {
        console.log(res)
        this.userType = res.data.type_id;
        if (this.userType == 10000) {
          this.form.website_id = res.data.website_id !== undefined ? res.data.website_id : 2;;
        }
        //if(res.data.type_id==10000){}//管理员
        //if(res.data.type_id==4){}//调研员
        //个人会员=1 政务会员=2 企业会员=3 调研员=4 管理员=10000 游客=20000
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '网络错误，请重试！'
        });
      })
    },
    //1.提交表单 start ------------------------------------------------------------>
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;
      console.log(this.imgurl.length, '-0--------------------------------')
      if (this.imgurl.length > 4) {
        this.$message.warning('只能上传5张图片');
        return false;
      }

      if (!isJPG && !isPNG) {
        this.$message.error('上传缩略图只能是 JPG 或 PNG 格式!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('上传缩略图大小不能超过 2MB!');
        return false;
      }

      const formData = new FormData();
      formData.append('file', file);

      this.$store.dispatch('pool/uploadFile', formData).then(res => {
        this.imgurl.push(res.data.imgUrl);//显示缩略图
        this.form.imgurl.push(res.data.imgUrl);//提供表单地址
        console.log(res.data.imgUrl, '00000')
      })
      // 阻止默认的上传行为
      return false;
    },
    deleteImage(index) { // 删除图片
      this.imgurl.splice(index, 1);
    },
    //1.2 提交表单
    addToServe() {
      //先进行验证
      this.$refs.form.validate(valid => {
        if (this.form.islong == 1 && this.form.validity == null) {
          this.form.validity = '1970-01-01 00:00:00';
        }
        if (valid) {
          if (this.form.validity) {
            console.log(this.form.validity, 'p0------------------')
            this.form.validity = formatLocalDate(this.form.validity);
            console.log(this.form.validity, 'p1-3333333333333333333333333')
          }
          this.form.imgurl = this.imgurl;
          if (this.form.islong == 1) {
            this.form.validity = null;
          }
          if (this.form.min == '') {
            this.form.min = null;
          }
          if (this.form.max == '') {
            this.form.max = null;
          }
          if (this.form.hits == '') {
            this.form.hits = null;
          }
          console.log(this.form, '提交的数据')
          this.$store.dispatch('news/addGood', this.form).then(res => {
            if (res.code == 200) {
              //汇报结果
              this.$message({
                type: 'success',
                message: '已成功添加商品！'
              });
              this.cleatForm();
              //返回列表页
              this.returnPage()
            } else {
              this.$message({
                type: 'error',
                message: "商品发布失败，请稍后再试！"
              });
            }
          })
        }
      })
    },
    formatDate(date) {
      if (date instanceof Date) {
        return date.toISOString().slice(0, 19).replace('T', ' ');
      } else if (typeof date === 'string') {
        // 将 ISO 8601 格式的字符串转换为 MySQL 期望的格式
        const parsedDate = new Date(date);
        return parsedDate.toISOString().slice(0, 19).replace('T', ' ');
      } else {
        return date;
      }
    },
    //1.3 清理表单
    cleatForm() {
    },
    //提交表单 end ------------------------------------------------------------>

    //2.跳转操作 start ------------------------------------------------------------>
    returnPage() {
      this.$router.push({
        path: '/goodList',
      });
    },
    //跳转操作 end ------------------------------------------------------------>

    //3.回显操作 ------------------------------------------------------------>
    //3.1回显数据
    getMainData() {
      let data = {
        id: this.$route.query.id
      };
      this.$store.dispatch('news/getGoodInfo', data).then(res => {
        console.log(res);
        this.form.name = res.data.name;
        // 回显导航池
        this.form.cat_arr_id = Array.isArray(res.data.cat_arr_id) ? res.data.cat_arr_id : JSON.parse(res.data.cat_arr_id);
        this.form.city_arr_id = Array.isArray(res.data.city_arr_id) ? res.data.city_arr_id : JSON.parse(res.data.city_arr_id);
        this.parentKey += 1; // 触发级联选择器重新加载
        this.loadCascaderPath(this.form.cat_arr_id); // 加载路径数据
        //回显推荐等级

        this.form.imgurl = Array.isArray(res.data.imgurl) ? res.data.imgurl : JSON.parse(res.data.imgurl);
        this.imgurl = Array.isArray(res.data.imgurl) ? res.data.imgurl : JSON.parse(res.data.imgurl);
        this.form.keyword = res.data.keyword;
        this.form.type_id = res.data.type_id;
        this.form.website_id = res.data.website_id;
        this.form.catid = res.data.catid;
        this.form.price = res.data.price;
        this.form.unit = res.data.unit;
        this.form.min = res.data.min;
        this.form.max = res.data.max;
        this.form.islong = res.data.islong == 1 ? true : false;
        this.form.validity = res.data.validity;
        this.form.keyword = res.data.keyword;
        this.form.description = res.data.description;
        this.form.detail = res.data.detail;
        this.form.hits = res.data.hits;
        this.form.contact = res.data.contact;
        this.form.phone = res.data.phone;
        this.form.landline = res.data.landline;
        this.form.email = res.data.email;
        this.form.postal = res.data.postal;
        this.form.address = res.data.address;

      })
    },
    async loadCascaderPath(path) {
      for (let i = 0; i < path.length; i++) {
        const parentId = path[i - 1] || 0; // 获取当前层级的父级ID
        const level = i; // 当前层级的索引
        // self.$store.dispatch('news/getWebsiteNavList', parames).then(res => {
        //     if (res.data) {
        //       const nodes = res.data.map(item => ({
        //         value: item.category_id,
        //         label: item.name,
        //         leaf: level >= 3,
        //         children: []
        //       }))
        //       resolve(nodes)
        await this.$store.dispatch('pool/categoryList', { pid: parentId })
          .then((res) => {
            const nodes = res.data.map(item => ({
              value: item.id,
              label: item.name,
              leaf: level >= 3, // 假设4层结构，设置叶子节点标记
            }));
            // 级联选择器加载数据
            if (level === path.length - 1) {
              this.form.cat_arr_id = path; // 确保最后一级路径正确设置
              this.parentKey += 1; // 强制刷新 cascader
            }
          });
      }
    },
    //1.3提交修改
    editToServe() {
      //提交之前先判断是否为外链
      //如果使用了外链，清理掉除了外链以外的内容
      console.log(this.form)
      //添加要修改的id
      this.form.id = this.editId;
      //先进行验证
      console.log(this.form.validity, 'validity')
      if (this.form.islong == 1 && this.form.validity == null) {
        this.form.validity = '1970-01-01 00:00:00';
      }
      this.$refs.form.validate(valid => {

        if (valid) {
          if (this.form.validity) {
            console.log(this.form.validity, 'p0------------------')
            this.form.validity = formatLocalDate(this.form.validity);
            console.log(this.form.validity, '0------------')
          }
          if (this.form.islong == 1) {
            this.form.validity = null;
          }
          if (this.form.min == '') {
            this.form.min = null;
          }
          if (this.form.max == '') {
            this.form.max = null;
          }
          if (this.form.hits == '') {
            this.form.hits = null;
          }
          this.form.imgurl = this.imgurl;
          //console.log(this.form)
          this.$store.dispatch('news/updateGood', this.form).then(res => {
            if (res.code != 200) {
              this.$message.error("修改失败，请稍后再试！");
            } else {
              //汇报结果
              this.$message({
                type: 'success',
                message: '已成功编辑商品！'
              });
              this.cleatForm();
              //返回列表页
              this.returnPage()
            }
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '网络错误，请重试！'
            });
          })
        }
      })
    },
    //跳转操作 end ------------------------------------------------------------>

    //4.富文本编辑器 start ------------------------------------------------------------>
    //4.1 编辑器点击上传图片
    handleImageClick() {
      this.$refs.multiFileInput.click(); // 打开文件选择框
    },
    handleMultipleFiles(event) {
      const files = event.target.files;
      if (files.length) {
        this.uploadMultipleImages(files); // 处理多图片上传
      }
    },
    uploadMultipleImages(files) {
      const uploadPromises = [];
      for (let i = 0; i < files.length; i++) {
        uploadPromises.push(this.uploadImage(files[i]));
      }

      Promise.all(uploadPromises).then(urls => {
        const quillEditor = this.$refs.quillEditor.quill;
        urls.forEach(url => {
          const range = quillEditor.getSelection();
          quillEditor.insertEmbed(range.index, 'image', url); // 在编辑器中插入图片
        });
      }).catch(error => {
        this.$message.error('图片上传失败，请重试！');
      });
    },
    uploadImage(file) {
      const formData = new FormData();
      formData.append('file', file);
      return this.$store.dispatch('pool/uploadFile', formData)
        .then(res => {
          if (res && res.data && res.data.imgUrl) {
            return res.data.imgUrl;
          } else {
            throw new Error('图片上传失败');
          }
        })
        .catch(error => {
          this.$message.error('图片上传失败，请重试！');
          throw error;
        });
    },

    //4.2 图片粘贴上传
    // 处理从网页粘贴的图片 URL
    handleImageFromWeb(imageUrl) {
      return new Promise((resolve) => {
        console.log('开始下载图片:', imageUrl);
        this.fetchImageAsBlob(imageUrl).then((blob) => {
          console.log('图片已下载为 Blob:', blob);

          const formData = new FormData();
          formData.append('file', blob, 'image.jpg');

          this.$store.dispatch('pool/uploadFile', formData).then((res) => {
            if (res && res.data && res.data.imgurl) {
              console.log('图片上传成功:', res.data.imgurl);
              resolve(res.data.imgurl);
            } else {
              console.log('图片上传失败，保留原 URL:', imageUrl);
              resolve(imageUrl);
            }
          }).catch((error) => {
            console.error('图片上传时出现错误:', error);
            resolve(imageUrl);
          });
        }).catch((error) => {
          console.error('图片下载失败:', error);
          resolve(imageUrl);
        });
      });
    },
    fetchImageAsBlob(url) {
      return fetch(url)
        .then(response => {
          if (!response.ok) {
            throw new Error('Failed to fetch image');
          }
          return response.blob();
        });
    },
    //编辑源码
    toggleSourceMode() {
      if (!this.showHtml) {
        // 切换到源码模式，将编辑器内容同步到 textarea 中
        this.editorHtml = this.$refs.quillEditor.quill.root.innerHTML;
        this.showHtml = true; // 显示 textarea
      } else {
        // 切换回富文本模式，将 textarea 内容同步回编辑器
        this.showHtml = false; // 显示 Quill 编辑器

        // Quill 编辑器可能被销毁，所以使用 $nextTick 确保 DOM 渲染完成后再操作编辑器
        this.$nextTick(() => {
          if (this.$refs.quillEditor) {
            this.$refs.quillEditor.quill.root.innerHTML = this.editorHtml;
          } else {
            console.error('Quill 编辑器实例未找到');
          }
        });
      }
    }
    //富文本编辑器 end ------------------------------------------------------------>

  },
  watch: {
    'form.type_id': {
      handler(newVal, oldVal) {
        if (newVal !== oldVal) {
          if (this.$route.query.id != undefined) {
          } else {
            console.log('-------新增--变化了------------');
            this.form.name = '';
            this.form.city_arr_id = [];
            this.form.city_id = '';
            this.form.cat_arr_id = '';
            this.form.website_id = '';
            this.form.catid = "";
            this.form.price = "";
            this.form.unit = "";
            this.form.min = null;
            this.form.max = null;
            this.form.islong = 0;
            this.form.validity = "";
            this.form.keyword = "";
            this.form.description = "";
            this.form.detail = "";
            this.form.hits = null;
            this.form.contact = '';
            this.form.phone = '';
            this.form.landline = '';
            this.form.email = '';
            this.form.postal = '';
            this.form.address = '';
            this.form.imgurl = [];
            this.form.city_id = '';
          }

          // 清空特定字段的数据
          if (newVal === 1) {
            // 从求购商品切换到供应商品
            this.form.price = '';
            console.log('供应商品');
          } else if (newVal === 2) {
            // 从供应商品切换到求购商品
            console.log('求购商品');
          }
        }
      },
      immediate: true // 立即执行一次
    },
    //监控 website_id
    // 若 website_id 发生变化，则清空 cat_arr_id 和 catid
    'form.website_id': {
      handler(newVal, oldVal) {
        if (newVal !== oldVal) {
          this.form.cat_arr_id = [];
          this.form.catid = "";
          this.parentKey += 1;
        }
      },
      immediate: true // 立即执行一次
    }
  },
  mounted() {
    //1.判断是新建还是回显
    if (this.$route.query.id != undefined) {
      this.editId = this.$route.query.id;
      this.editStatus = true;
      this.tableDivTitle = "编辑商品";
      console.log("编辑商品")
      this.getMainData();
    } else {
      this.editStatus = false;
      console.log("添加商品！")
    }
    this.fetchWebsiteOptions();
    this.getUserInfo();

    //复制内容到富文本 start ------------------------------------------------------------>
    this.$nextTick(() => {
      const quillEditor = this.$refs.quillEditor.quill;

      if (quillEditor) {
        console.log('Quill 编辑器已初始化');

        // 在粘贴事件触发时，记录所有 img 的 src
        quillEditor.clipboard.addMatcher(Node.ELEMENT_NODE, (node, delta) => {
          if (node.tagName === 'IMG') {
            const imageUrl = node.getAttribute('src');
            console.log('检测到粘贴的图片 URL:', imageUrl);

            if (imageUrl && !imageUrl.startsWith('data:') && !imageUrl.startsWith('file://')) {
              // 先处理图片上传
              this.handleImageFromWeb(imageUrl).then((uploadedImageUrl) => {
                // 查找编辑器中所有 img 标签并替换 src
                const imgs = quillEditor.root.querySelectorAll('img');
                imgs.forEach((img) => {
                  if (img.getAttribute('src') === imageUrl) {
                    img.setAttribute('src', uploadedImageUrl);  // 替换 src
                    console.log('图片 src 已替换为:', uploadedImageUrl);
                  }
                });
              });
            }
          }
          return delta;  // 返回原始 delta
        });
      } else {
        console.error('Quill 初始化失败');
      }

    });
    //复制富文本 end ------------------------------------------------------------>
  },
};
</script>
<style scoped lang="less">
//文本编辑器
.QuillTitle {
  line-height: 36px;
  font-size: 14px;
  color: #606266;
  font-weight: bold;
  padding-left: 30px;

  span {
    color: #ff4949
  }

  .QuillModelBtn {
    display: inline-block;
    margin-left: 10px;
    font-size: 12px;
    color: #999;
    cursor: pointer;
  }
}

.editor-container {
  height: 420px;
  padding-bottom: 20px;
}

.my-quill-editor {
  height: 320px;
}

.ql-editor {
  height: 320px;
}

/* 富文本对齐方式 */
.ql-align-center {
  text-align: center;
}

.ql-align-right {
  text-align: right;
}

.ql-indent-1 {
  padding-left: 16px;
}

.ql-indent-2 {
  padding-left: 32px;
}

.ql-indent-3 {
  padding-left: 48px;
}

.ql-indent-4 {
  padding-left: 64px;
}

.ql-indent-5 {
  padding-left: 80px;
}

.ql-indent-6 {
  padding-left: 96px;
}

.ql-indent-7 {
  padding-left: 112px;
}

.ql-indent-8 {
  padding-left: 128px;
}


//执行v-deep穿透scope选择器 start------------------------------------------------------------>*/
::v-deep .custom-form-item>.el-form-item__label {
  line-height: 140px !important;
}

::v-deep .custom-textarea .el-textarea__inner {
  resize: none;
  /* 禁止用户拖拽调整大小 */
}

::v-deep .custom-align-right .el-form-item__label {
  text-align: right;
  /* 设置标签文字右对齐 */
}

::v-deep .el-select {
  width: 100%;
  /* 禁止用户拖拽调整大小 */
}

::v-deep .el-input-group__prepend {
  color: black !important;
}

.formLabelFloatBox {
  margin-bottom: 10px;
  position: relative;

  .formLabeladdIcon {
    position: absolute;
    right: 45px;
    top: 5px;
    width: 38px;
    height: 24px;
  }

  .formLabelDelIcon {
    position: absolute;
    right: 5px;
    top: 5px;
    width: 38px;
    height: 24px;
  }
}

//执行v-deep穿透scope选择器 end------------------------------------------------------------>*/</style>
