<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="nover">
          <el-form :model="state.form" ref="formRef" :rules="state.rules" label-width="120px" :inline="false" size="normal">
            <el-form-item label="项目名称：" prop="productId">
              <div v-if="type == 'show'">{{ state.form.productName }}</div>
              <el-select
                v-else
                :disabled="type == 'edit'"
                v-model="state.form.productId"
                filterable
                remote
                :remote-method="getProjectOptions"
                :loading="loading"
                placeholder="请选择项目"
                @change="selectProject"
              >
                <el-option v-for="item in projectOptions" :key="item.id" :label="item.productName" :value="item.id"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="项目编号：" prop="productSn">
              <div v-if="type == 'show'">{{ state.form.productSn }}</div>
              <el-input v-else v-model="state.form.productSn" placeholder="请选择项目（项目编号根据选择的项目自动绑定）" disabled></el-input>
            </el-form-item>
            <el-form-item label="项目阶段：" prop="reviewSn">
              <div v-if="type == 'show'">{{ state.form.productStageName }}阶段</div>
              <el-select v-else :disabled="type == 'edit'" v-model="state.form.reviewSn" 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="paper">
              <div class="file-item">
                <div v-for="(item, index) in state.form.paper" class="position-relative">
                  <el-form-item class="mb-18px" label="论文名称：" :prop="`paper[${index}][paperName]`" :rules="state.rules.paperName">
                    <div v-if="type == 'show'">{{ item.paperName }}</div>
                    <el-input v-else v-model="item.paperName" placeholder="请输入论文名称"></el-input>
                  </el-form-item>
                  <el-form-item class="mb-18px" label="期刊号：" :prop="`paper[${index}][periodicalNumber]`" :rules="state.rules.periodicalNumber">
                    <div v-if="type == 'show'">{{ item.periodicalNumber }}</div>
                    <el-input v-else v-model="item.periodicalNumber" placeholder="请输入期刊号"></el-input>
                  </el-form-item>
                  <el-form-item label="论文文件：" :prop="`paper[${index}][paperPath]`" :rules="state.rules.paperPath">
                    <div class="file-list" v-if="type == 'show'">
                      <div>{{ item.paperPath[0]?.name || '-' }}</div>
                      <a :href="item.paperPath[0]?.url || ''" :download="item.paperPath[0]?.name" class="download" target="_blank">下载</a>
                    </div>
                    <el-upload
                      v-else
                      :ref="(el) => uploadPaperRef(el, index)"
                      :headers="upload.headers"
                      :action="upload.url"
                      :limit="1"
                      class="upload-main"
                      accept=".doc,.docx,.pdf "
                      :on-exceed="handleExceed"
                      :on-success="(res, file, fileList) => handleSuccess(res, file, fileList, 'paper', index)"
                      :auto-upload="true"
                      drag
                      v-model:file-list="item.paperPath"
                    >
                      <el-icon class="el-icon--upload">
                        <i-ep-upload-filled />
                      </el-icon>
                      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em>，仅允许导入.doc、.docx、.pdf 格式文件。</div>
                    </el-upload>
                  </el-form-item>
                  <div class="icon-main position-absolute" v-if="type != 'show'">
                    <el-icon>
                      <CirclePlus @click="PlusPaper" />
                    </el-icon>
                    <el-icon class="minus-icon">
                      <Remove v-show="state.form.paper.length > 1" @click="MinusPaper(index)" />
                    </el-icon>
                  </div>
                  <el-divider v-if="index < state.form.paper.length - 1" />
                </div>
              </div>
            </el-form-item>
            <el-form-item label="专利：" prop="patent">
              <div class="file-item">
                <div v-for="(item, index) in state.form.patent" class="position-relative">
                  <el-form-item class="mb-18px" label="专利号：" :prop="`patent[${index}][patentNumber]`" :rules="state.rules.patentNumber">
                    <div v-if="type == 'show'">{{ item.patentNumber }}</div>
                    <el-input v-else v-model="item.patentNumber" placeholder="请输入专利号"></el-input>
                  </el-form-item>
                  <el-form-item class="mb-18px" label="发明创造名称：" :prop="`patent[${index}][nameInvention]`" :rules="state.rules.nameInvention">
                    <div v-if="type == 'show'">{{ item.nameInvention }}</div>
                    <el-input v-else v-model="item.nameInvention" placeholder="请输入发明创造名称"></el-input>
                  </el-form-item>
                  <el-form-item label="专利文件：" :prop="`patent[${index}][patentPath]`" :rules="state.rules.patentPath">
                    <div class="file-list" v-if="type == 'show'">
                      <div>{{ item.patentPath[0]?.name || '-' }}</div>
                      <a :href="item.patentPath[0]?.url || ''" :download="item.patentPath[0]?.name" class="download" target="_blank">下载</a>
                    </div>
                    <el-upload
                      v-else
                      :ref="(el) => uploadPatentRef(el, index)"
                      :headers="upload.headers"
                      :action="upload.url"
                      :limit="1"
                      class="upload-main"
                      accept=".doc,.docx,.pdf "
                      :on-exceed="handleExceed"
                      :on-success="(res, file, fileList) => handleSuccess(res, file, fileList, 'patent', index)"
                      :auto-upload="true"
                      drag
                      v-model:file-list="item.patentPath"
                    >
                      <el-icon class="el-icon--upload">
                        <i-ep-upload-filled />
                      </el-icon>
                      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em>，仅允许导入.doc、.docx、.pdf 格式文件。</div>
                    </el-upload>
                  </el-form-item>
                  <div class="icon-main position-absolute" v-if="type != 'show'">
                    <el-icon>
                      <CirclePlus @click="PlusPatent" />
                    </el-icon>
                    <el-icon>
                      <Remove v-show="state.form.patent.length > 1" @click="MinusPatent(index)" />
                    </el-icon>
                  </div>
                  <el-divider v-if="index < state.form.patent.length - 1" />
                </div>
              </div>
            </el-form-item>
          </el-form>
          <div style="flex: 1; text-align: right">
            <el-button @click="Cancel">返回</el-button>
            <el-button type="primary" v-if="type != 'show'" @click="confirmSubmit">确定</el-button>
          </div>
        </el-card>
      </div>
    </transition>
  </div>
</template>

<script setup lang="ts">
import { getProjectSelList, getFile, addProjectFile, getDetail, updateProjectFile } from '@/api/filemanage';
import { globalHeaders } from '@/utils/request';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { item_stage } = toRefs<any>(proxy?.useDict('item_stage'));
const stageObj = computed(() => {
  return item_stage.value.reduce((acc, cur) => {
    acc[cur.value] = cur.label;
    return acc;
  }, {});
});
const id = computed(() => proxy?.$route.query.id || '');
const type = computed(() => proxy?.$route.query.type || '');
const from = computed(() => proxy?.$route.query.from || '');

const upload = reactive<UploadOption>({
  headers: globalHeaders(),
  url: import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload'
});
const state = ref({
  form: {
    productId: '',
    productSn: '',
    reviewSn: '',
    // 论文
    paper: [
      {
        paperName: '',
        periodicalNumber: '',
        paperPath: []
      }
    ],
    // 专利
    patent: [
      {
        patentNumber: '',
        nameInvention: '',
        patentPath: []
      }
    ]
  },
  rules: {
    productId: [{ required: true, message: '请选择项目', trigger: 'blur' }],
    productSn: [{ required: true, message: '请选择项目编号', trigger: 'blur' }],
    reviewSn: [{ required: true, message: '请选择项目阶段', trigger: 'blur' }],
    paperName: [{ required: true, message: '请输入论文名称', trigger: 'blur' }],
    periodicalNumber: [{ required: true, message: '请输入期刊号', trigger: 'blur' }],
    patentNumber: [{ required: true, message: '请输入专利号', trigger: 'blur' }],
    nameInvention: [{ required: true, message: '请输入发明创造名称', trigger: 'blur' }],
    paperPath: [
      {
        required: true,
        validator: (rule, value, callback) => {
          if (value.length == 0) {
            callback(new Error('请上传论文文件'));
          } else {
            callback();
          }
        },
        trigger: 'change'
      }
    ],
    patentPath: [
      {
        required: true,
        validator: (rule, value, callback) => {
          if (value.length == 0) {
            callback(new Error('请上传专利文件'));
          } else {
            callback();
          }
        },
        trigger: 'change'
      }
    ]
  }
});
const projectOptions = ref([]);
const loading = ref(false);
const getProjectOptions = async (query) => {
  if (!query) return;
  loading.value = true;
  let res = await getProjectSelList(query);
  if (res.code != 200) {
    ElNotification({
      title: '提示',
      message: res.msg,
      type: 'error'
    });
    return;
  }
  projectOptions.value = res.data;
  loading.value = false;
};
const stageOptions = computed(() => item_stage.value);
const selectProject = () => {
  state.value.form.productSn = projectOptions.value.find((e) => e.id == state.value.form.productId).productSn;
};
const getFileInfo = async (ids) => {
  let res = await getFile(ids);
  if (res.code != 200) {
    ElNotification({
      title: '提示',
      message: res.msg,
      type: 'error'
    });
    return;
  }
  return res.data;
};
const getData = async () => {
  let res = await getDetail(id.value);
  if (res.code != 200) {
    ElNotification({
      title: '提示',
      message: res.msg,
      type: 'error'
    });
    return;
  }
  projectOptions.value = [
    {
      id: res.data.productId,
      productName: res.data.productName
    }
  ];
  let paperIds = res.data.zjkExpertPaperList.map((e) => e.paperPath);
  let patentIds = res.data.zjkExpertPatentsList.map((e) => e.patentPath);
  let files = await getFileInfo([...paperIds, ...patentIds].join(','));
  state.value.form = {
    ...res.data,
    productStageName: stageObj.value[res.data.reviewSn],
    paper: res.data.zjkExpertPaperList.map((e) => {
      let file = files.find((f) => f.ossId == e.paperPath);
      return {
        ...e,
        paperPath: [
          {
            name: file.originalName,
            ossId: file.ossId,
            url: file.url
          }
        ]
      };
    }),
    patent: res.data.zjkExpertPatentsList.map((e) => {
      let file = files.find((f) => f.ossId == e.patentPath);
      return {
        ...e,
        patentPath: [
          {
            name: file.originalName,
            ossId: file.ossId,
            url: file.url
          }
        ]
      };
    })
  };
};
const PlusPaper = () => {
  state.value.form.paper.push({
    paperName: '',
    periodicalNumber: '',
    paperPath: []
  });
};
const MinusPaper = (index) => {
  state.value.form.paper.splice(index, 1);
};
const PlusPatent = () => {
  state.value.form.patent.push({
    patentNumber: '',
    nameInvention: '',
    patentPath: []
  });
};
const MinusPatent = (index) => {
  state.value.form.patent.splice(index, 1);
};

const handleExceed = (files, fileList) => {
  ElNotification({
    title: '提示',
    message: '最多只能上传一个文件',
    type: 'error'
  });
};
const paperFileRefs = ref([]);
const uploadPaperRef = (el, index) => {
  paperFileRefs.value[index] = el;
};
const patentFileRefs = ref([]);
const uploadPatentRef = (el, index) => {
  patentFileRefs.value[index] = el;
};
const formRef = ref(null);
const handleSuccess = (res, file, fileList, key, index) => {
  if (res.code != 200) {
    ElNotification({
      title: `${file.name}上传失败`,
      message: res.msg,
      type: 'error'
    });
    let refEl = key == 'paper' ? paperFileRefs : patentFileRefs;
    refEl.value[index]!.clearFiles();
  }
};

const Cancel = () => {
  proxy?.$tab.closePage(proxy?.$route).then(() => {
    proxy?.$router.replace(from.value == 'manage' ? '/project/fileManage' : '');
  });
};
const confirmSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return;
    ElMessageBox.confirm('是否确定上传文档', '系统提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        let params = {
          id: state.value.form.productId,
          reviewSn: state.value.form.reviewSn,
          zjkExpertPaperList: state.value.form.paper.map((e) => {
            return {
              ...e,
              paperPath: e.paperPath[0]?.response?.data.ossId || e.paperPath[0].ossId
            };
          }),
          zjkExpertPatentsList: state.value.form.patent.map((e) => {
            return {
              ...e,
              patentPath: e.patentPath[0]?.response?.data.ossId || e.patentPath[0].ossId
            };
          })
        };
        if (type.value == 'edit') {
          params.productReviewId = id.value;
        }
        let ajax = type.value == 'edit' ? updateProjectFile : addProjectFile;
        let res = await ajax(params);
        if (res.code != 200) {
          ElNotification({
            title: '提示',
            message: res.msg,
            type: 'error'
          });
          return;
        }
        ElNotification({
          title: '提示',
          message: `${type.value == 'add' ? '新建' : '编辑'}成功`,
          type: 'success'
        });
        Cancel();
      })
      .catch(() => {});
  });
};
onActivated(() => {
  if (id.value) {
    getData();
  }
});
onMounted(() => {
  if (id.value) {
    getData();
  }
});
</script>

<style scoped lang="scss">
:deep(.el-form) {
  width: 800px;
}
.mb-18px {
  margin-bottom: 18px;
}
.file-item {
  background-color: #f1f1f1;
  flex: 1;
  padding: 18px;
  border-radius: 6px;
}
.icon-main {
  left: calc(100% + 24px);
  top: 50%;
  transform: translateY(-50%);
  height: 72px;
  display: flex;
  flex-direction: column;
  gap: 8px;
  :deep(.el-icon) {
    cursor: pointer;
    font-size: 32px;
  }
}
.upload-main {
  width: 100%;
}
:deep(.el-upload-dragger) {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 10px;
  .el-icon--upload {
    font-size: 30px;
    line-height: 30px;
    margin-bottom: 0;
  }
}
:deep(.el-form-item__content) {
  line-height: 24px;
}
.file-list {
  display: flex;
  align-items: center;
  max-width: 100%;
  gap: 10px;
  font-size: 14px;
  line-height: 32px;
  color: #606266;
  .download {
    cursor: pointer;
    color: var(--el-color-primary);
  }
}
</style>
