<template>
  <a-modal
    title="新增菜单"
    :width="1000"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :destroyOnClose="true"
  >
    <a-spin :spinning="formLoading">
      <a-form-model ref="ruleForm" :model="form" :rules="rules" >
        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-model-item
              label="菜单名称"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              hasFeedback
              prop="name"
            >
              <a-input v-model="form.name" />
            </a-form-model-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-model-item
              style="width: 100%"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="菜单编号"
              hasFeedback
              prop="code"
            >
              <a-input v-model="form.code" />
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="菜单层级"
              prop="type"
            >
              <a-radio-group v-model="form.type" >
                <a-radio :value="0" @click="meneTypeFunc(0)">目录</a-radio>
                <a-radio :value="1" @click="meneTypeFunc(1)">菜单</a-radio>
                <a-radio :value="2" @click="meneTypeFunc(2)">按钮</a-radio>
              </a-radio-group>
            </a-form-model-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <div v-show="pidShow">
              <a-form-model-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="父级菜单"
                has-feedback
                prop="pid"
              >
                <a-tree-select
                  v-model="form.pid" 
                  style="width: 100%"
                  :dropdownStyle="{ maxHeight: '300px', overflow: 'auto' }"
                  :treeData="menuTreeData"
                  placeholder="请选择父级菜单"
                  treeDefaultExpandAll
                  :replaceFields="{
                    children:'children',
                    title:'name',
                    key:'id',
                    value:'id'
                  }"
                >
                  <span slot="title" slot-scope="{ id }">{{ id }}
                  </span>
                </a-tree-select>
              </a-form-model-item>
            </div>
          </a-col>
        </a-row>

        <a-row :gutter="24" >
          <a-col :md="12" :sm="24">
            <div v-show="componentShow">
              <a-form-model-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                hasFeedback
                prop="component"
              >
                <span slot="label">
                  <a-tooltip title="前端vue组件 views文件夹下路径，例：system/menu/index。注：目录级填写：RouteView(不带面包屑)，PageView(带面包屑)，菜单级内链打开http链接填写：Iframe">
                    <a-icon type="question-circle-o" />
                  </a-tooltip>&nbsp;
                  前端组件
                </span>
                <a-input placeholder="请输入前端组件" :disabled="componentDisabled" v-model="form.component"/><!-- ,{rules: [{required: componentRequired, min: 1, message: '请输入前端组件！'}]}  -->
              </a-form-model-item>
            </div>
          </a-col>
          <a-col :md="12" :sm="24">
            <div v-show="routerShow">
              <a-form-model-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                hasFeedback
                prop="router"
              >
                <span slot="label">
                  <a-tooltip title="浏览器显示的URL，例：/menu，对应打开页面为菜单页面">
                    <a-icon type="question-circle-o" />
                  </a-tooltip>&nbsp;
                  路由地址
                </span>
                <a-input placeholder="请输入路由" v-model="form.router" />
              </a-form-model-item>
            </div>
            <div v-show="permissionShow">
              <a-form-model-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="权限标识"
                hasFeedback
                prop="permission"
              >
                <a-input placeholder="请输入权限标识" v-model="form.permission" />
              </a-form-model-item>
            </div>
          </a-col>
        </a-row>

        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="是否可见"
              prop="visible"
            >
              <a-switch checked-children="开" un-checked-children="关" default-checked v-model="form.visible"/><!-- defaultChecked -->
            </a-form-model-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="排序"
              prop="intCode"
            >
              <a-input-number style="width: 100%" v-model="form.intCode" />
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row :gutter="24">
          
          <a-col :md="12" :sm="24">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="备注"
              hasFeedback
              prop="remark"
            >
              <a-input v-model="form.remark"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>

      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>
  import { menuTree, menuAdd, menuEdit } from '@/api/security/menu'
  export default {

    data () {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        form: {
          name: '',
          code: '',
          pid: '',
          type: 1,
          router: '',
          component: '',
          permission: '',
          visible: true,
          intCode: 0,
          remark: ''
        },
        rules: {
          name: [{ required: true, message: '请输入用户名', trigger: 'blur' }, { min: 5, message: '长度不能小于5', trigger: 'blur' }],
          code: [{ required: true, message: '请输入姓名', trigger: 'blur' }, { min: 2, message: '长度不能小于5', trigger: 'blur' }]
        },
        visible: false,
        confirmLoading: false,
        menuTreeData: [],
        componentShow: true,
        componentDisabled: false,
        componentRequired: true,
        routerRequired: true,
        routerShow: true,
        pidShow: true,
        permissionShow: true,
        permissionRequired: true,
        formLoading: true
      }
    },

    methods: {
      // 新增打开页面初始化
      add (type) {
        this.visible = true

        // 默认选中菜单项，并初始化
        this.meneTypeFunc(1)

        // 默认加载菜单树
        this.getMenuTree()

        this.formLoading = false
      },
      // 编辑打开页面初始化
      edit (record) {
        this.visible = true
        
        // 默认选中菜单项，并初始化
        this.meneTypeFunc(record.type)
        
        setTimeout(() => {
           // 默认加载菜单树
           this.getMenuTree()
           
           this.form = record
           // 默认选中的单选框
           this.form.visible = record.visible === 1
           
           this.formLoading = false
        }, 100)
      },
      getMenuTree () {
        menuTree().then((res) => {
          if (res.code == 200) {
            this.form.pid = ''
            this.menuTreeData = [{
              'id': '-1',
              'parentId': '0',
              'name': '顶级',
              'value': '0',
              'pid': '0',
              'children': res.data
            }]
            console.log(this.menuTreeData)
          } else {
            this.$message.warning(res.msg)
          }
        })
      },
      /**
       * 选择菜单类型执行初始化表单变量
       */
      meneTypeFunc (type) {
        if (type === 0 || type === 1) {
          // 路由必填，设置空值，并显示
          this.routerRequired = true
          this.routerShow = true
          this.form.router = ''
          // 权限标识框隐藏，选填，给空值
          this.permissionShow = false
          this.permissionRequired = false
          this.form.permission = ''
        }
        // eslint-disable-next-line eqeqeq
        if (type === 0) {
          // 组件默认为显示，设置可输入，给默认组件 PageView，验证必填
          this.componentShow = true
          this.componentDisabled = false
          
          this.form.component = 'PageView'
          this.componentRequired = true
          // 父级初始化顶级，并将其隐藏
          this.form.pid = 0
          this.pidShow = false
        } else {
          // eslint-disable-next-line eqeqeq
          if (type === 1) {
            // 组件可以手输，取消值
            this.componentDisabled = false
            this.form.component = ''
          }
          // 父级选择放开
          this.pidShow = true
        }
        // eslint-disable-next-line eqeqeq
        if (type === 2) {
          // 组件设置不填，不可输入，并给空（手输的跟设置的）
          this.componentRequired = false
          this.componentDisabled = true
          // this.form.resetFields(`component`, []) 不懂
          this.form.component = ''
          // 路由选填，设置空值，并隐藏
          this.routerRequired = true
          this.form.router = ''
          this.routerShow = false
          // 权限标识框显示，必填，给空值
          this.permissionShow = true
          this.permissionRequired = true
          this.form.permission = ''
        }
      },
      handleSubmit () {
        this.$refs.ruleForm.validate(valid => {
          if (valid) {
            if (this.form.visible) {
              this.form.visible = 1
            } else {
              this.form.visible = 0
            }
            if (this.form.id) {
              menuAdd(this.form).then((res) => {
                this.confirmLoading = false
                if (res.code == 200) {
                  this.$message.success('新增成功')
                  this.$emit('ok', this.form)
                  this.handleCancel()
                } else {
                  this.$message.error('新增失败：' + res.msg)
                }
              }).finally((res) => {
                this.confirmLoading = false
              })
            } else {
              menuEdit(this.form).then((res) => {
                this.confirmLoading = false
                if (res.code == 200) {
                  this.$message.success('新增成功')
                  this.$emit('ok', this.form)
                  this.handleCancel()
                } else {
                  this.$message.error('新增失败：' + res.msg)
                }
              }).finally((res) => {
                this.confirmLoading = false
              })
            } 
          } else {
            return false
          }
        })
      },
      handleCancel () {
        this.$refs.ruleForm.resetFields()
        delete this.form.id
        this.confirmLoading = false
        this.visible = false
      }
    }
  }
</script>
