<template>
  <el-dialog
    v-loading="loading"
    :title="title"
    :center="true"
    align="left"
    top="10vh"
    width="750px"
    :close-on-click-modal="false"
    :visible.sync="showModelThis"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
    append-to-body
    @close="showModelThis = false"
  >
    <el-card style="margin-top: -20px">
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        is_show-icon
        :rules="rulesThis"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item v-if="level < 3" label="名称：" prop="name">
              <el-input
                v-model="ruleForm.name"
                :disabled="isDetail"
                maxlength="10"
                placeholder="例如：用户管理"
              />
            </el-form-item>
            <el-form-item v-if="level === 3" label="按钮标识：" prop="code">
              <el-select
                v-model="ruleForm.code"
                placeholder="请选择按钮标识"
                clearable
                filterable
                :disabled="isDetail"
                @change="codeChange"
              >
                <el-option
                  v-for="item in btnList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
            <el-row>
              <el-col v-if="level < 3" :span="12">
                <el-form-item label="路由：" prop="route">
                  <el-input
                    v-model="ruleForm.route"
                    :disabled="isDetail"
                    maxlength="100"
                    placeholder="例如：user"
                  />
                </el-form-item>
              </el-col>
              <el-col v-if="level < 3" :span="12">
                <el-form-item label="图标：" prop="img">
                  <el-row :gutter="10">
                    <el-col v-if="ruleForm.img" :span="3" style="width: 45px">
                      <div class="g-block" >
                        <i :class="ruleForm.img" />
                      </div>
                    </el-col>
                    <el-col v-if="!ruleForm.img" :span="7">
                      <el-button type="warning" size="mini" @click="showIconModel = true">
                        选择图标
                      </el-button>
                    </el-col>
                  </el-row>
                  <iconDialog
                    :show-model="showIconModel"
                    @setVal="setVal"
                    @cancel="showIconModel = false"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item v-if="level === 2" label="页面路径：" prop="component">
              <el-input
                v-model="ruleForm.component"
                :disabled="isDetail"
                maxlength="100"
                placeholder="例如：park/user"
              >
                <template slot="prepend">views/</template>
              </el-input>
            </el-form-item>

            <el-row>
              <el-col :span="12">
                <el-form-item v-if="level < 3" label="页面状态：" prop="is_display">
                  <el-radio
                    v-model="ruleForm.is_display"
                    :label="'1'"
                    :disabled="isDetail"
                  >
                    显示
                  </el-radio>
                  <el-radio
                    v-model="ruleForm.is_display"
                    :label="'0'"
                    :disabled="isDetail"
                  >
                    隐藏
                  </el-radio>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="排序权重：" prop="weight">
                  <el-input
                    v-model.number="ruleForm.weight"
                    type="number"
                    maxlength="3"
                    :disabled="isDetail"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-form>

      <el-col :span="24" style="text-align: right; padding: 0 0 10px 0">
        <el-button v-if="!isDetail" type="primary" @click="submitForm"> 保 存 </el-button>
        <el-button @click="showModelThis = false">{{
          isDetail ? "关 闭" : "取 消"
        }}</el-button>
      </el-col>
    </el-card>
  </el-dialog>
</template>

<script>
import asyncRequest from "@/apis/service/system/setMenu";
import btnList from "@/assets/js/btnList";
import iconDialog from "@/views/system/setMenu/iconDialog";
import resToken from "@/mixins/resToken";
export default {
  components: {
    iconDialog,
  },
  mixins: [resToken],
  props: [
    "showModel",
    "id",
    "isDetail",
    "parentIds",
    "level",
    "isAdd",
    "type",
    "formData",
  ],
  data() {
    return {
      loading: false,
      showIconModel: false,
      title: "",
      btnList,
      showModelThis: this.showModel,
      ruleForm: {},
      rulesThis: this.rules,
      rules: {
        name: [
          {
            required: true,
            message: "请输入名称",
            trigger: "blur",
          },
          {
            min: 1,
            max: 50,
            message: "长度在 1 到 50 个字符",
            trigger: "blur",
          },
        ],
        code: [
          {
            required: true,
            message: "请输入按钮标识编码（用于判断按钮是否显示）",
            trigger: "change",
          },
        ],
        level: [
          {
            required: true,
            message: "请选择菜单等级",
            trigger: "change",
          },
        ],
        img: [
          {
            required: true,
            message: "请选择图标",
            trigger: "blur",
          },
        ],
        route: [
          {
            required: true,
            message: "请输入路由",
            trigger: "blur",
          },
          {
            min: 1,
            max: 50,
            message: "长度在 1 到 50 个字符",
            trigger: "blur",
          },
        ],
        component: [
          {
            required: true,
            message: "请输入页面组件路径",
            trigger: "blur",
          },

          {
            min: 1,
            max: 100,
            message: "长度在 1 到 100 个字符",
            trigger: "blur",
          },
        ],

        weight: [
          {
            required: true,
            message: "请输入权重，数值越大排名越靠前",
            trigger: "blur",
          },
        ],
        is_show: [
          {
            required: true,
            message: "请选择状态",
            trigger: "change",
          },
        ],
        is_display: [
          {
            required: true,
            message: "请选择页面状态",
            trigger: "change",
          },
        ],
      },
    };
  },
  watch: {
    showModel: function (val) {
      this.showModelThis = val;
      if (val) {
        this.initForm();
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit("cancel");
      }
    },
  },
  methods: {
    codeChange(code) {
      for (let i = 0; i < this.btnList.length; i++) {
        if (this.btnList[i].code === code) {
          this.ruleForm.name = this.btnList[i].name;
          break;
        }
      }
    },
    setVal(val) {
      this.ruleForm.img = val;
      this.$refs.ruleForm.validateField("img");
    },
    async initForm() {
      this.loading = true
      const title_type = this.isAdd ? "添加" : this.isDetail ? "查看" : "编辑",
        title_style = this.level === 1 ? "一级菜单" : "二级页面";
      this.title = title_type + title_style;
      await this.resetForm();
      if (this.isDetail) {
        this.rulesThis = {};
      } else {
        this.rulesThis = this.rules;
      }
      if(!this.isAdd){
        await this.initData();
      }
      this.loading = false;
    },
    async initData() {
      let parentIds = "";
      if (this.isAdd) {
        if (this.id === 0) {
          parentIds = "0";
        } else {
          parentIds = this.parentIds;
        }
      } else {
        parentIds = this.parentIds;
      }
      const {
        menu_name,
        menu_img,
        menu_route,
        is_show,
        weight,
        menu_url,
        is_private: is_display,
        level,
      } = this.formData;

   
        // 重置
        this.ruleForm = {
          parentId: this.id + "", // 父级ID（一级为0）
          parentIds: parentIds + "", // 所有父级编号（用逗号分隔）
          name: menu_name + "", // 名称
          code: "", // 编码（用于按钮是否显示）
          img: menu_img + "", // 图标（导航图标）
          route: menu_route + "", // 路由
          component: this.level === 1 ? "" : menu_url + "", // 页面组件
          menuCategory: 1 + "", // 菜单类别（1.导航菜单 2.按钮）
          type: this.type + "", // 类型（1.运营菜单 2.物业菜单）
          is_show: is_show + "", // 状态（1启用 0禁用）
          is_display: is_display + "",
          weight: parseInt(weight + ""), // 权重，越大越靠前
          level: String(level),
        };
        if (this.level === 1) {
          delete this.ruleForm["parentIds"];
        }
  
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.clearValidate();
        }
      });
    },
    async resetForm() {
      let parentIds = "";
      if (this.isAdd) {
        if (this.id === 0) {
          parentIds = "0";
        } else {
          parentIds = this.parentIds;
        }
      } else {
        parentIds = this.parentIds;
      }

      // 重置
      this.ruleForm = {
        parentId: this.id, // 父级ID（一级为0）
        parentIds, // 所有父级编号（用逗号分隔）
        name: "", // 名称
        code: "", // 编码（用于按钮是否显示）
        img: "", // 图标（导航图标）
        route: "", // 路由
        component: "", // 页面组件
        menu_api: "",
        menuCategory: this.level < 3 ? 1 : 2, // 菜单类别（1.导航菜单 2.按钮）
        type: this.type + "", // 类型（1.运营菜单 2.物业菜单）
        is_show: "1", // 状态（1启用 0禁用）
        is_display: "1", // 页面状态（1显示 0隐藏）
        weight: 1, // 权重，越大越靠前
      };
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.clearValidate();
        }
      });
    },
    async submitForm() {
      if (this.loading) {
        return false;
      }
      this.loading = true;

      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          let model = {};
          let res = {};
          const {
            name,
            img,
            route,
            is_show,
            is_display,
            weight,
            component,
            menu_api,
          } = this.ruleForm;

          model = {
            id: this.id,
            pid: this.parentIds,
            menuid: this.parentIds,
            action_name: name,
            name,
            img: img,
            is_show: is_show,
            weight: weight,
            route: route,
            private: is_display,
            url: component,
            menu_api: menu_api,
            status: is_show,
            level: 0,
          };

          if (this.level === 1) {
            model["menu_name"] = model["name"];
            model["menu_type"] = "1";
            model["menu_img"] = model["img"];
            model["menu_route"] = model["route"];
            delete model["route"];
            delete model["img"];
            delete model["pid"];
            delete model["name"];
            delete model["menuid"];
            delete model["url"];
            delete model["status"];
          } else if (this.level === 2) {
            model["menu_name"] = model["name"];
            model["menu_type"] = "2";
            model["menu_img"] = model["img"];
            model["menu_route"] = model["route"];
            model["menu_url"] = model["url"];
            delete model["route"];
            delete model["url"];
            delete model["img"];
            delete model["name"];
            delete model["menuid"];
           
            delete model["status"];
          } 

          if (this.isAdd) {
            delete model["id"];
          }

            if (this.isAdd) {
              res = await asyncRequest.create(model);
            } else {
              res = await asyncRequest.update(model);
            }
          this.loading = false;
          const {code}=res
          if (code === 1) {
            this.ruleForm = {};
            const title = this.isAdd ? "添加成功" : "修改成功";
            this.$notify.success({
              title,
              message: "",
            });
            this.showModelThis = false;
            let pids = this.parentIds;
            if (this.id === 0) {
              pids = "0";
            }
            this.$emit("refresh", this.id, pids, this.level, this.isAdd, this.parentIds);
          }
        } else {
          this.loading = false;
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.g-block {
  display: inline-block;
  padding: 10px 5px;
  text-align: center;
  border: 1px #ccc dashed;
  margin: 1px;
  font-size: 0px;
  cursor: pointer;
  i {
    font-size: 30px;
    line-height: 30px;
    display: block;
    margin: 0 auto;
    width: 30px;
  }
}
</style>
