<template>
  <div v-loading="loading">
    <baseTitle title="角色信息录入"></baseTitle>
    <fvForm :schema="schame" @getInstance="getInstance" :rules="rules"></fvForm>
    <div class="assign-menu-title" >
      <baseTitle title="分配菜单"></baseTitle>
      <fvSelect
        :options="localData.tempRoleOpt"
        v-model="localData.tempRoleSelect"
        style="width: 200px;"
        placeholder="请选择模版角色"
        @change="roleTempChange"
      />
    </div>
    <fvCheckbox :options="localData.checkOptions" v-model="localData.checkList" @change="checkBoxChange" />
    <el-input v-model="localData.filterText" placeholder="请输入关键词" style="width: 400px;" />
    <div class="menu-assign">
      <el-tree
        ref="menuTree"
        :data="localData.menuData"
        :filter-node-method="filterMenu"
        :props="localData.menuTreeProps"
        :check-strictly="!localData.checkStrictly"
        show-checkbox
        node-key="value"
        @check-change="checkChange"
      />
    </div>
    <div class="oper-page-btn">
      <el-button color="#DED0B2" @click="handleSubmit">提交</el-button>
      <el-button  @click="handleBack">返回</el-button>
    </div>
  </div>
</template>

<script setup lang="jsx">
import { useTagsView } from '@/stores/tagsview.js'
import { useAuthStore } from '@/stores/userstore.js'
import fvRadio from '@/fvcomponents/fvRadio/index.vue'
import { ElLoading, ElNotification } from 'element-plus';
import { getMenuOptRole } from '@/api/system/menuman.js'
import { getRoleDetail, operate, getTemRoleOption } from "@/api/role/role";

const tagsViewStore = useTagsView()
const authStore = useAuthStore()
const route = useRoute()

const form = ref(null)
const menuTree = ref(null)
const loading = ref(false)

const isExpand = ref('展开')
const isAllChose = ref('全选')
const localData = reactive({
  filterText: '',
  menuData: [],
  menuTreeProps: {
    value: "value",
    label: 'label',
    children: 'children'
  },
  checkStrictly: true,
  checkList: ['3'],
  checkOptions: [
    {
      label: isExpand.value,
      value: '1'
    },
    {
      label: isAllChose.value,
      value: '2'
    },
    {
      label: '父子联动',
      value: '3'
    },
  ],
  tempRoleOpt: [],
  tempRoleSelect: ''
})

const schame = computed(()=>{
  let arr = [
    {
      label: '角色名称',
      prop: 'roleName',
      component: 'el-input',
      props: {
        placeholder: '请输入'
      }
    },
    {
      label: '角色标识',
      prop: 'roleKey',
      component: 'el-input',
      props: {
        placeholder: '请输入'
      }
    },
    {
      label: '显示顺序',
      prop: 'roleSort',
      component: 'el-input',
      props: {
        placeholder: '请输入',
        type: 'number'
      }
    },
    {
      label: '状态',
      prop: 'state',
      component: markRaw(fvRadio),
      props: {
        cacheKey: 'normal_disable'
      }
    },
    {
      label: '是否为模版',
      prop: 'template',
      component: markRaw(fvRadio),
      props: {
        options: [
          { label: '是', value: true },
          { label: '否', value: false },
        ]
      }
    },
  ]
  return !authStore.roles.includes('superAdmin') ? arr.slice(0, arr.length - 1) : arr
})

const rules = reactive({
  roleName: [{required: true, message: '请输入', trigger: 'change'}],
  roleKey: [{required: true, message: '请输入', trigger: 'change'}],
  roleSort: [{required: true, message: '请输入', trigger: 'change'}],
})

const getInstance = (e) => {
  form.value = e
}

const init = async () => {
  form.value.setValues({state: '1', template: false})
  const res = await getTemRoleOption()
  localData.tempRoleOpt = res.data
  const { data } = await getMenuOptRole(0)
  localData.menuData = data.menuOption
  // localData.checked = data.checked
}

const getInfo = async () => {
  if(!route.query.id) return
  const { data } = await getRoleDetail(route.query.id)
  data.menuIds.forEach(key=>{
    menuTree.value.setChecked(key, true, false)
  })
  form.value.setValues(data)
}

const roleTempChange = async (val) => {
  try {
    loading.value = true
    const { data } = await getRoleDetail(val.value)
    data.menuIds.forEach(key=>{
      menuTree.value.setChecked(key, true, false)
    })
    delete data.roleId
    delete data.roleName
    delete data.roleKey
    form.value.setValues(data)
    loading.value = false
  } catch (error) {
    loading.value = false
  }

}

const filterMenu = (value, data) => {
  if(!value) return true
  return data.menuName.includes(value)
}

const checkChange = (data) => {
  // 获取已选
  const checkedKeys = menuTree.value.getCheckedKeys()
  // 获取半选
  const halfCheckedKeys = menuTree.value.getHalfCheckedKeys()
  return [...checkedKeys, ...halfCheckedKeys]
}

const checkBoxChange = (val) => {
  localData.checkStrictly = val.includes('3')
  let nodes = menuTree.value.store.nodesMap
  if (val.includes('1')) {
    for (const node in nodes) {
      nodes[node].expanded = true;
    }
    isExpand.value = '折叠'
  } else {
    for (const node in nodes) {
      nodes[node].expanded = false;
    }
    isExpand.value = '展开'
  }
  if (val.includes('2')) {
    menuTree.value.setCheckedNodes(localData.menuData)
    isAllChose.value = '不全选'
  } else {
    menuTree.value.setCheckedNodes([])
    isAllChose.value = '全选'
  }
}

const handleSubmit = async () => {
  const loading = ElLoading.service({fullscreen: true})
  const { isValidate } = await form.value.validate()
  if(!isValidate){
    loading.close()
    return Promise.reject()
  }
  const values = form.value.getValues()
  values.menuIds = checkChange()
  operate(values).then(res=>{
    ElNotification({
      title: route.query.isAdd ? '新增' : '编辑',
      message: res.msg,
      type: res.code === 1000 ? 'success' : 'error'
    })
    loading.close()
    res.code === 1000 ? tagsViewStore.delViewAndGoView('/system/role') : null
  }).finally(()=>{
    loading.close()
  })
}

const handleBack = () => {
  history.back()
}

watch(localData, (val)=>{
  menuTree.value.filter(val.filterText)
})

onMounted( async ()=>{
  loading.value = true
  await init()
  if(route.query.id) {
    await getInfo()
  }
  loading.value = false
})
</script>

<style lang="scss" scoped>
.assign-menu-title {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  >div:first-child {
    margin-right: 15px;
  }
}
.menu-assign {
  width: 400px;
  max-height: 500px;
  overflow: auto;
}
</style>
