<template>
  <ElDrawer ref="elDrawerRef" v-model="drawerVisible" :title="drawerProps.title" v-bind="$attrs" destroy-on-close>
    <template #header="scope">
      <slot name="header" v-bind="scope">
        <div style="display: flex">
          <slot name="title">
            <span style="flex: 1">{{ drawerProps.title }}</span>
          </slot>
        </div>
      </slot>
    </template>

    <el-form ref="ruleFormRef" label-width="100px" label-suffix=" :" :rules="rules" :model="drawerProps.row" @submit.enter.prevent="handleConfirm">
      <el-form-item label="上级字典" prop="parentId">
        <el-tree-select
          v-model="drawerProps.row.parentId"
          :data="treeData"
          check-strictly
          placeholder="请选择上级"
          :render-after-expand="false"
          clearable
          :default-expand-all="true"
          :props="treeProps" />
      </el-form-item>
      <el-form-item label="字典类型" prop="category">
        <el-radio-group v-model="drawerProps.row.category">
          <el-radio-button :value="item.dictValue" v-for="(item, index) in dictTypes" :key="index" :label="item.dictLabel" />
        </el-radio-group>
      </el-form-item>
      <el-form-item label="字典标签" prop="dictLabel">
        <el-input v-model="drawerProps.row.dictLabel" placeholder="字典标签" clearable />
      </el-form-item>
      <el-form-item label="字典值" prop="dictValue">
        <el-input v-model="drawerProps.row.dictValue" placeholder="字典值" clearable />
      </el-form-item>
      <el-form-item label="排序" prop="orderNum">
        <el-input-number v-model="drawerProps.row.orderNum" :precision="0" :min="1" :max="999999" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="drawerProps.row.status">
          <el-radio-button :value="item.dictValue" v-for="(item, index) in commonStatus" :key="index" :label="item.dictLabel" />
        </el-radio-group>
      </el-form-item>
      <el-form-item label="回显样式" prop="callbackShowStyle">
        <el-radio-group v-model="drawerProps.row.callbackShowStyle">
          <el-radio :value="item.dictValue" v-for="item in callbackShowStyles" :key="item.dictLabel" :label="item.dictLabel">
            <el-tag :type="item.dictValue">
              {{ item.dictLabel }}
            </el-tag>
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="drawerProps.row.remark" placeholder="请填写备注" clearable />
      </el-form-item>
    </el-form>

    <template #footer>
      <slot name="footer">
        <ElButton @click="drawerVisible = false">取 消</ElButton>
        <ElButton type="primary" @click="handleConfirm()">确 定</ElButton>
      </slot>
    </template>
  </ElDrawer>
</template>

<script setup lang="ts" name="OrgForm">
import { DictBO, DictItem, DictTreeVO } from '@/api/interface/system/dict'
import DictApi from '@/api/module/system/dict'
import { ResultEnum } from '@/enums/HttpEnum'
import { useDictOptions } from '@/hooks'

const commonStatus = useDictOptions('COMMON_STATUS')
const callbackShowStyles = useDictOptions('CALLBACK_SHOW_STYLE') as unknown as DictItem[]
const dictTypes = useDictOptions('DICT_TYPE')

import { FormInstance } from 'element-plus'
const rules = reactive({
  name: [{ required: true, message: '请填写组织名称' }],
  parentId: [{ required: true, message: '请选择上级' }],
  dictLabel: [{ required: true, message: '请填写字典标签' }],
  dictValue: [{ required: true, message: '请填写字典值' }],
  category: [{ required: true, message: '请选择字典类型' }],
  orderNum: [{ required: true, message: '排序不能为空' }],
  status: [{ required: true, message: '状态不能为空' }]
})

interface EcoDrawerProps {
  api?: (params: any) => Promise<any> // 调用接口
  title: string // 顶部标题
  isView: boolean
  row: Partial<DictBO>
  getTableList?: () => void
}

const treeData = ref<DictTreeVO[]>([])
const treeProps = {
  value: 'dictId',
  label: 'dictLabel'
}

const drawerVisible = ref(false)
const drawerProps = ref<EcoDrawerProps>({
  isView: false,
  title: '',
  row: {}
})

// emit
const emit = defineEmits(['submit'])

// 接收父组件传过来的参数
const acceptParams = (params: EcoDrawerProps) => {
  drawerProps.value = params
  drawerVisible.value = true
  loadTree()
  drawerProps.value.row.status = drawerProps.value.row.status || '1'
  drawerProps.value.row.callbackShowStyle = drawerProps.value.row.callbackShowStyle || 'primary'
}

const loadTree = () => {
  DictApi.tree().then(res => {
    treeData.value = [
      {
        parentId: '-1',
        dictId: '0',
        dictLabel: '顶层',
        children: res.data
      }
    ]
  })
}

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>()
const handleConfirm = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return
    try {
      const { code } = await drawerProps.value.api!(drawerProps.value.row)
      if (code == ResultEnum.SUCCESS) {
        ElMessage.success({ message: `${drawerProps.value.title}成功！` })
        // drawerProps.value.getTableList!()
        emit('submit')
        drawerVisible.value = false
      }
    } catch (error) {
      console.log(error)
    }
  })
}

defineExpose({
  acceptParams
})
</script>

<style scoped lang="scss"></style>
