<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="mb-[10px]">
        <el-card shadow="never" class="pt-[40px] position-relative">
          <a class="back-to-list" @click="Cancel">
            <el-icon><ArrowLeftBold /></el-icon>
            <span>返回列表</span>
          </a>
          <el-form
            :disabled="type == 'view'"
            :model="summarizeAddForm"
            ref="summarizeAddFormRef"
            :rules="projectRules"
            label-width="170px"
            :class="['logview', 'view'].includes(type) ? '' : 'form-main'"
          >
            <div class="model-title">项目信息</div>
            <el-form-item label="所属项目：" prop="productId">
              <el-select
                filterable
                :disabled="type == 'edit'"
                v-model="summarizeAddForm.productId"
                placeholder="请选择所属项目"
                @change="getStageSelData"
              >
                <el-option v-for="item in projectOptions" :key="item.productId" :label="item.productName" :value="item.productId"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="评审阶段：" prop="reviewId">
              <el-select :disabled="type == 'edit'" v-model="summarizeAddForm.reviewId" placeholder="请选择评审阶段" @change="changeStage">
                <el-option v-for="item in stageOptions" :key="item.reviewId" :label="`${item.label}阶段`" :value="item.reviewId"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="项目总结名称：" prop="productSummarizeName">
              <el-input v-model="summarizeAddForm.productSummarizeName" :maxlength="50" show-word-limit placeholder="请输入项目总结名称"></el-input>
            </el-form-item>
            <el-form-item label="总结分类：" prop="productSummarizeType">
              <el-select v-model="summarizeAddForm.productSummarizeType" disabled placeholder="请选择评审阶段">
                <el-option v-for="item in stageOptions" :key="item.value" :label="`${item.label}总结`" :value="item.value"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="总结标签" prop="remark">
              <el-input v-model="summarizeAddForm.remark" placeholder="请输入总结标签（多个标签请用英文逗号隔开）"></el-input>
            </el-form-item>
            <el-form-item label="项目概况：" prop="productGeneral">
              <el-input
                v-model="summarizeAddForm.productGeneral"
                type="textarea"
                :rows="5"
                resize="none"
                placeholder="请输入项目概况"
                :maxlength="200"
                show-word-limit
              ></el-input>
            </el-form-item>
            <el-form-item label="评审范围：" prop="reviewScope">
              <el-input
                v-model="summarizeAddForm.reviewScope"
                type="textarea"
                :rows="5"
                resize="none"
                placeholder="请输入评审范围"
                :maxlength="200"
                show-word-limit
              ></el-input>
            </el-form-item>
            <el-form-item label="评审结论：" prop="reviewConclusion">
              <el-input
                v-model="summarizeAddForm.reviewConclusion"
                type="textarea"
                :rows="5"
                resize="none"
                placeholder="请输入评审结论"
                :maxlength="200"
                show-word-limit
              ></el-input>
            </el-form-item>
            <el-form-item label="反馈与建议：" prop="feedback">
              <el-input
                v-model="summarizeAddForm.feedback"
                type="textarea"
                :rows="5"
                resize="none"
                placeholder="请输入反馈与建议"
                :maxlength="200"
                show-word-limit
              ></el-input>
            </el-form-item>
            <el-form-item label="后续改进措施：" prop="subsequent">
              <el-input
                v-model="summarizeAddForm.subsequent"
                type="textarea"
                :rows="5"
                resize="none"
                placeholder="请输入后续改进措施"
                :maxlength="200"
                show-word-limit
              ></el-input>
            </el-form-item>
            <el-form-item label="附件资料" :rules="{ required: true, message: '请上传附件资料', trigger: 'change' }">
              <el-upload
                ref="uploadFJRef"
                :limit="10"
                class="upload-main"
                :multiple="multiple"
                accept=".xls,.xlsx,.doc,.docx,.txt,.zip,.pdf "
                :headers="upload.headers"
                :on-remove="handleFJRemove"
                :action="upload.url"
                :on-success="handleFJSuccess"
                :auto-upload="true"
                drag
                v-model:file-list="files"
              >
                <el-icon class="el-icon--upload">
                  <i-ep-upload-filled />
                </el-icon>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <template #tip>
                  <div class="text-center el-upload__tip">
                    <span>仅允许导入.xls、.xlsx、.doc、.docx、.txt、.zip、.pdf 格式文件。</span>
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-form>
          <span class="model-title">
          关联信息
          <span style="color: red; font-size: 13px; margin-left: 5px;">
            （请前往“文档管理”上传专利、论文信息）
          </span>
          </span>

          <div class="mb-[18px]">
            <el-tabs v-model="activeName">
              <el-tab-pane key="expert" label="专家" name="expert">
                <el-table height="100%" :data="expertsOptions">
                  <el-table-column
                    :label="label"
                    :align="align || 'center'"
                    prop="expertName"
                    :min-width="minWidth || '100px'"
                    v-for="{ label, prop, align, minWidth } in headers"
                    :key="prop"
                  >
                    <template #default="{ row }">
                      <span>{{ row[prop] || '-' }}</span>
                    </template>
                  </el-table-column>
                </el-table>
              </el-tab-pane>
              <el-tab-pane key="patent" label="专利" name="patent">
                <div class="file-item" v-if="patents.length > 0">
                  <div class="file-list" v-for="(item, index) in patents">
                    <div class="file-item-content">
                      <div class="file-label">专利号：</div>
                      <div>{{ item.paperName || 1 }}</div>
                    </div>
                    <div class="file-item-content">
                      <div class="file-label">发明创造名称：</div>
                      <div>{{ item.periodicalNumber ? item.periodicalNumber : 2 }}</div>
<!--                      <div>{{ item.periodicalNumber || 2 }}</div>-->
                    </div>
                    <div class="file-item-content">
                      <div class="file-label">论文文件:</div>
                      <div class="file-value">
                        <div>{{ item.originalName || '-' }}</div>
                        <a :href="item.url || ''" :download="item.originalName" class="download" target="_blank">下载</a>
                      </div>
                    </div>
                    <el-divider v-if="index < patents.length - 1" />
                  </div>
                </div>
                <div v-else>暂无专利</div>
              </el-tab-pane>
              <el-tab-pane key="paper" label="论文" name="paper">
                <div class="file-item" v-if="papers.length > 0">
                  <div class="file-list" v-for="(item, index) in papers">
                    <div class="file-item-content">
                      <div class="file-label">论文名称:</div>
                      <div>{{ item.paperName || 1 }}</div>
                    </div>
                    <div class="file-item-content">
                      <div class="file-label">期刊号:</div>
                      <div>{{ item.periodicalNumber || 2 }}</div>
                    </div>
                    <div class="file-item-content">
                      <div class="file-label">论文文件:</div>
                      <div class="file-value">
                        <div>{{ item.originalName || '-' }}</div>
                        <a :href="item.url || ''" :download="item.originalName" class="download" target="_blank">下载</a>
                      </div>
                    </div>
                    <el-divider v-if="index < papers.length - 1" />
                  </div>
                </div>
                <div v-else>暂无论文</div>
              </el-tab-pane>
            </el-tabs>
          </div>
          <div style="flex: 1; text-align: right">
            <el-button @click="Cancel">取消</el-button>
            <el-button type="primary" @click="SubmitAdd(1)">暂存</el-button>
            <el-button type="primary" @click="SubmitAdd(3)">提交</el-button>
          </div>
        </el-card>
      </div>
    </transition>
  </div>
</template>
<script lang="ts" setup>
import {
  getProjectSelList,
  getStage,
  SummarizeAddAjax,
  getSummarizeInfo,
  SummarizeUpdateAjax,
  getExperts,
  getProductPaperFiles,
  getProductPatentFiles
} from '@/api/project/summarize';
import { globalHeaders } from '@/utils/request';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const id = computed(() => proxy.$route.query.id);
const type: any = computed(() => proxy.$route.query.type || '');
const { item_stage } = toRefs<any>(proxy?.useDict('item_stage'));
const { perform_work_type } = toRefs<any>(proxy?.useDict('perform_work_type'));
const performWorkType = computed(() => perform_work_type.value);
const summarizeAddForm = ref<any>({
  productId: '',
  reviewId: '',
  productSummarizeName: '',
  productSummarizeType: '',
  remark: '',
  productGeneral: '',
  reviewScope: '',
  reviewConclusion: '',
  feedback: '',
  subsequent: '',
  attachment: []
});
const upload = reactive<UploadOption>({
  headers: globalHeaders(),
  url: import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload'
});
const projectRules = ref<any>({
  productId: [{ required: true, message: '请选择项目', trigger: 'change' }],
  reviewId: [{ required: true, message: '请选择阶段', trigger: 'change' }],
  productSummarizeName: [
    { required: true, message: '请输入项目名称', trigger: 'blur' }
    // { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  productSummarizeType: [{ required: true, message: '请选择分类', trigger: 'change' }],
  productGeneral: [
    { required: true, message: '请输入项目概况', trigger: 'blur' }
    // { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  reviewScope: [
    { required: true, message: '请输入评审范围', trigger: 'blur' }
    // { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  reviewConclusion: [
    { required: true, message: '请输入评审结论', trigger: 'blur' }
    // { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  feedback: [
    { required: true, message: '请输入反馈与建议', trigger: 'blur' }
    // { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  subsequent: [
    { required: true, message: '请输入后续改进措施', trigger: 'blur' }
    // { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  attachment: [{ type: 'array', required: true, message: '请上传附件', trigger: 'blur' }]
});
const itemStage = computed(() => item_stage.value);
const stageOptions = ref([]);
const getStageSelData = async () => {
  summarizeAddForm.value.productSummarizeType = '';
  summarizeAddForm.value.reviewId = '';
  let res: any = await getStage(summarizeAddForm.value.productId);
  stageOptions.value = res.map((e) => {
    let item = itemStage.value.find((el) => el.value == e.reviewSn);
    return {
      ...e,
      ...item
    };
  });
};
const expertsOptions = ref([]);
const patents = ref([]);
const papers = ref([]);
const changeStage = async () => {
  let item = stageOptions.value.find((e) => e.reviewId == summarizeAddForm.value.reviewId);
  summarizeAddForm.value.productSummarizeType = item.value;
  let res = await getExperts(summarizeAddForm.value.reviewId);
  if (res.code != 200) {
    ElNotification({
      title: '提示',
      message: res.msg,
      type: 'error'
    });
    return;
  }
  expertsOptions.value = res.data.map((e) => {
    return {
      ...e,
      performWorkId: e.performWorkId
        ?.split(',')
        .map((e) => {
          let item = performWorkType.value.find((t) => t.value == e);
          return item?.label || '';
        })
        .join(',')
    };
  });
  let paperRes = await getProductPaperFiles({ productId: summarizeAddForm.value.productId, reviewSn: summarizeAddForm.value.productSummarizeType });
  if (paperRes.code != 200) {
    ElNotification({
      title: '提示',
      message: paperRes.msg,
      type: 'error'
    });
    return;
  }
  papers.value = paperRes.data;
  let patentRes = await getProductPatentFiles({ productId: summarizeAddForm.value.productId, reviewSn: summarizeAddForm.value.productSummarizeType });
  if (patentRes.code != 200) {
    ElNotification({
      title: '提示',
      message: patentRes.msg,
      type: 'error'
    });
    return;
  }
  patents.value = patentRes.data;
};

const activeName = ref('expert');
const headers = ref<any>([
  {
    label: '专家姓名',
    prop: 'expertName'
  },
  {
    label: '联系方式',
    prop: 'contact'
  },
  {
    label: '工作单位',
    prop: 'workUnit'
  },
  {
    label: '职务',
    prop: 'duty'
  },
  {
    label: '专业/学历',
    prop: 'major'
  },
  {
    label: '研究领域',
    prop: 'performWorkId'
  }
]);
const projectOptions = ref([]);
const getProjectOptions = async () => {
  let res = await getProjectSelList();
  if (res.code != 200) {
    ElNotification({
      title: '提示',
      message: res.msg,
      type: 'error'
    });
    return;
  }
  projectOptions.value = res.rows;
};
const multiple = ref(true);
//删除附件资料
const handleFJRemove = (uploadFile: any) => {
  let isExist = summarizeAddForm.value.attachment.indexOf(uploadFile.response.data.url);
  if (isExist != -1) {
    summarizeAddForm.value.attachment.splice(isExist, 1);
  }
};
let files = ref([]);
const uploadFJRef = ref(null);
/** 附件上传成功处理 */
const handleFJSuccess = (response: any, file: UploadFile) => {
  if (response.code != 200) {
    ElNotification({
      title: `${file.name}上传失败`,
      message: response.msg,
      type: 'error'
    });
    uploadFJRef.value!.clearFiles();
    return;
  }
  if (!summarizeAddForm.value.attachment.find((e) => e.url == response.data?.url)) {
    summarizeAddForm.value.attachment.push({
      name: response.data.fileName,
      url: response.data.url
    });
  }
};
const summarizeAddFormRef = ref(null);
const Cancel = () => {
  proxy?.$tab.closePage(proxy?.$route).then(() => {
    proxy?.$router.replace('/project/summarize');
  });
};
const isSubmitting = ref(false);
const SubmitAdd = (status) => {
  if (isSubmitting.value) return;  // 如果正在提交，返回，防止重复提交
  isSubmitting.value = true;  // 设置提交状态为 true，表示正在提交

  summarizeAddFormRef.value.validate((valid) => {
    if (!valid) {
      isSubmitting.value = false;  // 如果验证失败，重置提交状态
      return;
    }
    let attachment =
      summarizeAddForm.value.attachment.length == 0
        ? files.value.map((e) => {
          return {
            name: e.name,
            url: e.url || e.response.data.url
          };
        })
        : summarizeAddForm.value.attachment;

    summarizeAddForm.value.attachment = attachment;

    summarizeAddForm.value.attachment = JSON.stringify(attachment || []);


    summarizeAddForm.value.expertIds = (summarizeAddForm.value.expertIds || []).join(',');
    summarizeAddForm.value.reviewSn = summarizeAddForm.value.productSummarizeType;

    let params = {
      ...summarizeAddForm.value,
      status
    };

    let ajax = SummarizeAddAjax;
    if (type.value == 'edit') {
      ajax = SummarizeUpdateAjax;
      params.id = id.value;
    }

    ElMessageBox.confirm(`是否确定${status == 2 ? '提交' : '暂存'}此项目总结`, '系统提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        let res = await ajax(params);
        if (res.code != 200) {
          ElNotification({
            title: '提示',
            message: res.msg,
            type: 'error'
          });
          isSubmitting.value = false;  // 处理完后重置提交状态
          return;
        }
        ElNotification({
          title: '提示',
          message: `${status == 2 ? '提交' : '暂存'}成功`,
          type: 'success'
        });
        // 关闭tag页面，并跳转到列表页面
        Cancel();
        isSubmitting.value = false;  // 提交成功后重置提交状态
      })
      .catch(() => {
        isSubmitting.value = false;  // 取消或错误时重置提交状态
      });
  });
};
/*
const SubmitAdd = (status) => {

  summarizeAddFormRef.value.validate((valid) => {
    if (!valid) return;
    let attachment =
      summarizeAddForm.value.attachment.length == 0
        ? files.value.map((e) => {
            return {
              name: e.name,
              url: e.url || e.response.data.url
            };
          })
        : summarizeAddForm.value.attachment;
    summarizeAddForm.value.attachment = JSON.stringify(attachment || []);
    summarizeAddForm.value.expertIds = (summarizeAddForm.value.expertIds || []).join(',');
    summarizeAddForm.value.reviewSn = summarizeAddForm.value.productSummarizeType;
    let params = {
      ...summarizeAddForm.value,
      status
    };
    let ajax = SummarizeAddAjax;
    if (type.value == 'edit') {
      ajax = SummarizeUpdateAjax;
      params.id = id.value;
    }
    ElMessageBox.confirm(`是否确定${status == 2 ? '提交' : '暂存'}此项目总结`, '系统提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        let res = await ajax(params);
        if (res.code != 200) {
          ElNotification({
            title: '提示',
            message: res.msg,
            type: 'error'
          });
          return;
        }
        ElNotification({
          title: '提示',
          message: `${status == 2 ? '提交' : '暂存'}成功`,
          type: 'success'
        });
        // 关闭tag页面，并跳转到列表页面
        Cancel();
      })
      .catch(() => {});
  });
};*/
const getInfo = async () => {
  let res = await getSummarizeInfo(id.value as string);
  summarizeAddForm.value = res.data;
  summarizeAddForm.value.attachment = JSON.parse(res.data.attachment);
  files.value = [...summarizeAddForm.value.attachment];
  summarizeAddForm.value.expertIds = (res.data.expertIds || '').split(',');
  projectOptions.value = [
    {
      productId: res.data.productId,
      productName: res.data.productName
    }
  ];
  let item = itemStage.value.find((el) => el.value == res.data.productSummarizeType);
  stageOptions.value = [
    {
      reviewId: res.data.reviewId,
      ...item
    }
  ];
  expertsOptions.value = res.data.zjkExpertList.map((e) => {
    return {
      ...e,
      performWorkId: e.performWorkId
        ?.split(',')
        .map((e) => {
          let item = performWorkType.value.find((t) => t.value == e);
          return item?.label || '';
        })
        .join(',')
    };
  });
  let paperRes = await getProductPaperFiles({ productId: summarizeAddForm.value.productId, reviewSn: summarizeAddForm.value.productSummarizeType });
  if (paperRes.code != 200) {
    ElNotification({
      title: '提示',
      message: paperRes.msg,
      type: 'error'
    });
    return;
  }
  papers.value = paperRes.data;
  let patentRes = await getProductPatentFiles({ productId: summarizeAddForm.value.productId, reviewSn: summarizeAddForm.value.productSummarizeType });
  if (patentRes.code != 200) {
    ElNotification({
      title: '提示',
      message: patentRes.msg,
      type: 'error'
    });
    console.log(patents.value);
    console.log(papers.value);
    return;
  }
  patents.value = patentRes.data;
};
onActivated(() => {
  summarizeAddFormRef.value.resetFields();
  if (type.value != 'add') {
    getInfo();
  } else {
    getProjectOptions();
  }
});
onMounted(() => {
  if (type.value != 'add') {
    getInfo();
  } else {
    getProjectOptions();
  }
});
</script>
<style lang="scss" scoped>
.form-item-gird {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
}
.model-title {
  margin-bottom: 24px;
  font-size: 20px;
  font-weight: bold;
}
.back-to-list {
  display: flex;
  align-items: center;
  gap: 10px;
  position: absolute;
  top: 10px;
  left: 10px;
  line-height: 20px;
  &:hover * {
    color: var(--el-color-primary);
  }
}
:deep(.el-form-item__content) {
  align-items: flex-start;
}
.form-main {
  width: 800px;
}
.upload-main {
  width: 100%;
}
.file-item {
  background-color: #f1f1f1;
  padding: 18px;
  border-radius: 6px;
  font-size: 14px;
  .file-item-content {
    display: flex;
    align-items: center;
    &:not(:last-child) {
      margin-bottom: 10px;
    }
    .file-label {
      width: 110px;
      padding-right: 10px;
      text-align: right;
      color: #606266;
      font-weight: bold;
    }
    .file-value {
      display: flex;
      align-items: center;
      gap: 10px;
      line-height: 32px;
      color: #606266;
      .download {
        cursor: pointer;
        color: var(--el-color-primary);
      }
    }
  }
}
</style>
