<template>
  <div class="menu">
    <div class="menu-head">
      <a-input placeholder="名称" style="width: 300px"></a-input>
      <a-button type="primary">查询</a-button>
      <a-button type="primary" style="background: green" @click="addMenu"
        >新增</a-button
      >
    </div>
    <a-spin :spinning="loading">
      <a-table
        :columns="columns"
        :dataSource="tableList"
        :pagination="false"
        style="background: #fff"
        :customRow="customRow"
        rowKey="id"
      >
        <div class="operation-list" slot="operation" slot-scope="text, record">
          <a-button type="danger" @click="delMenu({ text, record })"
            >删除
          </a-button>
          <a-button type="primary" @click="editMenu({ text, record })"
            >编辑</a-button
          >
        </div>
      </a-table>
    </a-spin>

    <a-modal
      v-model="visible"
      :title="title"
      @ok="handleOk"
      layout="inline"
      width="50%"
      :confirm-loading="confirmLoading"
    >
      <a-form :layout="formLayout" :form="form" :rules="rules">
        <a-form-item
          label="菜单类型"
          v-bind="formItemLayout"
          v-show="!authType"
        >
          <a-radio-group :default-value="'目录'" v-model="dataForm.type">
            <a-radio
              v-for="(item, index) in menuTypeList"
              :key="index"
              :value="index"
            >
              {{ item }}
            </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          :label="menuTypeList[dataForm.type] + '名称'"
          v-bind="formItemLayout"
          v-show="!authType"
        >
          <a-input
            :placeholder="menuTypeList[dataForm.type] + '名称'"
            v-decorator="[
              'name',
              {
                rules: [
                  {
                    required: true,
                    message: '请输入' + menuTypeList[dataForm.type] + '名称',
                  },
                ],
              },
            ]"
          />
        </a-form-item>
        <a-form-item
          label="上级菜单"
          v-bind="formItemLayout"
          v-show="!authType"
        >
          <a-popover placement="rightTop">
            <a-input
              placeholder="请选择上级菜单"
              :readonly="true"
              v-model="dataForm.parentName"
            />
            <template slot="content">
              <a-tree
                :tree-data="tableList"
                :title="'11'"
                :replaceFields="replaceFields"
                @select="onSelect"
              >
                <template slot="custom" slot-scope="item">
                  <span>{{ item }}</span>
                  <!-- <span style="color: #f50">({{ item.num }})</span> -->
                </template>
              </a-tree>
            </template>
          </a-popover>
        </a-form-item>
        <a-form-item
          label="授权标识"
          v-bind="formItemLayout"
          v-show="dataForm.type == 1 && !authType"
        >
          <a-input placeholder="请输入授权标识" v-model="dataForm.perms" />
        </a-form-item>
        <a-form-item
          label="菜单路由"
          v-bind="formItemLayout"
          v-show="dataForm.type != 2 && !authType"
        >
          <a-input
            placeholder="请输入菜单路由"
            v-decorator="[
              'url',
              {
                rules: [
                  {
                    required: true,
                    message: '请输入菜单名称',
                  },
                ],
              },
            ]"
          />
        </a-form-item>
        <a-form-item
          label="排序编号"
          v-bind="formItemLayout"
          v-show="!authType"
        >
          <a-input-number
            id="请输入排序编号"
            v-model="dataForm.orderNum"
            :min="0"
          />
        </a-form-item>
        <a-form-item
          label="菜单图标"
          v-bind="formItemLayout"
          v-show="!authType"
        >
          <a-input
            placeholder="菜单图标名称（如：fa fa-home fa-lg）"
            v-model="dataForm.icon"
          />
        </a-form-item>

        <!-- 此处是数据权限 -->
        <a-form-item label="接口地址" v-bind="formItemLayout" v-show="authType">
          <a-input placeholder="接口地址" v-model="authPermissions.url" />
        </a-form-item>

        <a-form-item
          label="是否自定义脚本"
          v-bind="formItemLayout"
          v-show="authType"
        >
          <a-switch
            checked-children="是"
            un-checked-children="否"
            v-model="authPermissions.customScriptFlag"
          ></a-switch>
          <!-- {{ authPermissions.customScriptFlag }} -->
        </a-form-item>
        <a-form-item
          label="数据权限分类"
          v-bind="formItemLayout"
          v-show="authType && !authPermissions.customScriptFlag"
        >
          <a-select v-model="authPermissions.dataPermissionId">
            <a-select-option
              v-for="item in authList"
              :key="item.id"
              :value="item.id"
              >{{ item.label }}</a-select-option
            >
          </a-select>
        </a-form-item>
        <a-form-item
          label="脚本"
          v-bind="formItemLayout"
          v-show="authType && authPermissions.customScriptFlag"
        >
          <a-input
            placeholder="脚本内容"
            v-model="dataForm.icon"
            type="textarea"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
const columns = [
  {
    title: "ID",
    dataIndex: "id",
  },

  {
    title: "名称",
    dataIndex: "name",
  },
  {
    title: "图标",
    dataIndex: "icon",
  },
  {
    title: "类型",
    dataIndex: "type",

    scopedSlots: { customRender: "type" },
  },
  {
    title: "上级菜单",

    dataIndex: "parentName",
    scopedSlots: { customRender: "parentName" },
  },
  {
    title: "授权标识",

    dataIndex: "perms",
  },
  {
    title: "排序",
    dataIndex: "orderNum",
  },
  {
    title: "操作",
    key: "operation",
    scopedSlots: { customRender: "operation" },
  },
];

export default {
  components: {},
  data() {
    return {
      visible: false,
      confirmLoading: false,
      title: "",
      formLayout: "horizontal",
      menuTypeList: ["目录", "菜单", "按钮"],
      replaceFields: {
        children: "children",
        title: "name",
        key: "id",
      },
      form: this.$form.createForm(this, { name: "dynamic_rule" }),
      rules: {
        requiredField: [
          { required: true, message: "请输入必填项", trigger: "blur" },
        ],
      },
      dataForm: {
        id: 0,
        type: 1,
        name: "",
        parentId: 0,
        parentName: "",
        url: "",
        perms: "",
        orderNum: 0,
        icon: "",
      },
      formItemLayout: {
        labelCol: {
          xs: { span: 5 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
      },
      menuList: [],
      columns,
      tableList: [],
      loading: false,
      resetForm: {},
      authType: false,
      authList: [],
      authPermissions: {
        customScriptFlag: 0,
        dataPermissionId: "",
        id: undefined,
        menuId: 0,
        scriptContent: "",
        url: "",
      },
    };
  },
  created() {
    this.getList();
    this.resetForm = { ...this.dataForm };
    this.getAuthList();
  },
  // watch: {
  //   dataForm(val) {
  //     console.log(val);
  //     this.form.updateFields({
  //       name: this.$form.createFormField({
  //         ...this.username,
  //         value: this.username.value,
  //       }),
  //     });
  //   },
  // },
  mounted() {},
  methods: {
    customRow(record, index) {
      console.log(record, index);
      return {
        style: {
          cursor: "move",
        },
        // 鼠标移入
        onMouseenter: (event) => {
          // 兼容IE
          var ev = event || window.event;
          ev.target.draggable = true;
        },
        // 开始拖拽
        onDragstart: (event) => {
          console.log(event);
          // 兼容IE
          var ev = event || window.event;
          // 阻止冒泡
          ev.stopPropagation();
          // 得到源目标数据
          this.sourceObj = record;
        },
        // 拖动元素经过的元素
        onDragover: (event) => {
          // 兼容 IE
          var ev = event || window.event;
          // 阻止默认行为
          ev.preventDefault();
        },
        // 鼠标松开
        onDrop: (event) => {
          // 兼容IE
          var ev = event || window.event;
          // 阻止冒泡
          ev.stopPropagation();
          // 得到目标数据
          this.targetObj = record;
          console.log(this.sourceObj, this.targetObj);
          const tempDta = this.data;
          tempDta[this.targetObj.weight] = this.sourceObj;
          tempDta[this.sourceObj.weight] = this.targetObj;
          let weightList = [];
          tempDta.forEach((item, index) => {
            item.weight = index;
            weightList.push({
              id: item.id,
              weight: index,
            });
          });
          // this.handleWeightModify(weightList); // 更改顺序接口
        },
      };
    },

    getAuthList() {
      this.$API.sysManage.getAuthModule("sjqx").then((res) => {
        if (res.data.code === 200) {
          this.authList = [...res.data.data];
        }
      });
    },
    delMenu(item, type) {
      this.dataForm = { ...item.record };
      let that = this;

      this.$confirm({
        title: "确认删除吗？",
        onOk() {
          if (type) {
            that.$API.sysManage
              .removeMenuAuth({ menuId: item.record.id })
              .then((res) => {
                if (res.data.code === 200) {
                  that.$message.success("操作成功");
                  that.loading = false;
                  that.getList();
                }
              });
          } else
            that.$API.sysManage
              .delMenuItem([{ id: item.record.id }])
              .then((res) => {
                if (res.data.code === 200) {
                  that.$message.success("操作成功");
                  that.loading = false;
                  that.getList();
                }
              });
        },
      });
      // this.$API.sysManage.delMenuItem([{ id: item.record.id }]).then((res) => {
      //   if (res.data.code === 200) {
      //     this.getList();
      //   }
      // });
    },
    editMenu(item, type) {
      this.title = "编辑";
      this.visible = true;

      this.$nextTick(() => {
        this.dataForm = { ...item.record };

        this.form.setFieldsValue({ ["name"]: item.record.name });
        this.form.setFieldsValue({ ["url"]: item.record.url });
      });

      if (type) {
        this.authType = true;
        this.authPermissions.menuId = item.record.id;
        this.$API.sysManage
          .getMenuAuthItem({ menuId: item.record.id })
          .then((res) => {
            if (res.data.code === 200) {
              this.authPermissions = { ...res.data.data };
            }
          });
      } else {
        this.authType = false;
      }
    },
    onSelect(val, { node }) {
      this.dataForm.parentId = val[0];
      this.dataForm.parentName = node.title;
    },
    getList() {
      this.loading = true;
      this.$API.sysManage.getMenuList({}).then((res) => {
        if (res.data.code === 200) {
          this.loading = false;

          this.tableList = [...res.data.data];
        } else {
          this.loading = false;
          this.$message.error(res.data.msg);
        }
      });
    },
    addMenu() {
      this.title = "新增";
      this.visible = true;
      this.dataForm = { ...this.resetForm };
      this.form.setFieldsValue({ ["name"]: "" });
      this.form.setFieldsValue({ ["url"]: "" });
    },
    handleOk() {
      this.form.validateFields((err, values) => {
        if (!err) {
          // console.log(values, this.dataForm);
          if (this.authType) {
            this.$API.sysManage
              .setMenuAuth({
                customScriptFlag: this.authPermissions.customScriptFlag ? 1 : 0,
                dataPermissionId:
                  this.authPermissions.customScriptFlag == 0
                    ? this.authPermissions.dataPermissionId
                    : undefined,
                id: this.authPermissions.id,
                menuId: this.authPermissions.menuId,
                scriptContent: this.authPermissions.customScriptFlag
                  ? this.authPermissions.scriptContent
                  : undefined,
                url: this.authPermissions.url,
              })
              .then((res) => {
                if (res.data.code === 200) {
                  this.$message.success("操作成功");
                  this.confirmLoading = false;
                  this.visible = false;
                  this.loading = false;
                  this.getList();
                }
              });
          } else
            this.$API.sysManage
              .setMenuItem({
                ...this.dataForm,
                name: values.name,
                url: values.url,
              })
              .then((res) => {
                if (res.data.code === 200) {
                  this.$message.success("操作成功");
                  this.confirmLoading = false;
                  this.visible = false;
                  this.loading = false;
                  this.getList();
                }
              });
        }
      });
    },
  },
};
</script>
<style lang='less' scoped>
.menu {
  display: flex;
  flex-direction: column;
  background: #fff;
  padding: 15px;
  box-sizing: border-box;
  .menu-head {
    display: flex;
    button {
      margin-left: 15px;
    }
  }
  /deep/ .ant-form .ant-form-item {
    display: flex !important;
  }
  .operation-list {
    button {
      margin-right: 10px;
    }
  }
}
</style>