<template>
  <div class="role-manage">
    <div class="role-manage-aside">
      <div class="role-head">
        <a-input
          placeholder="角色名"
          style="width: 300px"
          v-model="name"
          allowClear
        ></a-input>
        <a-button type="primary" @click="search">查询</a-button>
        <a-button type="primary" @click="addRole">新增</a-button>
      </div>
      <div style="margin-top: 10px">
        <standard-table
          bordered
          :columns="columns"
          :dataSource="tableList"
          :pagination="pagination"
          @change="onChange"
          :loading="loading"
          @onClickRow="onClickRow"
          :selectedRows="checkTable"
          @selectedRowChange="selectedRowChange"
        >
          <div slot="operation" slot-scope="text">
            <a-button @click.stop="edit(text)" style="margin-right: 10px"
              >编辑</a-button
            >
            <a-button type="danger" @click.stop="del(text)">删除</a-button>
          </div>
        </standard-table>
      </div>
    </div>
    <div class="role-manage-article">
      <div>
        <a-tree
          v-model="checkedKeys"
          checkable
          :auto-expand-parent="autoExpandParent"
          :selected-keys="selectedKeys"
          :tree-data="treeData"
          @select="onSelect"
          :replaceFields="replaceFields"
          :disabled="treeDisabled"
          ref="menuTree"
          :expandedKeys="expandedKeys"
          @expand="expand"
        />
      </div>
      <div class="role-head">
        <a-checkbox
          v-if="checkTable.length < 1"
          @change="handleCheckAll"
          v-model="checkAll"
          :disabled="!tableItem.id"
        >
          全选
        </a-checkbox>
        <a-checkbox
          v-if="checkTable.length > 1"
          @change="handleCheckAll"
          v-model="checkAll"
          :disabled="checkTable.length < 1"
        >
          全选
        </a-checkbox>
        <a-button @click="reset" :disabled="!tableItem.id">重置</a-button>
        <a-button type="primary" @click="submit" :disabled="!tableItem.id"
          >提交</a-button
        >
        <a-button
          type="primary"
          :disabled="checkTable.length < 1"
          @click="batchOperation"
          >批量操作</a-button
        >
      </div>
    </div>
    <a-modal
      v-model="visible"
      :title="title"
      @ok="handleOk"
      layout="inline"
      width="50%"
      :confirm-loading="confirmLoading"
    >
      <a-form :layout="formLayout" :wrapper-col="{ span: 12 }" :form="form">
        <a-form-item label="角色名称" v-bind="formItemLayout">
          <a-input
            placeholder="请输入角色名称"
            v-decorator="[
              'name',
              { rules: [{ required: true, message: '请输入角色名称' }] },
            ]"
          />
        </a-form-item>
        <a-form-item label="备注" v-bind="formItemLayout">
          <a-input placeholder="请输入备注" v-model="dataForm.remark" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import StandardTable from "@/components/table/StandardTable";

const columns = [
  {
    title: "ID",
    dataIndex: "id",
    width: "100px",
  },
  {
    title: "角色名",
    dataIndex: "name",
  },
  {
    title: "备注",
    dataIndex: "remark",
    // sorter: true,
    needTotal: true,
  },
  {
    title: "创建人",
    dataIndex: "createBy",
    needTotal: true,
    slots: { title: "statusTitle" },
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
  },
  {
    title: "操作",
    dataIndex: "operation",
    // width: "120px",
    scopedSlots: { customRender: "operation" },
  },
];
export default {
  components: {
    StandardTable,
  },
  data() {
    return {
      formLayout: "horizontal",
      dataForm: {
        name: "",
        remark: "",
      },
      name: "",
      formItemLayout: {
        labelCol: {
          xs: { span: 5 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
      },
      form: this.$form.createForm(this, { name: "dynamic_rule" }),
      visible: false,
      confirmLoading: false,
      title: "",
      columns,
      tableList: [],
      pagination: {
        current: 1,
        defaultPageSize: 10,
        total: 0,
        pagesize0ptions: ["10", "20", "30", "50", "100"],
        hideOnSinglePage: false,
        showQuickJumper: true, //
        showSizeChanger: true, //是否可以改变pagesize
      },
      loading: false,
      treeData: [],
      checkedKeys: [],
      autoExpandParent: true,
      selectedKeys: [],
      replaceFields: {
        children: "children",
        title: "name",
        key: "id",
      },
      treeDisabled: true,
      tableItem: {},
      checkAll: false,
      resetForm: {},
      expandedKeys: [],
      checkTable: [],
    };
  },
  created() {
    this.getList();
    this.getMenuList();
    this.resetForm = { ...this.dataForm };
  },
  mounted() {},
  methods: {
    //批量功能操作
    batchOperation() {
      // this.treeDisabled = false;
      this.$API.sysManage
        .saveBatchRoleMenus({
          roleIdIds: this.checkTable,
          menuIds: this.checkedKeys,
          sysType: 2,
        })
        .then((res) => {
          if (res.data.code === 200) {
            this.$message.success(res.data.msg);
            this.expandedKeys = [];
            this.checkTable = [];
            // this.$refs.menuTree.setCheckedNodes(allMenus);
          } else {
            this.$message.error(res.data.msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //表格选择
    selectedRowChange(val) {
      this.checkTable = val.map((v) => {
        return v.id;
      });
      if (val.length > 0) {
        this.treeDisabled = false;
      } else {
        this.treeDisabled = true;
      }
    },
    edit(item) {
      this.dataForm = { ...item.record };

      this.$nextTick(() => {
        this.form.setFieldsValue({
          name: item.record.name,
        });
      });
      this.visible = true;
      this.title = "编辑";
    },
    del(item) {
      let that = this;
      this.$confirm({
        title: "确认删除吗？",
        onOk() {
          that.$API.sysManage
            .deleteRoleItem([{ id: item.record.id }])
            .then((res) => {
              if (res.data.code === 200) {
                that.$message.success("操作成功");
                that.getList();
              }
            });
        },
      });
    },
    handleOk() {
      //   this.visible = false;
      // this.confirmLoading = true;

      this.form.validateFields((err, values) => {
        if (!err) {
          this.$API.sysManage
            .setRoleItem({
              ...this.dataForm,
              name: values.name,
            })
            .then((res) => {
              if (res.data.code === 200) {
                this.$message.success("操作成功");
                this.confirmLoading = false;
                this.visible = false;
                this.getList();
              }
            });
        }
      });
    },
    addRole() {
      this.visible = true;
      this.title = "新增";
      this.dataForm = { ...this.resetForm };
      this.$nextTick(() => {
        this.form.setFieldsValue({ ["name"]: "" });
      });
    },
    search() {
      this.pagination.current = 1;

      this.pagination.defaultPageSize = 10;
      this.getList();
    },
    submit() {
      // console.log(this.$refs.menuTree.$store);

      // this.$refs.menuTree.expandedKeys([]);

      this.$API.sysManage
        .roleRelationMenu({
          roleId: this.tableItem.id,
          menuIds: this.checkedKeys,
          sysType: 2,
        })
        .then((res) => {
          if (res.data.code === 200) {
            this.$message.success(res.data.msg);
            this.expandedKeys = [];
            // this.$refs.menuTree.setCheckedNodes(allMenus);
          } else {
            this.$message.error(res.data.msg);
          }
        });
    },
    reset() {
      this.checkedKeys = [];
      this.checkAll = false;
      this.tableItem = {};
      this.treeDisabled = true;
    },
    expand(expand) {
      // console.log(expand);
      this.expandedKeys = [...expand];
    },
    // 全选操作
    handleCheckAll() {
      if (this.checkAll) {
        let allMenus = [];
        this.checkAllMenu(this.treeData, allMenus);
        // this.$refs.menuTree.setCheckedNodes(allMenus);
      } else {
        this.checkedKeys = [];
      }
    },
    // 递归全选
    checkAllMenu(treeData, allMenus) {
      treeData.forEach((menu) => {
        this.checkedKeys.push(menu.id);
        allMenus.push(menu);
        if (menu.children) {
          this.checkAllMenu(menu.children, allMenus);
        }
      });
    },
    onClickRow(val) {
      this.tableItem = { ...val };
      this.checkedKeys = [];
      this.treeDisabled = false;
      this.$API.sysManage
        .roleFindMenus({
          roleId: val.id,
        })
        .then((res) => {
          if (res.data.code) {
            let allMenus = [];
            if (res.data.data.length < 1) {
              this.checkedKeys = [];
            } else {
              // res.data.data.forEach((item) => {
              //   item.children.forEach((v) => {
              //     this.checkedKeys.push(v.id);
              //   });
              // });
              this.checkAllMenu(res.data.data, allMenus);
            }
          }
        });
    },
    // // 递归列表数
    // checkAllMenu(treeData, allMenus) {
    //   treeData.forEach((menu) => {
    //     this.checkedKeys.push(menu.id);
    //     allMenus.push(menu);
    //     if (menu.children) {
    //       this.checkAllMenu(menu.children, allMenus);
    //     }
    //   });
    // },
    getMenuList() {
      this.$API.sysManage.getMenuList().then((res) => {
        if (res.data.code === 200) {
          this.loading = false;

          this.treeData = [...res.data.data];
        }
      });
    },
    getList() {
      this.$API.sysManage
        .getRoleList({
          sysType: 2,
          pageNum: this.pagination.current,
          pageSize: this.pagination.defaultPageSize,
          roleName: this.name,
        })
        .then((res) => {
          console.log(res.data);
          if (res.data.code === 200) {
            this.tableList = [...res.data.data.content];
            this.pagination.current = res.data.data.current;
            this.pagination.defaultPageSize = res.data.data.pageSize;
            this.pagination.total = res.data.data.totalSize;
          }
        });
    },
    onChange(pagination) {
      // this.$message.info('表格状态改变了')
      // console.log(pagination, filters, sorter, { currentDataSource });
      this.pagination = {
        current: pagination.current,
        defaultPageSize: pagination.pageSize,
        total: pagination.total,
      };
      this.getList();
    },

    onCheck(checkedKeys) {
      console.log("onCheck", checkedKeys);
      this.checkedKeys = checkedKeys;
    },
    onSelect(selectedKeys, info) {
      console.log("onSelect", info);
      this.selectedKeys = selectedKeys;
    },
  },
};
</script>
<style lang='less' scoped>
.role-manage {
  width: 100%;
  height: 100%;
  background: #fff;
  display: flex;
  padding: 15px;
  box-sizing: border-box;
  > div {
    flex: 1;
  }
  .role-manage-aside {
    flex: none;
    width: 60% !important;
  }

  .role-head {
    display: flex;
    button {
      margin-left: 15px;
    }
  }
}
</style>