<template>
  <div class="mainBox">
    <!--搜索功能 start------------------------------------------------------------>
    <div class="layerBox_search">
      <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-row>
    </div>
    <div class="layerBoxNoBg">
      <div>
        <el-button type="primary" @click="openWindow">关联导航池</el-button>
      </div>
      <div>
        <el-button @click="clearSearch">重置</el-button>
        <el-button type="primary" style="margin-right:20px" @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_category" label="导航池名称"></el-table-column>
            <el-table-column prop="website_name" label="网站名称"></el-table-column>
            <el-table-column prop="website_nav" 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="280" header-align="center">
              <template slot-scope="scope">
                <div class="listBtnBox">
                  <!-- <div class="listDeleteBtn" @click="deleteRow(scope.row.id, tableData)"><i class="el-icon-delete"></i>移除</div> -->
                  <div class="listEditBtn" @click="editRow(scope.row.id, scope.row.website_name)"><i class="el-icon-edit-outline"></i>编辑</div>
                  <div class="listMainBtn" @click="manageRow(scope.row.id, tableData)"><i class="el-icon-edit-outline"></i>详情</div>
                </div>
                <!-- <el-button @click.native.prevent="deleteRow(scope.row.id, tableData)" type="text" size="small">移除</el-button>
                <el-button @click.native.prevent="editRow(scope.row.id, scope.row.website_name)" type="text" size="small">编辑</el-button>
                <el-button @click.native.prevent="manageRow(scope.row.id)" type="text" size="small">详情</el-button> -->
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-row>
    </div>

    <!--分页 start------------------------------------------------------------>
    <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------------------------------------------------------------>
    <!--表格内容 end------------------------------------------------------------>

    <!--弹出框 start------------------------------------------------------------>
    <el-dialog :title="editId ? '关联导航池' : '编辑关联导航池'" :visible.sync="windowStatus" :close-on-click-modal="false">
      <el-form :model="form" ref="form" :rules="formRules" label-position="left">
        <div class="formDiv">
          <el-form-item label="关联网站名称：" :label-width="formLabelWidth" prop="webSiteName" class="custom-align-right">
            <el-select v-model="form.webSiteName" :multiple="false" :multiple-limit="1" filterable remote reserve-keyword placeholder="请输入网站关键词"
                :remote-method="getWebNavList" :loading="webSiteLoading" @change="detectionWebSite">
                <el-option
                  v-for="item in webSiteList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
          </el-form-item>
          <el-form-item label="导航名称：" :label-width="formLabelWidth" prop="navNames" class="custom-align-right">
            <el-select v-model="form.navNames" multiple filterable remote reserve-keyword placeholder="请输入导航关键词"
                :remote-method="getWebsiteList" :loading="navNamesLoading">
                <el-option
                  v-for="item in navList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <div>
          <el-button @click="closeWindow">取 消</el-button>
          <el-button type="warning" @click="editToServe" v-if="editBtn==true" :loading="editLoading" :disabled="editLoading">编辑</el-button>
          <el-button type="primary" @click="addToServe" v-else>提交</el-button>
        </div>
      </div>
    </el-dialog>
    <!--弹出框 end------------------------------------------------------------>
  </div>
</template>

<script>
//引入公用样式
import '@/styles/global.less';
//表格标题
import tableTitle from './components/tableTitle';

export default {
  components: {
    tableTitle,//表格标题
  },
  data() {
    //0.全局操作 start ------------------------------------------------------------>
    const validateWebSiteName = (rule,value,callback) => {
      if (value.length == 0) {
        callback(new Error('该项不能为空！'))
      } else {
        callback()
      }
    }
    const validateNavNames = (rule,value,callback) => {
      if (value.length == 0) {
        callback(new Error('该项不能为空！'))
      } else {
        callback()
      }
    }
     //0.全局操作 end ------------------------------------------------------------>
    return {
      //1.列表和分页相关 start ------------------------------------------------------------>
      tableDivTitle:"网站导航列表",
      tableData: [],//列表
      allCount:0,//总条数
      editId:0,//要修改的网站id
      getApiData:{
        keyword:"",//网站名称
        website_column_id:"",//网系
        page:1,//当前是第几页
        pageSize:10,//一共多少条
      },
      website_column_arr:[],//获得的网系
      //分页相关 end ------------------------------------------------------------>

      //2.弹出框设置 start ------------------------------------------------------------>
      //是否显示弹出窗口
      windowStatus:false,
      formLabelWidth: '120px',
      editBtn:false,//当显示编辑按钮的时候，就不显示提交
      editLoading:false,//编辑按钮的加载中  
      //弹出框设置 end ------------------------------------------------------------>

      //3.弹出框中的表单设置 start ------------------------------------------------------------>
      form: {
        webSiteName:"",//关联网站名称
        navNames:[]//导航名称
      },
      webSiteLoading:false,//获取关联网站列表的加载中
      webSiteList:[],//获取关联网站列表
      navNamesLoading: false, //获取网站导航的加载中
      navList:[],//获取的网站导航列表
      ordArr:[],//老导航
      //3.2 表单验证规则
      formRules: {
        webSiteName: [{type:'array',required:true,trigger:'change',message:'关联网站不能为空！',validator:validateWebSiteName}],
        navNames: [{type:'array',required:true,trigger:'change',message:'导航名称不能为空！',validator:validateNavNames}],
      },
      //弹出框中的表单设置 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(type=="search"){
        this.getApiData.page = 1;
      }
      this.$store.dispatch('pool/getWebsiteCategoryList',this.getApiData).then(res=> {
        let data = res.data.rows;
        //给数据得
        for(let item of res.data.rows){
          item.website_nav = "";
        }
        //显示导航名称
        data.forEach(item => {
          if (item.website_category && item.website_category.length > 0) {
            // 如果 website_category 有值，提取 name 并用逗号隔开
            const categoryNames = item.website_category.map(category => category.alias);
            // 将结果存储在一个新的属性上，去掉两端的方括号
            item.website_nav = categoryNames.join(', ');
          } else {
            // 如果没有值，可以设置为空数组或其他处理
            item.website_nav = '';
          }
        });
        //显示导航池名称
        data.forEach(item => {
          if (item.website_category && item.website_category.length > 0) {
            // 如果 website_category 有值，提取 name 并用逗号隔开
            const categoryNames = item.website_category.map(category => category.name);
            // 将结果存储在一个新的属性上，去掉两端的方括号
            item.website_category = categoryNames.join(', ');
          } else {
            // 如果没有值，可以设置为空数组或其他处理
            item.website_category = '';
          }
        });
        console.log(data)
        this.tableData = data;//放入数据
        this.allCount = res.data.count;//放入总条数
      })
    },
    //1.2 删除内容
    deleteRow(id){
      this.$confirm('删除后，该条信息及其绑定关系全部删除，确定吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //website_id
        //category_id
        console.log("当前删除：" + id)
        this.$store.dispatch('pool/delWebsiteCategory',{category_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.5 清理搜索框
    clearSearch(){
      this.getApiData.keyword = "";
      this.getApiData.website_column_id = "";
      this.getApiData.page = 1;
      this.getApiData.pageSize = 10;
      this.getData();
    },
    //列表和分页相关 end ------------------------------------------------------------>

    //2.搜索 start ------------------------------------------------------------>
    //2.1 获得所有网系
    getwebsiteColumn(){
      let that = this;
      this.$store.dispatch('pool/getwebsiteColumn').then(res=> {
        let arrData = this.transformData(res.data)
        this.website_column_arr = arrData;
      })
    },
    //2.2对网系进行格式化
    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;
      });
    },
    //搜索 end ------------------------------------------------------------>

    //3.弹出框设置 start ------------------------------------------------------------>
    //3.1 打开弹出框
    openWindow() {
      this.windowStatus = true;
      this.clearToServe();
      //显示添加按钮
      this.editBtn = false;
    },
    //2.2 关闭弹出框
    closeWindow(){
      this.windowStatus = false;
      this.clearToServe();
    },
    //3.3 清理弹出框
    clearToServe(){
      this.form.webSiteName = "";
      this.form.navNames = [];
      this.webSiteList = [];
      this.navList = [];
      this.ordArr = [];
    },
    //弹出框设置 end ------------------------------------------------------------>

    //4.添加网站导航 start ------------------------------------------------------------>
    //4.1 获得网站列表
    getWebNavList(query){
      if (query !== '') {
        this.webSiteLoading = true;
        let data = {keyword:query}
        let dataArr = [];
        this.$store.dispatch('pool/getNavWebList',data).then(res=> {
          console.log(res.data)
          for(let item of res.data){
            let data = {};
            data.key = item.id;
            data.value = item.id;
            data.label = item.website_name;
            dataArr.push(data)
          }
          this.webSiteList = dataArr;
          this.webSiteLoading = false;
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '网络错误，请重试！'
          });
        })
      } else {
        this.navList = [];
      }
    },
    //4.2 获得导航列表
    getWebsiteList(query){
      if (query !== '') {
        this.navNamesLoading = true;
        let data = {
          pid:0,//默认只有第一级
          name:query,
        }
        let dataArr = [];
        this.$store.dispatch('pool/categoryList',data).then(res=> {
          console.log(res.data)
          for(let item of res.data){
            let data = {};
            data.key = item.category_id;
            data.value = item.category_id;
            data.label = item.name;
            dataArr.push(data)
          }
          this.navList = dataArr;
          this.navNamesLoading = false;
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '网络错误，请重试！'
          });
        })
      } else {
        this.navList = [];
      }
    },
    //4.3添加导航
    addToServe(){
      console.log(this.form.webSiteName) //关联网站id
      console.log(this.form.navNames) //导航名称
      let data = {
        website_id:this.form.webSiteName,//只能关联1个网站
        category_arr_id:this.form.navNames//可以关联多个导航
      }
      //console.log(data)
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$store.dispatch('pool/addWebsiteCategory',data).then(res=> {
            console.log(res.data)
            if(res.code==200){
              this.$message({
                type: 'success',
                message: '添加成功！'
              });
              //关闭并重置窗口
              this.closeWindow();
              //重新请求页面
              this.getData();
            }else{
              this.$message({
                type: 'info',
                message: '添加失败，请重试！'
              });
            }
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '网络错误，请重试！'
            });
          })
        }
      })

    },
    //添加网站导航 end ------------------------------------------------------------>

    //5.编辑网站 start ------------------------------------------------------------>
    //打开弹出窗口
    editRow(id,name){
      //清理并且打开弹窗
      this.openWindow();
      this.getWebsiteCategory(id,name);
      //显示编辑按钮
      this.editBtn = true;
    },
    //编辑导航
    getWebsiteCategory(id,name){
      //把id放到待编辑的id中
      this.editId = id;
      //查询这个站点下面关联的导航有哪些
      let data = {website_id:id}
      this.$store.dispatch('pool/getAdminWebsiteCategory',data).then(res=> {
        //先回显站点信息
        this.form.webSiteName = name;
        //把查询出来的导航回显到编辑窗口中
        let categories = res.data;
        // 将返回的数据处理成 {label:'',value:''} 格式，用于 el-select
        this.navList = categories.map(item => {
          return {
            label: item.name,// 显示的名称
            value: item.category_id// 选项的唯一标识符
          };
        });
        //将选中的导航 ID 列表设置到 form.navNames 中
        this.form.navNames = categories.map(item => item.category_id);
        //把老的导航存起来
        if(res.data.length>0){
          for(let item of res.data){
            this.ordArr.push(item.category_id) //之前拿的是id 现在改为category_id
          }
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '网络错误，请重试！'
        });
      })
    },
    //更新网站导航
    editToServe() {
      this.editLoading = true;
      //把老数组和新数组都提交过去
      console.log(this.ordArr)
      const olddata = this.ordArr.filter(id => !this.form.navNames.includes(id));
      this.ordArr = olddata;
      console.log("老数组为："+ olddata)
      console.log("新数组为："+ this.form.navNames)
      let data = {
        //old_category_arr_id:this.ordArr,
        old_category_arr_id:[],
        new_category_arr_id:this.form.navNames,
        website_id:this.editId
      }
      console.log(data)
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$store.dispatch('pool/upWebsiteCategory',data).then(res=> {
            if(res.code==200){
              this.$message({
                type: 'success',
                message: '导航修改成功！'
              });
            }
            //关闭并重置窗口
            this.closeWindow();
            //重新请求页面
            this.getData();
            this.editLoading = false;
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '网络错误，请重试！'
            });
            this.editLoading = false;
          })
        }
      })
    },
    //编辑网站 end ------------------------------------------------------------>

    //6.管理网站 start ------------------------------------------------------------>
    manageRow(website_id){
      let data = {
        website_id:website_id,//网站id
        page:1,// 页码
        pageSize:10//每页条数
      }
      //console.log(data)
      //跳转到关联页面
      this.$router.push({
        path: '/editNavigation',
        query: data
      });
    },
    //判断是否已经关联了网站
    detectionWebSite(value){
      let data  = {
        website_id:value
      }
      //验证一下是不是存在了关联网站名称
      this.$store.dispatch('pool/getAdminWebsiteCategory',data).then(res=> {
        if(res.data.length>0){
          this.form.webSiteName = "";
          this.$message({
            type: 'warning',
            message: '该网站已经关联了导航，请重新选择！'
          });
        }
      })
    }
    //编辑网站 end ------------------------------------------------------------>
  },
  mounted(){
    //1.获得初始数据
    this.getData();
    //2.获取所有网系
    this.getwebsiteColumn();
  }
}
</script>

<style scoped lang="less">
//表单微调 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; /* 设置标签文字右对齐 */
}
.formDiv .el-select {
  width: 100%;
}
</style>

