<template>
  <div>
    <el-card class="box-card" shadow="never">
      <el-row>
        <el-col :span="12">
          <el-button 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="320">
          <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="showEditSurvey(row)">
                设置问卷
              </el-button>
              <el-button type="primary" link @click="showEditQuestion(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> -->

    <el-dialog
      :close-on-click-modal="false"
      title="问卷设置"
      v-model="setting.visible"
    >
      <el-form>
        <el-form-item label="问卷标题" required>
          <el-input
            v-model="setting.name"
            placeholder="请输入问卷标题，最多60字"
            maxlength="60"
          ></el-input>
        </el-form-item>
        <el-form-item label="问卷简介">
          <el-input
            v-model="setting.description"
            placeholder="请输入简介"
            maxlength="16"
          ></el-input>
        </el-form-item>
        <el-form-item label="重复答题">
          <el-switch v-model="setting.canRepeat"></el-switch>
          <span class="text-yellow-600 text-xs"
            >开启后，用户可以重复多次填写该问卷，后台会记录每次答题结果</span
          >
        </el-form-item>
        <el-form-item label="匿名答题">
          <el-switch v-model="setting.isPublic"></el-switch>
          <span class="text-yellow-600 text-xs"
            >开启后，用户无需登录，点击问卷链接即可答题，问卷结果无法记录答题人，此项开启，重复答题设置将失效，用户可多次进行答题</span
          >
        </el-form-item>
        <el-form-item label="问卷封面" required>
          <div class="flex items-center">
            <el-upload
              :action="`#`"
              :data="{
                type: 'avatar'
              }"
              :headers="{}"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="file => settingUpload(file, 'cover')"
            >
              <el-image
                v-if="setting.cover"
                class="rounded-lg w-24 h-24 mr-4 border border-dashed border-gray-200"
                :src="setting.cover"
                fit="cover"
              />
              <div
                v-else
                class="border-dashed border-2 border-gray-200 rounded-lg w-24 h-24 mr-4 flex items-center justify-center"
              >
                <Plus class="w-5" />
              </div>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="提问者头像">
          <div class="flex items-center">
            <el-upload
              :action="`#`"
              :data="{
                type: 'avatar'
              }"
              :headers="{}"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="file => settingUpload(file, 'systemAvatar')"
            >
              <el-image
                v-if="setting.systemAvatar"
                class="rounded-lg w-12 h-12 mr-4 border border-dashed border-gray-200"
                :src="setting.systemAvatar"
                fit="cover"
              />
              <div
                v-else
                class="border-dashed border-2 border-gray-200 rounded-lg w-12 h-12 mr-4 flex items-center justify-center"
              >
                <Plus class="w-5" />
              </div>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="回答者头像">
          <div class="flex items-center">
            <el-upload
              :action="`#`"
              :data="{
                type: 'avatar'
              }"
              :headers="{}"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="file => settingUpload(file, 'memberAvatar')"
            >
              <el-image
                v-if="setting.memberAvatar"
                class="rounded-lg w-12 h-12 mr-4 border border-dashed border-gray-200"
                :src="setting.memberAvatar"
                fit="cover"
              />
              <div
                v-else
                class="border-dashed border-2 border-gray-200 rounded-lg w-12 h-12 mr-4 flex items-center justify-center"
              >
                <Plus class="w-5" />
              </div>
            </el-upload>
          </div>
        </el-form-item>
      </el-form>
      <el-form label-position="top">
        <el-form-item label="问卷开始文案">
          <el-input
            v-model="setting.greetingText"
            type="textarea"
            maxlength="200"
            show-word-limit
            :autosize="{ minRows: 4 }"
          ></el-input>
        </el-form-item>
        <el-form-item label="问卷结束文案:" required>
          <el-input
            v-model="setting.endingText"
            type="textarea"
            maxlength="200"
            show-word-limit
            :autosize="{ minRows: 4 }"
          ></el-input>
        </el-form-item>
        <el-form-item label="问卷介绍：" required>
          <div class="border border-solid border-gray-200">
            <div>
              <Editor
                v-model:value="setting.remark"
              />
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="setting.visible = false">取消</el-button>
        <el-button type="primary" @click="saveSetting">保存</el-button>
      </template>
    </el-dialog>
    <DialogEditQuestion
      v-model:show="editQuestionVisible"
      :surveyId="editQuestionSurveyId"
      :submit-questions="saveQuestions"
      :submit-logic="saveLogicCode"
    />
  </div>
</template>
<script 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";

import Editor from "@/components/Editor.vue";
import DialogEditQuestion from "@/components/Survey/DialogEditQuestion.vue";

import { Plus, Delete } from "@element-plus/icons-vue";
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/custom/about`;
});

const getList = () => {
  loading.value = true;
  request
    .get("/surveyService/mechanism/customSurvey/paginate", {
      params: query.value
    })
    .then(resp => {
      tableData.value = resp.data.list;
      total.value = resp.data.total;
    })
    .finally(() => {
      loading.value = false;
    });
};
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 handleCopyLink = row => {
  if (!row.id) return;
  handleCopy(url.value + "?id=" + row.sn);
  ElMessage.success("复制成功");
};
const startOrStop = row => {
  ElMessageBox.confirm(
    row.status === 2
      ? "确定要启用吗？启用后该问卷用户可以正常访问 "
      : "确定要暂停吗？暂停后该问卷用户将不能访问?",
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }
  )
    .then(async () => {
      await request.post(`/surveyService/mechanism/customSurvey/updateStatus`, {
        id: row.id,
        status: row.status === 1 ? 2 : 1
      });

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

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

const setting = ref({
  visible: false,
  name: "",
  description: "",
  status: 1,
  canSkipIntro: 1,
  isPublic: false,
  canRepeat: false,
  canSkipResult: 1,
  cover: "",
  systemAvatar: "https://oss.hhmdtech.com/public/chat_doctor_default_avatar.png",
  memberAvatar: "https://oss.hhmdtech.com/public/chat_user_default_avatar.png",
  greetingText:
    "感谢您能抽出几分钟时间来参加本次问卷填写，现在我们就马上开始吧！",
  endingText: "问卷结束，感谢您的填写！",
  remark: ""
});

const settingUpload = debounce(async (file, prop) => {
  setting.value[prop] = await uploadToOSS(file.raw, file.name);
}, 2e2);
const showAddSurvey = async () => {
  setting.value = {
    visible: true,
    name: "",
    description: "",
    status: 1,
    canSkipIntro: 1,
    canSkipResult: 1,
    isPublic: false,
    canRepeat: false,

    cover: "",
    systemAvatar: "https://oss.hhmdtech.com/public/chat_doctor_default_avatar.png",
    memberAvatar: "https://oss.hhmdtech.com/public/chat_user_default_avatar.png",
    greetingText:
      "感谢您能抽出几分钟时间来参加本次问卷填写，现在我们就马上开始吧！",
    endingText: "问卷结束，感谢您的填写！",
    remark: ""
  };
};
const showEditSurvey = row => {
  setting.value = {
    ...row,
    visible: true
  };
};

const saveSetting = async () => {
  const req = {
    ...setting.value
  };
  await request.post(
    "/surveyService/mechanism/customSurvey/updateOrCreate",
    req
  );
  ElMessage.success("保存成功");
  setting.value.visible = false;
  getList();
};

const editQuestionVisible = ref(false);
const editQuestionSurveyId = ref();
const showEditQuestion = row => {
  editQuestionSurveyId.value = row.id;
  editQuestionVisible.value = true;
};

const saveQuestions = async questions => {
  await request.post(`/surveyService/mechanism/customSurvey/updateContent`, {
    surveyId: editQuestionSurveyId.value,
    content: JSON.stringify(questions)
  });
  ElMessage.success("保存成功");
}
const saveLogicCode = async rules => {

  await request.post(`/surveyService/mechanism/customSurvey/updateLogicCode`, {
    surveyId: editQuestionSurveyId.value,
    logicCode: JSON.stringify(rules),
  })
  ElMessage.success("保存成功");
}


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

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

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