<template>
  <div>
    <el-card class="box-card" shadow="never">
      <div class="flex">
        <div>
          <el-button
            type="primary"
            @click="
              () => {
                rowData = {};
                visibleEditSurveyResult = true;
              }
            "
            >导出问卷结果</el-button
          >
        </div>
        <div class="flex flex-1 justify-end">
          <div>
            <el-date-picker
              v-model="date"
              type="daterange"
              start-placeholder="请选择日期"
              end-placeholder="请选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              clearable
            />
          </div>
          <el-select
            class="ml-2"
            v-model="query.surveyId"
            placeholder="选择问卷"
            clearable
          >
            <el-option
              v-for="item in surveyList"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            />
          </el-select>
          <SearchArchivesSelect v-model="query.archivesId" class="ml-2" />
          <el-button
            class="ml-2"
            type="primary"
            :icon="Search"
            @click="onSearch"
            :loading="loading"
            >查询</el-button
          >
        </div>
      </div>
    </el-card>
    <div class="mt-4">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="sn" label="问卷结果编号" />

        <el-table-column prop="nickname" label="问卷信息">
          <template #default="{ row }">
            <div class="">
              <el-text>{{ row.survey.name }}</el-text>
              <el-text>({{ row.survey.id }})</el-text>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="开始时间">
          <template #default="{ row }">
            <el-text>{{ row.startTime }}</el-text>
          </template>
        </el-table-column>
        <el-table-column label="提交时间">
          <template #default="{ row }">
            <el-text>{{ row.endTime }}</el-text>
          </template>
        </el-table-column>
        <!-- <el-table-column label="问卷耗时">
          <template #default="{ row }">
            <el-text>{{ getInterval(row.startTime, row.endTime) }}分钟</el-text>
          </template>
        </el-table-column> -->
        <el-table-column label="答题人">
          <template #default="{ row }">
            <el-text
              >{{ row.archives?.name || "匿名"
              }}{{ row.archivesId ? `(${row.archivesId})` : "" }}</el-text
            >
          </template>
        </el-table-column>
        <el-table-column prop="status" label="操作" fixed="right">
          <template #default="scope">
            <el-space spacer="|">
              <el-button
                type="primary"
                link
                @click="showViewResultDialog(scope.row)"
                >查看结果</el-button
              >
            </el-space>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        class="mt-4 justify-end"
        background
        :current-page="query.page"
        :page-size="query.pageSize"
        :total="total"
        layout="total, prev, pager, next"
        @current-change="onChangePage"
      />
    </div>

    <el-dialog v-model="visibleViewResult" title="问卷结果" width="80%">
      <div
        v-for="(item, index) in rowData.answerRaw"
        :key="index"
        class="m-1 bg-gray-100 rounded p-4 mb-3"
      >
        <!-- <div class="text-base mb-2">{{item.title}}</div>
        <div>{{item.value}}</div> -->

        <SimpleQuestionItem :info="item" :id="item.id" :edit="false" />
        <div v-if="item.isSkip" class="text-red-500 text-sm mt-2">
          该题目跳过未作答
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, onMounted, onBeforeUnmount, reactive } from "vue";
import { Search } from "@element-plus/icons-vue";
import { request } from "@/utils/http";
import { getInterval, parseJSON } from "@/utils";
import SimpleQuestionItem from "@/components/Survey/SimpleQuestionItem.vue";

import SearchArchivesSelect from "@/components/Archives/SearchArchivesSelect.vue";
import dayjs from "dayjs";

const tableData = ref([]);
const query = ref({
  page: 1,
  pageSize: 10,
  startTime: "",
  endTime: "",
  archivesId: "",
  surveyId: undefined
});

const date = ref([
  dayjs(Date.now()).subtract(365, "day").format("YYYY-MM-DD"),
  dayjs(Date.now()).add(1, "day").format("YYYY-MM-DD")
]);
const addTypeOptions = reactive([
  {
    label: "全部",
    value: 0
  },
  {
    label: "机构添加",
    value: 1
  },
  {
    label: "自主答题",
    value: 2
  }
]);
const surveyList = ref([]);

const loading = ref(false);
const total = ref(0);
const visibleEditSurveyResult = ref(false);
const visibleEditArchives = ref(false);
const visibleAnswerSurvey = ref(false);
const visibleViewResult = ref(false);
const rowData = ref({});

const getList = async () => {
  loading.value = true;
  const { data } = await request
    .get("/surveyService/mechanism/customSurvey/result/paginate", {
      params: {
        ...query.value,
        startTime: date.value[0],
        endTime: date.value[1]
      }
    })
    .finally(() => {
      loading.value = false;
    });
  tableData.value = data.list;
  total.value = data.total;
};
/**
 * 获取问卷列表
 */
const getSurveyList = () => {
  request
    .get("/surveyService/mechanism/customSurvey/paginate", {
      params: {
        key: undefined,
        pageSize: 9999
      }
    })
    .then(resp => {
      surveyList.value = resp.data.list.map(v => {
        return {
          ...v,
          label: `${v.name}（${v.id}）`
        };
      });
    });
};

const onSearch = () => {
  query.value.page = 1;
  getList();
};
const onChangePage = page => {
  query.value.page = page;
  getList();
};
const handleEdit = row => {
  rowData.value = row;
  visibleEditSurveyResult.value = true;
};

const showViewResultDialog = row => {
  row.answerRaw = parseJSON(row.answerRaw);
  rowData.value = row;
  console.log(row.answerRaw);
  visibleViewResult.value = true;
};

const onDelete = id => {
  if (!id) return;
  request
    .post("/surveyService/mechanism/surveyResult/delete", { id })
    .then(resp => {
      ElMessage.success(resp.message);
      getList();
    });
};

/** 使用公共函数，避免`removeEventListener`失效 */
function onkeypress({ code }) {
  if (code === "Enter") {
    onSearch();
  }
}

onMounted(() => {
  window.document.addEventListener("keypress", onkeypress);
});

onBeforeUnmount(() => {
  window.document.removeEventListener("keypress", onkeypress);
});

const initData = () => {
  getList();
  getSurveyList();
};
initData();
</script>
