<template>
  <!-- 专业管理 -->
  <div id="professionalManagement">
    <search-box :formList="formList" @search="search" @init="init"></search-box>
    <table-list
      class="table_list"
      :tableSets="tableSet"
      :tableData="tableData"
      :navText="navText"
      :rowKey="rowKey"
      @load="loadse"
      @addClick="addClick"
      @emitData="emitData"
      :loading="loading"
      ref="pager"
    >
      <template slot="btn" slot-scope="props">
        <el-button type="text" @click="addChild(props.scope.row)"
          >添加下级</el-button
        >
        <el-button type="text" @click="modify(props.scope.row)">修改</el-button>
        <el-button type="text" @click="del(props.scope.row)">删除</el-button>
      </template>
    </table-list>
    <pagination
      :total="total"
      :pageSize="pageSize"
      :currentPage="currentPage"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    />
    <el-dialog
      :visible.sync="dialogBox"
      width="720px"
      :show-close="false"
      :destroy-on-close="true"
      :before-close="closeBefore"
      :fullscreen="fullscreen"
    >
      <div slot="title" class="hearders">
        <div class="leftTitle">{{ statusPop === 1 ? "添加" : "修改" }}</div>
        <div class="rightBoxs">
          <img
            src="@/assets/images/Max@2x.png"
            alt=""
            @click="fullscreen = !fullscreen"
          />
          <img src="@/assets/images/Close@2x.png" alt="" @click="closeBefore" />
        </div>
      </div>
      <el-row class="contentBox" :span="24">
        <el-col :span="24">
          <header>上级分类：</header>
          <treeselect
            v-if="statusPop === 2"
            v-model="poppleData.categoryId"
            :options="optionsCascader"
            :normalizer="normalizer"
            :show-count="true"
            placeholder="选择上级菜单"
          />
          <treeselect
            v-else
            v-model="poppleData.pid"
            :options="optionsCascader"
            :normalizer="normalizer"
            :show-count="true"
            placeholder="选择上级菜单"
          />
        </el-col>
        <el-col :span="12">
          <header>分类名称：</header>
          <el-input
            placeholder="请输入分类名称"
            v-model="poppleData.categoryName"
          />
        </el-col>
        <el-col :span="12">
          <header>排序：</header>
          <el-input-number
            style="width: 100%"
            v-model="poppleData.sort"
            controls-position="right"
            :min="0"
            placeholder="请输入排序"
          ></el-input-number>
        </el-col>
        <el-col :span="12">
          <header>备注：</header>
          <el-input placeholder="请输入备注" v-model="poppleData.remark" />
        </el-col>
        <el-col :span="12">
          <header>是否启用：</header>
          <el-radio-group v-model="poppleData.status">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeBefore">取 消</el-button>
        <el-button type="primary" @click="submitTable">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

import searchBox from "@/components/searchBox";
import tableList from "@/components/tableList";
import pagination from "@/components/pagination";
export default {
  components: { Treeselect, searchBox, tableList, pagination },
  data() {
    return {
      rowKey: "categoryId", //根据XX分类
      loading: false, //当前表单加载是否加载动画
      navText: {
        title: "专业分类合计",
        index: 0,
        num: false,
        ch: "项",
        choice: false,
        backFatherBtn: {
          status: false,
          title: "未定义",
        },
      },
      formList: [
        {
          label: "分类名称",
          prop: "categoryName",
          placeholder: "输入分类名称",
        },
        {
          label: "启用状态",
          prop: "status",
          scope: "select",
          placeholder: "选择启用状态",
          options: [
            {
              label: "启用",
              value: 1,
            },
            {
              label: "关闭",
              value: 0,
            },
          ],
        },
      ], //搜索栏
      tableSet: [
        {
          label: "分类名称",
          prop: "categoryName",
          hidden: true,
        },
        {
          label: "应用状态",
          prop: "status",
          hidden: true,
          scope: "status",
        },
        {
          label: "排序",
          prop: "sort",
          hidden: true,
        },
        {
          label: "备注",
          prop: "remark",
          hidden: true,
        },
      ], //表头信息
      tableData: [], //表单数据
      total: 0, //一共多少条
      pageSize: 10, //每页多少条数据
      currentPage: 1, //当前页码
      dialogBox: false, //弹窗
      poppleData: {}, //弹窗表单数据
      optionsCascader: [], //弹窗分类数据
      fullscreen: false, //弹窗是否全屏
      statusPop: -1, //当前窗口处于什么状态 1是添加 0是修改
      disableds: false, //是否禁止打开级联
      treeObj: {},
    };
  },
  created() {
    this.search();
  },
  mounted() {},
  methods: {
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.categoryId,
        label: node.categoryName,
        children: node.children,
      };
    },

    getCascader() {
      this.$api.inquireProfessionClassification().then((res) => {
        var setObj = res.rows.filter((item, index) => {
          return item.status !== -1;
        });
        setObj.unshift({
          categoryId: 0,
          categoryName: "主类型",
        });
        this.optionsCascader = this.arrayChangeType(setObj);
      });
    },
    // 表单列添加下级
    addChild(options) {
      this.poppleData = {
        status: 1,
        pid: options.pid,
        categoryId: options.categoryId,
      };
      this.statusPop = 2;
      this.dialogBox = true;
    },
    // 表单列修改
    modify(v) {
      this.poppleData = {
        categoryName: v.categoryName,
        categoryId: v.categoryId,
        pid: v.pid,
        sort: v.sort,
        remark: v.remark,
        status: v.status,
      };
      this.statusPop = 0;
      this.dialogBox = true;
    },
    //窗口关闭
    closeBefore() {
      this.$confirm("此操作将关闭窗口, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.dialogBox = false;
          this.fullscreen = false;
          this.poppleData = {};
        })
        .catch(() => {});
    },
    submitTable() {
      console.log(this.poppleData);
      if (!this.poppleData.categoryName) {
        this.$message.error("请填写分类名称");
        return;
      }
      if (this.poppleData.sort === undefined) {
        this.$message.error("请填写排序");
        return;
      }
      if (this.poppleData.status === undefined) {
        this.$message.error("请选择是否启用");
        return;
      }
      // if (this.poppleData.categoryId === undefined) {
      //   this.$message.error("请选择上级分类");
      //   return;
      // } else {
      //   if (this.poppleData.categoryId.length === 0) {
      //     this.$message.error("请选择上级分类");
      //     return;
      //   } else {
      //     if (typeof this.poppleData.categoryId === "object") {
      //       this.poppleData.categoryId = this.poppleData.categoryId.pop();
      //     }
      //   }
      // }
      if (this.statusPop === 1) {
        this.poppleData.pid = this.poppleData.categoryId;
        delete this.poppleData.categoryId;
        this.$api
          .addProfessionClassification(this.poppleData)
          .then((res) => {
            this.$message.success("添加成功");
            this.tableData = [];
            this.search();
            this.dialogBox = false;
          })
          .catch((err) => {
            this.$message.error(err);
          });
      }
      if (this.statusPop === 0) {
        this.$api
          .modifyProfessionClassification(this.poppleData)
          .then((res) => {
            this.$message.success("修改成功");
            this.tableData = [];
            this.search();
            this.dialogBox = false;
          })
          .catch((err) => {
            this.$message.error(err);
          });
      }
    },
    // 表单列删除
    del(options) {
      var self = this;
      this.$confirm("此操作将删除该专业分类, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var data = {
            categoryId: options.categoryId,
            categoryName: options.categoryName,
            status: -1,
          };
          self.$api
            .modifyProfessionClassification(data)
            .then((res) => {
              self.$message.success("删除成功");
              self.tableData = [];
              self.search();
            })
            .catch((error) => {
              self.$message.error("删除失败,失败原因：" + error);
            });
        })
        .catch(() => {});
    },
    //添加表单列
    addClick() {
      this.poppleData = {
        status: 1,
        pid: 0,
      };
      this.statusPop = 1;
      this.dialogBox = true;
    },
    // 未定义
    emitData(v) {
      console.log(v);
    },
    // 接口数据转换级联类型
    arrayChangeType(options) {
      let result = [];
      if (!Array.isArray(options)) {
        return result;
      }
      options.forEach((item) => {
        delete item.children;
      });
      let map = {};
      options.forEach((item) => {
        map[item.categoryId] = item;
      });
      options.forEach((item) => {
        let parent = map[item.pid];
        if (parent) {
          (parent.children || (parent.children = [])).push(item);
        } else {
          result.push(item);
        }
      });
      return result;
    },
    sortBy(attr, rev) {
      //第二个参数没有传递 默认升序排列
      if (rev == undefined) {
        rev = 1;
      } else {
        rev = rev ? 1 : -1;
      }

      return function (a, b) {
        a = a[attr];
        b = b[attr];
        if (a < b) {
          return rev * -1;
        }
        if (a > b) {
          return rev * 1;
        }
        return 0;
      };
    },
    search(v) {
      this.loading = true;
      var self = this;
      var data = {
        status: "0,1",
        pageSize: this.pageSize,
        pageNum: this.currentPage,
        PId: 0,
      };
      this.$api
        .inquireProfessionClassification(data)
        .then((res) => {
          res.rows.forEach((item, index) => {
            item.hasChildren = true;
          });
          self.tableData = res.rows;
          self.tableData.sort(self.sortBy("sort", true));
          self.navText.index = res.total;
          self.total = res.total;
          self.loading = false;
          self.getCascader();
        })
        .catch((err) => {
          this.loading = false;
        });
    },
    init() {
      this.search();
    },

    //点击多级触发异步
    async loadse(tree, treeNode, resolve) {
      this.treeObj[tree.categoryId] = { tree, treeNode, resolve };
      var data = {
        status: "0,1",
        PId: tree.categoryId,
      };
      const loadChildren = await this.$api.inquireProfessionClassification(
        data
      );
      if (Array.isArray(loadChildren.rows) && loadChildren.rows.length > 0) {
        loadChildren.rows.forEach((item) => {
          item.hasChildren = true;
        });
        loadChildren.rows.sort(this.sortBy("sort", true));
        resolve(loadChildren.rows); // 返回最终数据对象
      } else {
        tree.children = [];
        resolve([]);
      }
    },

    //点击多级触发异步
    // async loadse(tree, treeNode, resolve) {
    //   this.treeObj[tree.categoryId] = { tree, treeNode, resolve };
    //   var datasten = {
    //     PId: tree.categoryId,
    //     status: '0,1'
    //   };
    //   this.$api.inquireProfessionClassification(datasten).then((res) => {

    //     res.rows.forEach((item, index) => {
    //       item.hasChildren = true;
    //     });
    //     res.rows.sort(this.sortBy("sort", true));

    //     if (res.rows.length === 0) {
    //       this.$message.warning("暂无下级");
    //     }
    //     resolve(res.rows);
    //   });
    // },
    handleSizeChange(v) {
      this.pageSize = v;
      this.currentPage = 1;
      this.search();
    },
    handleCurrentChange(v) {
      this.currentPage = v;
      this.search();
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.el-button {
  border-radius: 8px;
}
/deep/.el-dialog {
  border-radius: 8px;
  .el-dialog__header {
    padding: 0;
    .hearders {
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0px 18px 0px 20px;
      border-bottom: 1px solid #e2e2e2;
      .leftTitle {
        font-size: 14px;
        font-weight: bold;
        color: #2f4378;
      }
      .rightBoxs {
        display: flex;
        align-items: center;
        img {
          width: 14px;
          height: 14px;
          margin-left: 13px;
          cursor: pointer;
        }
      }
    }
  }
  .el-dialog__body {
    padding: 0;
    .contentBox {
      padding: 20px 20px 5px;
      .el-col {
        padding: 0px 20px;
        margin-bottom: 30px;
        header {
          margin-bottom: 6px;
          color: #2f4378;
          font-size: 14px;
        }
      }
    }
  }
  .el-dialog__footer {
    padding: 0;
    .dialog-footer {
      padding: 0px 40px;
      height: 70px;
      border-top: 1px solid #e2e2e2;
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }
  }
}
</style>
