<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="70%" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="140px">
        <el-form-item label="资料分类" prop="categoryId">
          <!--                      <category-cascader v-model="formData.categoryId" />-->
          <category-cascader v-model="formData.categoryId" @update:categoryName="formData.categoryName" />
        </el-form-item>
        <el-form-item label="资料名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入资料名称" />
        </el-form-item>
        <el-form-item label="资料介绍">
          <!--                      <Editor v-model="formData.description" :min-height="192"/>-->
          <el-input v-model="formData.description" placeholder="请输入资料介绍" type="textarea"/>
        </el-form-item>
        <el-form-item label="生效日期" prop="startTime">
          <el-date-picker clearable v-model="formData.startTime" type="datetime" value-format="timestamp" placeholder="选择生效效期" />
        </el-form-item>
        <el-form-item label="失效日期" prop="expireTime">
          <el-date-picker clearable v-model="formData.expireTime" type="datetime" value-format="timestamp" placeholder="选择失效日期" />
        </el-form-item>
        <el-form-item label="开启过期提醒" prop="remind">
          <el-switch v-model="formData.remind" />
          <el-input-number
            v-if="formData.remind"
            v-model="formData.dayleft"
            placeholder="请输入提前提醒天数"
            :min="0"
            :max="999999"
            :step="1"
            style="width: 100%;" />
        </el-form-item>

        <el-form-item label="共享范围" prop="shareType">
          <el-radio-group v-model="formData.shareType">
            <el-radio :label="1">全部组织</el-radio>
            <el-radio :label="2">指定组织</el-radio>
          </el-radio-group>

          <el-select
            v-if="formData.shareType === 2"
            v-model="formData.shareUserIds"
            multiple
            placeholder="请选择组织"
            style="width: 100%; margin-top: 10px"
          >
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.name"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
        <!--                    <el-form-item label="共享类型" prop="shareType">
                              <el-select v-model="formData.shareType" placeholder="请选择共享类型">
                                    <el-option v-for="dict in this.getDictDatas(DICT_TYPE.TRS_MATERIAL_SHARE)"
                                               :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
                              </el-select>
                            </el-form-item>-->
        <!--                    <el-form-item label="下载次数" prop="downloadCount">
                              <el-input v-model="formData.downloadCount" placeholder="请输入下载次数" />
                            </el-form-item>-->
        <!--                    <el-form-item label="状态" prop="status">
                              <el-select v-model="formData.status" placeholder="请选择状态">
                                    <el-option label="请选择字典生成" value="" />
                              </el-select>
                            </el-form-item>-->
        <!--                    <el-form-item label="备注信息" prop="reportRemark">
                              <el-input v-model="formData.reportRemark" placeholder="请输入备注信息" />
                            </el-form-item>-->
        <el-form-item label="附件名称" prop="attachment">
<!--          <FileUpload v-model="formData.attachment"
                      :file-size="15"
                      :file-type="['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'jpg', 'png', 'zip',  'rar']"
                      :limit="1"
                      :required="true"/>-->
          <FileUpload v-model="formData.attachment"
                      :file-size="uploadConfig.fileSize"
                      :file-type="uploadConfig.fileType"
                      :limit="uploadConfig.limit"
                      :required="uploadConfig.required"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as MaterialInfoApi from '@/api/server/materialinfo';
import CategoryCascader from '@/components/CategoryCascader'
import FileUpload from '@/components/FileUpload';
import {getFileForConfigPage} from "@/api/server/fileforconfig";

export default {
  name: "MaterialInfoForm",
  components: {
    FileUpload,
    CategoryCascader,
  },
  data() {
    return {
      userList: [],
      loadingUsers: false,
      selectedCategory: [],
      categoryOptions: [],
      categoryProps: {
        value: 'id',
        label: 'name',
        children: 'children',
        checkStrictly: true
      },
      dialogTitle: "",
      dialogVisible: false,
      formLoading: false,
      formData: {
        id: undefined,
        categoryId: undefined,
        categoryName: undefined,
        name: undefined,
        description: undefined,
        expireTime: undefined,
        remind: undefined,
        dayleft: undefined,
        shareType: 1, // 默认全部用户
        shareUserIds: [], // 存储选择的用户ID
        downloadCount: undefined,
        status: undefined,
        reportRemark: undefined,
        attachment: undefined,
      },
      formRules: {
        name: [{ required: true, message: '资料名称不能为空', trigger: 'blur' }],
        categoryId: [{ required: true, message: '请选择资料分类', trigger: 'blur' }],
        shareType: [{ required: true, message: '请选择共享范围', trigger: 'blur' }],
        attachment: [{ required: true, message: '附件不能为空', trigger: 'blur' }],
      },
      // 文件上传配置
      uploadConfig: {
        fileSize: 1, // 默认值，单位MB
        fileType: ['doc', 'docx', 'wps', 'pdf'], // 默认文件类型
        limit: 1, // 默认限制数量
        required: true // 默认必填
      }
    };
  },
  created() {
    this.loadCategoryTree();
    this.loadUserList();
  },
  methods: {
    /** 获取文件上传配置 */
    async fetchUploadConfig() {
      try {
        // 假设通过分页接口获取所有配置，然后根据配置键筛选
        const params = {
          pageNo: 1,
          pageSize: 100 // 获取足够多的配置
        };
        const res = await getFileForConfigPage(params);
        const configs = res.data.list;
        // 假设配置键为 'harmful_info_report_upload'
        const config = configs.find(item => item.configKey === 'MaterialInfo');
        if (config) {
          // 假设配置值是一个JSON字符串，包含fileSize, fileType, limit, required等属性
          this.uploadConfig = {
            fileSize: config.fileMaxSize || 15, // 使用 fileMaxSize
            fileType: config.fileTypes ? config.fileTypes.split(',') : ['doc', 'docx', 'wps', 'pdf'], // 将字符串转换为数组
            limit: config.fileMaxCount || 1, // 使用 fileMaxCount
            required: config.fileOther=='true' || true // 默认true
          };
        }
      } catch (error) {
        console.error('获取文件上传配置失败', error);
        // 使用默认配置
      }
    },
    // 加载用户列表
    async loadUserList() {
      this.loadingUsers = true;
      try {
        const res = await MaterialInfoApi.getUserList();
        this.userList = res.data;
      } catch (error) {
        console.error('获取用户列表失败:', error);
        this.$message.error('获取用户列表失败');
      } finally {
        this.loadingUsers = false;
      }
    },

    // 加载分类树
    async loadCategoryTree() {
      try {
        const res = await MaterialInfoApi.getMaterialCategoryTree();
        this.categoryOptions = res.data;
      } catch (error) {
        console.error('获取分类树失败:', error);
        this.$message.error('获取分类树失败');
      }
    },

    // 分类选择变化处理
    handleCategoryChange(categoryId) {
      this.formData.categoryId = categoryId;
      this.formData.categoryName = this.getCategoryNameById(categoryId, this.categoryOptions);
    },

    // 打开弹窗
    async open(id) {
      await this.fetchUploadConfig(); // 获取文件上传配置
      this.dialogVisible = true;
      this.reset();

      if (id) {
        this.formLoading = true;
        try {
          // 1. 加载资料基本信息
          const res = await MaterialInfoApi.getMaterialInfo(id);
          this.formData = res.data;
          this.dialogTitle = "修改资料库";

          // 2. 加载已选共享用户
          if (this.formData.shareType === 2) {
            const shareRes = await MaterialInfoApi.getShareUsers(id);
            this.formData.shareUserIds = shareRes.data.map(user => user.userId);
          }
        } catch (error) {
          console.error('加载资料信息失败:', error);
          this.$message.error('加载资料信息失败');
        } finally {
          this.formLoading = false;
        }
      } else {
        this.dialogTitle = "新增资料库";
      }
    },

    // 提交表单
    async submitForm() {
      try {
        await this.$refs.formRef.validate();
        this.formLoading = true;

        // 设置分类名称
        if (this.formData.categoryId) {
          this.formData.categoryName = this.getCategoryNameById(
            this.formData.categoryId,
            this.categoryOptions
          );
        }

        // 保存资料基本信息
        let materialId;
        if (this.formData.id) {
          await MaterialInfoApi.updateMaterialInfo(this.formData);
          materialId = this.formData.id;
          this.$modal.msgSuccess("修改成功");
        } else {
          const res = await MaterialInfoApi.createMaterialInfo(this.formData);
          materialId = res.data;
          this.$modal.msgSuccess("新增成功");
        }

        // 保存共享用户
        if (this.formData.shareType === 2) {
          // 获取选中的用户对应的部门名称
          const selectedUsers = this.userList.filter(user =>
            this.formData.shareUserIds.includes(user.id)
          );
          console.log(selectedUsers);
          const deptNames = selectedUsers.map(user => user.name).filter(Boolean);
          await MaterialInfoApi.saveShareUsers({
            materialId: materialId,
            userIds: this.formData.shareUserIds,
            deptNames: deptNames
          });
        } else {
          // 如果是全部用户共享，删除原有的共享用户记录
          await MaterialInfoApi.deleteShareUsers(materialId);
        }

        this.dialogVisible = false;
        this.$emit('success');
      } catch (error) {
        console.error('保存失败:', error);
        this.$message.error('保存失败');
      } finally {
        this.formLoading = false;
      }
    },

    // 递归查找分类名称
    getCategoryNameById(id, nodes, path = []) {
      for (const node of nodes) {
        if (node.id === id) {
          return [...path, node.name].join(' / ');
        }
        if (node.children && node.children.length) {
          const res = this.getCategoryNameById(id, node.children, [...path, node.name]);
          if (res) return res;
        }
      }
      return '';
    },

    // 重置表单
    reset() {
      this.formData = {
        id: undefined,
        categoryId: undefined,
        categoryName: undefined,
        name: undefined,
        description: undefined,
        expireTime: undefined,
        shareType: 1, // 重置为默认值
        shareUserIds: [], // 清空已选用户
        downloadCount: undefined,
        status: undefined,
        reportRemark: undefined,
        attachment: undefined,
      };
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields();
      }
    }
  }
};
</script>
