<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="所属项目">
              <!-- <el-select v-model="queryParams.productName" placeholder="全部">
                <el-option v-for="item in belongProjectOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
              </el-select> -->
              <el-input v-model="queryParams.search" placeholder="请输入所属项目"></el-input>
            </el-form-item>
            <el-form-item label="项目时间">
              <el-date-picker
                v-model="queryParams.reviewTime"
                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">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
          </template>

          <el-table v-loading="loading" :data="sunnarizeList">
            <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" min-width="150px">
              <template #default="scope">
                <el-button link type="primary" @click="handleShow(scope.row)">查看</el-button>
                <!-- <el-button link type="primary" @click="handleAudit(scope.row)" :disabled="scope.row.status != 2">审核</el-button> -->
                <el-button link type="primary" :disabled="scope.row.isEvaluate != 0" @click="handleEvaluate(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-dialog title="项目总结评价" v-model="evaluateDialog.visible" width="500px" :before-close="closeEvaluateDialog">
            <el-form :model="evaluateDialog.form" ref="evaluateFormRef" :rules="evaluateDialog.rules" label-width="120px">
              <el-form-item label="目标达成：" prop="goalAchievement">
                <el-rate v-model="evaluateDialog.form.goalAchievement" show-score text-color="#ff9900" score-template="{value} 分"></el-rate>
              </el-form-item>
              <el-form-item label="交付质量：" prop="deliveryQuality">
                <el-rate v-model="evaluateDialog.form.deliveryQuality" show-score text-color="#ff9900" score-template="{value} 分"></el-rate>
              </el-form-item>
              <el-form-item label="成本控制：" prop="costControl">
                <el-rate v-model="evaluateDialog.form.costControl" show-score text-color="#ff9900" score-template="{value} 分"></el-rate>
              </el-form-item>
              <el-form-item label="风险管理：" prop="riskManagement">
                <el-rate v-model="evaluateDialog.form.riskManagement" show-score text-color="#ff9900" score-template="{value} 分"></el-rate>
              </el-form-item>
              <el-form-item label="项目价值：" prop="projectValue">
                <el-rate v-model="evaluateDialog.form.projectValue" show-score text-color="#ff9900" score-template="{value} 分"></el-rate>
              </el-form-item>
              <el-form-item label="项目总结评价：">
                <el-input
                  v-model="evaluateDialog.form.projectSummaryEvaluation"
                  :rows="5"
                  resize="none"
                  type="textarea"
                  maxlength="200"
                  show-word-limit
                  placeholder="请输入项目总结评价"
                ></el-input>
              </el-form-item>
              <el-form-item label="线下评价文件：">
                <el-upload
                  ref="uploadRef"
                  :headers="upload.headers"
                  :action="upload.url"
                  :limit="1"
                  accept=".xls,.xlsx,.doc,.docx,.txt,.zip,.pdf"
                  v-model:file-list="evaluateDialog.form.evaluateFile"
                  :auto-upload="true"
                  drag
                  style="flex: 1"
                  :on-exceed="handleExceed"
                >
                  <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>
            <template #footer>
              <span>
                <el-button @click="closeEvaluateDialog">取消</el-button>
                <el-button type="primary" @click="confirmEvaluateDialog">确定</el-button>
              </span>
            </template>
          </el-dialog>
        </el-card>
      </div>
    </transition>
  </div>
</template>

<script setup lang="ts">
import { getAuditList, setEvaluate } 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<SummarizeVO[]>([]);
const loading = ref(true);
const showSearch = 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: 'summarizeId'
  },
  {
    label: '项目总结名称',
    prop: 'productSummarizeName'
  },
  {
    label: '总结分类',
    prop: 'productSummarizeType'
  },
  {
    label: '所属项目',
    prop: 'productName'
  },
  {
    label: '状态',
    prop: 'status'
  },
  {
    label: '项目时间',
    prop: 'reviewTime'
  }
]);

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

/** 查询expert列表 */
const getList = async () => {
  loading.value = true;
  let startTime = queryParams.value.reviewTime?.[0] || '';
  let endTime = queryParams.value.reviewTime?.[1] || '';
  const res = await getAuditList({ ...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 handleShow = (row?: SummarizeVO) => {
  const _id = row?.summarizeId;
  const auditid = row?.id;
  router.push({
    path: '/project/examine',
    query: { id: _id, auditid, type: 'view' }
  });
};

const upload = {
  headers: globalHeaders(),
  url: import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload'
};
const evaluateFormRef = ref(null);
const evaluateDialog = ref({
  visible: false,
  form: {
    goalAchievement: 0,
    deliveryQuality: 0,
    costControl: 0,
    riskManagement: 0,
    projectValue: 0,
    projectSummaryEvaluation: '',
    evaluateFile: []
  },
  rules: {
    goalAchievement: [{ required: true, message: '请选择目标达成分数', trigger: 'change' }],
    deliveryQuality: [{ required: true, message: '请选择交付质量分数', trigger: 'change' }],
    costControl: [{ required: true, message: '请选择成本控制分数', trigger: 'change' }],
    riskManagement: [{ required: true, message: '请选择风险管理分数', trigger: 'change' }],
    projectValue: [{ required: true, message: '请选择项目价值分数', trigger: 'change' }]
  }
});
const uploadRef = ref<ElUploadInstance>();
const handleExceed = () => {
  ElNotification({
    title: '提示',
    message: '最多只能上传一个文件',
    type: 'error'
  });
};
const closeEvaluateDialog = () => {
  evaluateFormRef.value.resetFields();
  evaluateDialog.value.visible = false;
};
const activeRow = ref(null);
const handleEvaluate = (row?: SummarizeVO) => {
  evaluateDialog.value.visible = true;
  activeRow.value = row;
};
const confirmEvaluateDialog = async () => {
  const params = {
    productSummarizeId: activeRow.value.id,
    summarizeId: activeRow.value.summarizeId,
    ...evaluateDialog.value.form,
    evaluateFile: evaluateDialog.value.form.evaluateFile?.[0]?.response.data.ossId || ''
  };
  let res = await setEvaluate(params);
  if (res.code != 200) {
    ElNotification({
      title: '提示',
      message: res.msg,
      type: 'error'
    });
    return;
  }
  ElNotification({
    title: '提示',
    message: '评价成功',
    type: 'success'
  });
  await getList();
  closeEvaluateDialog();
};
onActivated(() => {
  getList();
});
onMounted(() => {
  getList();
});
</script>
