<template>
  <div class="mainBox">
    <div class="layerBox">
      <tableTitle :name="tableDivTitle" />
      <el-form :model="form" ref="form" :rules="formRules" label-position="left" label-width="140px">
        <div class="formDiv">
          <div v-if="creatNews_user_type == 10000">
            <el-form-item label="站点名称：" prop="website_id" class="custom-align-right">
              <el-cascader :key="parentKey" v-model="form.website_id" placeholder="请选择站点名称"
                popper-class="my_cascader" :options="creatNews_nav_pool_arr"
                @change="creatNews_nav_pool_change_fun(form.website_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>
          <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>
          <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-form-item>
          <el-form-item label="推荐等级：" prop="level" class="custom-align-right">
              <el-select v-model="form.level" clearable placeholder="请选择公司的推荐等级">
                <el-option label="推荐企业" :value="1"></el-option>
              </el-select>
            </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="来源名称：" prop="source" class="custom-align-right">
            <el-input v-model="form.source" autocomplete="off" placeholder="请输入来源名称"></el-input>
          </el-form-item>
          <el-form-item label="来源链接：" prop="source_url" class="custom-align-right">
            <el-input v-model="form.source_url" autocomplete="off" placeholder="请输入来源链接"></el-input>
          </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; height:140px;">
                  <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 v-if="imgurl.length < 5"  class="avatar-uploader" action="#" :show-file-list="true"
                  :before-upload="beforeAvatarUpload" >
                  <!-- 预览图片 -->
                  <img v-if="imgurl.length > 5" :src="imgUrl" class="avatar">
                  <div v-else class="chooseImgDiv">
                    <div>
                      <img src="@/assets/public/upload/noImage.png">
                      <div>选择图片</div>
                    </div>
                  </div>
                </el-upload>
                <div v-if="hovering && imgUrl" class="delete-button" @click="handleDelete">
                  <i class="el-icon-delete"></i>
                </div>
              </div>
             
            </el-form-item>
             <p class="photo_tips" style="margin-left: 140px;"> 最多可上传5张，每张图片大小不能超过500K，推荐上传图片尺寸

              宽1000像素 高1000像素。(首张显示为企业头图)
            </p>
            <el-form-item label="内容简介：" prop="description" class="custom-align-right">
              <el-input v-model="form.description" autocomplete="off" placeholder="请输入内容简介" type="textarea" :rows="3"></el-input>
            </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="jobnature_id" class="custom-align-right">
              <el-select v-model="form.jobnature_id" clearable placeholder="请选择公司的性质">
                <el-option label="市场监管" :value="0"></el-option>
                <el-option label="信访纪检" :value="1"></el-option>
                <el-option label="公检法司" :value="2"></el-option>
                <el-option label="高关注机构" :value="3"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="负责人：" prop="manager" class="custom-align-right">
              <el-input v-model="form.manager" autocomplete="off" placeholder="请输入负责人"></el-input>
            </el-form-item>
            <el-form-item label="联系人：" prop="content_person" class="custom-align-right">
              <el-input v-model="form.content_person" autocomplete="off" placeholder="请输入联系人"></el-input>
            </el-form-item>
            <el-form-item label="企业网址：" prop="company_url" class="custom-align-right">
              <el-input v-model="form.company_url" autocomplete="off" placeholder="请输入企业网址"></el-input>
            </el-form-item>
            <el-form-item label="联系电话：" prop="telephone" class="custom-align-right">
              <el-input v-model="form.telephone" autocomplete="off" placeholder="请输入联系电话"></el-input>
            </el-form-item>
            <el-form-item label="手机：" prop="mobile" class="custom-align-right">
              <el-input v-model="form.mobile" autocomplete="off" placeholder="请输入手机"></el-input>
            </el-form-item>
            <el-form-item label="QQ：" prop="QQ" class="custom-align-right">
              <el-input v-model="form.QQ" autocomplete="off" placeholder="请输入QQ"></el-input>
            </el-form-item>
            <el-form-item label="邮编：" prop="post_code" class="custom-align-right">
              <el-input v-model="form.post_code" autocomplete="off" placeholder="请输入邮编"></el-input>
            </el-form-item>
            <el-form-item label="传真：" prop="fax" class="custom-align-right">
              <el-input v-model="form.fax" autocomplete="off" placeholder="请输入传真"></el-input>
            </el-form-item>
            <el-form-item label="电子邮件：" prop="email" class="custom-align-right">
              <el-input v-model="form.email" autocomplete="off" placeholder="请输入电子邮件"></el-input>
            </el-form-item>
            <el-form-item label="主营分类：" prop="main_business" class="custom-align-right">
              <el-input v-model="form.main_business" autocomplete="off" placeholder="请输入主营分类"></el-input>
            </el-form-item>
            <el-form-item label="行政区划：" class="custom-align-right" prop="city_arr_id">
              <CityCascader v-model="form.city_arr_id" @update-city-id="update_city_arr_id"></CityCascader>
            </el-form-item>
            <el-form-item label="详细地址：" prop="adress" class="custom-align-right">
              <el-input v-model="form.adress" autocomplete="off" placeholder="请输入详细地址"></el-input>
            </el-form-item>
            <el-form-item label="公司性质：" prop="nature_id" class="custom-align-right">
              <el-select v-model="form.nature_id" clearable placeholder="请选择公司的性质">
                <el-option v-for="item in companynature_array" :key="item.id" :label="item.nature_name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="行业分类：" prop="hy_id" class="custom-align-right">
              <el-select v-model="form.hy_id" clearable placeholder="请选择公司的行业分类">
                <el-option v-for="item in hy_array" :key="item.hyid" :label="item.hyname" :value="item.hyid">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="注册资本：" prop="zc_money" class="custom-align-right">
              <el-input v-model="form.zc_money" autocomplete="off" placeholder="请输入注册资本"></el-input>
            </el-form-item>
            <el-form-item label="注册地址：" prop="zc_address" class="custom-align-right">
              <el-input v-model="form.zc_address" autocomplete="off" placeholder="请输入注册地址"></el-input>
            </el-form-item>
            <el-form-item label="经营模式：" prop="manage_model" class="custom-align-right">
              <el-input v-model="form.manage_model" autocomplete="off" placeholder="请输入经营模式"></el-input>
            </el-form-item>
            <el-form-item label="成立日期：" prop="data" class="custom-align-right">
              <el-date-picker v-model="form.data" placeholder="请选择成立日期"> </el-date-picker>
            </el-form-item>
            <el-form-item label="主营产品或服务：" prop="main_products" class="custom-align-right">
              <el-input v-model="form.main_products" autocomplete="off" placeholder="请输入主营产品或服务"></el-input>
            </el-form-item>
            <el-form-item label="主要采购产品：" prop="main_buy_products" class="custom-align-right">
              <el-input v-model="form.main_buy_products" autocomplete="off" placeholder="请输入主要采购产品"></el-input>
            </el-form-item>
            <el-form-item label="员工人数：" prop="number_id" class="custom-align-right">
              <el-select v-model="form.number_id" clearable placeholder="请选择公司的员工人数">
                <el-option v-for="item in companysize_array" :key="item.evalue" :label="item.ename" :value="item.evalue">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="主要职能：" prop="main_functions" class="custom-align-right">
              <el-input v-model="form.main_functions" autocomplete="off" placeholder="请输入公司的主要职能"></el-input>
            </el-form-item>
              <el-form-item label="企业内容：" prop="content" class="custom-align-right">
                <myEditor ref="myEditor" v-model="form.content"></myEditor>
              </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: "",//创建时间

      // 企业专属-下拉列表
      companynature_array: [],//企业性质
      hy_array: [],//行业分类
      companysize_array: [],//公司规模
      form: {
        website_id: 0,//站点id
        cat_arr_id: [],//导航池名称
        nav_add_pool_id: [],//导航池子级
        title: '',//企业标题
        author: "",//作者
        source: "",//来源名称
        source_url: "",//来源地址
        imgurl: [],//缩略图
        introduce: "",//描述
        keyword: "",//关键词
        description: "",//简介
        jobnature_id: null,//企业性质
        manager: "",//负责人
        content_person: "",//联系人
        company_url: "",//企业网址
        telephone: "",//联系电话
        mobile: "",//手机
        QQ: "",//QQ
        post_code: "",//邮编
        fax: "",//传真
        email: "",//电子邮件
        main_business: "",//主营分类
        adress: "",//详细地址
        nature_id: null,//公司性质
        hy_id: null,//行业分类
        zc_money: "",//注册资本
        zc_address: "",//注册地址
        manage_model: "",//经营模式
        data: null,//成立日期
        main_products: "",//主营产品或服务
        main_buy_products: "",//主要采购产品
        number_id: null,//员工人数
        main_functions: "",//主要职能
        content: "",//企业内容
        user_type: "??",//判断用户类型'
        city_arr_id: [],//行政区划
        city_id: "",//区划最后一个数字
        status: 0,//状态状态：0：未审核；1：已审核；2：已拒绝；
        level: null,//推荐等级
      },
      //1.2 表单验证规则
      formRules: {
        //导航池名称不能为空
        website_id: [{ required: true, trigger: 'blur', validator: validateZero }],
        //企业名称不能为空
        title: [{ required: true, trigger: 'blur', validator: validateEmpty }],
        //如果使用了外链，外链地址不能为空
        // city_arr_id: [{ required: true, trigger: 'blur', validator: validateEmpty }],
        //导航池名称不能为空
        cat_arr_id: [{ required: true, trigger: 'blur', validator: validateArray }],
        //行政区划
        city_arr_id: [{ required: true, trigger: 'blur', validator: validateArray }],
        //内容不能为空
        content: [{ required: true, trigger: 'blur', validator: validateEmpty }],
        //企业性质
        imgurl: [{ required: true, trigger: 'blur', validator: validateArray }],
      },

      //1.4图片上传
      imgUrl: [],//在页面上显示缩略图
      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 = {
            'type': 1,
            '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: [],
                disabled: item.type != 1
              }))
              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 = {
            'type': 1,
            'website_id': self.form.website_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: [],
                disabled: item.type != 1
              }))
              resolve(nodes)
            }
          })
        }
      },
      inputList: [
        { value: '' }
      ]
      //表单项 end ------------------------------------------------------------>
    };

  }, watch: {
    '$route'(to, from) {
      console.log(from, '---------------------------------------');
      // 监听路由参数中的 id 变化，若变化则更新页面状态并获取数据
      if (to.query.id) {
        this.getMainData();
      }
    },
  },
  methods: {
    // 3.获取行业分类
    get_hyid(value) {
      this.$store.dispatch('news/getIndustry').then(res => {
        this.hy_array = res.data;
      })
    },
     //13.获取公司规模
     get_company_size(value) {
      this.$store.dispatch('news/getCompanySize').then(res => {
        this.companysize_array = res.data;
      })
    },
    //14.获取公司性质
    get_company_nature(value) {
      this.$store.dispatch('news/getCompanyNature').then(res => {
        this.companynature_array = res.data;
      })
    },
    //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;
      }
      // ---------------多图上传---处理
      if (this.imgurl.length > 4) {
        this.$message.warning('只能上传5张图片');
        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')
        // this.imgUrl = res.data.imgUrl;//显示缩略图
        // this.form.imgurl = res.data.imgUrl;//提供表单地址
        // console.log(res.data.imgUrl)
         // ---------------多图上传---处理
      })

      // 阻止默认的上传行为
      return false;
    },
    deleteImage(index) { // 删除图片
      this.imgurl.splice(index, 1);
      this.form.imgurl.splice(index, 1);
    },
    //1.2 提交表单
    addToServe() {
      
      //取出行政职能和行政区划数组的最后一个数字
      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.keyword = JSON.stringify(this.form.keyword);
      //判断用户身份
      if (this.creatNews_user_type == 10000) {
        console.log("用户身份为管理员,无需审核直接发布!")
        this.form.status = 1;
      } else {
        console.log("用户身份为其他用户,提交到审核!")
        this.form.status = 0;
        this.form.website_id = this.websiteid;
      }
      // console.log("this.form.city_arr_id==", JSON.stringify(this.form.city_arr_id));
      
      //先进行验证
      console.log( "this.form==", this.form);

      this.$refs.form.validate(valid => {
        if (valid) {
          // delete formData.cat_arr_id;
          if (this.form.data) {
            // 使用日期格式化工具函数
            const formatDate = (dateString, format = 'YYYY-MM-DD') => {
              const date = new Date(dateString);
              const year = date.getFullYear();
              const month = String(date.getMonth() + 1).padStart(2, '0');
              const day = String(date.getDate()).padStart(2, '0');
              
              return format
                .replace('YYYY', year)
                .replace('MM', month) 
                .replace('DD', day);
            };
            
            // 格式化日期并赋值给form.data
            this.form.data = formatDate(this.form.data);
            console.log('格式化后的日期:', this.form.data);
          } else {
            // 如果没有日期字段，可以设置默认值或其他处理
            this.form.data = null;
          }
          const formData = { ...this.form };
          formData.city_arr_id = Array.isArray(this.form.city_arr_id) ? JSON.stringify(this.form.city_arr_id):  this.form.city_arr_id ;
          console.log("formData==", typeof(this.form.city_arr_id));
          formData.imgurl =  Array.isArray(this.form.imgurl) ? JSON.stringify(this.form.imgurl):  this.form.imgurl ;
          this.form.cat_arr_id =  Array.isArray(this.form.cat_arr_id) ? JSON.stringify(this.form.cat_arr_id):  this.form.cat_arr_id ;
          delete formData.commend_id;
          delete formData.nav_add_pool_id;
          delete formData.user_type;
          // delete formData.data;
          this.$store.dispatch('company/addCompany', formData).then(res => {
            if (res.code == 200) {
              console.log("企业发布成功！200")
              //汇报结果
              if (this.creatNews_user_type == 10000) {
                this.$message({
                  type: 'success',
                  message: '已成功添加企业！'
                });
                this.cleatForm(2);
                //返回列表页
                this.returnPage()
              } else {
                this.$message({
                  type: 'success',
                  message: '待管理员审核！'
                });
                this.cleatForm(2);
                //返回列表页
                this.returnPage()
              }
            } else {
              this.$message({
                type: 'error',
                message: res.message
              });


            }
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '网络错误，请重试！'
            });
          })
        }
      })
    },
    //1.3 清理表单
    cleatForm() {
        this.form.website_id = 0;
        this.form.cat_arr_id = [];
        this.form.nav_add_pool_id = [],//导航池子级
        this.form.title = "";
        this.form.author = "";
        this.form.source = "";
        this.form.source_url = "";
        this.form.imgurl = [];
        this.form.introduce = "";
        this.form.keyword = "";
        this.form.description = "";
        this.form.jobnature_id = null;
        this.form.manager = "";
        this.form.content_person = "";
        this.form.company_url = "";
        this.form.telephone = "";
        this.form.mobile = "";
        this.form.QQ = "";
        this.form.post_code = "";
        this.form.fax = "";
        this.form.email = "";
        this.form.main_business = "";
        this.form.adress = "";
        this.form.nature_id = null;
        this.form.hy_id = null;
        this.form.zc_money = "";
        this.form.zc_address = "";
        this.form.manage_model = "";
        this.form.data = "";
        this.form.main_products = "";
        this.form.main_buy_products = "";
        this.form.number_id = null;
        this.form.main_functions = "";
        this.form.content = "";
        this.form.city_arr_id = [];
        this.form.city_id = "";
        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 == "checkCompany") {
        this.$router.push({
          path: '/checkcompanyList',
        });
      } else {
        this.$router.push({
          path: '/companyList',
        });
      }
    },
    //跳转操作 end ------------------------------------------------------------>

    //3.回显操作 ------------------------------------------------------------>
    //3.1回显数据
    getMainData() {
      let data = {
        id: this.$route.query.id
      };
      this.$store.dispatch('company/getCompanyInfo', data).then(res => {
        this.form.title = res.data.title;
        if (typeof res.data.website_id === 'string') {
          this.form.website_id = Number(res.data.website_id);
        } else {
          this.form.website_id = res.data.website_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);
        this.form.imgurl = Array.isArray(res.data.imgurl) ? res.data.imgurl : JSON.parse(res.data.imgurl);
        console.log("回显图片",this.form.imgurl)
        //回显导航池 连同非管理员得一起刷新
        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.form.imgurl = 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.tags = res.data.keyword ? res.data.keyword.split(",") : '';
        this.form.description = res.data.description;
        this.form.introduce = res.data.introduce;
        //回显编辑器内容
        this.$nextTick(() => {
          this.form.content = res.data.content;
        });
        this.form.author = res.data.author;
        this.form.jobnature_id = res.data.jobnature_id;
        this.form.manager = res.data.manager;
        this.form.source = res.data.source;
        this.form.source_url = res.data.source_url;
        this.form.status = res.data.status;
        this.form.manager = res.data.manager;
        this.form.content_person = res.data.content_person;
        this.form.company_url = res.data.company_url;
        this.form.telephone = res.data.telephone;
        this.form.mobile = res.data.mobile;
        this.form.QQ = res.data.QQ;
        this.form.post_code = res.data.post_code;
        this.form.fax = res.data.fax;
        this.form.email = res.data.email;
        this.form.main_business = res.data.main_business;
        this.form.adress = res.data.adress;
        this.form.nature_id = res.data.nature_id;
        this.form.hy_id = res.data.hy_id;
        this.form.zc_money = res.data.zc_money;
        this.form.zc_address = res.data.zc_address;
        this.form.manage_model = res.data.manage_model;
        this.form.data = res.data.data;
        this.form.main_business = res.data.main_business;
        this.form.main_buy_products = res.data.main_buy_products;
        this.form.main_products = res.data.main_products;
        this.form.main_functions = res.data.main_functions;
        this.form.number_id = res.data.number_id;
        this.form.level = res.data.level;
        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() {
      //不使用外联 验证投票逻辑
      this.form.id = this.editId;
      //先进行验证
      this.$refs.form.validate(valid => {
      if (valid) {
          // 如果没有，可以根据实际情况修改
        if (this.form.data) {
          // 使用日期格式化工具函数
          const formatDate = (dateString, format = 'YYYY-MM-DD') => {
            const date = new Date(dateString);
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            
            return format
              .replace('YYYY', year)
              .replace('MM', month)
              .replace('DD', day);
          };
          
          // 格式化日期并赋值给form.data
          this.form.data = formatDate(this.form.data);
          console.log('格式化后的日期:', this.form.data);
        } else {
          // 如果没有日期字段，可以设置默认值或其他处理
          this.form.data = null;
        }
        // ===== 日期处理逻辑结束 =====
          //取出行政职能和行政区划数组的最后一个数字
          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];
            }
          }
          if (this.creatNews_user_type == 10000) {
            console.log("用户身份为管理员,无需审核直接发布!")
            this.form.status = 1;
          } else {
            console.log("用户身份为其他用户,提交到审核!")
            this.form.status = 0;
            this.form.website_id = this.websiteid;
          }
          console.log("this.form111==", this.form);
          const formData = { ...this.form };
          // console.log("this.form222==", this.form);
          formData.city_arr_id = Array.isArray(this.form.city_arr_id) ? JSON.stringify(this.form.city_arr_id):  this.form.city_arr_id ;
          formData.imgurl =  Array.isArray(this.form.imgurl) ? JSON.stringify(this.form.imgurl):  this.form.imgurl ;
          delete formData.commend_id;
          delete formData.nav_add_pool_id;
          delete formData.user_type;
          // console.log("formData==", formData);
          this.$store.dispatch('company/upCompany', formData).then(res => {
          if (res.code != 200) {

            this.$message({
              type: 'error',
              message: res.message
            });

          } else {
            //汇报结果
            if (this.creatNews_user_type == 10000) {
              this.$message({
                type: 'success',
                message: '已成功编辑企业！'
              });
              this.cleatForm(2);
              //返回列表页
              this.returnPage()
            } else {
              this.$message({
                type: 'success',
                message: '待管理员审核！'
              });
              this.cleatForm(2);
              //返回列表页
              this.returnPage()
            }
          }
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '网络错误，请重试！'
            });
          })
        }
      })
    },
    //1.4 修改是否原创
    changeIsOriginal() {
      if (this.form.is_original == 1) {
        this.form.source = "本网";
      } else {
        this.form.source = "";
        this.form.source_url = "";
      }
    },
    //跳转操作 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;
      // console.log("website_id",this.form.website_id)
      this.form.website_id = this.form.website_id[0];
      that.parentKey_2 += 1;
      this.$store.dispatch('pool/get_creatNews_nav_son_actions', { type: 1, pid: String(this.creatNews_pid_num), website_id: String(this.form.website_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.tags = newTags;
      if(this.tags.length == 0){
        this.form.keyword = '';
      }else{
        this.form.keyword = JSON.stringify(newTags);
      }
     
      console.log(this.form.keyword);
    },
    //推荐等级多选获取到的数据
    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('company/getCompanyList', 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_company_nature()  //企业性质
    this.get_hyid()    //企业行业
    this.get_company_size()   //企业规模
    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;
      // this.tableDivTitle = "编辑企业";
      console.log("编辑企业！")
      this.getMainData();
    } else {
      this.editStatus = false;
      // this.tableDivTitle = "添加企业";
      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>
