<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="130px"
      >
        <el-form-item label="User Type: " prop="UserTypeName">
          <el-input v-model="form.UserTypeName" />
        </el-form-item>
        <el-form-item label="Shortname: " prop="UserTypeShortName">
          <el-input v-model="form.UserTypeShortName" />
        </el-form-item>
        <!-- <el-form-item
          :label="$t('system:role:form:isInternal')"
          prop="IsInternal"
        >
          <el-radio-group v-model="form.IsInternal">
            <el-radio
              v-for="item of $d.YesOrNo"
              :key="`IsInternal${item.value}`"
              :label="item.value"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item> -->
        <el-form-item :label="$t('system:role:form:IsEnable')" prop="IsEnable">
          <el-switch
            v-model="form.IsEnable"
            active-color="#13ce66"
            inactive-color="#dcdfe6"
            :active-value="true"
            :inactive-value="false"
            :active-text="$fd('IsEnable', true)"
            :inactive-text="$fd('IsEnable', false)"
          >
          </el-switch>
        </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 v-model="form.PermissionStr" />
        </el-form-item>
        <el-form-item label="User Type Enum: " prop="UserTypeEnum">
          <el-select v-model="form.UserTypeEnum">
            <el-option
              v-for="item of $d.UserType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="Description: " prop="Description">
          <el-input v-model="form.Description" type="textarea" :rows="5" />
        </el-form-item>
        <el-form-item label="role: ">
          <el-checkbox
            v-model="menuExpand"
            @change="handleCheckedTreeExpand($event)"
            >{{ $t('system:role:form:checkbox:menuExpand') }}</el-checkbox
          >
          <el-checkbox
            v-model="menuNodeAll"
            @change="handleCheckedTreeNodeAll($event)"
            >{{ $t('system:role:form:checkbox:menuNodeAll') }}</el-checkbox
          >
          <el-checkbox
            v-model="form.menuCheckStrictly"
            @change="handleCheckedTreeConnect($event)"
            >{{
              $t('system:role:form:checkbox:menuCheckStrictly')
            }}</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: '',
          UserTypeEnum: null,
          IsEnable: true,
        }
      },
    },
  },
  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,
        IsEnable: true,
      },
      rules: {
        UserTypeName: [
          { required: true, message: 'Please specify', trigger: 'blur' },
          {
            max: 50,
            message: 'The maximum length is 50',
          },
        ],
        UserTypeShortName: [
          { required: true, message: 'Please specify', trigger: 'blur' },
          {
            max: 50,
            message: 'The maximum length is 50',
            trigger: 'blur',
          },
        ],
        Description: [{ max: 500, message: 'The maximum length is 500' }],
        UserTypeGroupIdList: [
          { required: true, message: 'Please specify', trigger: 'blur' },
        ],
        UserTypeEnum: [
          { required: true, message: 'Please select', 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
          console.log(this.menuOptions)
          this.$nextTick(() => {
            this.form.MenuIds.forEach((v) => {
              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('Saved successfully!')
          })
          .catch(() => {
            this.btnLoading = false
            this.model_cfg.showClose = true
          })
      })
    },
  },
}
</script>
