<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.name"/>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="searchBox">
            <div class="searchTitle">行政职能部门：</div>
            <el-cascader :key="searchDepartmentKey" v-model="getApiData.department_id" placeholder="选择导航池所属行政区划" :props="searchDepartmentData" filterable clearable></el-cascader>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="searchBox">
            <div class="searchTitle">行政区划：</div>
            <el-cascader :key="searchCascaderKey" v-model="getApiData.city_id" placeholder="选择导航池所属行政区划" :props="searchCityData" filterable clearable></el-cascader>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="layerBoxNoBg">
      <div>
        <el-button type="primary" @click="addCategoryList">添加导航池</el-button>
      </div>
      <div>
        <el-button @click="clearSearchList">重置</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="name" label="导航池名称"></el-table-column>
            <el-table-column prop="department_name" label="行政职能部门"></el-table-column>
            <el-table-column prop="city_name" label="行政区划"></el-table-column>
            <el-table-column prop="sort" 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="200"  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>
                <!-- <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>
    <!--分页 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" @close="clearToServe(2)">
      <el-form :model="form" ref="form" :rules="formRules" autocomplete="off" label-position="left">
        <div class="formDiv">
          <el-form-item label="导航池名称：" :label-width="formLabelWidth" prop="name" class="custom-align-right">
            <el-input v-model="form.name" autocomplete="off" placeholder="请输入导航池名称"></el-input>
            <el-checkbox v-model="show_url" @change="ifUrl">引用外链</el-checkbox>
          </el-form-item>
          <div v-if="show_url==1">
            <el-form-item label="外链地址：" :label-width="formLabelWidth" prop="web_url" class="custom-align-right">
              <el-input v-model="form.web_url" autocomplete="off" placeholder="请输入外链地址"></el-input>
            </el-form-item>
            <el-form-item label="导航标题：" :label-width="formLabelWidth" prop="seo_title" class="custom-align-right">
              <el-input v-model="form.seo_title" autocomplete="off" placeholder="请输入导航标题"></el-input>
            </el-form-item>
            <el-form-item label="导航关键词：" :label-width="formLabelWidth" prop="seo_keywords" class="custom-align-right">
              <el-input v-model="form.seo_keywords" autocomplete="off" placeholder="请输入导航关键词"></el-input>
            </el-form-item>
            <el-form-item label="导航描述：" :label-width="formLabelWidth" prop="seo_description" class="custom-align-right">
              <el-input type="textarea" v-model="form.seo_description" placeholder="请输入导航描述"></el-input>
            </el-form-item>
            <el-form-item label="排序：" :label-width="formLabelWidth" class="custom-align-right">
              <el-input v-model="form.sort" autocomplete="off" placeholder="请输入排序"></el-input>
            </el-form-item>
          </div>
          <div v-if="show_url==0">
            <el-form-item label="关联职能部门：" :label-width="formLabelWidth" prop="department_arr_id" class="custom-align-right">
              <!-- <el-cascader :key="departmentKey" v-model="form.department_arr_id" placeholder="选择要绑定的职能部门" :props="departmentData" filterable clearable></el-cascader> -->
              <el-cascader :key="departmentKey" :props="{value:'id',label:'name',children:'children'}" :options="allDepartment" v-model="form.department_arr_id" :show-all-levels="false" filterable />
            </el-form-item>
            <el-form-item label="关联行政区划：" :label-width="formLabelWidth" prop="city_arr_id" class="custom-align-right">
              <el-cascader :key="cascaderKey" v-model="form.city_arr_id" placeholder="选择要绑定行政区划" :props="cityData" filterable clearable></el-cascader>
            </el-form-item>
            <el-form-item label="父级导航：" :label-width="formLabelWidth" class="custom-align-right">
              <el-cascader :key="parentKey" v-model="form.pid_arr" placeholder="请选择要绑定的父级导航" :props="parentData" filterable clearable></el-cascader>
            </el-form-item>
            <el-form-item label="导航标题：" :label-width="formLabelWidth" prop="seo_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.seo_title" autocomplete="off" placeholder="请输入导航标题"></el-input>
            </el-form-item>
            <el-form-item label="导航关键词：" :label-width="formLabelWidth" prop="seo_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.seo_keywords" autocomplete="off" placeholder="请输入导航关键词"></el-input>
            </el-form-item>
            <el-form-item label="导航描述：" :label-width="formLabelWidth" prop="seo_description" class="custom-align-right">
              <template #label>
                <span class="askBox">
                  导航池描述：
                  <el-tooltip class="item" effect="dark" content="导航池描述，如：中国三农市场网，农资产品商城属市场类频道，共有5个栏目。" placement="top">
                    <i class="el-icon-question"></i>
                  </el-tooltip>
                </span>
              </template>
              <el-input type="textarea" v-model="form.seo_description" class="custom-textarea" placeholder="请输入导航描述"></el-input>
            </el-form-item>
            <el-form-item label="排序：" :label-width="formLabelWidth" class="custom-align-right">
              <el-input v-model="form.sort" autocomplete="off" placeholder="请输入排序"></el-input>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeWindow">取 消</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>
    </el-dialog>
    <!--弹出框 end------------------------------------------------------------>

  </div>
</template>

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

export default {
  components: {
    tableTitle,//表格标题
  },
  data() {
    //0.全局操作 start ------------------------------------------------------------>
    //表单验证
    const validateEmpty = (rule,value,callback) => {
      if (value.length == 0) {
        callback(new Error('该项不能为空！'))
      } else {
        callback()
      }
    }
    const validateDepartment = (rule,value,callback) => {
      if (value.length === 0) {
          callback(new Error('请选择职能部门！'))
      } else {
          callback()
      }
    }
    const validateCity = (rule,value,callback) => {
      if (value.length === 0) {
          callback(new Error('请选择行政区划！'))
      } else {
          callback()
      }
    }
    const validatePid = (rule,value,callback) => {
      if (value.length === 0) {
          callback(new Error('请选择父级导航！'))
      } else {
          callback()
      }
    }
    let self = this;
    //0.全局操作 end ------------------------------------------------------------>
    return {
      //1.列表和分页相关 start ------------------------------------------------------------>
      tableDivTitle:"导航池列表",
      tableData:[],//内容
      allCount:0,//总条数
      editId:0,//要修改的网站id
      getApiData:{
        name:"",//导航池名称查询
        department_id:[],//行政职能部门id
        city_id:[],//行政区划
        page:1,//当前是第几页
        pageSize:10,//一共多少条
      },
      allDepartment:[],//所有职能
      //列表和分页相关 end ------------------------------------------------------------>

      //2.搜索相关 start ------------------------------------------------------------>
      //行政职能部门
      searchDepartmentKey:0, //列表缓存key
      searchDepartmentData: {
        checkStrictly: true,
        lazy: true,
        async lazyLoad (node, resolve) {
          const { level, data } = node;
          if (data && data.children && data.children.length !== 0) {
            return resolve(node)
          }
          console.log(level)
          let parentId = level == 0 ? 0 : data.value
          let parames = {
            'pid':parentId
          }
          self.$store.dispatch('pool/getDepartment',parames).then(res=> {
            if (res.data) {
              const nodes = res.data.map(item => ({
                value: item.id,
                label: item.name,
                leaf: level >= 3,
                children: []
              }))
              resolve(nodes)
            }
          })
        }
      },
      //获取城市列表
      searchCascaderKey:0, //列表缓存key
      searchCityData: {
        checkStrictly: true,
        lazy: true,
        async lazyLoad (node, resolve) {
          const { level, data } = node;
          if (data && data.children && data.children.length !== 0) {
            return resolve(node)
          }
          console.log(level)
          let parentId = level == 0 ? 0 : data.value
          let parames = {
            'pid':parentId
          }
          self.$store.dispatch('pool/getcityList',parames).then(res=> {
            if (res.data) {
              const nodes = res.data.map(item => ({
                value: item.id,
                label: item.name,
                leaf: level >= 3,
                children: []
              }))
              resolve(nodes)
            }
          })
        }
      },
      //搜索相关 end ------------------------------------------------------------>

      //3.弹出框设置 start ------------------------------------------------------------>
      windowStatus:false, //显示弹出框
      formLabelWidth: '140px',
      show_url:false, //是否显示外链输入框
      editBtn:false,//当显示编辑按钮的时候，就不显示提交
      //弹出框设置 end ------------------------------------------------------------>

      //4.弹出框中的表单设置 start ------------------------------------------------------------>
      //4.1表单收集的数据
      form: {
        name: '',//导航池名称
        is_url:0,//是否为外链，0=否 1=是
        web_url:"",//外链地址
        department_arr_id:[],//职能部门
        city_arr_id:[],//行政区划
        sort:0,//排序
        //pid:2,
        seo_title:"",//标题
        seo_keywords:"",//关键词
        seo_description:"",//描述
        pid_arr:[]//父级导航
      },
      //4.2表单验证规则
      formRules: {
        //网站名称不能为空
        name:[{required:true,trigger:'blur',validator:validateEmpty}],//导航池名称不能为空
        web_url:[{required:true,trigger:'blur',validator:validateEmpty}],//外链地址不能为空
        department_arr_id: [{type:'array',required:true,trigger:'change',message:'请选择职能部门！',validator:validateDepartment}],
        city_arr_id: [{type:'array',required:true,trigger:'change',message:'请选择行政区划！',validator:validateCity}],
        //pid_arr: [{type:'array',required:true,trigger:'change',message:'请选择父级导航！',validator:validatePid}],
        seo_title:[{required:true,trigger:'blur',validator:validateEmpty}],//标题不能为空
        seo_keywords:[{required:true,trigger:'blur',validator:validateEmpty}],//关键词不能为空
        seo_description:[{required:true,trigger:'blur',validator:validateEmpty}],//描述不能为空
      },
      //获取城市列表
      cascaderKey:0,//弹窗用的key
      cityData: {
        checkStrictly: true,
        lazy: true,
        async lazyLoad (node, resolve) {
          const { level, data } = node;
          if (data && data.children && data.children.length !== 0) {
            return resolve(node)
          }
          console.log(level)
          let parentId = level == 0 ? 0 : data.value
          let parames = {
            'pid':parentId
          }
          self.$store.dispatch('pool/getcityList',parames).then(res=> {
            if (res.data) {
              const nodes = res.data.map(item => ({
                value: item.id,
                label: item.name,
                leaf: level >= 3,
                children: []
              }))
              resolve(nodes)
            }
          })
        }
      },
      //获取职能部门
      departmentKey:0,//弹窗用的key
      departmentData: {
        checkStrictly: true,//父级不可选
        lazy: true,
        async lazyLoad (node, resolve) {
          const { level, data } = node;
          if (data && data.children && data.children.length !== 0) {
            return resolve(node)
          }
          console.log(level)
          let parentId = level == 0 ? 0 : data.value
          let parames = {
            'pid':parentId
          }
          self.$store.dispatch('pool/getDepartment',parames).then(res=> {
            if (res.data) {
              const nodes = res.data.map(item => ({
                value: item.id,
                label: item.name,
                leaf: level >= 3,
                children: []
              }))
              resolve(nodes)
            }
          })
        }
      },
      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)
          }
          console.log(level)
          let parentId = level == 0 ? 0 : data.value
          let parames = {
            'pid':parentId
          }
          self.$store.dispatch('pool/categoryList',parames).then(res=> {
            if (res.data) {
              const nodes = res.data.map(item => ({
                value: item.id,
                label: item.name,
                leaf: level >= 3,
                children: []
              }))
              resolve(nodes)
            }
          })
        }
      },
      //弹出框中的表单设置 end ------------------------------------------------------------>
    }
  },
  methods: {
    //1.列表和分页相关 start ------------------------------------------------------------>
    //1.1 开始请求列表信息方法
    getData(type){
      //搜索条件
      if(this.getApiData.department_id.length>0){
        //网系只提交最后一个
        this.getApiData.department_id = this.getApiData.department_id[this.getApiData.department_id.length - 1];
      }
      if(this.getApiData.city_id.length>0){
        //城市id只提交最后一个
        this.getApiData.city_id = this.getApiData.city_id[this.getApiData.city_id.length - 1];
      }
      //如果是搜索，重新加载第一页
      if(type=="search"){
        this.getApiData.page = 1;
      }
      this.$store.dispatch('pool/getCategoryList',this.getApiData).then(res=> {
        this.tableData = res.data.rows; //��与内容
        this.allCount = res.data.count; //给与总条数
      }).catch(() => {
        this.$message({
          type: 'warning',
          message: '网络错误，请重试！'
        });
      })
    },
    //1.2 删除内容
    deleteData(id){
      this.$confirm('删除后，该条信息及其绑定关系全部删除，确定吗', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log("当前删除：" + id)
        this.$store.dispatch('pool/delCategory',{id:id}).then(res=> {
          if(res.code==200){
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          }else if(res.code==0){
            this.$message({
              type: 'warning',
              message: res.message
            });
          }
          this.getData();
        }).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 重置按钮
    clearSearchList(){
      this.tableData = [];
      this.getApiData.name = "";
      this.getApiData.department_id = [];
      this.getApiData.city_id = [];
      this.getApiData.page = 1;
      this.getApiData.pageSize = 10;
      this.getData();
    },
    //1.6 获取所有职能
    getAllDepartment(){
      this.$store.dispatch('cms/getAllDepartment').then(res=> {
        console.log(res)
        this.allDepartment = res.data;
      })
    },
    //列表和分页相关 end ------------------------------------------------------------>

    //2.弹出框设置 start ------------------------------------------------------------>
    //2.1 打开弹出框
    openWindow() {
      //this.clearToServe();
      this.windowStatus = true;
    },
    //2.1.1 添加导航池
    addCategoryList(){
      this.editId = 0;
      this.editBtn = false;
      this.openWindow();
    },
    //2.2 关闭弹出框
    closeWindow(){
      this.windowStatus = false;
      this.clearToServe(2);
    },
    //2.3 清理弹出框
    clearToServe(type){
      if(type==1){ //type1 使用了外部链接
        this.form.department_arr_id = [];
        this.form.city_arr_id = [];
        this.form.pid_arr = [];
      }
      if(type==2){ //type2 全部清理
        this.form.name = "";
        this.form.is_url = 0;
        this.form.web_url = "";
        this.form.department_arr_id = [];
        this.form.city_arr_id = [];
        this.form.sort = 0;
        this.form.seo_title = "";
        this.form.seo_keywords = "";
        this.form.seo_description = "";
        this.form.pid_arr = [];
        //存在验证的时候再清理
        if (this.$refs.form && this.$refs.form.fields.some(field => field.validateState === 'error')) {
          this.$refs.form.clearValidate();
        }
      }
    },
    //弹出框设置 end ------------------------------------------------------------>

    //3.添加导航池 start ------------------------------------------------------------>
    ifUrl(value){
      //console.log(value)
      if(value == true){
        this.form.is_url = 1
      }else{
        this.form.is_url = 0
      }
      this.$refs.form.clearValidate();
    },
    addToServe(){
      //先判断是否使用了外链
      if(this.show_url == true){
        this.clearToServe(1)
      }
      //判断有没有添加父级导航
      if(this.form.pid_arr.length==0){
        this.form.pid_arr = [0];
      }
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$store.dispatch('pool/addCategory',this.form).then(res=> {
            //汇报结果
            this.$message({
              type: 'success',
              message: '已成功添加导航池！'
            });
            //清空并退出
            this.closeWindow();
            this.getData();
          }).catch(() => {
            this.$message({
              type: 'warning',
              message: '网络错误，请重试！'
            });
          })
        }
      })

    },
    //添加导航池 end ------------------------------------------------------------>

    //编辑导航池 start ------------------------------------------------------------>
    getDataMain(id){
      //先清空窗口
      this.clearToServe(2)
      //打开输入窗口
      this.openWindow();
      //添加修改id
      this.editId = id;

      //获取网站详情
      this.$store.dispatch('pool/getCategoryInfo',{id:id}).then(res=> {
        //清除错误状态
        //this.$refs.form.clearValidate();
        console.log(res)
        //回显导航池名称
        this.form.name = res.data.name;

        //回显示是否使用外链
        if(res.data.is_url==1){
          this.show_url = true;
        }else if(res.data.is_url==0||res.data.is_url==null){
          this.show_url = false;
        }
       
        console.log(res.data.is_url)

        //回显外链
        this.form.web_url = res.data.web_url;

        //回显行政区划
        this.form.city_arr_id = JSON.parse(res.data.city_arr_id);
        //当cascaderKey的值改变的时候 级联选择器会重置里面的内容
        this.cascaderKey += 1;
        this.loadCascaderPath(this.form.city_arr_id,"xzqh");

        //回显父级导航
        this.form.pid_arr = JSON.parse(res.data.pid_arr);
        this.parentKey += 1;
        this.loadCascaderPath(this.form.pid_arr,"fjdh");

        //回显职能部门
        this.form.department_arr_id = JSON.parse(res.data.department_arr_id);
        this.departmentKey += 1;
        // this.loadCascaderPath(this.form.department_arr_id,"znbm");

        //回显导航池标题，描述，关键词
        this.form.seo_title = res.data.seo_title;
        this.form.seo_keywords = res.data.seo_keywords;
        this.form.seo_description = res.data.seo_description;

        //回显排序
        this.form.sort = res.data.sort;

      })
      this.editBtn = true;//显示编辑按钮
    },
    //回显行政区划
    async loadCascaderPath(path,type) {
      for (let i = 0; i < path.length; i++) {
        const parentId = path[i - 1] || 0; // 获取当前层级的父级ID
        const level = i; // 当前层级的索引
        await this.$store.dispatch('pool/getcityList', { pid: parentId })
          .then((res) => {
            const nodes = res.data.map(item => ({
              value: item.id,
              label: item.name,
              leaf: level >= 3, // 这里假设4层结构，设置叶子节点标记
            }));
            // 将数据传递到 resolve，通知 cascader 这一层的数据加载完毕
            if (level === path.length - 1) {
              if(type=="xzqh"){this.form.city_arr_id = path;}
              if(type=="fjdh"){this.form.pid_arr = path;}
              if(type=="znbm"){this.form.department_arr_id = path;}
            }
          });
      }
    },
    //修改表单
    editToServe(){
      //防止提交[1,1]这种重复的数据
      if (this.form.department_arr_id.length > 1) {
        const lastIndex = this.form.department_arr_id.length - 1;
        if (this.form.department_arr_id[lastIndex] === this.form.department_arr_id[lastIndex - 1]) {
          this.form.department_arr_id.pop(); // Remove the last element if it's the same as the previous one
        }
      }
      this.form.id = this.editId;
      this.$refs.form.validate(valid => {
        if (valid) {
          //提交表单
          this.$store.dispatch('pool/updateCategory',this.form).then(res=> {
            //汇报结果
            this.$message({
              type: 'success',
              message: '已成功修改导航池信息！'
            });
            //清空并退出
            this.closeWindow();
            this.getData();
          }).catch(() => {
            this.$message({
              type: 'warning',
              message: '网络错误，请重试！'
            });
          })
        }
      })

    }
    //编辑导航池 end ------------------------------------------------------------>
  },
  mounted(){
    //1.获得初始数据
    this.getData();
    //2.获取所有网系
    //this.getwebsiteColumn();
    //本地转换id为文字
    //console.log(getLocationNameById("110000"))
    this.getAllDepartment();
  }
}
</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; /* 设置标签文字右对齐 */
  }
  //表单微调 end------------------------------------------------------------>*/
</style>

