<!--  -->
<template>
  <div class="customsManger_box">
    <el-card :style="'height:' + fullHeight + 'px'">
      <!-- 筛选 -->
      <el-row>
        <el-col>
          <!-- 组织搜索 -->
          <div class="search_box">
            <el-input
              size="mini"
              placeholder="请输入组织名称"
              v-model.trim="input"
              @change="searchData"
              clearable
            >
            </el-input>
            <div class="btn_box">
              <el-button type="primary" size="mini" @change="searchData"
                >搜索</el-button
              >
              <el-button type="primary" size="mini" @click="addrUser"
                >添加组织</el-button
              >
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 列表 -->
      <tree-table
        v-loading="loading"
        style="height: 680px; overflow-y: auto;"
        ref="recTree"
        :list.sync="treeDataSource"
        @actionFunc="actionFunc"
        @deleteFunc="deleteFunc"
        @addOrganization="addOrganization"
        @handlerExpand="handlerExpand"
        @orderByFunc="orderByFunc"
      ></tree-table>

      <!-- 分页 -->
      <!-- <el-pagination
        style="position: absolute; bottom: 0; left: 50%"
        :page-size="10"
        @current-change="newPage"
        :current-page="page"
        v-if="treeDataSource.length > 0"
        background
        layout="prev, pager, next, jumper"
        :total="tableSum"
      >
      </el-pagination> -->

      <el-pagination
        :page-size="10"
        @current-change="newPage"
        :current-page="page"
        v-if="treeDataSource.length > 0"
        background
        layout="prev, pager, next, jumper"
        :total="tableSum"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户 -->
    <el-dialog
      :title="tltData"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="addrUserVisible"
      width="25%"
    >
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="上级: ">
          <el-select
            size="mini"
            v-model="form.higher"
            placeholder="请选择活动区域"
            :disabled="true"
          >
            <el-option
              v-for="(item, index) in higherList"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="组织名称: ">
          <el-input
            style="width: 80%"
            size="mini"
            v-model.trim="form.name"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button size="small" type="primary" @click="onSubmit"
            >确定</el-button
          >
          <el-button size="small" @click="addrUserVisible = false"
            >取消</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import treeTable from "@/components/tree-table/tree_table.vue";
import "../../mock/mock";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {
    treeTable
  },
  data() {
    //这里存放数据
    return {
      fullHeight: document.documentElement.clientHeight - 116, //
      input: "", // 组织搜索
      treeDataSource: [],
      loading: false, // 组织 - 加载
      tableSum: 0, // 表格列表总数
      page: 1, // 当前页数

      // 添加隶属海关弹框
      addrUserVisible: false,
      higherList: [
        {
          value: "",
          label: ""
        }
      ],
      form: {
        name: "",
        higher: ""
      },
      tltData: "添加隶属海关",
      userData: {} // 点击编辑时获取到的当前数据
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    // 添加隶属海关弹框
    addrUserVisible(val) {
      if (val == false) {
        this.form.higher = ""; // 清除上级值
        this.form.name = ""; // 清除组织名称值
      }
    },

    fullHeight(val) {
      //监控浏览器高度变化
      if (!this.timer) {
        this.fullHeight = val;
        this.timer = true;
        let that = this;
        setTimeout(function() {
          //防止过度调用监测事件，导致卡顿
          that.timer = false;
        }, 400);
      }
    }
  },
  //方法集合
  methods: {
    //动态获取浏览器高度
    get_boderHeight() {
      const that = this;
      window.onresize = () => {
        return (() => {
          window.fullHeight = document.documentElement.clientHeight;
          that.fullHeight = window.fullHeight;
        })();
      };
    },

    // 树形表格
    orderByFunc(val) {
      console.log("排序");
      console.log(val);
    },
    // 编辑
    actionFunc(m) {
      console.log(m);
      this.userData = m;
      this.tltData = "编辑隶属海关"; //改变弹框标题
      if (m.level == 1) {
        this.$set(this.higherList, 0, {
          value: "",
          label: "根类别"
        });
        this.form.higher = "";
      } else {
        this.$set(this.higherList, 0, {
          value: m.parent_id,
          label: m.parent_name
        });
        this.form.higher = m.parent_name;
      }
      this.form.name = m.org_name;

      // console.log(this.higherList);
      this.addrUserVisible = true; //打开弹框
    },
    // 删除
    deleteFunc(m) {
      // console.log(m);
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$axios({
            method: "POST",
            url: "/api/api_gateway?method=sysmenage.usermanager.org_delete",
            data: this.qs.stringify({
              org_id: m.id
            })
          })
            .then(res => {
              if (res.data.data == true) {
                this.$message({
                  message: "删除成功了",
                  type: "success",
                  duration: 1500
                });
                this.tabListData();
              } else {
                this.$message({
                  message: "删除失败",
                  type: "error",
                  duration: 1500
                });
              }
              // console.log(res);
            })
            .catch(err => {
              // console.log(err);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });

      // this.$axios({
      //   method: 'POST',
      //   url: '/api/api_gateway?method=sysmenage.usermanager.org_add',
      //   data: this.qs.stringify({
      //     org_id: m.id
      //   })
      // }).then((res) => {
      //   console.log(res)
      // }).catch((err) => {
      //   console.log(err)
      // })
    },
    // 添加下级组织
    addOrganization(m) {
      console.log(m);
      this.tltData = "添加隶属海关"; //改变弹框标题
      this.$set(this.higherList, 0, {
        value: m.id,
        label: m.org_name
      });
      this.form.higher = m.org_name;
      this.addrUserVisible = true; //打开弹框
    },

    handlerExpand(m) {
      // console.log("展开/收缩");
      // console.log(m);
      m.isExpand = !m.isExpand;
    },

    // 请求下页数据
    newPage(page) {
      this.page = page;
      this.tabListData();
    },

    // 添加用户 -- 一级
    addrUser() {
      this.higherList = [
        {
          label: "根类别",
          value: ""
        }
      ];
      this.addrUserVisible = true;
    },

    // 添加用户 || 编辑用户 -- 确定
    onSubmit() {
      var that = this;
      if (this.form.name == "") {
        this.$message({
          message: "请填写组织名称!",
          type: "warning",
          duration: 1500
        });
      } else if (this.form.name.split(" ").join("").length == 0) {
        this.$message({
          message: "不能填写空格！",
          type: "warning",
          duration: 1500
        });
      } else {
        // 请求添加接口
        if (this.tltData == "编辑隶属海关") {
          // 编辑
          var url = "/api/api_gateway?method=sysmenage.usermanager.org_modify";
          var postData = this.qs.stringify({
            org_name: this.form.name, //组织名称
            org_id: this.userData.id // 组织id
          });
        } else if (this.tltData == "添加隶属海关") {
          // 添加
          var url = "/api/api_gateway?method=sysmenage.usermanager.org_add";
          var postData = this.qs.stringify({
            org_name: that.form.name, //组织名称
            parent_org_id: that.higherList[0].value // 上级组织id，没有上级组织表示创建的组织是顶级组织
          });
        }

        this.$axios({
          method: "POST",
          url,
          data: postData
        })
          .then(res => {
            console.log(res);
            if (res.data.data == true) {
              this.$message({
                message: "成功!",
                type: "success",
                duration: 1500
              });
              this.addrUserVisible = false;
              this.tabListData();
            }
            //  else {
            //   this.$message({
            //     message: "失败!",
            //     type: "error",
            //     duration: 1500
            //   });
            // }
          })
          .catch(err => {});
      }
    },

    // 请求表格列表
    tabListData() {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=sysmenage.usermanager.org_list",
        data: this.qs.stringify({
          page: this.page,
          page_item: "9",
          org_name: this.input
        })
      })
        .then(res => {
          if (res.data.data.total_item !== 0) {
            this.treeDataSource = res.data.data.page_list;
            this.tableSum = res.data.data.total_item;
          } else {
            this.treeDataSource = [];
            this.tableSum = 0;
          }
          this.loading = false;
        })
        .catch(err => {
          this.loading = false;
        });
    },

    // 搜索
    searchData() {
      this.tabListData();
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.loading = true;
    this.tabListData(); // 请求表格列表
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {} //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang="less" scoped>
.customsManger_box {
  /deep/.el-card {
    overflow: hidden;
    overflow-y: auto;
  }

  // 表单
  /deep/.el-form {
    .el-form-item {
      .el-form-item__content {
        // 上级
        .el-select {
          width: 80%;
        }
      }
    }
  }
}

// 组织搜索
.search_box {
  display: flex;
  /deep/.el-input {
    // width: 300px;
    width: 15%;
  }
  .btn_box {
    margin: 0 0 0 15px;
  }
}
</style>
