<template>
  <div class="mainBox">
    <!--搜索功能 start------------------------------------------------------------>
    <div class="layerBoxNoBg">
      <div>
        <el-button type="primary" @click="openWindow()">添加职能部门</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="编号"></el-table-column>
            <el-table-column prop="name" 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="deleteRow(scope.row.id)"><i class="el-icon-edit-outline"></i>删除</div>
                  <div class="listEditBtn" @click="editRow(scope.row.id)"><i class="el-icon-edit-outline"></i>编辑</div>
                </div>
              </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" autocomplete="off" label-position="left">
        <div class="formDiv">
          <el-form-item label="选择上级部门" :label-width="formLabelWidth" prop="pid" class="custom-align-right">
            <el-cascader :key="searchDepartmentKey" v-model="form.pid" placeholder="请选择上级部门" :props="searchDepartmentData" filterable clearable></el-cascader>
          </el-form-item>
        </div>
        <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-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <div>
          <el-button @click="closeWindow">取 消</el-button>
          <el-button type="primary" @click="addData" v-if="editId==0">提交</el-button>
          <el-button type="primary" @click="editData" 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 validateEmpty = (rule,value,callback) => {
      if (!value || value.trim() === "") {
        callback(new Error('该项不能为空！'));
      } else {
        callback();
      }
    }
    const validateArray = (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:{
        search:"",//职能部门名称
        page:1,//当前是第几页
        pageSize:10,//一共多少条
      },
      //行政职能部门
      searchDepartmentKey:0, 
      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('public/getAllDepartment',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 ------------------------------------------------------------>

      //2.弹出框设置 start ------------------------------------------------------------>
      //是否显示弹出窗口
      windowStatus:false,
      formLabelWidth: '120px',
      //弹出框设置 end ------------------------------------------------------------>

      //3.搜索相关 start ------------------------------------------------------------>
      //搜索相关 end ------------------------------------------------------------>

      //3.弹出框中的表单设置 start ------------------------------------------------------------>
      //3.1 表单收集的数据
      form: {
        pid:"",
        name:""
      },
     
      //3.2表单验证规则
      formRules: {
        //角色名称不能为空
        pid:[{required:true,trigger:'blur',validator:validateArray}],
        //职能描述不能为空
        name:[{required:true,trigger:'blur',validator:validateEmpty}],
      },
      //弹出框中的表单设置 end ------------------------------------------------------------>
    }
  },
  methods: {
    //1.列表和分页相关 start ------------------------------------------------------------>
    //1.1 获取内容
    getData(){
      this.$store.dispatch('public/getDepartmentList',this.getApiData).then(res=> {
        console.log(res)
        this.tableData = res.data.rows;
        this.allCount = res.data.count;
      }).catch(() => {
        this.$message({
          type: 'warning',
          message: '网络错误，请重试！'
        });
      })
    },
    //1.2 列表内容分页
    //直接跳转
    handleSizeChange(val) {
      this.getApiData.page = val;
      this.getData();
    },
    //1.3 点击分页
    handleCurrentChange(val) {
      this.getApiData.page = val;
      this.getData();
    },
    //1.4 删除职能部门
    deleteRow(id){
      this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log("当前删除：" + id)
        this.$store.dispatch('public/delDepartment',{id:id}).then(res=> {
          this.getData();
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'warning',
            message: '网络错误，请重试！'
          });
        })
      }).catch(() => {
        this.$message({
          type: 'warning',
          message: '已取消删除'
        });
      });
    },
    //列表和分页相关 end ------------------------------------------------------------>

    //2.弹出框设置 start ------------------------------------------------------------>
    //2.1 打开弹出框
    openWindow() {
      this.clearToServe();
      this.windowStatus = true;
      //this.$refs.form.clearValidate();
    },
    //2.2 关闭弹出框
    closeWindow(){
      this.windowStatus = false;
      this.clearToServe();
      this.$refs.form.clearValidate();
    },
    //2.3 清空提交窗口
    clearToServe(){
      this.editId = 0;
      this.form.pid = [];
      this.form.name = "";
    },
    //弹出框设置 end ------------------------------------------------------------>

    //4.添加 start ------------------------------------------------------------>
    addData(){
      if(this.form.pid.length!=0){
        const lastPicValue = this.form.pid[this.form.pid.length - 1];
        this.form.pid = String(lastPicValue);
      }
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$store.dispatch('public/addDepartment',this.form).then(res=> {
            if(res.code == 200){
              this.$message({
                type: 'success',
                message: '已成功添加职能部门！'
              });
              console.log(res)
              this.closeWindow();
              this.getData();
            }else{
              this.$message({
                type: 'warning',
                message: res.message
              });
              console.log(res)
              this.closeWindow();
              this.getData();
            }
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '网络错误，请重试！'
            });
          })
        }
      })
    },
    //添加 end ------------------------------------------------------------>

    //4.编辑 start ------------------------------------------------------------>
    //回显数据
    editRow(id){
      this.openWindow();
      //设置要编辑的id
      this.editId = id;
      this.$store.dispatch('public/getDepartmentMain',{id:id}).then(res=> {
        console.log(res)
        this.form.name = res.data.name;
        this.form.pid = res.data.pid;
        //回显父级导航

        // 这里的接口有问题，应该返回数组，但是返回的只有上一级的pid
        // 我这里没有办法判断他的层级关系
        // 检查 res.data.pid 的类型

        if (typeof res.data.pid === 'number') {
          // 如果是数字，将其转换为数组
          this.form.pid = [res.data.pid];
        } else {
          // 如果已经是数组，直接赋值
          this.form.pid = JSON.parse(res.data.pid); // 如果是字符串，解析为数组
        }
        this.searchDepartmentKey += 1;
        this.loadCascaderPath(this.form.pid);

        console.log(this.form.pid)
        console.log(this.searchDepartmentKey)

      }).catch(() => {
        this.$message({
          type: 'warning',
          message: '网络错误，请重试！'
        });
      })
    },
    //回显职能部门
    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('public/getDepartmentMain', { 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) {
              this.form.pid = path;
            }
          });
      }
    },
    //提交编辑
    editData(){
      this.form.id = this.editId;
      if(this.form.pid.length!=0){
        const lastPicValue = this.form.pid[this.form.pid.length - 1];
        this.form.pid = String(lastPicValue);
      } 
      //获取选中的节点
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$store.dispatch('public/upDepartment',this.form).then(res=> {
            console.log(res)
            this.closeWindow();
            this.$message({
              type: 'success',
              message: '修改成功！'
            });
            this.getData();
          }).catch(() => {
            this.$message({
              type: 'warning',
              message: '网络错误，请重试！'
            });
          })
        }
      })
    }
    //编辑 end ------------------------------------------------------------>

  },
  mounted(){
    //获取页面列表
    this.getData();
    //获取菜单树
    //this.getAllMenuList();
  } 
}
</script>

<style scoped lang="less">
.layerBoxNoBg {
  padding: 30px 0 0 0;
}
//表单微调 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-select-group__title {
  color: #909399;
}
::v-deep .el-select {
  width: 100% !important;
}
</style>
