<template>
  <div
    class="app-container"
    style="height: 100%; box-sizing: border-box; overflow-y: auto"
  >
    <div class="mymain-container">
      <div class="btn-group clearfix">
        <div class="fl">
          <el-button
            size="small"
            type="primary"
            icon="el-icon-plus"
            @click="openFormWin('add', '0')"
            >添加菜单</el-button
          >
        </div>
      </div>
      <div class="table">
        <el-table
          v-loading="listLoading"
          :data="dataList"
          row-key="moduleId"
          border
          default-expand-all
          :tree-props="{ children: 'pages' }"
        >
          <el-table-column prop="moduleName" label="菜单名称" min-width="150" />
          <el-table-column prop="url" label="菜单URL" min-width="150" />
          <el-table-column prop="fullUrl" label="菜单全URL" min-width="200" />
          <el-table-column align="center" prop="icon" label="菜单图标">
            <template slot-scope="scope">
              <i :class="scope.row.icon" style="font-size: 18px" />
            </template>
          </el-table-column>
          <el-table-column align="center" prop="status" label="状态">
            <template slot-scope="scope">
              <span>{{
                ["显示", "不显示"][[true, false].indexOf(scope.row.status)] ||
                ""
              }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="isCache" label="状态">
            <template slot-scope="scope">
              <span>{{
                ["缓存", "不缓存"][[1, 0].indexOf(scope.row.isCache)] || ""
              }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="sortNum" label="排序" />
          <el-table-column align="right" label="操作" width="150" fixed="right">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-plus"
                @click="openFormWin('add', scope.row.moduleId)"
              />
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-edit"
                @click="openFormWin('edit', scope.row.moduleId)"
              />
              <el-popconfirm
                style="margin-left: 10px"
                title="确定删除吗？"
                @confirm="handleDelete(scope.row.moduleId)"
              >
                <el-button slot="reference" size="mini" icon="el-icon-delete" />
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 创建编辑菜单 -->
    <div class="cartographer_big">
      <el-dialog
        :title="this.menuFormData.moduleId ? '编辑菜单' : '创建菜单'"
        width="100%"
        :modal="false"
        :visible.sync="menuFormBool"
        :before-close="cancelFormWin"
        :close-on-click-modal="false"
      >
        <zj-page-container v-if="menuFormBool">
          <zj-page-fill class="neibuviewaaaaa">
            <zj-form-container
              ref="formRef"
              :form-data="menuFormData"
              :form-attributes="{ size: 'medium' }"
              :styleSwitch="false"
            >
              <zj-form-module
                title="基本信息"
                :form-data="menuFormData"
                :form-items="basicInfo"
                :showHade="false"
                label-width="120px"
              />
            </zj-form-container>
          </zj-page-fill>
          <div>
            <div
              style="
                box-sizing: border-box;
                padding: 10px 60px;
                text-align: right;
              "
            >
              <el-button @click="cancelFormWin">取 消</el-button>
              <el-button type="primary" @click="submitMenuForm"
                >确 定</el-button
              >
            </div>
          </div>
        </zj-page-container>
      </el-dialog>
    </div>

    <!-- 添加功能 -->
    <el-dialog
      :title="formData.moduleId ? '编辑' : '新增'"
      :visible.sync="dialogVisible"
      :show-close="false"
      width="40%"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formData"
        :model="formData"
        :rules="formDataRules"
        label-position="left"
        label-width="100px"
      >
        <el-form-item label="code" prop="code">
          <el-input
            v-model="formData.code"
            placeholder="请输入类型"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="名称" prop="moduleName">
          <el-input
            v-model="formData.moduleName"
            placeholder="请输入接口名称"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="chongzhi">取 消</el-button>
        <el-button type="primary" @click="addOperative">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 选择图标 -->
    <el-dialog
      title="选择图标"
      :visible.sync="isChooseIconDialog"
      :show-close="true"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="iconList">
        <div
          v-for="(item, index) in iconList"
          :key="index"
          class="item"
          @click="chooseIcon(item.value)"
        >
          <i :class="item.value" />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { getToken } from "@/utils/auth";
import {
  getMenuList,
  addMenu,
  editMenu,
  deleteMenu,
  getMenuDetail,
} from "@/api/setting";
import iconList from "@/const/iconList.js";
export default {
  data() {
    return {
      dataList: [], // 列表数据
      listLoading: true, // 列表加载loading
      isChooseIconDialog: false,
      iconList: iconList,
      menuTypeList: [
        {
          value: 1,
          label: "目录",
        },
        {
          value: 2,
          label: "页面",
        },
        {
          value: 4,
          label: "外链",
        },
      ],
      dialogVisible: false,
      formData: {
        code: "",
        moduleName: "",
      },
      formDataRules: {
        code: [{ required: true, message: "请选择类型", trigger: "blur" }],
        moduleName: [
          { required: true, message: "请选择类型", trigger: "blur" },
        ],
      },
      menuFormData: {
        parentId: "",
        moduleId: "",
        moduleName: "",
        code: "",
        url: "",
        fullUrl: "",
        icon: "",
        sortNum: 0,
        flag: "",
        type: 1,
        status: true,
        isCache: 1,
        childList: [],
      },
      menuFormBool: false,
    };
  },
  computed: {
    ...mapGetters(["userid", "name"]),
    columns() {
      return [
        {
          columnAttributes: {
            label: "名称",
            prop: "moduleName",
          },
        },
        {
          columnAttributes: {
            label: "code",
            prop: "code",
          },
        },
        {
          columnAttributes: {
            label: "操作",
            prop: "",
          },
          render: (h, { row, column, index }) => {
            return (
              <div style="padding-left:10px">
                {row.moduleId ? (
                  <el-button
                    size="mini"
                    type="text"
                    onClick={() => {
                      getMenuDetail({ moduleId: row.moduleId }).then((res) => {
                        this.formData = {
                          ...this.formData,
                          ...res.data,
                        };
                        this.dialogVisible = true;
                      });
                    }}
                  >
                    编辑
                  </el-button>
                ) : null}
                <el-popconfirm
                  title="确定删除吗？"
                  onConfirm={() => {
                    if (row.moduleId && this.menuFormData.moduleId) {
                      deleteMenu({ id: row.moduleId }).then((res) => {
                        this.$successMsg("删除成功");
                        if (this.menuFormData.moduleId) {
                          getMenuDetail({
                            moduleId: this.menuFormData.moduleId,
                          }).then((res) => {
                            this.menuFormData.childList = res.data.childList;
                          });
                        }
                      });
                    } else {
                      var i = this.menuFormData.childList.findIndex(
                        (item) => item.type == 3 && item.code == row.code
                      );
                      if (i > -1) {
                        this.menuFormData.childList.splice(i, 1);
                      }
                    }
                  }}
                >
                  <el-button slot="reference" type="text" size="mini">
                    删除
                  </el-button>
                </el-popconfirm>
              </div>
            );
          },
        },
      ];
    },
    basicInfo() {
      return [
        {
          name: "el-radio",
          md: 24,
          options: this.menuTypeList,
          attributes: {
            placeholder: "请选择",
          },
          formItemAttributes: {
            label: "类型",
            prop: "type",
          },
        },
        {
          name: "el-cascader",
          md: 24,
          attributes: {
            placeholder: "请选择",
            options: [
              { moduleId: "0", moduleName: "设定一级" },
              ...this.dataList,
            ],
            props: {
              checkStrictly: true,
              value: "moduleId",
              label: "moduleName",
              emitPath: false,
            },
            filterable: true,
            clearable: true,
            style: { width: "100%" },
          },
          formItemAttributes: {
            label: "上级菜单",
            prop: "parentId",
          },
        },
        {
          name: "el-input",
          md: 24,
          attributes: {
            placeholder: "请输入菜单名称",
          },
          formItemAttributes: {
            label: "菜单名称",
            prop: "moduleName",
            rules: [{ required: true, message: "请选择类型", trigger: "blur" }],
          },
        },
        {
          name: "el-input",
          md: 24,
          attributes: {
            placeholder: "请输入CODE",
          },
          formItemAttributes: {
            label: "CODE",
            prop: "code",
            rules: [{ required: true, message: "请选择类型", trigger: "blur" }],
          },
        },
        {
          name: "el-input",
          md: 24,
          attributes: {
            placeholder: "请输入URL",
          },
          formItemAttributes: {
            label: "URL",
            prop: "url",
          },
        },
        {
          name: "el-input",
          md: 24,
          attributes: {
            placeholder: "请输入全URL",
          },
          formItemAttributes: {
            label: "全URL",
            prop: "fullUrl",
          },
        },
        {
          name: "slot-component",
          md: 24,
          formItemAttributes: {
            label: "图标",
            prop: "icon",
          },
          render: (h, { props, onInput }) => {
            var { formData, value } = props;
            return (
              <div class="iconInput">
                {formData.icon ? (
                  <div class="icon">
                    <i class={formData.icon} />
                  </div>
                ) : null}
                <el-input
                  value={value}
                  onInput={onInput}
                  placeholder="请选择图标"
                />
                <el-button
                  type="primary"
                  onClick={() => {
                    this.toChooseIcon(2);
                  }}
                >
                  选择
                </el-button>
              </div>
            );
          },
        },
        {
          name: "el-input",
          md: 24,
          attributes: {
            placeholder: "请输入排序",
          },
          formItemAttributes: {
            label: "排序",
            prop: "sortNum",
          },
        },
        {
          name: "el-switch",
          md: 24,
          attributes: {
            "active-value": true,
            "inactive-value": false,
            "active-color": "#13ce66",
            "inactive-color": "#ff4949",
          },
          formItemAttributes: {
            label: "是否显示",
            prop: "status",
          },
        },
        {
          name: "el-switch",
          md: 24,
          attributes: {
            "active-value": 1,
            "inactive-value": 0,
            "active-color": "#13ce66",
            "inactive-color": "#ff4949",
          },
          formItemAttributes: {
            label: "是否缓存页面",
            prop: "isCache",
          },
        },
        {
          isShow: this.menuFormData.type == 2,
          name: "slot-component",
          md: 24,
          formItemAttributes: {
            label: "功能",
            prop: "",
          },
          render: (h, { props, onInput }) => {
            var { formData, value } = props;
            return (
              <div>
                <el-button
                  style="margin-bottom: 10px"
                  type="primary"
                  size="small"
                  onClick={this.hasShowTable}
                >
                  新增
                </el-button>
                <zj-table
                  is-drop={true}
                  columns={this.columns}
                  table-data={this.menuFormData.childList.filter(
                    (item) => item.type != 2
                  )}
                  table-attributes={{
                    border: true,
                  }}
                />
              </div>
            );
          },
        },
      ];
    },
  },
  created() {
    this.getList();
  },
  methods: {
    // 获取菜单列表
    getList() {
      this.listLoading = true;
      getMenuList({
        adminUserId: this.userid,
        flag: "menu",
      })
        .then((res) => {
          this.dataList = this.recursionFn(res.data);
        })
        .finally(() => {
          this.listLoading = false;
        });
    },
    // 组合数据
    recursionFn(arr) {
      if (!arr.length) return;
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].children.length) {
          arr[i].pages = [];
          arr[i].controls = [];
          for (let j = 0; j < arr[i].children.length; j++) {
            if ([1, 2, 4].includes(arr[i].children[j].type)) {
              arr[i].pages.push(arr[i].children[j]);
            }
            if ([3].includes(arr[i].children[j].type)) {
              arr[i].controls.push(arr[i].children[j]);
            }
          }
          this.recursionFn(arr[i].children);
        }
      }
      return arr || [];
    },
    // 去选择图标
    toChooseIcon(type) {
      this.isChooseIconDialog = true;
    },

    // 选择图标
    chooseIcon(value) {
      this.menuFormData.icon = value;
      this.isChooseIconDialog = false;
    },

    // 打开功能窗口
    hasShowTable() {
      this.dialogVisible = true;
    },

    // 添加功能确定按钮
    addOperative() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          const params = {
            parentId: this.menuFormData.moduleId || "",
            moduleId: this.formData.moduleId || "",
            moduleName: this.formData.moduleName,
            code: this.formData.code,
            childList: this.formData.childList || null,
            type: 3,
          };
          if (this.menuFormData.moduleId) {
            if (this.formData.moduleId) {
              params.parentId = null;
              editMenu(params).then((res) => {
                this.$successMsg("编辑成功");
                this.chongzhi();
                getMenuDetail({ moduleId: this.menuFormData.moduleId }).then(
                  (res) => {
                    this.menuFormData.childList = res.data.childList;
                  }
                );
              });
            } else {
              addMenu(params).then((res) => {
                this.$successMsg("添加成功");
                this.chongzhi();
                getMenuDetail({ moduleId: this.menuFormData.moduleId }).then(
                  (res) => {
                    this.menuFormData.childList = res.data.childList;
                  }
                );
              });
            }
          } else {
            var index = this.menuFormData.childList.findIndex(
              (item) => item.type == 3 && item.code == params.code
            );
            if (index == -1) {
              this.menuFormData.childList.push(params);
            } else {
              this.menuFormData.childList.splice(index, 1, params);
            }
            this.chongzhi();
          }
        }
      });
    },

    // 关闭功能添加窗口
    chongzhi() {
      this.formData = {
        code: "",
        moduleName: "",
      };
      this.dialogVisible = false;
    },

    // 打开 新增编辑
    openFormWin(type, cid) {
      if (type == "add") {
        this.menuFormData.parentId = cid;
        this.menuFormBool = true;
      } else if (type == "edit") {
        getMenuDetail({ moduleId: cid }).then((res) => {
          this.menuFormData = {
            ...res.data,
          };
          this.menuFormBool = true;
        });
      }
    },

    // 关闭窗口
    cancelFormWin() {
      this.$data.menuFormData = this.$options.data().menuFormData;
      this.$refs?.formRef?.resetFields();
      this.menuFormBool = false;
    },

    // 提交菜单
    submitMenuForm() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          if (this.menuFormData.moduleId) {
            editMenu(this.menuFormData).then((res) => {
              this.getList();
              this.cancelFormWin();
              this.$successMsg("编辑成功");
            });
          } else {
            addMenu(this.menuFormData).then((res) => {
              this.getList();
              this.cancelFormWin();
              this.$successMsg("添加成功");
            });
          }
        }
      });
    },

    // 操作 - 删除
    handleDelete(id) {
      deleteMenu({ id: id }).then((res) => {
        this.getList();
        this.$successMsg();
      });
    },
  },
};
</script>

<style scoped lang="scss">
.iconList {
  display: flex;
  flex-wrap: wrap;
  max-height: 40vh;
  overflow-y: scroll;
  .item {
    width: 40px;
    height: 40px;
    text-align: center;
    line-height: 40px;
    cursor: pointer;
    i {
      font-size: 18px;
    }
    &:hover {
      background: #f5f5f5;
      i {
        color: #409eff;
      }
    }
  }
}
::v-deep .iconInput {
  display: flex;
  .icon {
    margin-right: 10px;
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    box-sizing: border-box;
    color: #606266;
    width: 40px;
    height: 40px;
    text-align: center;
    line-height: 40px;
    flex-shrink: 0;
    i {
      font-size: 18px;
    }
  }
  input {
    flex: 1;
  }
  button {
    margin-left: 10px;
  }
}
</style>

<style lang="scss">
.el-image-viewer__wrapper .el-icon-circle-close {
  color: #ffffff !important;
  font-size: 60px;
}
.el-table__row.expanded {
  background: #f5f5f5;
}
.neibuviewaaaaa {
  .zj-page-fill-scroll {
    box-sizing: border-box;
    padding: 20px 50px;
  }
}
</style>
