<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="总结分类" prop="productSummarizeType">
              <el-select v-model="queryParams.productSummarizeType" 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="status">
              <el-select v-model="queryParams.status" placeholder="全部">
                <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="所属项目" prop="search">
              <el-input v-model="queryParams.search" placeholder="请输入所属项目"></el-input>
            </el-form-item>
            <el-form-item label="总结标签" prop="remark">
              <el-input v-model="queryParams.remark" placeholder="请输入总结标签"></el-input>
            </el-form-item>
            <el-form-item label="项目时间">
              <el-date-picker
                v-model="queryParams.projectTime"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                end-placeholder="结束时间"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        <el-card shadow="never" class="mt-[10px]">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAdd">录入</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="info" plain icon="FolderAdd" @click="handleExportTem">下载模板</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="warning" plain icon="Upload" @click="handleImport">导入</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
              </el-col>
              <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
          </template>

          <el-table v-loading="loading" :data="sunnarizeList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" fixed="left" align="center" />
            <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 v-if="prop == 'productSummarizeType'">
                  {{ getStage(row.productSummarizeType) }}
                </span>
                <span v-else-if="prop == 'status'">
                  {{ getStatus(row.status) }}
                </span>
                <span v-else>{{ row[prop] || '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-button link type="primary" @click="handleShow(scope.row)">查看</el-button>
                <el-button link type="primary" :disabled="!['1', '4'].includes(scope.row.status)" @click="handleUpdate(scope.row)"> 修改 </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
          />
        </el-card>

        <!-- 项目总结导入对话框 -->
        <el-dialog v-model="upload.open" :title="upload.title" width="400px" append-to-body>
          <el-upload
            ref="uploadRef"
            :limit="1"
            accept=".xlsx, .xls"
            :headers="upload.headers"
            :action="upload.url"
            :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="false"
            drag
          >
            <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">
                <!-- <div class="el-upload__tip"><el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据</div> -->
                <span>仅允许导入xls、xlsx格式文件。</span>
              </div>
            </template>
          </el-upload>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="submitFileForm">确 定</el-button>
              <el-button @click="upload.open = false">取 消</el-button>
            </div>
          </template>
        </el-dialog>
      </div>
    </transition>
  </div>
</template>

<script setup lang="ts">
import { listSummarize } from '@/api/project/summarize';
import { SummarizeVO } from '@/api/project/summarize/types';
import { globalHeaders } from '@/utils/request';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { summarize_status } = toRefs<any>(proxy?.useDict('summarize_status'));
const { item_stage } = toRefs<any>(proxy?.useDict('item_stage'));

const sunnarizeList = ref<any[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const router = useRouter();

const queryFormRef = ref<ElFormInstance>();

const stageOptions = computed(() => item_stage.value);
const getStage = (id:any) => {
  let item = stageOptions.value.find((item:any) => item.value == id);
  return item?.label + '总结' || '';
};
const statusOptions = computed(() => summarize_status.value);
const getStatus = (id:any) => {
  let item = statusOptions.value.find((item:any) => item.value == id);
  return item?.label || '';
};

interface Header {
  label: string;
  prop: string;
  align?: 'center' | 'left' | 'right';
  minWidth?: string | number;
}
const headers = ref<Header[]>([
  {
    label: '项目总结编号',
    prop: 'id'
  },
  {
    label: '项目总结名称',
    prop: 'productSummarizeName'
  },
  {
    label: '总结分类',
    prop: 'productSummarizeType'
  },
  {
    label: '总结标签',
    prop: 'remark'
  },
  {
    label: '所属项目',
    prop: 'productName'
  },
  {
    label: '总结状态',
    prop: 'status'
  },
  {
    label: '项目时间',
    prop: 'reviewTime'
  }
]);

const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
  status: '',
  productSummarizeType: '',
  remark: '',
  search: '',
  projectTime: []
});

/** 查询expert列表 */
const getList = async () => {
  loading.value = true;
  let startTime = queryParams.value.projectTime?.[0] || '';
  let endTime = queryParams.value.projectTime?.[1] || '';
  const res = await listSummarize({ ...queryParams.value, startTime, endTime });
  sunnarizeList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: SummarizeVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 查看按钮操作 */
const handleShow = (row?: SummarizeVO) => {
  const _id = row?.id || ids.value[0];

  router.push({
    path: '/project/examine',
    query: { id: _id, type: 'summarizeView' }
  });
};

/** 修改按钮操作 */
const handleUpdate = (row?: SummarizeVO) => {
  const _id = row?.id || ids.value[0];

  router.push({ path: '/project/summarizeAdd', query: { id: _id, type: 'edit' } });
};

/** 导入按钮操作 */
const handleAdd = () => {
  router.push({ path: '/project/summarizeAdd', query: { type: 'add' } });
};
/** 导出按钮操作 */
const handleExport = () => {
  let startTime = queryParams.value.projectTime?.[0] || '';
  let endTime = queryParams.value.projectTime?.[1] || '';
  proxy?.download('/zjk-api/productSummarize/export', { ...queryParams.value, startTime, endTime }, `项目总结_${new Date().getTime()}.xlsx`);
};
const handleExportTem = () => {
  proxy?.download('/zjk-api/productSummarize/export/template', {}, `项目总结导入模板.xlsx`);
};
/* 导入 */
const upload = reactive<ImportOption>({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/zjk-api/productSummarize/export/import'
});
const handleImport = () => {
  upload.title = '项目总结导入';
  upload.open = true;
};
const uploadRef = ref<ElUploadInstance>();
/**文件上传中处理 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: UploadFile) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.handleRemove(file);
  if (response.code == 200) {
    ElNotification({
      title: '提示',
      message: '导入成功',
      type: 'success'
    });
  } else {
    ElNotification({
      title: '提示',
      message: response.msg,
      type: 'error'
    });
  }
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  uploadRef.value?.submit();
}
onActivated(() => {
  getList();
});
onMounted(() => {
  getList();
});
</script>
