<template>
  <el-dialog
    v-loading="loading"
    :title="title"
    :center="true"
    align="left"
    top="5vh"
    width="900px"
    :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="closeModel"
  >
    <el-card>
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form
            ref="ruleForm"
            :model="ruleForm"
            is_show-icon
            :rules="rulesThis"
            label-width="130px"
            class="demo-ruleForm"
          >
            <el-form-item v-if="level < 3" label="名称：" prop="name">
              <el-input
                v-model="ruleForm.name"
                :disabled="isDetail"
                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-form-item v-if="level < 3" label="图标：" prop="img">
              <el-row :gutter="10">
                <el-col v-show="ruleForm.img" :span="3" style="width: 45px">
                  <div class="g-block" @click="showIconModel = true">
                    <i :class="ruleForm.img" />
                  </div>
                </el-col>
                <el-col v-show="!ruleForm.img" :span="7">
                  <el-button
                    type="warning"
                    size="mini"
                    @click="showIconModel = true"
                  >
                    选择图标
                  </el-button>
                </el-col>
              </el-row>
              <iconDialog
                :show-model="showIconModel"
                @setVal="(val) => (ruleForm.img = val)"
                @cancel="showIconModel = false"
              />
            </el-form-item>
            <el-form-item v-if="level < 3" label="路由：" prop="route">
              <el-input
                v-model="ruleForm.route"
                :disabled="isDetail"
                placeholder="例如：user"
              />
            </el-form-item>
            <el-form-item
              v-if="level === 2"
              label="页面组件路径："
              prop="component"
            >
              <el-input
                v-model="ruleForm.component"
                :disabled="isDetail"
                placeholder="例如：park/user"
              >
                <template slot="prepend">views/</template>
              </el-input>
            </el-form-item>
            <el-form-item label="状态：" prop="is_show">
              <el-radio
                v-model="ruleForm.is_show"
                :label="'1'"
                :disabled="isDetail"
              >
                启用
              </el-radio>
              <el-radio
                v-model="ruleForm.is_show"
                :label="'0'"
                :disabled="isDetail"
              >
                禁用
              </el-radio>
            </el-form-item>
            <el-form-item v-if="level < 3" label="排序权重：" prop="weight">
              <el-row :gutter="10">
                <el-col :span="16" style="padding: 0">
                  <el-input
                    v-model.number="ruleForm.weight"
                    type="number"
                    :disabled="isDetail"
                  />
                </el-col>
                <el-col :span="7">
                  <el-tag type="danger">数值越大排名越靠前</el-tag>
                </el-col>
              </el-row>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="24" style="text-align: right">
          <el-button v-if="!isDetail" type="primary" @click="submitForm">
            保 存
          </el-button>
          <el-button @click="showModelThis = false">{{
            isDetail ? "关 闭" : "取 消"
          }}</el-button>
        </el-col>
      </el-row>
    </el-card>
  </el-dialog>
</template>

<script>
import asyncRequest from "@/apis/service/system/menu";
import btnList from "@/assets/js/btnList";
import iconDialog from "@/views/system/menuOperator/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: "blur",
          },
          {
            min: 1,
            max: 50,
            message: "长度在 1 到 50 个字符",
            trigger: "blur",
          },
        ],
        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",
          },
          // {
          //   validator: this.$positiveInteger,
          //   trigger: "blur"
          // }
        ],
        is_show: [
          {
            required: true,
            message: "请选择状态",
            trigger: "change",
          },
        ],
      },
    };
  },
  watch: {
    showModel: function (val) {
      this.showModelThis = val;
      if (val) {
        this.initForm();
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit("cancel");
      }
    },
  },
  methods: {
    closeModel() {
      console.log("closeModel!!");
    },
    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;
        }
      }
    },
    async initForm() {
      console.log(this.id, this.parentIds, this.level);
      if (this.isAdd) {
        // this.title = "添加";
        if (this.level === 1) {
          this.title = "添加一级菜单";
        } else if (this.level === 2) {
          this.title = "添加二级菜单";
        } else {
          this.title = "添加按钮";
        }
        this.loading = false;
        this.rulesThis = this.rules;
        await this.resetForm();
      } else {
        console.log(this.isDetail);
        if (this.isDetail) {
          // this.title = "资源详情";
          if (this.level === 1) {
            this.title = "一级菜单详情";
          } else if (this.level === 2) {
            this.title = "二级菜单详情";
          } else {
            this.title = "按钮详情";
          }
          this.rulesThis = {};
        } else {
          // this.title = "修改";
          if (this.level === 1) {
            this.title = "修改一级菜单";
          } else if (this.level === 2) {
            this.title = "修改二级菜单";
          } else {
            this.title = "修改按钮";
          }
          this.rulesThis = this.rules;
        }
        // await this.resetForm();
        await this.initData(this.id);
      }
    },
    async initData(id) {
      console.log(this.formData);
      this.loading = true;
      let parentIds = "";
      if (this.isAdd) {
        if (this.id === 0) {
          // 添加一级菜单
          parentIds = "0";
        } else {
          console.log(this.parentIds);
          // 添加非一级菜单
          parentIds = this.parentIds;
          // + "," + this.id;
        }
      } else {
        console.log(this.parentIds);
        // 修改
        parentIds = this.parentIds;
      }

      if (this.level === 1) {
        // 重置
        this.ruleForm = {
          parentId: this.id, // 父级ID（一级为0）
          // parentIds, // 所有父级编号（用逗号分隔）
          name: this.formData.menu_name, // 名称
          code: "", // 编码（用于按钮是否显示）
          img: this.formData.menu_img, // 图标（导航图标）
          route: this.formData.menu_route, // 路由
          component: "", // 页面组件
          menuCategory: this.level < 3 ? 1 : 2, // 菜单类别（1.导航菜单 2.按钮）
          type: this.type, // 类型（1.运营菜单 2.物业菜单）
          is_show: this.formData.is_show, // 状态（1启用 0禁用）
          weight: parseInt(this.formData.weight), // 权重，越大越靠前
        };
      } else if (this.level === 2) {
        this.ruleForm = {
          parentId: this.id, // 父级ID（一级为0）
          parentIds: this.parentIds, // 所有父级编号（用逗号分隔）
          name: this.formData.menu_name, // 名称
          code: "", // 编码（用于按钮是否显示）
          img: this.formData.menu_img, // 图标（导航图标）
          route: this.formData.menu_route, // 路由
          component: this.formData.menu_url, // 页面组件
          menuCategory: this.level < 3 ? 1 : 2, // 菜单类别（1.导航菜单 2.按钮）
          type: this.type, // 类型（1.运营菜单 2.物业菜单）
          is_show: this.formData.is_show, // 状态（1启用 0禁用）
          weight: parseInt(this.formData.weight), // 权重，越大越靠前
        };
      } else {
        this.ruleForm = {
          parentId: this.id, // 父级ID（一级为0）
          parentIds: this.formData.menuid, // 所有父级编号（用逗号分隔）
          name: this.formData.action_name, // 名称
          code: this.formData.action_code, // 编码（用于按钮是否显示）
          img: "", // 图标（导航图标）
          route: "", // 路由
          component: "", // 页面组件
          menuCategory: this.level < 3 ? 1 : 2, // 菜单类别（1.导航菜单 2.按钮）
          type: this.type, // 类型（1.运营菜单 2.物业菜单）
          is_show: this.formData.status, // 状态（1启用 0禁用）
          weight: 1, // 权重，越大越靠前
        };
      }
      console.log(this.ruleForm);
      // // let res = await asyncRequest.detail({ id });
      this.loading = false;
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          // 去掉验证信息
          this.$refs.ruleForm.clearValidate();
        }
      });
      // if (res.code === 0) {
      //   this.ruleForm = res.data;
      // }
    },
    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: "", // 页面组件
        menuCategory: this.level < 3 ? 1 : 2, // 菜单类别（1.导航菜单 2.按钮）
        type: this.type, // 类型（1.运营菜单 2.物业菜单）
        is_show: "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) {
          console.log(this.ruleForm);
          console.log(this.parentIds);
          // let obj = JSON.parse(JSON.stringify(this.ruleForm));
          let model = {};
          let res = {};
          if (this.level === 1) {
            model = {
              id: this.id,
              name: this.ruleForm.name,
              img: this.ruleForm.img,
              route: this.ruleForm.route, // 路由
              is_show: this.ruleForm.is_show,
              weight: this.ruleForm.weight,
            };
          } else if (this.level === 2) {
            model = {
              id: this.id,
              pid: this.parentIds,
              name: this.ruleForm.name,
              img: this.ruleForm.img,
              is_show: this.ruleForm.is_show,
              weight: this.ruleForm.weight,
              route: this.ruleForm.route,
              url: this.ruleForm.component,
            };
          } else {
            model = {
              id: this.id,
              menuid: this.parentIds,
              action_code: this.ruleForm.code,
              name: this.ruleForm.name,
              status: this.ruleForm.is_show,
            };
          }
          console.log(1234567890);
          console.log(this.isAdd);
          if (this.isAdd) {
            delete model["id"];
          }
          console.log(model);
          if (this.level < 3) {
            console.log(111);

            res = await asyncRequest.update(model);
          } else {
            if (this.isAdd) {
              console.log(222);

              res = await asyncRequest.actionadd(model);
            } else {
              console.log(333);
              res = await asyncRequest.actionedit(model);
            }
          }
          this.loading = false;
          if (res && res.code === 0) {
            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);
          } else if (res && res.code >= 100 && res.code <= 104) {
            await this.logout();
          } else {
            this.$message.warning(res.message);
          }
        } else {
          this.loading = false;
          console.log("error submit!!");
          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>
