<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" @click="showIconModel = true">
                        <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 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-col>
              <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-row>

            <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"
                    maxlength="10"
                    :disabled="isDetail"
                  />
                </el-col>
                <el-col :span="7">
                  <el-tag type="danger">数值越大排名越靠前</el-tag>
                </el-col>
              </el-row>
            </el-form-item>

            <el-form-item v-if="level < 3" label="菜单等级" prop="level">
              <el-select v-model="ruleForm.level">
                <el-option label="超管" value="1" />
                <el-option label="运营" value="2" />
                <el-option label="其他" value="3" />
              </el-select>
            </el-form-item>

          </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/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: '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() {
      if (this.isAdd) {
        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 {
        if (this.isDetail) {
          if (this.level === 1) {
            this.title = '一级菜单详情'
          } else if (this.level === 2) {
            this.title = '二级菜单详情'
          } else {
            this.title = '按钮详情'
          }
          this.rulesThis = {}
        } else {
          if (this.level === 1) {
            this.title = '修改一级菜单'
          } else if (this.level === 2) {
            this.title = '修改二级菜单'
          } else {
            this.title = '修改按钮'
          }
          this.rulesThis = this.rules
        }
        await this.initData()
      }
    },
    async initData() {
      this.loading = true
      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,
        status,
        menu_url,
        menuid,
        action_name,
        action_code,
        is_display,
        level
      } = this.formData

      if (this.level !== 3) {
        // 重置
        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']
        }
      } else {
        this.ruleForm = {
          parentId: this.id + '', // 父级ID（一级为0）
          parentIds: menuid + '', // 所有父级编号（用逗号分隔）
          name: action_name + '', // 名称
          code: action_code + '', // 编码（用于按钮是否显示）
          img: '', // 图标（导航图标）
          route: '', // 路由
          component: '', // 页面组件
          menuCategory: 2 + '', // 菜单类别（1.导航菜单 2.按钮）
          type: this.type + '', // 类型（1.运营菜单 2.物业菜单）
          is_show: status + '', // 状态（1启用 0禁用）
          weight: 1 + '' // 权重，越大越靠前
        }
      }
      this.loading = false
      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: '', // 页面组件
        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,
            code,
            level
          } = 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,
            is_display: is_display,
            url: component,
            action_code: code,
            status: is_show,
            level
          }

          if (this.level === 1) {
            delete model['pid']
            delete model['menuid']
            delete model['url']
            delete model['action_code']
            delete model['action_name']
            delete model['status']
          } else if (this.level === 2) {
            delete model['menuid']
            delete model['action_code']
            delete model['action_name']
            delete model['status']
          } else {
            delete model['pid']
            delete model['img']
            delete model['is_show']
            delete model['weight']
            delete model['route']
            delete model['is_display']
            delete model['url']
            delete model['name']
          }

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

          if (this.level < 3) {
            res = await asyncRequest.update(model)
          } else {
            if (this.isAdd) {
              res = await asyncRequest.actionadd(model)
            } else {
              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
          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>
