<template>
  <div>
    <el-card class="box-card" shadow="never">
      <el-row>
        <el-col :span="12">
          <el-button v-if="curTab == 'custom'" type="primary" @click="showAddSurvey">新建问卷</el-button>
        </el-col>
        <el-col :span="12" class="flex">
          <el-input
            class="ml-2"
            v-model="query.key"
            placeholder="请输入问卷搜索"
            clearable
          />
          <el-button
            class="ml-2"
            type="primary"
            :icon="Search"
            @click="onSearch"
            :loading="loading"
            >查询</el-button
          >
        </el-col>
      </el-row>
    </el-card>
    <div class="mt-4">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="surveyId" label="问卷ID">
          <template #default="{ row }">
            {{ row.id || "-" }}
          </template>
        </el-table-column>
        <el-table-column prop="id" label="问卷名称">
          <template #default="{ row }">
            {{ row.name || "-" }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="用户是否可使用问卷">
          <template #default="{ row }">
            <span
              :class="row.status == 1 ? 'text-green-500' : 'text-red-600'"
              >{{ row.status == 1 ? "启用" : "停用" }}</span
            >
          </template>
        </el-table-column>
        <el-table-column prop="status" label="操作" width="280">
          <template #default="{ row }">
            <el-space spacer="|">
              <el-button type="primary" link @click="startOrStop(row)">{{
                row.status === 1 ? "暂停" : "启用"
              }}</el-button>
              <!-- <el-button type="primary" link @click="getSurveyDetail">
                问卷详情
              </el-button> -->
              <el-button type="primary" link @click="handleEditSurvey(row)">
                设置问卷
              </el-button>
              <el-button type="primary" @click="handleCopyLink(row)" link>
                问卷链接
              </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"
      ></el-pagination>
    </div>
    <ComponentEditSurveyModal
      v-model:show="visibleEditSurvey"
      :rowData="rowData"
      @success="getList"
    ></ComponentEditSurveyModal>

  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, onBeforeUnmount, shallowRef, computed } from "vue";
import { Search } from "@element-plus/icons-vue";
import { uploadToOSS, debounce, request } from "@/utils";

import { ElMessage, ElMessageBox } from "element-plus";

import ComponentEditSurveyModal from "./Components/EditSurveyModal.vue";
import { useUserStoreHook } from "@/store/modules/user";
import { handleCopy } from "@/utils/index";


const curTab = ref('system')
const tableData = ref([]);
const query = ref({
  page: 1,
  pageSize: 10,
  key: ""
});
const surveyList = ref([]);

const loading = ref(false);
const total = ref(0);

const { VITE_APP_H5 } = import.meta.env;
const url = computed(() => {
  let channelAccount = useUserStoreHook()?.profile.id;

  return `${VITE_APP_H5}/#/${channelAccount}/survey`;
});

const rowData = ref({});
const visibleEditSurvey = ref(false);
const getList = () => {
  loading.value = true;
  request
    .get("/surveyService/mechanism/survey/paginate", {
      params: query.value
    })
    .then(resp => {
      tableData.value = resp.data.list;
      total.value = resp.data.total;
    })
    .finally(() => {
      loading.value = false;
    });
};
/**
 * 获取问卷列表
 */
const getSurveyList = () => {
  request
    .get("/backend/survey/list", {
      params: {
        key: undefined
      }
    })
    .then(resp => {
      surveyList.value = resp.data.list;
    });
};

const onSearch = () => {
  query.value.page = 1;
  getList();
};
const onChangePage = page => {
  query.value.page = page;
  getList();
};
const getSurveyDetail = row => {
  request
    .get("/surveyService/mechanism/survey/detail", {
      params: {
        id: "exZYNwWp"
      }
    })
    .then(resp => {})
    .finally(() => {
      loading.value = false;
    });
};

const handleEditSurvey = row => {
  visibleEditSurvey.value = true;
  rowData.value = row;
};

const handleCopyLink = row => {
  if (!row.id) return;
  handleCopy(url.value + "?id=" + row.id);
  ElMessage.success("复制成功");
};
const startOrStop = row => {
  ElMessageBox.confirm(
    row.status === 2
      ? "确定要启用吗？启用后该问卷用户可以正常访问 "
      : "确定要暂停吗？暂停后该问卷用户将不能访问?",
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }
  )
    .then(async () => {
      await request.post(`/surveyService/mechanism/survey/update/status`, {
        id: row.id,
        status: row.status === 1 ? 2 : 1
      });

      ElMessage.success("操作成功");
      getList();
    })
    .catch(() => {});
};

const onDelete = id => {
  // request.post("/backend/role/delete", { id }).then(resp => {
  //   ElMessage.success(resp.message);
  //   getList();
  // });
};

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


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

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

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