<script setup>
import { orgMenu_add, org_setting } from '../api'
import { asyncFilteredRoutes } from '~/router/index'
import { constantRoutes } from '~/router/routes'

const props = defineProps({
  deptId: '',
  userId: '',
  currentName: '',
  uom_type: '',
})

const emit = defineEmits(['close'])

const treeRef = ref(null)

const customNodeClass = (data, node) => {
  if (data.isPenultimate)
    return 'is-penultimate'

  return null
}

const defaultProps = {
  children: 'children',
  label: 'label',
  class: customNodeClass,
}
const checkedKeys = ref([])

const allRoutes = computed(() => {
  const routes = [...constantRoutes, ...asyncFilteredRoutes.value]
  return routes.sort((a, b) => a.meta.sort - b.meta.sort)
})

const routeData = ref([])
const treeData = ref([])
initPermission()
function initPermission() {
  routeData.value = []
  allRoutes.value.map((val) => {
    if (val.meta.hidden) {
      if (Array.isArray(val.children)) {
        val.children.map((value) => {
          const obj = handleItem(value)
          obj.isPenultimate = true
          routeData.value.push(obj)
        })
      }
    }
    else {
      const obj = handleItem(val)
      if (!val.children)
        obj.isPenultimate = true

      routeData.value.push(obj)
    }
  })
}

// 权限
function handleItem(item) {
  const returnObj = {
    // id: item.id,
    label: item.meta.title,
    name: item.name,
  }

  if (Array.isArray(item.children)) {
    const arr = []
    init(item.children, arr)
    returnObj.children = arr
  }
  // else {
  //   returnObj.children = [
  //     {
  //       name: `${item.name}add`,
  //       label: '添加',
  //     },
  //     {
  //       name: `${item.name}edit`,
  //       label: '编辑',
  //     },
  //   ]
  // }

  return returnObj
}

function init(arg, arr) {
  arg.map((val) => {
    if (val.meta.hidden == undefined || val.meta.hidden == false) {
      const obj = handleItem(val)
      if (!val.children)
        obj.isPenultimate = true

      arr.push(obj)
    }
    else if (val.children) {
      init(val.children, arr)
    }
  })
}

initPermissionData()
async function initPermissionData() {
  const obj = {
    cpm_id: '10000',
    dept_id: props.deptId,
    user_id: props.userId,
    keyname: 'cmu_name',
    uom_type: props.uom_type,
  }
  const res = await org_setting(obj)
  if (res.code == 1) {
    treeData.value = [...routeData.value]
    if (props.userId != '' && props.uom_type == 1) {
      const obj = res.data.cmu_setting_dept
      const arr1 = []
      for (const key in obj) {
        if (obj[key] != '')
          arr1.push(key)
      }
      treeRef.value.filter(arr1)
    }
    const data = props.userId == '' ? res.data.cmu_setting_dept : res.data.cmu_setting_user
    const arr = []
    for (const key in data) {
      if (data[key] != '')
        arr.push(key)
    }
    checkedKeys.value = [...arr]
  }
}

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

const ruleFormRef = ref(null)
const ruleForm = reactive({
  bmmc: '',
  rs: '',
  fzr: '',
})

const handleCheckChange = async (
  data,
  checked,
  indeterminate,
) => {
  if (!data.children) {
    await handleHideCheck(data.name, checked)
    if (data.name == 'ktjl') {
      handleHideCheck('kttl', checked)
    }
    else if (data.name == 'BJSJDA_INDEX') {
      handleHideCheck('BJSJDA_STUDENT', checked)
    }
    else if (data.name == 'dsj_jypj1') {
      handleHideCheck('dsj_jypj2', checked)
    }
    else if (data.name == 'xsxqbg') {
      handleHideCheck('xsxqbg_two', checked)
      handleHideCheck('xsxqbg_three', checked)
    }
    initPermissionData()
  }
}

const handleHideCheck = async (name, checked) => {
  const obj = {
    user_org_menu: {
      cpm_id: '10000',
      dept_id: props.deptId,
      user_id: props.userId,
      cmu_name: name,
      cmu_permission: checked ? 'show' : '',
      uom_type: props.uom_type,
    },
  }
  await orgMenu_add(obj)
}

const handleCancel = (type) => {
  emit('close', type)
}

const handleSubmit = () => {
  handleCancel(1)
}
</script>

<template>
  <div class="addAndEdit px-50px">
    <el-form ref="ruleFormRef" class="mb-10" :model="ruleForm" :rules="rules" label-width="60px">
      <el-form-item label="部门">
        {{ currentName }}
      </el-form-item>
      <el-form-item label="权限">
        <el-tree ref="treeRef" :data="routeData" node-key="name" :props="defaultProps" show-checkbox default-expand-all :default-checked-keys="checkedKeys" :expand-on-click-node="false" highlight-current :filter-node-method="filterNode" @check-change="handleCheckChange" />
      </el-form-item>
    </el-form>

    <div class="flex_center space-x-12">
      <el-button size="large" @click="handleCancel(2)">
        取消
      </el-button>
      <el-button size="large" type="primary" @click="handleSubmit">
        确定
      </el-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-form) {
  .el-tree-node.is-expanded.is-penultimate > .el-tree-node__children {
    display: flex;
    flex-direction: row;
  }
  // .is-penultimate > .el-tree-node__children > div {
  //   width: 50%;
  // }
}
</style>
