<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue';
import {
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElUpload,
  ElMessage,
  ElButton,
  ElIcon,
} from 'element-plus';
import { Upload, Plus, Delete } from '@element-plus/icons-vue';
import '#/assets/iconfonts/font/iconfont.css';
import { useAccessStore } from '@vben/stores';
import { getUploadAction } from '#/components/upload/config';
import { queryKnowledgeCategory } from '#/api/knowledge/category';
const accessStore = useAccessStore();
// 定义表单数据类型
interface FormData {
  name: string;
  description: string;
  upiconname: string;
  icon: string;
  managers: any[];
  visibleApps: any[];
  visiblePositions: any[];
  association: string;
}

// 定义组件的props
const props = defineProps<{
  mode: string;
  initialData?: FormData;
}>();

// 定义事件
const emit = defineEmits(['close', 'save']);

// 表单引用
const formRef = ref();

// 表单数据
const form = ref<FormData>({
  name: '',
  description: '',
  upiconname: '',
  icon: '',
  managers: [],
  visibleApps: [],
  visiblePositions: [],
  association: '',
});

// 表单规则
const rules = {
  name: [
    { required: true, message: '请输入知识库名称', trigger: 'blur' },
    { max: 50, message: '知识库名称不能超过50个字符', trigger: 'blur' },
  ],
  description: [
    { required: true, message: '请输入知识库描述', trigger: 'blur' },
    { max: 200, message: '知识库描述不能超过200个字符', trigger: 'blur' },
  ],
  icon: [{ required: true, message: '请选择知识库图标', trigger: 'change' }],
};

// 默认图标选项
const defaultIcons = [
  {
    name: '蓝色书籍',
    icon: 'iconfont icon-tushu',
    iconValue: 'blue-book',
    color: '#1890ff',
  },
  {
    name: '橙色书籍',
    icon: 'iconfont icon-tushu',
    iconValue: 'orange-book',
    color: '#fa8c16',
  },
  {
    name: '黄色书籍',
    icon: 'iconfont icon-tushu',
    iconValue: 'yellow-book',
    color: '#fadb14',
  },
  {
    name: '绿色书籍',
    icon: 'iconfont icon-tushu',
    iconValue: 'green-book',
    color: '#52c41a',
  },
  {
    name: '紫色书籍',
    icon: 'iconfont icon-tushu',
    iconValue: 'purple-book',
    color: '#722ed1',
  },
  {
    name: '蓝色列表',
    icon: 'iconfont icon-liebiao',
    iconValue: 'blue-list',
    color: '#1890ff',
  },
  {
    name: '橙色列表',
    icon: 'iconfont icon-liebiao',
    iconValue: 'orange-list',
    color: '#fa8c16',
  },
  {
    name: '黄色列表',
    icon: 'iconfont icon-liebiao',
    iconValue: 'yellow-list',
    color: '#fadb14',
  },
  {
    name: '绿色列表',
    icon: 'iconfont icon-liebiao',
    iconValue: 'green-list',
    color: '#52c41a',
  },
  {
    name: '紫色列表',
    icon: 'iconfont icon-liebiao',
    iconValue: 'purple-list',
    color: '#722ed1',
  },
];

// 监听初始数据变化
watch(
  () => props.initialData,
  (newData) => {
    // console.log('执行了监听器');

    if (newData) {
      form.value = { ...newData };
      console.log(form.value);
    }

    // 重置滚动条到最上面
    setTimeout(() => {
      const drawerContent = document.querySelector('.el-drawer__body');
      if (drawerContent) {
        drawerContent.scrollTop = 0;
      }
    }, 0);
  },
  { deep: true, immediate: true },
);
const createCategory = async () => {
  try {
    const res = await queryKnowledgeCategory({});
    knowledgeList.value = res.rows || [];
  } catch (error) {
    console.log(error);
  }
};
onMounted(() => {
  createCategory();
});
const knowledgeList = ref([]) as any;
// 上传图片处理
// const uploadFile = (file: any) => {
//   // 这里可以添加图片上传逻辑
//   ElMessage.success('图片上传成功');
//   form.value.icon = URL.createObjectURL(file.raw);
//   return false; // 阻止默认上传行为
// };

// 上传成功处理
const handleSuccess = (res: any, file: any) => {
  console.log('上传成功', res);
  if (res.code === 200) {
    form.value.icon = res.data.url;
    form.value.upiconname = res.data.fileName;
    ElMessage.success('图片上传成功');
  } else {
    ElMessage.error('图片上传失败');
  }
};

// 选择默认图标
const selectDefaultIcon = (icon: any) => {
  form.value.icon = `${icon.icon},${icon.color},${icon.iconValue}`;
};

// 删除上传的图标
const handleDeleteIcon = () => {
  form.value.icon = '';
  form.value.upiconname = '';
  ElMessage.success('图标已删除');
};

// 表单提交
const submitForm = () => {
  // 这里可以添加表单提交逻辑
  formRef.value.validate((valid: any) => {
    console.log(form.value);

    if (valid) {
      emit('save', form.value);
      ElMessage.success(props.mode === 'create' ? '创建成功' : '编辑成功');
    } else {
      ElMessage.error('请填写正确的信息');
    }
  });
};

// 关闭表单
const closeForm = () => {
  emit('close');
};
</script>

<template>
  <ElForm
    :model="form"
    :rules="rules"
    ref="formRef"
    label-position="top"
    class="knowledge-form"
  >
    <!-- 知识库名称 -->
    <ElFormItem label="知识库名称" prop="name">
      <ElInput
        v-model="form.name"
        placeholder="请输入"
        maxlength="50"
        show-word-limit
      />
    </ElFormItem>

    <!-- 知识库描述 -->
    <ElFormItem label="知识库描述" prop="description">
      <ElInput
        v-model="form.description"
        type="textarea"
        placeholder="请输入"
        maxlength="200"
        show-word-limit
        :rows="4"
      />
    </ElFormItem>

    <!-- 知识库图标 -->
    <ElFormItem label="知识库图标" prop="icon">
      <!-- :on-change="uploadFile" -->
      <ElUpload
        :action="getUploadAction()"
        :show-file-list="false"
        @success="handleSuccess"
        :headers="{
          Authorization: `Bearer ${accessStore.accessToken}`,
        }"
      >
        <div class="icon-upload">
          <ElIcon><Upload /></ElIcon>
          <div class="upload-text">上传图标</div>
        </div>
      </ElUpload>
      <div
        v-if="
          form.icon &&
          (form.icon.startsWith('blob:') ||
            form.icon.startsWith('http://') ||
            form.icon.startsWith('https://'))
        "
        class="icon-preview"
      >
        <img :src="form.icon" alt="预览" />
        <div class="icon-delete" @click="handleDeleteIcon">
          <ElIcon><Delete /></ElIcon>
        </div>
      </div>
      <div class="icon-default">
        <div class="section-title">预览可选图标</div>
        <div class="icon-list">
          <div
            v-for="(icon, index) in defaultIcons"
            :key="index"
            class="icon-item"
            :class="{ active: form.icon?.includes(icon.iconValue) }"
            @click="selectDefaultIcon(icon)"
          >
            <!-- 这里可以根据icon.value显示不同的图标 -->
            <!-- <ElIcon class="icon-placeholder" :class="icon.value"></ElIcon> -->
            <span
              :class="icon.icon"
              :style="{ fontSize: '40px', color: icon.color }"
            ></span>
          </div>
        </div>
      </div>
    </ElFormItem>

    <!-- 知识库管理员 -->
    <ElFormItem
      label="知识库管理员（管理员具有知识库编辑、删除的权限）"
      prop="managers"
    >
      <ElSelect
        v-model="form.managers"
        placeholder="可多选"
        multiple
        filterable
      >
        <ElOption label="管理员1" value="admin1" />
        <ElOption label="管理员2" value="admin2" />
        <ElOption label="管理员3" value="admin3" />
      </ElSelect>
    </ElFormItem>

    <!-- 可见范围 -->
    <ElFormItem label="可见范围（可查看该知识库权限）">
      <div class="visible-range" style="width: 100%">
        <ElFormItem label="端" label-position="right" prop="visibleApps">
          <ElSelect
            v-model="form.visibleApps"
            placeholder="可多选"
            multiple
            filterable
            style="width: 100%"
          >
            <ElOption label="PC端" value="pc" />
            <ElOption label="移动端" value="mobile" />
            <ElOption label="小程序" value="miniprogram" />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="岗位" label-position="right" prop="visiblePositions">
          <ElSelect
            v-model="form.visiblePositions"
            placeholder="可多选"
            multiple
            filterable
            style="width: 100%"
          >
            <ElOption label="经理" value="manager" />
            <ElOption label="员工" value="employee" />
            <ElOption label="实习生" value="intern" />
          </ElSelect>
        </ElFormItem>
      </div>
    </ElFormItem>

    <!-- 知识库关联 -->
    <ElFormItem
      label="知识库关联（关联后，两个知识库内容同步编辑）"
      prop="association"
    >
      <ElSelect v-model="form.association" placeholder="单选" filterable>
        <ElOption
          v-for="(item, index) in knowledgeList"
          :key="item.id"
          :label="item.name"
          :value="String(item.id)"
        />
      </ElSelect>
    </ElFormItem>

    <!-- 操作按钮 -->
    <div class="form-actions">
      <ElButton type="primary" @click="submitForm">确定</ElButton>
      <ElButton @click="closeForm">取消</ElButton>
    </div>
  </ElForm>
</template>

<style lang="scss" scoped>
.knowledge-form {
  padding: 20px;
}

.icon-upload {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 120px;
  height: 120px;
  cursor: pointer;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  transition: all 0.3s;

  &:hover {
    border-color: #409eff;
  }

  .upload-text {
    margin-top: 8px;
    font-size: 14px;
    color: #666;
  }
}

.icon-preview {
  margin: 16px 0;
  position: relative;

  img {
    width: 120px;
    height: 120px;
    object-fit: cover;
    border-radius: 6px;
  }

  .icon-delete {
    position: absolute;
    top: -10px;
    right: -10px;
    width: 24px;
    height: 24px;
    border-radius: 50%;
    background-color: rgba(0, 0, 0, 0.6);
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      background-color: rgba(0, 0, 0, 0.8);
    }
  }
}

.icon-default {
  margin-top: 24px;

  .section-title {
    margin-bottom: 16px;
    font-size: 14px;
    font-weight: 500;
    color: #333;
  }

  .icon-list {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
  }

  .icon-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 80px;
    height: 80px;
    cursor: pointer;
    border: 2px solid transparent;
    border-radius: 6px;
    transition: all 0.3s;

    &:hover {
      border-color: #409eff;
    }

    &.active {
      background-color: #e6f7ff;
      border-color: #409eff;
    }

    .icon-placeholder {
      width: 40px;
      height: 40px;
      border-radius: 4px;
    }

    .icon-name {
      font-size: 12px;
      color: #666;
      margin-top: 4px;
      text-align: center;
      word-break: keep-all;
    }
  }
}

.visible-range {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 6px;
}

.form-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 32px;
}
</style>
