<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch, ref, unref } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
import { MENU_TYPE_DICT_LIST, STATUS_DICT_LIST, COMMON_DICT_LIST } from '../constants'
import { getDictOneApi, getMenuTreeApi } from '@/api/common'
import { ElTag, ElButton, ElMessage } from 'element-plus'
import AddButtonPermission from './AddButtonPermission.vue'
import { asyncRouterMap } from '@/router'
import { cloneDeep, find } from 'lodash-es'
import { treeToList } from '@/utils/tree'

const { required } = useValidator()

const props = defineProps({
  currentRow: {
    type: Object as PropType<any>,
    default: () => null
  },
  actionType: {
    type: String,
    default: 'add'
  }
})

const showDrawer = ref(false)

/** 递归循环 */
const deepMenuTree = function (data: any) {
  if(Array.isArray(data)){
    for (let i = 0; i < data.length; i++) {
      deepMenuTree(data[i]);
    }
  } else {
    const children = data.children;
    if (children && children.length) {
      for (let i = 0; i < children.length; i++) {
        deepMenuTree(children[i]);
      }
    }
    data.title = data?.meta?.title;
  }
  return data
}
let menuTreeToList: any = [];

const formSchema = reactive<FormSchema[]>([
  {
    field: 'id',
    label: '主键',
    component: 'Input',
    hidden: true
  },
  {
    field: 'type',
    label: '菜单类型',
    component: 'RadioButton',
    value: '0',
    colProps: {
      span: 24
    },
    componentProps: {
      options: MENU_TYPE_DICT_LIST,
    }
  },
  {
    field: 'parentId',
    label: '上级菜单',
    component: 'TreeSelect',
    optionApi: async () => {
      const res = await getMenuTreeApi()
      return res
    },
    componentProps: {
      style: {
        width: '100%'
      },
      filterable: true,
      checkStrictly: true,
      nodeKey: 'id',
      props: { children: 'childs', label: 'nodeName' }
    }
  },
  {
    field: 'routeName',
    label: '组件',
    component: 'TreeSelect',
    optionApi: async () => {
      const res = deepMenuTree(cloneDeep(asyncRouterMap));
      menuTreeToList = treeToList(res);
      return res
    },
    componentProps: {
      style: {
        width: '100%'
      },
      checkStrictly: true,
      nodeKey: 'name',
      props: { children: 'children', label: 'title' },
      on: {
        change: async (val: string) => {
          if (val) {
            const menuNode = find(menuTreeToList, { name: val });
            const { title, path = '' } = menuNode;
            setSchema([
              {
                field: 'url',
                path: 'componentProps.disabled',
                value: true
              }
            ])
            const formData = await getFormData()
            const { name, url } = formData
            if (!name && !url) {
              setValues({
                name: title,
                url: path.replace(/\//g, '').trim(),
              })
            }
          } else {
            setSchema([
              {
                field: 'url',
                path: 'componentProps.disabled',
                value: false
              }
            ])
          }
        }
      }
    }
  },
  {
    field: 'name',
    label: '菜单名称',
    component: 'Input',
    componentProps: {}
  },
  {
    field: 'url',
    label: '菜单链接',
    component: 'Input',
    componentProps: {}
  },
  // {
  //   field: 'type',
  //   label: '菜单类型',
  //   component: 'RadioGroup',
  //   componentProps: {
  //     options: TYPE_DICT_LIST
  //   },
  //   value: '0'
  // },
  {
    field: 'common',
    label: '权限类型',
    component: 'RadioGroup',
    componentProps: {
      options: COMMON_DICT_LIST
    },
    value: '0'
  },
  {
    field: 'systemCode',
    label: '归属系统',
    component: 'Select',
    optionApi: async () => {
      const res = await getDictOneApi({
        paramName: 'SystemTypeParam_param',
        systemCode: 'system'
      })
      return res
    },
    componentProps: {
      style: {
        width: '100%'
      }
    }
  },
  // {
  //   field: 'permissionStr',
  //   label: '权限标识',
  //   component: 'Input',
  //   componentProps: {}
  // },
  {
    field: 'icon',
    label: '图标',
    component: 'IconPicker',
    componentProps: {}
  },
  {
    field: 'sort',
    label: '排序',
    component: 'InputNumber',
    componentProps: {}
  },
  {
    field: 'status',
    label: '状态',
    component: 'RadioGroup',
    componentProps: {
      options: STATUS_DICT_LIST
    },
    value: '0'
  },
  {
    field: 'permissionList',
    label: '按钮权限',
    component: 'CheckboxGroup',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: (data: any) => (
          <>
            {data?.permissionList?.map((v) => {
              return (
                <ElTag class="mr-1" key={v.value} closable onClose={() => handleClose(v)}>
                  {v.label}
                </ElTag>
              )
            })}
            <ElButton type="primary" size="small" onClick={() => (showDrawer.value = true)}>
              添加权限
            </ElButton>
          </>
        )
      }
    }
  },
  {
    field: 'description',
    label: '菜单描述',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      type: 'textarea'
    }
  }
])

const rules = reactive({
  name: [required()],
  url: [required()],
  systemCode: [required()],
  routeName: [
    {
      asyncValidator: async (_, val, callback) => {
        const formData = await getFormData()
        const { type } = formData
        if (type === '1' && !val) {
          callback(new Error('菜单类型为菜单时,组件为必填项'))
        } else {
          callback()
        }
      }
    }
  ],
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose, setSchema } = formMethods

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    // 因为permissionStr是字符串类型, 所以此处转字符串
    formData.permissionStr = JSON.stringify(formData.permissionList)
    // // 匹配菜单关联字段
    // const { routeName } = formData;
    // if (routeName) {
    //     const menuNode = find(menuTreeToList, { name: routeName });
    //     if (menuNode && menuNode.menuId && menuNode.menuId !== routeName) {
    //       formData.routeName = menuNode.menuId;
    //     }
    // }
    return formData
  }
}

/** 字符串转数组 */
const stringToArray = function(str: any) {
  if (str && typeof str === 'string') {
    return JSON.parse(str);
  }
  return []
}

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    // 因为permissionStr是字符串类型, 所以此处转数组
    // currentRow.permissionStr = stringToArray(currentRow?.permissionStr);
    const data = {
      ...unref(currentRow)
    }
    data.permissionList = stringToArray(data.permissionStr);
    setValues(data)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  submit
})

const handleClose = async (tag: any) => {
  const formData = await getFormData()
  // 删除对应的权限
  setValues({
    permissionList: formData?.permissionList?.filter((v: any) => v.value !== tag.value)
  })
}

const confirm = async (data: any) => {
  const formData = await getFormData()
  const some = formData?.permissionList?.some((item) => item.value === data.value);
  if (some) {
    ElMessage({
      message: '按钮已存在，不允许重复添加！',
      type: 'warning',
    })
    return;
  }
  setValues({
    permissionList: [...(formData?.permissionList || []), data]
  })
}
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="formSchema" />
  <AddButtonPermission v-model="showDrawer" @confirm="confirm" />
</template>
