<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="title" class="custom-align-right">
            <el-input v-model="form.title" autocomplete="off" placeholder="请输入资讯标题"></el-input>
            <!-- <el-checkbox v-model="form.islink">是否使用外链</el-checkbox> -->
            <el-checkbox v-model="form.islink" v-if="creatNews_user_type == 10000">是否使用外链</el-checkbox> 
             
          </el-form-item>
          <div v-if="form.islink == true">
            <el-form-item label="站点名称：" prop="web_site_id" class="custom-align-right">
              <el-cascader :key="parentKey" v-model="form.web_site_id" placeholder="请选择站点名称" popper-class="my_cascader"
                :options="creatNews_nav_pool_arr" @change="creatNews_nav_pool_change_fun(form.web_site_id)" filterable
                clearable></el-cascader>
            </el-form-item>
            <el-form-item label="展示名称：" prop="cat_arr_id" class="custom-align-right">
              <el-cascader :key="parentKey_2" v-model="form.cat_arr_id" placeholder="请选择要绑定的展示名称" :props="parentData_2"
                popper-class="my_cascader" filterable clearable></el-cascader>
            </el-form-item>
            <el-form-item label="外链地址：" prop="linkurl" class="custom-align-right">
              <el-input v-model="form.linkurl" autocomplete="off" placeholder="请输入外链地址"></el-input>
            </el-form-item>
            <el-form-item label="作者：" prop="author" class="custom-align-right">
              <el-input v-model="form.author" autocomplete="off" placeholder="请输入作者"></el-input>
            </el-form-item>
          </div>
          <div v-if="form.islink == false">
            <div v-if="creatNews_user_type != 10000">
              <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"
                  popper-class="my_cascader" style="height: 100%;" filterable clearable></el-cascader>
              </el-form-item>
            </div>
            <div>
              <div v-if="creatNews_user_type == 10000">
                <el-form-item label="站点名称：" prop="web_site_id" class="custom-align-right">
                  <el-cascader :key="parentKey" v-model="form.web_site_id" placeholder="请选择站点名称"
                    popper-class="my_cascader" :options="creatNews_nav_pool_arr"
                    @change="creatNews_nav_pool_change_fun(form.web_site_id)" filterable clearable></el-cascader>
                </el-form-item>
                <el-form-item label="展示名称：" prop="cat_arr_id" class="custom-align-right">
                  <el-cascader :key="parentKey_2" v-model="form.cat_arr_id" placeholder="请选择要绑定的展示名称"
                    popper-class="my_cascader" style="height: 100%;" :props="parentData_2" filterable
                    clearable></el-cascader>
                </el-form-item>
              </div>
              <el-form-item label="行政区划：" class="custom-align-right">
                <CityCascader v-model="form.city_arr_id" @update-city-id="update_city_arr_id"></CityCascader>
              </el-form-item>
              <el-form-item label="行政职能：" class="custom-align-right">
                <el-cascader :key="searchDepartmentKey" v-model="form.department_arr_id" placeholder="请选择行政职能"
                  popper-class="my_cascader" :props="searchDepartmentData" filterable clearable></el-cascader>
              </el-form-item>
              <div v-if="creatNews_user_type == 10000">
                <el-form-item label="推荐等级：" class="custom-align-right">
                  <el-select v-model="form.level" multiple clearable placeholder="请选择推荐等级.." @change="levelChange">
                    <el-option label="头条" :value="1"></el-option>
                    <el-option label="轮播图" :value="2"></el-option>
                    <el-option label="今日热点" :value="6"></el-option>
                  </el-select>
                </el-form-item>
              </div>
              <el-form-item label="缩略图：" class="custom-align-right" prop="">
                <div class="uploaderBox" @mouseenter="hovering = true" mouseleave="hovering = false">
                  <el-upload class="avatar-uploader" action="#" :show-file-list="false"
                    :before-upload="beforeAvatarUpload">
                    <!-- 预览图片 -->
                    <img v-if="imgUrl" :src="imgUrl" class="avatar">
                    <div v-else class="chooseImgDiv">
                      <div>
                        <img src="@/assets/public/upload/noImage.png">
                        <div>选择图片</div>
                      </div>
                    </div>
                  </el-upload>
                  <input type="hidden" v-model="form.imgurl">
                  <span class="photo_tips">推荐图片长宽比例为 16:9，大小不能超过 500 K。</span>
                  <div v-if="hovering && imgUrl" class="delete-button" @click="handleDelete">
                    <i class="el-icon-delete"></i>
                  </div>
                </div>
              </el-form-item>
              <el-form-item label="资讯关键词：" prop="" class="custom-align-right">
                <template #label>
                  <span class="askBox">
                    资讯关键词：
                    <el-tooltip class="item" effect="dark" content="资讯关键词，如：三农市场网、全国三农、信息一体化。" placement="top">
                      <i class="el-icon-question"></i>
                    </el-tooltip>
                  </span>
                </template>
                <tagInput :initialTags="tags" @tags-updated="updateTags"></tagInput>
              </el-form-item>
              <el-form-item label="资讯描述：" prop="" class="custom-align-right">
                <template #label>
                  <span class="askBox">
                    资讯描述：
                    <el-tooltip class="item" effect="dark" content="资讯描述，如：中国三农市场网创建以来，社会效益和会员经济效益贡献。" placement="top">
                      <i class="el-icon-question"></i>
                    </el-tooltip>
                  </span>
                </template>
                <el-input type="textarea" v-model="form.introduce" class="custom-textarea"
                  placeholder="请输入资讯描述"></el-input>
              </el-form-item>
              <el-form-item label="作者：" prop="author" class="custom-align-right">
                <el-input v-model="form.author" autocomplete="off" placeholder="请输入作者"></el-input>
              </el-form-item>
              <el-form-item label="浏览量：" v-if="creatNews_user_type == 10000" class="custom-align-right">
                <el-input v-model="form.hits" autocomplete="off" placeholder="请输入浏览量"></el-input>
              </el-form-item>
              <el-form-item label="是否为原创：" prop="is_original" class="custom-align-right">
                <el-radio-group v-model="form.is_original" @change="changeIsOriginal">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
              <div v-if="form.is_original == 0">
                <el-form-item label="来源名称：" prop="copyfrom" class="custom-align-right">
                  <el-input v-model="form.copyfrom" autocomplete="off" placeholder="请输入来源名称"></el-input>
                </el-form-item>
                <el-form-item label="来源链接：" prop="fromurl" class="custom-align-right">
                  <el-input v-model="form.fromurl" autocomplete="off" placeholder="请输入来源链接"></el-input>
                </el-form-item>
                <div class="disclaimerBox">
                  <div class="disclaimerTitle">
                    <img src="@/assets/public/check.png" />同意《免责声明》：
                  </div>
                  <div class="disclaimerText">
                    本文来源于网络转载，仅供学习交流使用，不构成商业目的。版权归原作者所有，如涉及作品内容、版权和其他问题，请在30日内与本站联系，我们将在第一时间处理。</div>
                </div>
              </div>
              <div v-if="form.is_original == 1">
                <el-form-item label="来源名称：" prop="copyfrom" class="custom-align-right">
                  <el-input v-model="form.copyfrom" autocomplete="off" placeholder="请输入来源名称"
                    disabled="disabled"></el-input>
                </el-form-item>
              </div>
              <el-form-item label="资讯内容：" prop="content" class="custom-align-right">
                <myEditor ref="myEditor" v-model="form.content"></myEditor>
              </el-form-item>
              <el-form-item label="是否开启投票：" prop="is_survey" class="custom-align-right">
                <el-radio-group v-model="form.is_survey">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>


              <div v-if="form.is_survey == 1">
                <el-form-item label="问卷标题：" prop="survey_name" class="custom-align-right">
                  <el-input v-model="form.survey_name" autocomplete="off" placeholder="请输入问卷标题"></el-input>
                </el-form-item>
                <el-form-item label="选项：" prop="survey_type" class="custom-align-right">
                  <el-radio-group v-model="form.survey_type">
                    <el-radio :label="0">单选</el-radio>
                    <el-radio :label="1">多选</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="" class="custom-align-right">
                  <div v-for="(input, index) in inputList" :key="index">
                    <div class="formLabelFloatBox">
                      <el-input autocomplete="off" v-model="input.value" maxlength="150" :label-width="formLabelWidth"
                        placeholder="">
                        <template slot="prepend">{{ index + 1 }}</template>
                      </el-input>
                      <el-button type="info" icon="el-icon-plus" circle size="mini" @click="addInput(index)"
                        class="formLabeladdIcon"></el-button>
                      <el-button type="info" icon="el-icon-delete" circle size="mini" @click="deleteInput(index)"
                        class="formLabelDelIcon"></el-button>
                    </div>
                  </div>
                </el-form-item>
                <el-form-item label="" class="custom-align-right">
                  <el-checkbox v-model="checked">允许用户自己填写</el-checkbox>
                </el-form-item>
              </div>
              <el-form-item label="手动推荐：" prop="commend_id" class="custom-align-right">
                <el-select v-model="form.commend_id" placeholder="请选择手动推荐名称" multiple filterable clearable remote
                  :remote-method="remoteMethod" :loading="loading">
                  <el-option v-for="item in commend_article" :key="item.id" :label="item.title"
                    :value="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="" prop="commend_id" class="custom-align-right">
                <draggable v-model="form.commend_id" @end="onDragEnd">
                  <el-tag :key="item.id" v-for="item in form.commend_id" closable :disable-transitions="false"
                    @close="handleClose(item)"> {{ item }}
                  </el-tag>
                </draggable>
              </el-form-item>

              <el-form-item label="创建时间：" class="custom-align-right" v-if="created_at">
                <el-input v-model="created_at" autocomplete="off" disabled></el-input>
              </el-form-item>
            </div>
          </div>
        </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 { getWebSiteId, getUseType } from '@/utils/auth'
//表格标题
import tableTitle from './components/tableTitle.vue';
//引入tag标签组件
import tagInput from '../../components/InputTag/index.vue';
//引入公用样式
import '@/styles/global.less';
//城市级联选择器
import CityCascader from './components/CityCascader';
//引入富文本编辑器
import myEditor from '../../components/edit/myEditor.vue';
//引入拖拽组件
import draggable from 'vuedraggable';

export default {
  components: {
    tableTitle,
    CityCascader,
    tagInput,
    myEditor,
    draggable
  },
  data() {
    //0.全局操作 start ------------------------------------------------------------>
    //表单验证
    const validateEmpty = (rule, value, callback) => {
      if (value == '') {
        callback(new Error('该项不能为空！'))
      } else {
        callback()
      }
    }
    const validateArray = (rule, value, callback) => {
      if (value.length == 0) {
        callback(new Error('该项不能为空！'))
      } else {
        callback()
      }
    }
    const validateRadio = (rule, value, callback) => {
      if (value != '1' || value != '0') {
        callback()
      } else {
        callback()
      }
    }
    const validateZero = (rule, value, callback) => {
      if (value == 0 || value == '' || value == "0") {
        callback(new Error('该项不能为空！'))
      } else {
        callback()
      }
    }
    let self = this;
    //0.全局操作 end ------------------------------------------------------------>
    return {
      loading: false,
      logoUrl: '',
      hovering: false, // 鼠标悬浮状态 悬浮时显示删除
      tags: [],//标签数组
      websiteid: 0,
      creatNews_pid_num: "0",//请求子导航用的pid
      creatNews_nav_pool_arr: [],//
      creatNews_add_nav_pool_arr: [],//
      creatNews_son_website_id_num: "",
      checked: false,
      formLabelWidth: '80px',//表单的长度
      //1.表单项 start ------------------------------------------------------------>
      editStatus: false,
      tableDivTitle: "添加资讯",
      disclaimer: true,//免责声明
      //提交表单
      creatNews_user_type: 0,//判断用户类型'
      created_at: "",//创建时间
      commend_article: [],//手动推荐
      form: {
        user_type: "??",//判断用户类型'
        cat_arr_id: [],//导航池名称
        nav_add_pool_id: [],//导航池子级
        city_arr_id: [],//行政区划
        city_id: "",//区划最后一个数字
        department_arr_id: [],//行政职能部门
        department_id: "",//部门最后一个数字
        //1.1使用了外链
        title: '',//资讯标题
        islink: 0,//是否使用外链 0非 1是
        linkurl: "",//外链地址
        //1.2没有使用外链
        level: "",//推荐等级
        imgurl: "",//缩略图
        keyword: "",//关键词
        introduce: "",//描述
        content: "",//内容
        author: "",//作者
        hits: "",//浏览量
        is_original: 1,//是否为原创 0非 1是
        copyfrom: "本网",//来源名称
        fromurl: "",//来源地址
        status: 0,//状态 0待发布 1已发布 404已删除  如果是普通用户，这里始终为0
        web_site_id: 0,
        is_survey: 0,//调查问卷：0：否；1：是；
        survey_name: "",//问卷名称
        suvey_array: "",//选项名称集合 
        survey_type: 0, //0:单选 1：复选
        commend_id: [],//手动推荐
      },
      //1.2 表单验证规则
      formRules: {
        //导航池名称不能为空
        web_site_id: [{ required: true, trigger: 'blur', validator: validateZero }],
        //资讯名称不能为空
        title: [{ required: true, trigger: 'blur', validator: validateEmpty }],
        //如果使用了外链，外链地址不能为空
        linkurl: [{ required: true, trigger: 'blur', validator: validateEmpty }],
        //导航池名称不能为空
        cat_arr_id: [{ required: true, trigger: 'blur', validator: validateArray }],
        //推荐等级不能为空
        //level:[{required:true,trigger:'blur',validator:validateEmpty}],
        //关键词不能为空
        // keyword: [{ required: true, trigger: 'blur', validator: validateEmpty }],
        //描述不能为空
        // introduce: [{ required: true, trigger: 'blur', validator: validateEmpty }],
        //行政区划
        // city_arr_id: [{ required: true, trigger: 'blur', validator: validateArray }],
        //行政职能
        department_arr_id: [{ required: true, trigger: 'blur', validator: validateArray }],
        //内容不能为空
        content: [{ required: true, trigger: 'blur', validator: validateEmpty }],
        //作者不能为空
        author: [{ required: true, trigger: 'blur', validator: validateEmpty }],
        //是否原创不能为空
        is_original: [{ required: true, trigger: 'blur', validator: validateRadio }],
        //来源名称和地址不能为空
        copyfrom: [{ required: true, trigger: 'blur', validator: validateEmpty }],
        fromurl: [{ required: true, trigger: 'blur', validator: validateEmpty }],
        //缩略图不能为空
        imgUrl: [{ required: true, trigger: 'blur', validator: validateEmpty }],
        level: [{ required: true, trigger: 'blur', validator: validateEmpty }],
        //是否开启投票
        is_survey: [{ required: true, trigger: 'blur', validator: validateRadio }],
        //问卷标题
        survey_name: [{ required: true, trigger: 'blur', validator: validateEmpty }],
        //选项
        survey_type: [{ required: true, trigger: 'blur', validator: validateRadio }],
      },

      //1.4图片上传
      imgUrl: "",//在页面上显示缩略图
      //获取父级导航池
      parentKey: 0,//获取父级导航
      parentData: {
        checkStrictly: true,
        lazy: true,
        async lazyLoad(node, resolve) {
          const { level, data } = node;
          if (data && data.children && data.children.length !== 0) {
            return resolve(node)
          }
          let parentId;
          parentId = level == 0 ? 0 : data.value;
          let parames = {
            'website_id': getWebSiteId(),
            'pid': parentId
          }
          self.$store.dispatch('pool/get_creatNews_nav_son_actions', 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)
            }
          })
        }
      },
      parentKey_2: 0,//获取父级导航 
      parentData_2: {
        checkStrictly: true,
        lazy: true,
        async lazyLoad(node, resolve) {
          const { level, data } = node;
          if (data && data.children && data.children.length !== 0) {
            return resolve(node)
          }
          let parentId;
          if (self.ifwebsitId == true) {
            console.log("网站选择已经改变！")
            parentId = 0;
            self.ifwebsitId = false;
            self.cat_arr_id = [];
          } else {
            parentId = level == 0 ? 0 : data.value;
            self.ifwebsitId = false;
          }
          let parames = {
            'website_id': self.form.web_site_id,
            'pid': parentId
          }
          self.$store.dispatch('pool/get_creatNews_nav_son_actions', parames).then(res => {
            if (res.data) {
              const nodes = res.data.map(item => ({
                value: item.category_id,
                label: item.alias,
                leaf: level >= 3,
                children: []
              }))
              resolve(nodes)
            }
          })
        }
      },
      //行政职能部门
      searchDepartmentKey: 0, //列表缓存key
      searchDepartmentData: {
        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)
          let parentId = level == 0 ? 0 : data.value
          let parames = {
            'pid': parentId
          }
          self.$store.dispatch('pool/getDepartment', parames).then(res => {
            if (res.data) {
              const nodes = res.data.map(item => ({
                value: item.id,
                label: item.name,
                leaf: level >= 3,
                children: []
              }))
              resolve(nodes)
            }
          })
        }
      },
      inputList: [
        { value: '' }
      ]
      //表单项 end ------------------------------------------------------------>
    };

  }, watch: {
    '$route'(to, from) {
      console.log(from, '---------------------------------------');
      // 监听路由参数中的 id 变化，若变化则更新页面状态并获取数据
      if (to.query.id) {
        this.getMainData();
      }
    },


    // 监听路由参数中的 id 变化，若变化则更新页面状态并获取数据
    // '$route.query.id': function (newVal, oldVal) {
    //   console.log('当前 id:', newVal, '旧的 id:', oldVal);
    //   if (newVal) {
    //     this.editStatus = true;
    //     this.tableDivTitle = "编辑资讯";
    //     //     // 调用方法名保持大小写一致
    //     this.getMainData();
    //   } else {
    //     this.editStatus = false;
    //     this.tableDivTitle = "添加资讯";
    //   }
    // }


  },
  methods: {
    //1.提交表单 start ------------------------------------------------------------>
    //1.1 直接上传图片
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      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 = res.data.imgUrl;//显示缩略图
        this.form.imgurl = res.data.imgUrl;//提供表单地址
        console.log(res.data.imgUrl)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '网络错误，请重试！'
        });
      })

      // 阻止默认的上传行为
      return false;
    },
    //1.2 提交表单
    addToServe() {
      //判断是否为外链
      if (this.form.islink == false) {
        if (this.form.is_survey == 1) {
          const hasEmptyInput = this.inputList.some(input => input.value === '');
          if (hasEmptyInput) {
            // 如果有输入框为空，弹出提示信息
            this.$message.error('请确保所有输入框都有内容');
            return;
          }
          const inputLists = this.inputList.map(input => input.value);
          const allowList = [this.checked ? 1 : 0, ""];
          if (this.checked) {
            inputLists.push(allowList);
          }
          if (inputLists.length < 2) {
            this.$message.error('投票选项不少于2条');
            return;
          }
          this.form.suvey_array = JSON.stringify(inputLists);
        }
      }
      if (this.form.islink == true) {
        this.form.islink = 1;
        this.cleatForm(1)
      } else {
        this.form.islink = 0;
      }
      //取出行政职能和行政区划数组的最后一个数字
      if (this.form.department_arr_id == "[]" || this.form.department_arr_id == null) {
        this.form.department_arr_id = '[]'
        this.form.department_id = 0;
      } else {
        if (JSON.parse(this.form.department_arr_id.length == 0)) {
          this.form.department_id = 0;
        } else {
          this.form.department_id = this.form.department_arr_id[this.form.department_arr_id.length - 1];
        }
        this.form.department_arr_id = JSON.stringify(this.form.department_arr_id);

      }
      if (this.form.city_arr_id == "[]" || this.form.city_arr_id == null) {
        this.form.city_arr_id = '[]'
        this.form.city_id = 0;
      } else {
        if (JSON.parse(this.form.city_arr_id.length == 0)) {
          this.form.city_id = 0;
        } else {
          this.form.city_id = this.form.city_arr_id[this.form.city_arr_id.length - 1];
        }
        this.form.city_arr_id = JSON.stringify(this.form.city_arr_id);
      }

      //判断用户身份
      if (this.creatNews_user_type == 10000) {
        console.log("用户身份为管理员,无需审核直接发布!")
        this.form.status = 1;
      } else {
        console.log("用户身份为其他用户,提交到审核!")
        this.form.status = 0;
        this.form.web_site_id = this.websiteid;
        //如果是普通用户 推荐等级设置为0 
        this.form.level = "[0]";
      }

      //先进行验证
      // console.log( "this.form==", this.form);

      this.$refs.form.validate(valid => {
        if (valid) {
          //如果推荐等级为空，则设置为0
          if (this.form.level == "" || this.form.level == "[0]") {
            this.form.level = "[0]";
          } else {
            this.form.level = JSON.stringify(this.form.level);
          }
          //console.log(this.form)
          const formData = { ...this.form };
          if (formData.commend_id != undefined && formData.commend_id.length > 0) {
            formData.commend_id = JSON.stringify(formData.commend_id); // 提取推荐ID
          }
          if (formData.commend_id.length == 0) {
            formData.commend_id = '[]';
          }

          this.$store.dispatch('news/addArticle', formData).then(res => {//xx
            if (res.code == 200) {
               console.log("资讯发布成功！200")   
              //汇报结果
              this.$message({
                type: 'success',
                message: '已成功添加资讯！'
              });
              this.cleatForm(2);
              //返回列表页
              this.returnPage()
            } else {
              console.log("资讯发布失败！?????",res)    
              this.$message({
                type: 'error',
                message: "资讯发布失败，请稍后再试！"
              });
            }
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '网络错误，请重试！'
            });
          })
        }
      })
    },
    //1.3 清理表单
    cleatForm(type) {
      if (type == 1) {
        //使用了外链，进行部分表单清理
        //this.form.cat_arr_id = "";
        this.form.level = "";
        this.form.imgurl = "";
        this.form.keyword = "";
        this.form.introduce = "";
        this.form.content = "";
        //this.form.author = "";
        this.form.hits = "";
        this.form.is_original = "";
        this.form.copyfrom = "";
        this.form.fromurl = "";
        this.form.status = 0;
      }
      if (type == 2) {
        //完全清理表单
        this.form.title = "";
        this.form.islink = "";
        this.form.linkurl = "";
        this.form.cat_arr_id = "";
        this.form.level = "";
        this.form.imgurl = "";
        this.form.keyword = "";
        this.form.introduce = "";
        this.form.content = "";
        this.form.author = "";
        this.form.hits = "";
        this.form.is_original = "";
        this.form.copyfrom = "";
        this.form.fromurl = "";
        this.form.status = 0;
      }
    },
    //1.4更新详细地址
    update_city_arr_id(value) {
      console.log("行政区划ID已更新:", value);
      this.form.city_arr_id = value;
    },
    //1.5 删除图片
    handleDelete() {
      // 删除图片
      this.imgUrl = ''; // 清空图片 URL
      this.form.imgurl = ''; // 清空表单中的图片 URL
    },
    //提交表单 end ------------------------------------------------------------>

    //2.跳转操作 start ------------------------------------------------------------>
    returnPage() {
      if (this.$route.query.to == "examine") {
        this.$router.push({
          path: '/examine',
        });
      } else {
        this.$router.push({
          path: '/articleList',
        });
      }
    },
    //跳转操作 end ------------------------------------------------------------>

    //3.回显操作 ------------------------------------------------------------>
    //3.1回显数据
    getMainData() {
      let data = {
        id: this.$route.query.id
      };
      this.$store.dispatch('news/getArticleInfo', data).then(res => {
        this.form.title = res.data.title;
        //判断是否使用了外链
        if (res.data.islink == 1) {
          this.form.islink = true;
        } else {
          this.form.islink = false;
        }
        //不是原创的时候显示来源
        if (res.data.is_original == 1) {
          this.form.is_original = 1;
          this.form.copyfrom = "本网";
        } else {
          this.form.is_original = 0;
          this.$nextTick(() => {
            this.form.is_original = 0;
            console.log('is_original:', this.form.is_original); // 确保值已更新
          });
          this.form.copyfrom = res.data.copyfrom;
          this.form.linkurl = res.data.linkurl;
        }
        //如果推荐等级为0 不再回显等级
        if (res.data.level == "[0]") {
          this.form.level = "";
        } else {
          const arr = JSON.parse(res.data.level);
          const elementToRemove = [0, 3, 4, 5];
          let newArr = arr.filter(item => !elementToRemove.includes(item));;
          this.form.level = newArr;
        }
        //回显站点名称
        //判断web_site_id是否为字符串,如果是转换为数字
        if (typeof res.data.web_site_id === 'string') {
          this.form.web_site_id = Number(res.data.web_site_id);
        } else {
          this.form.web_site_id = res.data.web_site_id//站点名称
        }
        this.created_at = res.data.created_at;
        this.form.cat_arr_id = Array.isArray(res.data.cat_arr_id) ? res.data.cat_arr_id : JSON.parse(res.data.cat_arr_id);
        console.log(this.form.cat_arr_id)
        //回显导航池 连同非管理员得一起刷新
        this.parentKey += 1; // 触发级联选择器重新加载
        this.loadCascaderPath(this.form.cat_arr_id); // 加载路径数据
        this.parentKey_2 += 1; // 触发级联选择器重新加载
        this.loadCascaderPath(this.form.cat_arr_id); // 加载路径数据
        //回显行政区划
        this.form.city_arr_id = JSON.parse(res.data.city_arr_id);
        //回显行政职能
        this.searchDepartmentKey += 1;
        this.form.department_arr_id = JSON.parse(res.data.department_arr_id);
        //回显其他数据
        this.form.imgurl = res.data.imgurl;
        this.imgUrl = res.data.imgurl;
        this.form.keyword = res.data.keyword;
        this.tags = res.data.keyword ? res.data.keyword.split(",") : [];
        this.form.introduce = res.data.introduce;
        //回显编辑器内容
        this.$nextTick(() => {
          this.form.content = res.data.content;
        });
        this.form.author = res.data.author;
        this.form.hits = res.data.hits;
        this.form.is_original = res.data.is_original;
        this.form.copyfrom = res.data.copyfrom;
        this.form.fromurl = res.data.fromurl;
        this.form.status = res.data.status;
        this.form.survey_name = res.data.survey_name;
        this.form.commend_id = JSON.parse(res.data.commend_id);
        if (res.data.is_survey == null) {
          this.form.is_survey = 0;
        } else {
          this.form.is_survey = res.data.is_survey;
        }
        this.form.survey_type = res.data.survey_type;
        this.inputList = [];
        if (res.data.survey_array.length > 0) {
          res.data.survey_array.forEach(item => {
            if (item.is_other == 0) {
              this.inputList.push({ "value": item.choice_name });
            } else {
              this.checked = true
            }
          });
        } else {
          this.inputList.push({ "value": "" });
        }
        console.log(this.inputList)
      })
    },
    async loadCascaderPath(path) {
      for (let i = 0; i < path.length; i++) {
        const parentId = path[i - 1] || 0; // 获取当前层级的父级ID
        const level = i; // 当前层级的索引

        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() {
      //不使用外联 验证投票逻辑
      if (this.form.islink == false) {
        if (this.form.is_survey == 1) {
          const hasEmptyInput = this.inputList.some(input => input.value === '');
          if (hasEmptyInput) {
            // 如果有输入框为空，弹出提示信息
            this.$message.error('请确保所有输入框都有内容');
            return;
          }
          const inputLists = this.inputList.map(input => input.value);
          const allowList = [this.checked ? 1 : 0, ""];
          if (this.checked) {
            inputLists.push(allowList);
          }
          if (inputLists.length < 2) {
            this.$message.error('投票选项不少于2条');
            return;
          }
          this.form.suvey_array = JSON.stringify(inputLists);
        }
      }
      console.log(this.form)
      if (this.form.islink == 1) {
        this.cleatForm(1)
      }

      //取出行政职能和行政区划数组的最后一个数字
      if (this.form.department_arr_id == "[]" || this.form.department_arr_id == null) {
        this.form.department_arr_id = '[]'
        this.form.department_id = 0;
      } else {
        if (JSON.parse(this.form.department_arr_id.length == 0)) {
          this.form.department_id = 0;
        } else {
          this.form.department_id = this.form.department_arr_id[this.form.department_arr_id.length - 1];
        }
        this.form.department_arr_id = JSON.stringify(this.form.department_arr_id);

      }
      if (this.form.city_arr_id == "[]" || this.form.city_arr_id == null) {
        this.form.city_arr_id = '[]'
        this.form.city_id = 0;
      } else {
        if (JSON.parse(this.form.city_arr_id.length == 0)) {
          this.form.city_id = 0;
        } else {
          this.form.city_id = this.form.city_arr_id[this.form.city_arr_id.length - 1];
        }
        this.form.city_arr_id = JSON.stringify(this.form.city_arr_id);
      }


      //将department_id和city_id转换为字符串  
      // this.form.department_arr_id = JSON.stringify(this.form.department_arr_id);
      // this.form.city_arr_id = JSON.stringify(this.form.city_arr_id);
      //添加要修改的id
      this.form.id = this.editId;

      //判断用户身份
      if (this.creatNews_user_type == 10000) {
        if (this.$route.query.to == "examine") {
          //如果是管理员在编辑用户的新闻这里的status需要设置为0
          this.form.status = 0;
        } else {
          console.log("用户身份为管理员,无需审核直接发布!")
          this.form.status = 1;
        }
      } else {
        console.log("用户身份为其他用户,提交到审核!")
        this.form.status = 0;
        this.form.web_site_id = this.websiteid;
      }

      //先进行验证
      this.$refs.form.validate(valid => {
        if (valid) {
          //如果推荐等级为空，则设置为0
          if (this.form.level == "" || this.form.level == "[0]") {
            this.form.level = "[0]";
          } else {
            this.form.level = JSON.stringify(this.form.level);
          }
          const formData = { ...this.form };
          if (formData.commend_id != undefined && formData.commend_id.length > 0) {
            formData.commend_id = JSON.stringify(formData.commend_id); // 提取推荐ID
          }
          if (formData.commend_id.length == 0) {
            formData.commend_id = '[]';
          }
          //console.log(this.form)
          this.$store.dispatch('news/updateArticle', formData).then(res => {
            if (res.code != 200) {
              this.$message.error("修改失败，请稍后再试！");
            } else {
              //汇报结果
              this.$message({
                type: 'success',
                message: '已成功编辑资讯！'
              });
              this.cleatForm(2);
              //返回列表页
              this.returnPage()
              console.log(this.form);

              // this.form.level=JSON.parse(this.form.level);
            }
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '网络错误，请重试！'
            });
          })
        }
      })
    },
    //1.4 修改是否原创
    changeIsOriginal() {
      if (this.form.is_original == 1) {
        this.form.copyfrom = "本网";
      } else {
        this.form.copyfrom = "";
        this.form.fromurl = "";
      }
    },
    //跳转操作 end ------------------------------------------------------------>


    //5.站点选择 曹国庆 start ------------------------------------------------------------>
    get_creatNews_form_id_fun() {
      //判断用户类型ajax
      this.$store.dispatch('public/getInfo').then(res => {
        //     console.log("res======",res)
        this.form.user_type = res.data.type_id;
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '网络错误，请重试！'
        });
      })
    },
    get_creatNews_nav_pool_arr_fun() {//
      this.$store.dispatch('pool/get_creatNews_nav_actions', { page: 1, pageSize: 666666 }).then(res => {
        res.data.rows.forEach((per_obj) => {
          let new_per = {
            label: per_obj.website_name,
            value: per_obj.id,
          }
          this.creatNews_nav_pool_arr.push(new_per)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '网络错误，请重试！'
        });
      })
    },
    creatNews_nav_pool_change_fun() {
      //开启导航池级联选择器
      this.ifwebsitId = true;
      console.log(this.ifwebsitId)
      //  导航池级
      let that = this;
      this.form.web_site_id = this.form.web_site_id[0]
      that.parentKey_2 += 1;
      this.$store.dispatch('pool/get_creatNews_nav_son_actions', { pid: String(this.creatNews_pid_num), website_id: String(this.form.web_site_id) }).then(res => {
        if (res.data.length == 0) {//没有导航池子级
          // alert("没有导航池子级");
          return
        }
        this.creatNews_add_nav_pool_arr = res.data;
        this.creatNews_add_nav_pool_arr.forEach((per_obj) => {
          per_obj.label = per_obj.name,
            per_obj.value = per_obj.id,
            this.creatNews_pid_num = per_obj.category_id
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '网络错误，请重试！'
        });
      })
    },
    updateTags(newTags) {
      // this.foem.seo_keywords = newTags;
      this.tags = newTags;
      this.form.keyword = newTags.join(',');
    },
    //推荐等级多选获取到的数据
    levelChange(value) {
      this.form.level = value;
    },
    getNews() {
      this.$store.dispatch('news/getArticleList', { page: 1, pageSize: 20 }).then(res => {
        let data = [];
        for (let item of res.data.rows) {
          data.push(item)
        }
        this.commend_article = data;
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '网络错误，请重试！'
        });
      })
    },
    // 远程搜索方法
    remoteMethod(query) {
      const artical_params = { page: 1, pageSize: 20, id: query }
      if (query !== '') {
        this.loading = true;
        //如果全是数字，就id，其他就是搜title
        let reg = /^[0-9]+$/;
        let isNum = reg.test(query);
        if (isNum) {
          delete artical_params.title;
          artical_params.id = query;
        } else {
          delete artical_params.id;
          artical_params.title = query;
        }
        this.$store.dispatch('news/getArticleList', artical_params).then(res => {
          this.loading = false;
          let data = [];
          for (let item of res.data.rows) {
            data.push(item);
          }
          this.commend_article = data;
        }).catch(() => {
          this.loading = false;
          this.$message({
            type: 'info',
            message: '网络错误，请重试！'
          });
        });
      } else {
        this.commend_article = [];
      }
    },
    //5.站点选择 曹国庆 end ------------------------------------------------------------>

    //6.问卷 刘佳伟 start ------------------------------------------------------------>
    addInput(index) {
      // 在当前索引后插入一个新的输入框对象
      if (this.inputList.length > 10) {
        this.$message.warning('最多只能添加10个文本框');
        return false;
      }
      this.inputList.splice(index + 1, 0, { value: '' });
    },
    deleteInput(index) {
      if (this.inputList.length > 1) {
        // 如果输入框数量大于 1，则删除当前索引对应的输入框对象
        this.inputList.splice(index, 1);
      } else {
        this.$message.warning('至少保留一个输入框');
      }
    },
    onDragEnd() {
      // 处理拖拽结束事件（如果需要）
      console.log('拖拽结束', this.commend_article);
    },
    handleClose(item) {
      const index = this.form.commend_id.indexOf(item);
      if (index > -1) {
        this.form.commend_id.splice(index, 1);
      }
    },
    //6.问卷 刘佳伟 end ------------------------------------------------------------>
  },
  mounted() {
    console.log("mounted")
    this.getNews()
    console.log(this.commend_article, '-------news-------');
    this.creatNews_user_type = getUseType()
    this.websiteid = getWebSiteId()
    //1.获得站点标识
    this.get_creatNews_form_id_fun()
    this.get_creatNews_nav_pool_arr_fun()
    //2.判断是新建还是回显
    if (this.$route.query.id != undefined) {
      this.editId = this.$route.query.id;
      this.editStatus = true;
      console.log("编辑新闻！")
      this.getMainData();
    } else {
      this.editStatus = false;
      console.log("添加新闻！")
    }
  },
};
</script>

<style scoped lang="less">
//执行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-popper {
  height: 500px;
}

::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 .el-form-item__error {
  color: #ff4949;
  font-size: 12px;
  line-height: 1;
  padding-top: 4px;
  position: relative;
  // top: 22%;
  // left: 93%;
}

//输入框距离底部的距离
::v-deep .el-form-item {
  margin-bottom: 5px;
}

//图片提示文字样式
.photo_tips {
  font-size: 12px;
  color: #999;
}

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