<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="Visible"
      width="650px"
      @close="handleClose"
      :close-on-click-modal="false"
      top="10vh"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        size="medium"
        label-width="130px"
      >
        <el-form-item label="父级菜单" prop="parentId">
          <treeselect
            v-model="form.parentId"
            :options="menuList"
            :normalizer="normalizer"
            :show-count="true"
            placeholder="选择父级菜单"
          />
        </el-form-item>
        <el-form-item label="菜单类型" prop="menuType">
          <el-radio-group v-model="form.menuType">
            <el-radio
              v-for="(item, key) in dict.menuType"
              :key="key"
              :label="Number(key)"
              >{{ item }}</el-radio
            >
          </el-radio-group>
        </el-form-item>

        <el-form-item label="菜单名称" prop="name">
          <el-input
            placeholder="请输入菜单名称"
            v-model="form.name"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="菜单图标" prop="imgPath" v-if="form.menuType != 2">
          <icon-select v-model="form.imgPath"></icon-select>
        </el-form-item>

        <!-- <el-form-item label="权限类型" prop="authType" v-if="form.menuType != 2">
          <el-select clearable v-model="form.authType" placeholder="请选择权限类型">
            <el-option
              v-for="(item, key) in dict.authType"
              :key="key"
              :label="item"
              :value="Number(key)"
            >
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item prop="url" v-if="form.menuType != 2">
          <span slot="label">
            <el-tooltip content="访问的路由地址，如：`system`" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
            路由地址
          </span>
          <el-input
            clearable
            placeholder="请输入菜单路由地址"
            v-model="form.url"
          ></el-input>
        </el-form-item>
        <el-form-item prop="component" v-if="form.menuType != 2">
          <span slot="label">
            <el-tooltip
              content="访问的组件路径，如：`pages/system/menu/Menu`，默认在`src`目录下"
              placement="top"
            >
              <i class="el-icon-question"></i>
            </el-tooltip>
            组件路径
          </span>
          <el-input
            clearable
            placeholder="请输入组件路径"
            v-model="form.component"
          ></el-input>
        </el-form-item>
        <el-form-item prop="activeDir" v-if="form.menuType != 2">
          <span slot="label">
            <el-tooltip content="顶部菜单栏激活路由" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
            激活菜单
          </span>
          <el-input
            clearable
            placeholder="请输入激活菜单地址"
            v-model="form.activeDir"
          ></el-input>
        </el-form-item>
        <el-form-item prop="perms" v-if="form.menuType == 2">
          <span slot="label">
            <el-tooltip
              content="控制器中定义的权限字符，如：'system:menu:add'"
              placement="top"
            >
              <i class="el-icon-question"></i>
            </el-tooltip>
            权限字符
          </span>
          <el-input
            clearable
            placeholder="请输入权限字符"
            v-model="form.perms"
          ></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="12" v-if="form.menuType != 2">
            <el-form-item prop="visible">
              <span slot="label">
                <el-tooltip
                  content="控制路由和子路由是否显示在菜单栏"
                  placement="top"
                >
                  <i class="el-icon-question"></i>
                </el-tooltip>
                显示状态
              </span>
              <el-radio-group v-model="form.visible">
                <el-radio
                  v-for="(item, key) in dict.visible"
                  :key="key"
                  :label="Number(key)"
                  >{{ item }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.menuType != 2">
            <el-form-item prop="cache">
              <span slot="label">
                <el-tooltip
                  content="选择是则会被`keep-alive`缓存"
                  placement="top"
                >
                  <i class="el-icon-question"></i>
                </el-tooltip>
                是否缓存
              </span>
              <el-radio-group v-model="form.cache">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" v-if="form.menuType != 2">
            <el-form-item prop="hideChildrenInMenu">
              <span slot="label">
                <el-tooltip
                  content="强制菜单显示为Item而不是SubItem"
                  placement="top"
                >
                  <i class="el-icon-question"></i>
                </el-tooltip>
                是否隐藏子菜单
              </span>
              <el-radio-group v-model="form.hideChildrenInMenu">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="(item, key) in dict.status"
                  :key="key"
                  :label="Number(key)"
                  >{{ item }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="资源类型" prop="resourceType">
              <el-radio-group v-model="form.resourceType">
                <el-radio :label="1">从资源列表获取</el-radio>
                <el-radio :label="2">自定义资源地址</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" v-show="form.resourceType == 1">
            <el-form-item label="资源" prop="resourceUrl">
              <select-res
                v-model="form.resourceUrl"
                :clearable="false"
              ></select-res>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-show="form.resourceType == 2">
            <el-form-item class="url-params-box" label="资源">
              <el-form-item
                class="url-params"
                v-for="(v, i) in form.urls"
                :key="i"
                :prop="`urls.${i}.value`"
                :rules="[
                  { required: false, validator: validatorUrl, trigger: 'blur' },
                ]"
              >
                <el-input
                  style="margin-right: 10px"
                  v-model="v.value"
                  placeholder="请输入链接地址"
                />
                <div class="flex">
                  <el-button type="primary" @click="changeParams(i, 'add')">
                    <i class="el-icon-plus"></i>
                  </el-button>
                  <el-button
                    type="danger"
                    v-if="i > 0"
                    @click="changeParams(i, 'remove')"
                    ><i class="el-icon-minus"></i
                  ></el-button>
                </div>
              </el-form-item>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="medium" @click="handleRest">重 置</el-button>
        <el-button
          size="medium"
          type="primary"
          :loading="loading"
          @click="handleOk"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { saveMenu } from "@/api/system";
import IconSelect from "./IconSelect";
import SelectRes from "./SelectRes.vue";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  components: {
    IconSelect,
    Treeselect,
    SelectRes,
  },
  props: {
    title: {
      type: String,
      required: true,
      default: "",
    },
    show: {
      type: Boolean,
      required: true,
      default: false,
    },
    menuList: {
      required: true,
      type: Array,
      default: () => [],
    },
    dict: {
      required: true,
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      loading: false,
      defaultProps: {
        children: "childList",
        label: "name",
      },
      form: {
        name: "", // 菜单名称
        url: "", // 路由地址
        ancestors: "", // 当前节点父id路径，“，”分割
        parentId: 0, // 父菜单ID，一级菜单的该字段值为-1
        linkType: 0, // 链接方式 (0.普通，1.弹出，2.脚本)
        imgPath: "", // 主菜单图标，主菜单图标的css样式名
        buttonImgPath: "", // 按钮图标，按钮图标的css样式名
        imgCommPath: "", // 常用菜单图标，常用菜单图标的css样式名
        commMenu: 1, // 是否常用菜单 (0.非常用，1.常用)
        component: "", // vue组件路径
        menuType: 0, // 菜单类型 (0.目录，1.菜单，2.按钮)
        authType: 3, // 权限类型 (0.无限制，1.无需登录查看，2.需要登录查看，3.需要角色权限查看)
        visible: 0, // 菜单显示状态 (0.显示，1.隐藏)
        perms: "", // 权限标识，多个逗号分割
        remark: "", // 备注信息
        orderId: "", // 排序编号
        status: 1, // 菜单状态 (0.停用，1.启用)
        cache: 0, // 是否缓存
        activeDir: "", // 激活菜单
        resourceType: 1, // 资源类型 (1.按资源id，1.链接地址)
        resourceUrl: [], // 资源id或者路径
        hideChildrenInMenu: 1, // 是否隐藏子菜单
        urls: [
          {
            value: "",
          },
        ],
      },
      rules: {
        name: [{ required: true, message: "请输入菜单名称", trigger: "blur" }],
        url: [
          { required: true, message: "请输入菜单访问地址", trigger: "blur" },
        ],
        component: [
          { required: true, message: "请输入组件路径", trigger: "blur" },
        ],
        // authType: [{ required: true, message: '请输入选择权限类型', trigger: 'change' }]
      },
    };
  },
  computed: {
    Visible: {
      get() {
        return this.show;
      },
      set(val) {
        this.$emit("update:show", val);
      },
    },
  },
  methods: {
    // 确定
    handleOk() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          let resourceUrl;
          let form = { ...this.form };
          if (this.form.resourceType === 1) {
            resourceUrl = this.form.resourceUrl.join(",");
          } else {
            resourceUrl = this.form.urls
              .map((v) => {
                return v.value.startsWith("/") ? v.value : "/" + v.value;
              })
              .join(",");
          }
          this.$delete(form, "resourceType");
          this.$delete(form, "urls");
          let res = await saveMenu({
            ...form,
            resourceUrl,
          });
          let { code, msg } = res.data;
          if (code === 1) {
            this.$message.success(msg);
            this.$emit("success");
            this.handleClose();
          }
          this.loading = false;
        }
      });
    },
    // 新增
    onAdd() {
      Object.assign(this.form, this.$options.data().form);
      this.form.id && this.$delete(this.form, "id");
    },
    // 编辑
    onEdit(row) {
      setTimeout(() => {
        this.form = { ...row };
        this.$set(this.form, "resourceType", 1);
        this.$set(this.form, "urls", [{ value: "" }]);
        this.form.resourceUrl = [];
        if (row.resourceUrl) {
          let arr = row.resourceUrl.split(",");
          if (this.isUrl(row.resourceUrl)) {
            this.form.urls = arr.map((v) => {
              return {
                value: v,
              };
            });
            this.form.resourceType = 2;
            this.form.resourceUrl = arr;
          } else {
            this.form.resourceUrl = arr.map(Number);
          }
        }
      }, 10);
    },
    // 判断资源是否是链接
    isUrl(val) {
      return val.startsWith("/");
    },
    // 重置
    handleRest() {
      this.$resetForm("form");
    },
    // 关闭
    handleClose() {
      this.$resetForm("form");
      this.Visible = false;
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.childList && !node.childList.length) {
        delete node.childList;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.childList,
      };
    },
    // 判断是否存在链接
    isRepeat(val) {
      return this.form.urls.filter((v) => v.value == val).length > 1;
    },
    // 校验链接地址
    validatorUrl(rule, value, callback) {
      if (!value) {
        if (rule.required) {
          callback(new Error("请输入链接"));
        } else {
          callback();
        }
      } else if (this.isRepeat(value)) {
        callback(new Error("重复的链接地址"));
      } else {
        callback();
      }
    },
    changeParams(index, type) {
      if (type == "add") {
        let obj = {
          value: "",
        };
        if (this.form.urls.some((v) => !v.value)) {
          this.$message.warning("请先完成前面地址的填写");
          return;
        }
        this.form.urls.splice(index + 1, 0, obj);
      } else {
        this.form.urls.splice(index, 1);
      }
      // this.$forceUpdate();
    },
  },
};
</script>

<style lang="less" scoped>
:deep(.el-dialog__body) {
  max-height: 650px;
  overflow: auto;
}
:deep(.el-select) {
  width: 100%;
}
:deep(.url-params) {
  margin-bottom: 22px;
  .el-form-item__content {
    display: flex;
  }
}
</style>
