<template>
  <div>
    <el-dialog
      v-model="state.showDialog"
      destroy-on-close
      title="加载共享文件夹"
      draggable
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="600px"
    >
      <el-form :model="form" ref="formRef" label-width="120px">
        <el-alert
          v-if="state.isReadonly"
          title="当前为指定文件夹加载模式，父级文件夹和文件路径已自动设置"
          type="info"
          :closable="false"
          style="margin-bottom: 20px"
        />
        <el-row :gutter="35">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="父级文件夹">
              <el-input 
                v-if="state.isReadonly"
                v-model="state.parentName" 
                readonly 
                placeholder="根目录"
                class="w100"
              />
              <el-tree-select
                v-else
                v-model="form.parentId"
                :data="templateTreeData.filter(item => (item.type || 1) === 1)"
                node-key="id"
                check-strictly
                default-expand-all
                render-after-expand
                fit-input-width
                clearable
                :empty-values="[0, null, undefined]"
                class="w100"
                :props="{ label: 'name', value: 'id' }"
                placeholder="请选择父级文件夹，为空则表示根目录"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="文件夹路径" prop="folderPath" :rules="[{ required: true, message: '请输入文件夹路径', trigger: ['blur', 'change'] }]">
              <el-input 
                v-model="form.folderPath" 
                :readonly="state.isReadonly"
                clearable 
                placeholder="请输入共享文件夹路径" 
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="包含子文件夹">
              <el-switch v-model="form.includeSubfolders" />
              <el-text type="info" size="small" style="margin-left: 10px">
                是否包含子文件夹内容
              </el-text>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancel">取 消</el-button>
          <el-button type="primary" @click="onSure" :loading="state.sureLoading">开始加载</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup name="admin/templatecenter/folder-load-form">
import { reactive, toRefs, getCurrentInstance, ref, PropType } from 'vue'
import { TemplateCenterGetTreeOutput } from '/@/api/admin/TemplateCenter'
import { TemplateCenterApi } from '/@/api/admin/TemplateCenter'
import eventBus from '/@/utils/mitt'

defineProps({
  templateTreeData: {
    type: Array as PropType<TemplateCenterGetTreeOutput[]>,
    default: () => [],
  },
})

const { proxy } = getCurrentInstance() as any
const formRef = ref()
const state = reactive({
  showDialog: false,
  sureLoading: false,
  isReadonly: false,
  parentName: '',
  form: {
    parentId: undefined as number | undefined,
    folderPath: '',
    includeSubfolders: false,
  },
})
const { form } = toRefs(state)

// 打开对话框
const open = async (parentId?: number, parentName?: string, folderPath?: string) => {
  state.isReadonly = !!(parentId && parentName) // 如果传入了父级信息，则为只读模式
  state.parentName = parentName || ''
  
  state.form = {
    parentId: parentId || undefined,
    folderPath: folderPath || '',
    includeSubfolders: false,
  }
  state.showDialog = true
}

// 取消
const onCancel = () => {
  state.showDialog = false
}

// 确定
const onSure = () => {
  formRef.value.validate(async (valid: boolean) => {
    if (!valid) return

    state.sureLoading = true
    
    const res = await new TemplateCenterApi().getSharedFolderContent({
      folderPath: state.form.folderPath,
      parentId: state.form.parentId && state.form.parentId > 0 ? state.form.parentId : undefined,
      includeSubfolders: state.form.includeSubfolders,
    }, { showSuccessMessage: true }).catch(() => {
      state.sureLoading = false
    })

    state.sureLoading = false

    if (res?.success) {
      eventBus.emit('refreshTemplateCenter')
      state.showDialog = false
    }
  })
}

defineExpose({
  open,
})
</script>

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