<template>
  <base-model :config="model_cfg">
    <template slot="dialog-body">
      <el-form
        ref="roleForm"
        v-loading="dict.type.UserTypeGroup.length === 0"
        :rules="rules"
        :model="form"
        class="demo-ruleForm"
        size="small"
        label-width="120px"
      >
        <el-form-item label="User Type: " prop="UserTypeName">
          <el-input :maxLength="$inputMax" v-model="form.UserTypeName" />
        </el-form-item>
        <el-form-item label="Shortname: " prop="UserTypeShortName">
          <el-input :maxLength="$inputMax" v-model="form.UserTypeShortName" />
        </el-form-item>
        <el-form-item label="是否内部角色: " prop="IsInternal">
          <el-radio-group v-model="form.IsInternal">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="Group: " prop="UserTypeGroupIdList">
          <el-select v-model="form.UserTypeGroupIdList" multiple>
            <el-option
              v-for="item of dict.type.UserTypeGroup"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="Order: ">
          <el-input-number v-model="form.Order" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="PermissionStr: " prop="PermissionStr">
          <el-input :maxLength="$inputMax" v-model="form.PermissionStr" />
        </el-form-item>
        <el-form-item label="Description: " prop="Description">
          <el-input :maxLength="$inputMax" v-model="form.Description" type="textarea" :rows="5" />
        </el-form-item>
        <el-form-item label="role: ">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event)">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event)">全选/全不选</el-checkbox>
          <el-checkbox v-model="form.menuCheckStrictly" @change="handleCheckedTreeConnect($event)">父子联动</el-checkbox>
          <el-tree
            ref="menu"
            class="tree-border"
            :check-strictly="!form.menuCheckStrictly"
            :data="menuOptions"
            show-checkbox
            node-key="MenuId"
            empty-text="加载中，请稍后"
            :props="defaultProps"
          />
          <!--:check-strictly="!form.deptCheckStrictly"-->
        </el-form-item>
      </el-form>
    </template>
    <template slot="dialog-footer">
      <el-button :disabled="btnLoading" size="small" type="primary" @click="model_cfg.visible = false">Cancel
      </el-button>
      <el-button size="small" type="primary" :loading="btnLoading" @click="handleSave">Save</el-button>
    </template>
  </base-model>
</template>
<script>
import { addOrUpdateUserType } from '@/api/admin'
// import { addOrUpdateUserType } from '@/api/system/role'
// import { getMenuList } from '@/api/system/menu'
import { getMenuList } from '@/api/system/menu'
import { model_cfg } from '../role'
import BaseModel from '@/components/BaseModel'

export default {
  components: { BaseModel },
  dicts: ['UserTypeGroup'],
  props: {
    data: {
      type: Object,
      default() {
        return {
          Id: '',
          UserTypeName: '',
          IsInternal: true,
          UserTypeShortName: '',
          Order: '',
          Description: '',
          PermissionStr: ''
        }
      }
    }
  },
  data() {
    return {
      menuExpand: false,
      menuNodeAll: false,
      userTypeGroupOptions: [{ value: 1, label: 'Trial' }, { value: 2, label: 'Reviewer' }, { value: 3, label: 'Other' }],
      model_cfg,
      defaultProps: {
        children: 'Children',
        label: 'MenuName'
      },
      form: {
        Id: '',
        UserType: '',
        IsInternal: true,
        UserTypeShortName: '',
        Type: null,
        Description: '',
        UserTypeGroupIdList: [],
        menuCheckStrictly: true
      },
      rules: {
        UserTypeName: [{ required: true, message: '请注明', trigger: 'blur' }, {
          max: 50,
          message: '最大长度为 50'
        }],
        UserTypeShortName: [{ required: true, message: '请注明', trigger: 'blur' }, {
          max: 50,
          message: '最大长度为 50',
          trigger: 'blur'
        }],
        Description: [{ max: 500, message: '最大长度为 500' }],
        UserTypeGroupIdList: [{ required: true, message: '请注明', trigger: 'blur' }]
      },
      menuOptions: [],
      btnLoading: false
    }
  },
  mounted() {
    this.getMenuList()
    if (Object.keys(this.data).length && this.data.Id) {
      this.form = { ...this.data }
    }
  },
  methods: {
    handleCheckedTreeConnect(value) {
      this.form.menuCheckStrictly = !!value
    },
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      const checkedKeys = this.$refs.menu.getCheckedKeys()
      // 半选中的菜单节点
      const halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },

    handleCheckedTreeExpand(value) {
      const treeList = this.menuOptions
      for (let i = 0; i < treeList.length; i++) {
        this.$refs.menu.store.nodesMap[treeList[i].MenuId].expanded = value
      }
    },
    handleCheckedTreeNodeAll(value, type) {
      this.$refs.menu.setCheckedNodes(value ? this.menuOptions : [])
    },
    toTree(arr, ParentId) {
      function loop(ParentId) {
        const res = []
        for (let i = 0; i < arr.length; i++) {
          const item = arr[i]
          item.hasChildren = false
          if (item.ParentId !== ParentId) {
            continue
          }
          item.Children = loop(item.MenuId)
          res.push(item)
        }
        return res
      }

      return loop(ParentId)
    },
    getMenuList() {
      getMenuList({}).then(res => {
        const menu = this.toTree(res.Result, '00000000-0000-0000-0000-000000000000')
        this.menuOptions = menu
        this.form.MenuIds.forEach(v => {
          this.$nextTick(() => {
            this.$refs.menu.setChecked(v, true, false)
          })
        })
      }).catch(function() {
      })
    },
    handleSave() {
      this.$refs.roleForm.validate(valid => {
        if (!valid) return
        this.btnLoading = true
        this.model_cfg.showClose = false
        this.form.MenuIds = this.getMenuAllCheckedKeys()
        console.log(this.form.MenuIds)
        addOrUpdateUserType(this.form).then(res => {
          this.btnLoading = false
          this.$refs['roleForm'].resetFields()
          this.$emit('close')
          this.model_cfg.showClose = true
          this.$message.success(this.$t('common:message:savedSuccessfully'))
        }).catch(() => {
          this.btnLoading = false
          this.model_cfg.showClose = true
        })
      })
    }
  }
}
</script>
