<template>
  <div>
    <el-form
      :model="menuForm"
      :rules="addMenuRules"
      ref="addUserForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="上级目录:" prop="parentId" v-if="activeName !== '1'">
        <treeselect
          :normalizer="normalizer"
          :noChildrenText="'没有子选项'"
          :noOptionsText="'没有可选项'"
          :noResultsText="'没有匹配的结果'"
          :placeholder="'请选择'"
          :searchable="true"
          v-model="menuForm.parentId"
          placeholder="请选择"
          :options="menuOptions"
        ></treeselect>
      </el-form-item>
      <el-form-item label="菜单名称:" prop="pname">
        <el-input
          v-model="menuForm.pname"
          placeholder="请输入菜单名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="菜单标识:" prop="pcode">
        <el-input
          v-model="menuForm.pcode"
          placeholder="请输入菜单标识"
        ></el-input>
      </el-form-item>
      <el-form-item label="显示排序:" prop="psort">
        <el-input
          type="number"
          :min="0"
          v-model="menuForm.psort"
          placeholder="请输入菜单标识"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="菜单图标"
        prop="piconUrl"
        v-if="activeName !== '3' && activeName !== '2'"
      >
        <el-popover
          placement="bottom-start"
          width="460"
          trigger="click"
          @show="$refs['iconSelect'].reset()"
        >
          <IconSelect
            ref="iconSelect"
            @selected="selected"
            :active-icon="menuForm.piconUrl"
          />
          <el-input
            slot="reference"
            v-model="menuForm.piconUrl"
            placeholder="点击选择图标"
            readonly
          >
            <svg-icon
              v-if="menuForm.piconUrl"
              slot="prefix"
              :icon-class="menuForm.piconUrl"
              style="width: 25px; height: 25px"
            />
            <i v-else slot="prefix" class="el-icon-search el-input__icon" />
          </el-input>
        </el-popover>
      </el-form-item>
      <el-form-item label="路由地址:" prop="purl" v-if="activeName !== '1'">
        <el-input
          v-model="menuForm.purl"
          placeholder="请输入路由地址"
        ></el-input>
      </el-form-item>
      <el-form-item label="是否显示:" prop="permissionShow">
        <el-select
          v-model="menuForm.permissionShow"
          placeholder="请选择状态"
          style="width: 100%"
        >
          <el-option label="显示" :value="1"></el-option>
          <el-option label="不显示" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态:" prop="pstat">
        <el-select
          v-model="menuForm.pstat"
          placeholder="请选择状态"
          style="width: 100%"
        >
          <el-option label="启用" :value="1"></el-option>
          <el-option label="停用" :value="0"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import Treeselect from "@riophae/vue-treeselect";
import { addMenuFn, updateMenuFn } from "@/api/system";
import IconSelect from "@/components/IconSelect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  components: {
    Treeselect,
    IconSelect,
  },
  props: {
    activeName: {
      type: String,
    },
    tableData: {
      type: Array,
    },
    checkId: {
      type: Number,
    },
    title: {
      type: String,
    },
    row: {
      type: Object,
    },
  },
  data() {
    return {
      name: "",
      menuForm: {
        psort: 0,
        parentId: null,
        pname: null,
        purl: null,
        pstat: null,
        pcode: null,
        permissionShow: null,
        piconUrl: "",
      },
      addMenuRules: {
        permissionShow: {
          required: true,
          message: "请选择",
          trigger: "change",
        },
        psort: [{ required: true, message: "请填写显示排序", trigger: "blur" }],
        pcode: [{ required: true, message: "请填写菜单标识", trigger: "blur" }],
        pname: [{ required: true, message: "请填写菜单名称", trigger: "blur" }],
        purl: [{ required: true, message: "请填写路由地址", trigger: "blur" }],
        parentId: [
          { required: true, message: "请选择上级目录", trigger: "change" },
        ],
        pstat: [{ required: true, message: "请选择状态", trigger: "change" }],
      },
      stateOptions: [],
      menuOptions: [
        { permissionId: 0, permissionName: "主类目", children: [] },
      ],
    };
  },
  created() {
    this.initializeForm();
  },

  watch: {
    row: {
      handler(newVal) {
        if (newVal) {
          this.initializeForm();
        }
      },
      immediate: true,
      deep: true,
    },
    checkId(newVal) {
      if (newVal !== null && newVal !== undefined) {
        this.menuForm.parentId = newVal;
        this.initializeForm();
      }
    },
    tableData: {
      handler(newData) {
        this.$nextTick(() => {
          this.menuOptions[0].children = [];
          this.menuOptions[0].children.push(...newData);
        });
      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    // 选择图标
    selected(name) {
      this.menuForm = {
        ...this.menuForm,
        piconUrl: name,
      };
    },
    initializeForm() {
      this.menuOptions[0].children.push(...this.tableData);
      if (this.row && this.title === "编辑" && this.activeName === "2") {
        this.menuForm = {
          parentId: this.row.parentId,
          pname: this.row.permissionName,
          purl: this.row.permissionUrl,
          pstat: this.row.permissionState,
          pcode: this.row.permissionCode,
          psort: this.row.permissionSort,
          permissionShow: this.row.permissionShow,
        };
      } else if (this.title === "新增" && this.activeName === "2") {
        this.menuForm.parentId = this.checkId;
      } else {
        this.menuForm.parentId = 0;
      }

      if (this.row && this.title === "编辑") {
        this.menuForm = {
          parentId: this.row.parentId,
          pname: this.row.permissionName,
          purl: this.row.permissionUrl,
          pstat: this.row.permissionState,
          pcode: this.row.permissionCode,
          permissionShow: this.row.permissionShow,
          psort: this.row.permissionSort,
          piconUrl: this.row.permissionIconUrl,
        };
        if (this.activeName === "1") {
          this.$nextTick(() => {
            this.menuForm = {
              pname: this.row.permissionName,
              pstat: this.row.permissionState,
              parentId: 0,
              pcode: this.row.permissionCode,
              permissionShow: this.row.permissionShow,
              psort: this.row.permissionSort,
              piconUrl: this.row.permissionIconUrl,
            };
          });
        }
      } else if (this.title === "新增" && this.activeName === "2") {
        this.menuForm.parentId = this.checkId;
      } else {
        this.menuForm.parentId = 0;
      }
    },

    normalizer(node) {
      const children = Array.isArray(node.children) ? node.children : [];
      if (children.length === 0) {
        delete node.children;
      }
      return {
        id: node.permissionId,
        label: node.permissionName,
        children: children.length > 0 ? [...children] : undefined,
      };
    },
    submit() {
      this.$refs["addUserForm"].validate((valid) => {
        if (valid) {
          if (this.title === "编辑" && this.row) {
            updateMenuFn({
              ...this.menuForm,
              ptype: this.activeName,
              permissionId: this.row.permissionId,
            })
              .then((res) => {
                this.$message({
                  type: "success",
                  message: "编辑成功",
                });
                this.cancel();
                this.$emit("updateList");
              })
              .catch((error) => {
                this.$message({
                  type: "error",
                  message: "编辑失败",
                });
              });
          } else if (this.title === "新增") {
            addMenuFn({
              ...this.menuForm,
              purl:
                this.menuForm.purl !== null ? this.menuForm.purl : undefined,
              ptype: this.activeName,
              parentId:
                this.activeName === "1" ? undefined : this.menuForm.parentId,
            })
              .then((res) => {
                this.$message({
                  type: "success",
                  message: "新增成功",
                });
                this.cancel();
                this.$emit("updateList");
              })
              .catch((error) => {
                this.$message({
                  type: "error",
                  message: "新增失败",
                });
              });
          }
        } else {
          return false;
        }
      });
    },
    cancel() {
      this.$refs["addUserForm"].resetFields();
      this.menuForm = {
        parentId: null,
        pname: null,
        purl: null,
        pstat: null,
        pcode: null,
        psort: 0,
        permissionShow: null,
      };
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-input__prefix {
  line-height: 50px !important;
}
.demo-ruleForm {
  .el-form-item {
    margin-bottom: 25px;
  }
}
</style>
