<template>
  <div class="mainBox">
    <!--搜索功能 start------------------------------------------------------------>
    <div class="layerBox_search">
      <div class="layerBoxLine">
        <el-row>
        <el-col :span="8">
          <div class="searchBox">
            <div class="searchTitle">网站名称：</div>
            <el-input placeholder="请输入网站名称" autocomplete="off" v-model="getApiData.keyword"/>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="searchBox">
            <div class="searchTitle">上级网系：</div>
            <el-cascader v-model="getApiData.website_column_id" :props="{checkStrictly:true}" :options="website_column_arr" clearable></el-cascader>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="searchBox">
            <div class="searchTitle">网站城市：</div>
            <CityCascader v-model="getApiData.city_arr_id" @update-city-id="updateCityId"></CityCascader>
          </div>
        </el-col>
      </el-row>
      </div>
    </div>
    <div class="layerBoxNoBg">
      <div>
        <el-button type="primary" @click="addData">添加网站</el-button>
      </div>
      <div>
        <el-button type="info" @click="clearSearchList">重置</el-button>
        <el-button type="primary" @click="getData('search')">搜索</el-button>
      </div>
    </div>
    <!--搜索功能 end------------------------------------------------------------>
    <!--表格内容 start------------------------------------------------------------>
    <div class="layerBox">
      <tableTitle :name="tableDivTitle"/>
      <el-row>
        <template>
          <el-table :data="tableData" style="width: 100%">
            <el-table-column fixed prop="id" label="编号" width="50"></el-table-column>
            <el-table-column prop="website_name" label="网站名称"></el-table-column>
            <el-table-column prop="column_name" label="上级网系"></el-table-column>
            <el-table-column label="网站地址">
              <template slot-scope="scope">
                <div>
                  <div v-for="(url, index) in scope.row.website_url" :key="index">
                    {{ url }}
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="city_name" label="网站城市"></el-table-column>
            <el-table-column prop="created_at" label="创建时间"></el-table-column>
            <el-table-column prop="updated_at" label="修改时间"></el-table-column>
            <el-table-column fixed="right" label="操作" width="240" header-align="center">
              <template slot-scope="scope">
                <div class="listBtnBox">
                  <div class="listDeleteBtn" @click="deleteData(scope.row.id, tableData)"><i class="el-icon-delete"></i>移除</div>
                  <div class="listEditBtn" @click="getDataMain(scope.row.id, tableData)"><i class="el-icon-edit-outline"></i>编辑</div>
                  <!-- <div class="listMainBtn" @click="creatWebsite(scope.row.id)"><i class="el-icon-brush"></i>搭建</div> -->
                </div>
                <!-- <div class="listMainBtn"><i class="el-icon-view"></i>详情</div> -->
                <!-- <el-button @click.native.prevent="deleteData(scope.row.id, tableData)" type="text" size="small">移除</el-button>
                <el-button @click.native.prevent="getDataMain(scope.row.id, tableData)" type="text" size="small">编辑</el-button> -->
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-row>
    </div>
    <div class="alignBox">
      <el-row>
        <el-col :span="24">
          <el-pagination :current-page="getApiData.page" @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-size="10" layout="total, prev, pager, next, jumper" :total="allCount"></el-pagination>
        </el-col>
      </el-row>
    </div>
    <!--表格内容 end------------------------------------------------------------>
    <!--弹出框1：外部表单弹出框 start------------------------------------------------------------>
    <el-dialog :title="editId ? '编辑网站' : '添加网站'" :visible.sync="windowStatus" :close-on-click-modal="false">
      <!--弹出框2：内部模板弹出框 start------------------------------------------------------------>
      <el-dialog width="39%" title="皮肤库" :visible.sync="innerVisible" append-to-body>
        <div class="templateBox">
          <div class="templateListClass">
            <div class="templateListClassItem">简约现代</div>
            <div class="templateListClassItem">复古风格</div>
            <div class="templateListClassItem">扁平化</div>
          </div>
          <div class="templateListBox">
            <div v-for="item in TemplateList" class="templateList" @click="useThatTemplate(item.id,item.template_name,item.template_img)">
              <img :src="item.template_img" class="templateImg">
              <div>{{item.template_name}}</div>
            </div>
          </div>
        </div>
        <div class="pageNumBox">
          <el-pagination @size-change="handleTemplateSize" @current-change="handleChangeCurrent" :page-size="10" layout="total, prev, pager, next, jumper" :total="TemplateallCount"></el-pagination>
        </div>
        <div class="webSiteBtn">
          <el-button type="primary" @click="innerVisible = false">确 定</el-button>
        </div>
      </el-dialog>
      <!--弹出框2：内部模板弹出框 end------------------------------------------------------------>
      <el-form :model="form" ref="form" :rules="formRules" autocomplete="off" label-position="left">
        <div class="formDiv">
          <el-form-item label="网站名称：" :label-width="formLabelWidth" prop="website_name" class="custom-align-right">
            <el-input v-model="form.website_name" autocomplete="off" @blur="checkWebsiteName(form.website_name)" placeholder="请输入网站名称"></el-input>
          </el-form-item>
          <el-form-item label="网站地址1：" :label-width="formLabelWidth" prop="website_url[0].url" class="custom-align-right">
            <div class="formLabelFloatBox">
              <el-input v-model="form.website_url[0].url" autocomplete="off" @blur="checkWebsiteUrl(form.website_url[0].url,0)" placeholder="请输入网站地址1"></el-input>
              <el-button type="info" icon="el-icon-plus" circle size="mini" @click="addUrlInput(1)" class="formLabeladdIcon"></el-button>
              <el-button type="info" icon="el-icon-delete" circle size="mini" @click="" class="formLabelDelIcon" disabled></el-button>
            </div>
          </el-form-item>
          <el-form-item label="网站地址2：" :label-width="formLabelWidth" v-if="form.website_url[1].show==true" class="custom-align-right">
            <div class="formLabelFloatBox">
              <el-input v-model="form.website_url[1].url" autocomplete="off" @blur="checkWebsiteUrl(form.website_url[1].url,1)"  placeholder="请输入网站地址2"></el-input>
              <el-button type="info" icon="el-icon-plus" circle size="mini" @click="addUrlInput(2)" class="formLabeladdIcon"></el-button>
              <el-button type="info" icon="el-icon-delete" circle size="mini" @click="deleteUrlInput(1)" class="formLabelDelIcon"></el-button>
            </div>
          </el-form-item>
          <el-form-item label="网站地址3：" :label-width="formLabelWidth" v-if="form.website_url[2].show==true" class="custom-align-right">
            <div class="formLabelFloatBox">
              <el-input v-model="form.website_url[2].url" autocomplete="off" @blur="checkWebsiteUrl(form.website_url[2].url,2)"  placeholder="请输入网站地址3"></el-input>
              <el-button type="info" icon="el-icon-plus" circle size="mini" @click="addUrlInput(3)" class="formLabeladdIcon"></el-button>
              <el-button type="info" icon="el-icon-delete" circle size="mini" @click="deleteUrlInput(2)" class="formLabelDelIcon"></el-button>
            </div>
          </el-form-item>
          <el-form-item label="网站地址4：" :label-width="formLabelWidth" v-if="form.website_url[3].show==true" class="custom-align-right">
            <div class="formLabelFloatBox">
              <el-input v-model="form.website_url[3].url" autocomplete="off" @blur="checkWebsiteUrl(form.website_url[3].url,3)"  placeholder="请输入网站地址4"></el-input>
              <el-button type="info" icon="el-icon-plus" circle size="mini" @click="addUrlInput(4)" class="formLabeladdIcon"></el-button>
              <el-button type="info" icon="el-icon-delete" circle size="mini" @click="deleteUrlInput(3)" class="formLabelDelIcon"></el-button>
            </div>
          </el-form-item>
          <el-form-item label="网站地址5：" :label-width="formLabelWidth" v-if="form.website_url[4].show==true" class="custom-align-right">
            <div class="formLabelFloatBox">
              <el-input v-model="form.website_url[4].url" autocomplete="off" @blur="checkWebsiteUrl(form.website_url[4].url,4)"  placeholder="请输入网站地址5"></el-input>
              <el-button type="info" icon="el-icon-plus" circle size="mini" @click="" class="formLabeladdIcon" disabled></el-button>
              <el-button type="info" icon="el-icon-delete" circle size="mini" @click="deleteUrlInput(4)" class="formLabelDelIcon"></el-button>
            </div>
          </el-form-item>
          <el-form-item label="上级网系：" :label-width="formLabelWidth" prop="website_column_arr_id" class="custom-align-right">
            <el-cascader v-model="form.website_column_arr_id" :props="{checkStrictly:true}" :options="website_column_arr"></el-cascader>
          </el-form-item>
          <el-form-item label="城市：" :label-width="formLabelWidth" class="custom-align-right">
            <CityCascader v-model="form.city_arr_id" @update-city-id="updateFormCityId"></CityCascader>
          </el-form-item>
          <el-form-item label="网站logo：" prop="logo" :label-width="formLabelWidth" :class="['custom-form-item']" class="custom-align-right">
            <div class="uploaderBox">
              <!-- <el-upload class="avatar-uploader" action="#" :show-file-list="false" :before-upload="beforeAvatarUpload">
                <img v-if="logoUrl" :src="logoUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload> -->
              <!--图片上传组件 start ------------------------------------------------------------>
              <div class="avatar-upload-container" @mouseenter="hovering = true" @mouseleave="hovering = false">
                <!-- 上传组件 -->
                <el-upload
                  class="avatar-uploader"
                  action="#"
                  :show-file-list="false"
                  :before-upload="beforeAvatarUpload"
                >
                  <!-- 预览图片 -->
                  <img v-if="logoUrl" :src="logoUrl" class="avatar">
                  <!-- 上传图标 -->
                  <!-- <i v-else class="el-icon-plus avatar-uploader-icon"></i> -->
                  <div v-else class="chooseImgDiv">
                    <div>
                      <img src="@/assets/public/upload/noImage.png">
                      <div>选择图片</div>
                    </div>
                  </div>
                  <input type="hidden" name="logo" v-model="form.logo">
                </el-upload>
                <!-- 删除按钮，当鼠标悬浮时显示 -->
                <div v-if="hovering && logoUrl" class="delete-button" @click="handleDelete">
                  <i class="el-icon-delete"></i>
                </div>
              </div>
              <!--图片上传组件 end ------------------------------------------------------------>
            </div>
          </el-form-item>
          <el-form-item label="网站标题：" :label-width="formLabelWidth" prop="title" 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 v-model="form.title" autocomplete="off"  placeholder="请输入网站标题"></el-input>
          </el-form-item>
          <el-form-item label="网站关键词：" :label-width="formLabelWidth" prop="keywords" 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 v-model="form.keywords" autocomplete="off"  placeholder="请输入网站关键词"></el-input>
          </el-form-item>
          <el-form-item label="网站描述：" :label-width="formLabelWidth" prop="description" 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.description" class="custom-textarea" placeholder="请输入网站描述"></el-input>
          </el-form-item>
          <el-form-item label="模板：" :label-width="formLabelWidth" class="custom-align-right" prop="template_id">
            <div class="webSiteTemplate" @click="getTemplateList">
              <!-- <div class="webSiteTitle"></div> -->
              <div class="webSiteTemplateImg">
                <div>
                  <img v-if="TemplateImg" :src="TemplateImg" class="selectWebSiteTemplateImg">
                  <div v-else>
                    <img src="@/assets/public/upload/noImage.png">
                    <div class="webSiteTemplateText">皮肤库</div>
                  </div>
                  <input type="hidden" name="template_id" v-model="form.template_id">
                </div>
              </div>
            </div>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <div class="footerBtnbox">
          <el-button @click="closeWindow" type="info">取 消</el-button>
          <el-button type="primary" @click="editToServe" v-if="editBtn==true">确定</el-button>
          <el-button type="primary" @click="addToServe" v-else>提交</el-button>
        </div>
      </div>
    </el-dialog>
    <!--弹出框2：外部表单弹出框 end------------------------------------------------------------>
  </div>
</template>

<script>
//本地编译城市代码
//import getLocationNameById from '@/utils/citytocode';
//城市级联选择器
import CityCascader from './components/CityCascader';
//表格标题
import tableTitle from './components/tableTitle';
//引入公用样式
import '@/styles/global.less';

export default {
  components: {
    CityCascader, //城市级联选择器
    tableTitle,//表格标题
  },
  data() {
    //0.全局操作 start ------------------------------------------------------------>
    //表单验证
    const validateEmpty = (rule,value,callback) => {
      if (value.length == 0) {
        callback(new Error('该项不能为空！'))
      } else {
        callback()
      }
    }
    const validateWebsiteUrl = (rule,value,callback) => {
      if (!value || value.trim() === "") {
        callback(new Error('至少要填写一个网站地址！'));
      } else {
        callback();
      }
    }
    const validateColumn = (rule,value,callback) => {
      if (value.length === 0) {
          callback(new Error('必须选择一个上级网系！'))
      } else {
          callback()
      }
    }
    let self = this;
    //0.全局操�� end ------------------------------------------------------------>
    return {
      //1.列表和分页相关 start ------------------------------------------------------------>
      tableDivTitle:"网站列表",
      tableData:[],//内容
      editId:0,//要修改的网站id
      getApiData:{
        keyword:"",//网站名称查询
        website_column_id:[],//使用网系id查询
        city_id:[],//使用城市id查询
        page:1,//当前是第几页
        pageSize:10,//一共多少条
      },
      allCount:0,//总条数
      //分页相关 end ------------------------------------------------------------>

      //2.弹出框设置 start ------------------------------------------------------------>
      windowStatus:false, //显示第一层弹窗
      innerVisible:false, //显示第二层弹窗
      formLabelWidth: '120px',//表单的长度
      editBtn:false,//当显示编辑按钮的时候，就不显示提交
      //弹出框设置 start ------------------------------------------------------------>

      //3.弹出框中的表单设置 start ------------------------------------------------------------>
      //3.1 表单收集的数据
      form: {
        website_name: '',//需要提交的网站名称
        website_url:[//需要绑定的网站���址
          {url:"",show:true},
          {url:"",show:false},
          {url:"",show:false},
          {url:"",show:false},
          {url:"",show:false}
        ],
        website_column_arr_id:[],//需要提交的上级网系 数组
        city_arr_id:[0],//需要提交的城市id
        logo:"",//logo地址 提交文件换取地址
        title:"",//需要提交的网站标题
        keywords:"",//需要提交的网站标题
        description:"",//需要提交的网站描述
        template_id:""//选择的网站皮肤
      },
      //3.2 表单验证规则
      formRules: {
        //网站名称不能为空
        website_name:[{required:true,trigger:'blur',validator:validateEmpty}],
        //网站地址不能为空
        'website_url[0].url': [
          {required: true, message:'至少要填写一个网站地址！',trigger:'blur'},
          {validator: this.validateWebsiteUrl,trigger:'blur'}
        ],
        //网系不能为空 注意，因为是select框，只有提交的时候才会验证
        website_column_arr_id: [{type:'array',required:true,trigger:'change',message:'必须选择一个网系！',validator:validateColumn}],
        //网站标题，关键词，描述不能为空
        title:[{required:true,trigger:'blur',validator:validateEmpty}],
        keywords:[{required:true,trigger:'blur',validator:validateEmpty}],
        description:[{required:true,trigger:'blur',validator:validateEmpty}],
        logoUrl:[{required:true,trigger:'blur',validator:validateEmpty}],
        template_id:[{required:true,trigger:'blur',validator:validateEmpty}],
      },
      //3.3 通过api获的的数据 弹窗
      website_column_arr:[],//api获得的网系列表
      //3.4 上传logo图片
      logoUrl:'',
      hovering: false, // 鼠标悬浮状态 悬浮时显示删除
      //3.5 模板列表
      TemplateList:[],
      getTemplateData:{
        template_class_id:1,//模板类型，暂时为1
        page:1,//当前是第几页
        pageSize:9,//请求多少条
      },
      TemplateallCount:0,//总条数
      TemplateName:"未选择模板..",//选择的模板名称
      TemplateImg:"",//选择的模板图片
      //弹出框中的表单设置 end ------------------------------------------------------------>
    }
  },
  methods: {
    //1.列表和分页相关 start ------------------------------------------------------------>
    //1.1 开始请求列表信息方法
    getData(type){
      //搜索条件 - 网系和城市id只提交最后一个
      if(this.getApiData.website_column_id.length>0){
        this.getApiData.website_column_id = this.getApiData.website_column_id[this.getApiData.website_column_id.length - 1];
      }
      if(this.getApiData.city_id.length>0){
        this.getApiData.city_id = this.getApiData.city_id[this.getApiData.city_id.length - 1];
      }
      //如果是搜索，重新加载第一页
      if(type=="search"){
        this.getApiData.page = 1;
      }
      //console.log(this.getApiData)
      this.$store.dispatch('pool/getWebList',this.getApiData).then(res=> {
        let newData = [];
        for(let item of res.data.rows){
          if(item.city_name==null){item.city_name="--"}
          newData.push(item)
        }
        //格式化网站地址
        // res.data.rows.forEach(item => {
        //   item.website_url = item.website_url.join(', ');
        // });
        this.tableData = newData; //给与内容
        this.allCount = res.data.count; //给与总条数
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '网络错误，请重试！'
        });
      })
    },
    //1.2 删除内容
    deleteData(id){
      this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log("当前删除：" + id)
        this.$store.dispatch('pool/deleteWebList',{id:id}).then(res=> {
          this.getData();
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'warning',
            message: '网络错误，请重试！'
          });
        })
      }).catch(() => {
        this.$message({
          type: 'warning',
          message: '已取消删除'
        });
      });
    },
    //1.3 列表内容分页
    //直接跳转
    handleSizeChange(val) {
      this.getApiData.page = val;
      this.getData();
    },
    //1.4 点击分页
    handleCurrentChange(val) {
      this.getApiData.page = val;
      this.getData();
    },
    //1.6 重置按钮
    clearSearchList(){
      this.tableData = [];
      this.getApiData.keyword = "";
      this.getApiData.website_column_id = [];
      this.getApiData.city_id = [];
      this.getApiData.city_arr_id = [];
      this.getApiData.page = 1;
      this.getApiData.pageSize = 10;
      this.getData();
    },
    //1.7搜索栏的城市选择器
    updateCityId(value) {
      // 这里可以处理选择后的回调逻辑
      console.log("城市ID已更新:", value);
      // 可以在此处执行额外逻辑
      this.getApiData.city_id = value;
    },
    //列表和分页相关 end ------------------------------------------------------------>

    //2.弹出框设置 start ------------------------------------------------------------>
    //2.1 打开弹出框
    openWindow() {
      this.clearToServe();
      this.windowStatus = true;
    },
    //2.2 关闭弹出框
    closeWindow(){
      this.windowStatus = false;
      this.clearToServe();
    },
    //2.3 重置窗口内容
    clearToServe(){
      //还原表单
      this.form.website_name = "";
      this.form.website_column_arr_id = "";
      this.form.website_url = [
        {url:"",show:true},
        {url:"",show:false},
        {url:"",show:false},
        {url:"",show:false},
        {url:"",show:false}
      ];
      this.form.city_arr_id = [0];
      this.form.logo = "";
      this.form.title = "";
      this.form.keywords = "";
      this.form.description = "";
      this.form.template_id = "";
      //还原logo缩略图
      this.logoUrl = "";
      //还原模板
      this.TemplateList = [];
      this.getTemplateData.page = 1;
      this.TemplateImg = "";
      this.TemplateallCount = 0;
    },
    //弹出框设置 end ------------------------------------------------------------>

    //3.添加新网站 start ------------------------------------------------------------>
    //3.1 获得所有网系
    getwebsiteColumn(){
      let that = this;
      this.$store.dispatch('pool/getwebsiteColumn').then(res=> {
            console.log("res.data",res.data)
        let arrData = this.transformData(res.data)
        this.website_column_arr = arrData;
      })
    },
    transformData(arrData) {
      let that = this;
      return arrData.map(item => {
        // 创建一个新的对象，替换键名
        let newItem = {
          label: item.column_name,
          value: item.id,
          // 保留其他不需要改动的字段
          pid: item.pid,
          sort: item.sort,
          remark: item.remark,
          column_arr_id: item.column_arr_id,
          updated_at: item.updated_at,
          created_at: item.created_at,
        };

        // 如果有 children，则递归处理 children 数组
        if (item.children && item.children.length > 0) {
          newItem.children = that.transformData(item.children);
        }

        return newItem;
      });
    },
    //3.2 开始添加内容
    addData(){
      //先获取所有网系
      this.getwebsiteColumn()
      //显示网系到弹出窗口
      this.openWindow()
      //显示提交按钮
      this.editBtn = false;
      //清除错误状态
      this.$refs.form.clearValidate();
    },
    //3.3 添加一条网站地址
    addUrlInput(key){
      this.form.website_url[key].show=true;
    },
    //3.4 删除一条网站地址
    deleteUrlInput(key){
      this.form.website_url[key].show=false;
      this.form.website_url[key].url="";
    },
    //3.5 弹出框的城市选择器
    updateFormCityId(value){
      console.log("城市ID已更新:", value);
      this.form.city_arr_id = value;
    },
    //3.6 上传图片操作
    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.logoUrl = res.data.imgUrl;//显示缩略图
        this.form.logo = res.data.imgUrl;//提供表单地址
        console.log(res.data.imgUrl)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '网络错误，请重试！'
        });
      })

      // 阻止默认的上传行为
      return false;
    },
    handleDelete() {
      // 删除图片
      this.logoUrl = ''; // 清空图片 URL
    },
    //3.7 提交表单
    addToServe(){
      console.log(this.form)
      //先进行验证
      this.$refs.form.validate(valid => {
        if (valid) {
          //提交之前把域名列表转换成数组
          let webSiteArray = [];
          for(let item of this.form.website_url){
            if(item.url!=""){
              webSiteArray.push(item.url)
            }
          }
          //循环完毕 重置提交的url
          this.form.website_url = webSiteArray;
          //console.log(webSiteArray)
          console.log(this.form)
          //提交表单
          this.$store.dispatch('pool/addWebsite',this.form).then(res=> {
            if(res.code==200){
              //汇报结果
              this.$message({
                type: 'success',
                message: '已成功添加网站！'
              });
              //重新获取表单
              this.getData();
              //清空并退出
              this.closeWindow();
            }else{
              this.$message({
                type: 'success',
                message: '添加失败！请检查网络！'
              });
              //清空并退出
              this.closeWindow();
            }
            
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '网络错误，请重试！'
            });
          })
        }
      })
    },
    //3.8 检测网站名称是否存在
    checkWebsiteName(name){
      let data = {
        website_name:name
      }
      if(this.editId!=""){
        data.id = this.editId;
      }
      this.$store.dispatch('pool/checkWebsiteName',data).then(res=> {
        if(res.code==200){
          this.form.website_name = "";
          this.$message({
            type: 'warning',
            message: '网站名称已存在！请重新输入！'
          });
        }
      })
    },
    //3.9 检测网站url是否存在
    checkWebsiteUrl(url,num){
      let data = {
        website_url:url
      }
      if(this.editId!=""){
        data.id = this.editId;
      }
      this.$store.dispatch('pool/checkWebsiteUrl',data).then(res=> {
        if(res.code==200){
          if(num==0){this.form.website_url[0].url=""}
          if(num==1){this.form.website_url[1].url=""}
          if(num==2){this.form.website_url[2].url=""}
          if(num==3){this.form.website_url[3].url=""}
          if(num==4){this.form.website_url[4].url=""}
          this.$message({
            type: 'warning',
            message: '当前网站已经被占用，请重新输入！'
          });
        }
      })
    },
    //添加新网站 end ------------------------------------------------------------>

    //4.选择模板 start ------------------------------------------------------------>
    //4.1 获取模板列表
    getTemplateList(){
      //先打开弹出框
      this.innerVisible = true;
      //获取模板列表
      this.$store.dispatch('pool/getTemplate',this.getTemplateData).then(res=> {
        //直接给与数据
        //this.TemplateList = res.data.rows;
        //格式化 目前缩略图给了两张，我只展示其中一张
        let data = res.data.rows;
        for(let item of data){
          //item.template_img
          let imgSrc = item.template_img;
          item.template_img = imgSrc[0];
        }
        this.TemplateList = data;
        //给与总条数
        this.TemplateallCount = res.data.count;
      }).catch(() => {
        this.$message({
          type: 'warning',
          message: '网络错误，请重试！'
        });
      })
    },
    //4.2 选择一个模板
    useThatTemplate(id, template_name, template_img) {
        console.log(template_name);
        console.log(template_img);
        // 关闭弹出框
        this.innerVisible = false;
        // 显示用户选择的名称
        this.TemplateName = template_name;
        // 确保这里设置了 TemplateImg
        this.TemplateImg = template_img; // 确保 template_img 是有效的路径
        // 记录选择的模板id
        this.form.template_id = id;
    },
    //4.1 模板列表分页
    //直接跳转
    handleTemplateSize(val) {
      this.getTemplateData.page = val;
      this.getTemplateList();
    },
    //4.2 点击分页
    handleChangeCurrent(val) {
      this.getTemplateData.page = val;
      this.getTemplateList();
    },
    //选择模板 end ------------------------------------------------------------>

    //5.编辑网站 start ------------------------------------------------------------>
    //5.1获取详情
    getDataMain(id){
      //先清空窗口
      this.clearToServe()
      //打开输入窗口
      this.openWindow();
      //添加修改id
      this.editId = id;

      //获取网站详情
      this.$store.dispatch('pool/getWebsiteInfo',{id:id}).then(res=> {
        //清除错误状态
        this.$refs.form.clearValidate();
        console.log(res)
        //回显网站名称
        this.form.website_name = res.data.website_name;
        //回显星系
        this.form.website_column_arr_id = res.data.website_column_arr_id;
        //回显logo
        this.form.logo = res.data.logo;
        this.logoUrl = res.data.logo;
        //回显url
        let that = this;
        if(res.data.website_url==null){
          //为null什么都不执行
        }else{
          for(let index in res.data.website_url){
            this.form.website_url[index].url = res.data.website_url[index];
            this.form.website_url[index].show = true;
          }
        }
        //回显id
        //存放城市id
        this.form.city_arr_id = res.data.city_arr_id;
        //当cascaderKey的值改变的时候 级联选择器会重置里面的内容
        //this.cascaderKey += 1;
        //回显网站标题，描述，关键词
        console.log(res.data.title,res.data.keywords,res.data.description)
        this.form.title = res.data.title;
        this.form.keywords = res.data.keywords;
        this.form.description = res.data.description;
        //回显模板信息
        this.form.template_id = res.data.template_id;
        this.TemplateName = res.data.template_name;
        this.TemplateImg = JSON.parse(res.data.template_img)[0];
      })

      this.editBtn = true;//显示编辑按钮
    },
    //5.2修改表单
    editToServe(){
      //执行验证
      this.$refs.form.validate(valid => {
        if (valid) {
          //提交之前把域名列表转换成数组
          let webSiteArray = [];
          for(let item of this.form.website_url){
            if(item.url!=""){
              webSiteArray.push(item.url)
            }
          }
          //循环完毕 重置提交的url
          this.form.website_url = webSiteArray;
          this.form.id = this.editId;
          //提交表单
          this.$store.dispatch('pool/updateWebsite',this.form).then(res=> {
            //汇报结果
            this.$message({
              type: 'success',
              message: '已成功修改网站信息！'
            });
            //清空并退出
            this.closeWindow();
            //重新请求列表
            this.getData();
          }).catch(() => {
            this.$message({
              type: 'warning',
              message: '网络错误，请重试！'
            });
          })
        }
      }) 
    },
    //编辑旧网站 end ------------------------------------------------------------>

    //6.搭建网站 start ------------------------------------------------------------>
    creatWebsite(id){
      this.$router.push({ 
        path: '/creatWebsite', 
        query: {id:id} 
      });
    } 
    //编辑旧网站 end ------------------------------------------------------------>
  },
  mounted(){
    //1.获得初始数据
    this.getData();
    //2.获取所有网系
    this.getwebsiteColumn();
    //本地转换id为文字
    //console.log(getLocationNameById("110000"))
  }
}
</script>

<style scoped lang="less">
  /*表单特殊样式 start------------------------------------------------------------>*/
  //1.1 模板表单
  .webSite {
    background:#f0f2f5;
    width:200px;
    height:300px;
    line-height: 300px;
    text-align: center;
    margin:0 auto;
  }
  .webSiteTemplate {
    display:flex;
    .webSiteTitle {
      width:120px;
      line-height: 140px;
      text-align: right;
      padding-right:12px;
      font-weight: bold;
    }
  }
  .webSiteBtn {
    padding:50px 0 0 0;
    text-align:center;
  }
  .formLabelFloatBox {
    position: relative;
    .formLabeladdIcon {
      position: absolute;
      right:45px;
      top:5px;
      width:38px;
      height:24px;
    }
    .formLabelDelIcon {
      position: absolute;
      right:5px;
      top:5px;
      width:38px;
      height:24px;
    }
  }
  .templateBox {
    display: flex;
    .templateListClass {
      margin-right:20px;
      .templateListClassItem {
        width: 120px;
        height: 38px;
        text-align: center; 
        line-height: 38px;
        border:1px solid #E3E8FA;
        background: #F5F7FB;
        margin-bottom: 10px;
        border-radius: 8px;
        cursor: pointer;
      }
    }
    .templateListBox {
      box-sizing: border-box;
      width: 100%;
      display:flex;
      flex-wrap:wrap;
      .templateList {
        margin-right:10px;
        text-align: center;
        font-size:12px;
        margin-bottom: 10px;
        border:1px solid #fff;
        padding: 5px;
        .templateImg {
          width: 129px;
          height:157px;
          border-radius: 8px;
          cursor: pointer;
        }
      }
    }
  }
  
  //1.1 模板分页
  .pageNumBox {
    text-align: center;
    padding-top:20px;
  }
  .webSiteTemplateName {
    margin-left: 10px;
    line-height: 36px;
  }
  //1.2 模板缩略图
  .webSiteTemplateImg {
    width: 140px;
    height: 140px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 12px;
    border: 1px solid #E1E2E9;
    .selectWebSiteTemplateImg {
      width: 140px;
      height: 140px;
      border-radius: 12px;
      display: block;
      cursor: pointer;
    }
    .webSiteTemplateText {
      color: #5570F1;
      height: 36px;
      line-height: 36px;
      text-align: center;
    }
    img {
      display: block;
    }
  }
  /*表单样式 end------------------------------------------------------------>*/

  //执行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穿透scope选择器 end------------------------------------------------------------>*/
</style>  

