<template>
  <div class="p-2 h-full flex flex-col">
    <PageHeader></PageHeader>
    <el-card class="mt-20px" style="min-height: 80px">
      <div class="flex justify-between">
        <div class="tabs">
          <div :class="{ 'active': activeTab == 'preview' }" class="tab-item" @click="handleTabClick('preview')">
            <div class="tab-content">问卷预览</div>
          </div>
          <div :class="{ 'active': activeTab == 'detail' }" class="tab-item" @click="handleTabClick('detail')">
            <div class="tab-content">调查详情</div>
          </div>
        </div>
        <div class="tabs">
          <el-button @click="handleBack">返回</el-button>
        </div>
      </div>
    </el-card>
    <div class="flex-1 mt-20px">
      <el-card v-if="activeTab == 'preview'">
        <div class="container_box flex-1">
          <div v-loading="viewLoading" class="contentBox h-full">
            <div class="detail-header">
              <h2>{{ viewData.title }}</h2>
              <p style="color: #666">{{ viewData.description }}</p>
            </div>
            <el-divider />
            <div class="detail-content">
              <div v-for="(q, index) in viewData.content" :key="q.cid" class="question-item">
                <div class="title">
                  <span style="font-weight: bold">{{ index + 1 }}. {{ q.title }}</span>
                  <span v-if="q.required" style="color: #f56c6c; margin-left: 5px">*</span>
                </div>
                <div class="type-tag">
                  <el-tag size="small">{{ getComponentLabel(q.type) }}</el-tag>
                </div>

                <!-- 单选题/多选题选项展示 -->
                <div v-if="q.type === 'radio' || q.type === 'checkbox'" class="options">
                  <div v-for="(opt, idx) in q.options" :key="idx" class="option-item">
                    <span :class="q.type === 'radio' ? 'radio__type' : 'checkbox__type'"></span>
                    <span class="option-label">{{ opt.label }}</span>
                  </div>
                </div>
                <!-- 填空题/多行文本展示 -->
                <div v-else-if="q.type === 'input'" class="input-placeholder">
                  <el-input disabled placeholder="用户输入区域" />
                </div>
                <div v-else-if="q.type === 'textarea'" class="input-placeholder">
                  <el-input disabled placeholder="用户输入区域" type="textarea" />
                </div>
              </div>
            </div>
            <el-divider />
            <div>
              <span>备注: {{ viewData.remark ? viewData.remark : '暂无' }}</span>
            </div>
          </div>
        </div>
      </el-card>
      <el-card v-else-if="activeTab == 'detail'">
        <div>
          <el-table :data="list" style="width: 100%">
            <el-table-column label="答题人" prop="answerName" />
            <el-table-column label="提交时间" prop="type" />
            <el-table-column label="操作" prop="options">
              <template #default="scope">
                <el-button link type="primary" @click="handleGetMain(scope.row.id)">查看详情</el-button>
              </template>
            </el-table-column>
          </el-table>
          <Pagination
            v-show="total > 0"
            v-model:limit="queryParams.pageSize"
            v-model:page="queryParams.pageNum"
            :total="total"
            @pagination="getList"
          />
        </div>
      </el-card>
    </div>
    <el-dialog v-model="dialog.visible" :title="dialog.title" append-to-body width="680px">
      <el-form ref="houseRentalFormRef" :model="form.content" label-width="120px">
        <div class="detail-header">
          <h2>{{ viewData.title }}</h2>
          <p style="color: #666">{{ viewData.description }}</p>
        </div>
        <el-divider />
        <div class="detail-content">
          <div v-for="(q, index) in form.content" :key="q.cid" class="question-item">
            <div class="title">
              <span style="font-weight: bold">{{ index + 1 }}. {{ q.title }}</span>
              <span v-if="q.required" style="color: #f56c6c; margin-left: 5px">*</span>
            </div>
            <div class="type-tag">
              <el-tag size="small">{{ getComponentLabel(q.type) }}</el-tag>
            </div>

            <!-- 单选题/多选题选项展示 -->
            <div v-if="q.type === 'radio'" class="options">
              <el-radio-group v-model="q.value as string">
                <div>
                  <div v-for="(opt, idx) in q.options" :key="idx">
                    <el-radio :value="opt.label" disabled>{{ opt.label }}</el-radio>
                  </div>
                </div>
              </el-radio-group>
            </div>
            <div v-if="q.type === 'checkbox'" class="options">
              <el-checkbox-group v-model="q.value as string[]">
                <div v-for="(opt, idx) in q.options" :key="idx">
                  <el-checkbox :label="opt.label" :value="opt.label" disabled />
                </div>
              </el-checkbox-group>
            </div>
            <!-- 填空题/多行文本展示 -->
            <div v-else-if="q.type === 'input'" class="input-placeholder">
              <el-input v-model="q.value as string" disabled placeholder="" />
            </div>
            <div v-else-if="q.type === 'textarea'" class="input-placeholder">
              <el-input v-model="q.value as string" disabled placeholder="" type="textarea" />
            </div>
          </div>
        </div>
        <el-divider />
        <div>
          <span>备注: {{ viewData.remark ? viewData.remark : '暂无' }}</span>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { getQuestionnaire, getQuestionnaireAnswer, getQuestionnaireAnswerMain } from '@/api/system/Questionnaire';
import { QuestionComponentItem } from '@/api/system/Questionnaire/type';
import { ref } from 'vue';
import PageHeader from '@/components/Pageheader/index.vue';
import QuestionnaireEdit from '@/views/system/Questionnaire/components/QuestionnaireEdit.vue';
import Pagination from '@/components/Pagination/index.vue';
import { UploadFilled } from '@element-plus/icons-vue';
const viewLoading = ref(false);
const viewData = ref({
  'id': '',
  'villageId': null,
  'title': '',
  'description': '',
  'content': [] as QuestionComponentItem[],
  'status': '0',
  'scope': '0',
  'residents': '',
  'startTime': '2026-04-03 00:00:00',
  'endTime': '2026-04-09 00:00:00',
  'remark': ''
});
const queryParams = ref({
  pageNum: 1,
  pageSize: 10
});
const total = ref(0);
const route = useRoute();

const activeTab = ref<'preview' | 'detail'>('preview');
function handleTabClick(tab: 'preview' | 'detail') {
  activeTab.value = tab;
  if (activeTab.value === 'detail') {
    getList();
  }
}

const viewid = ref(null);
// 组件库定义（用于获取类型名称）
const componentList = [
  { type: 'radio', label: '单选题' },
  { type: 'checkbox', label: '多选题' },
  { type: 'input', label: '填空题' },
  { type: 'textarea', label: '多行文本' }
];
// 辅助方法：获取组件名称
function getComponentLabel(type) {
  const item = componentList.find((c) => c.type === type);
  return item ? item.label : '';
}

function init() {
  if (route.query.id) {
    viewid.value = route.query.id;
  }
  viewLoading.value = true;
  getQuestionnaire(viewid.value).then((res) => {
    viewData.value = {
      ...viewData.value,
      ...res.data,
      content: [] as QuestionComponentItem[]
    };
    if (typeof res.data.content === 'string') {
      viewData.value.content = JSON.parse(res.data.content) as QuestionComponentItem[];
    } else {
      viewData.value.content = res.data.content as QuestionComponentItem[];
    }

    viewLoading.value = false;
  });
}
init();
const router = useRouter();
function handleBack() {
  router.back();
}

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
type FormQuestionComponentItem = QuestionComponentItem & { value?: string | string[] };
const form = ref({
  id: '',
  questionnaireId: '',
  answerContent: [] as FormQuestionComponentItem[],
  answerId: '',
  answerName: '',
  answerStatus: '',
  content: [] as FormQuestionComponentItem[]
});
const list = ref([]);
function getList() {
  getQuestionnaireAnswer({
    pageSize: queryParams.value.pageSize,
    pageNum: queryParams.value.pageNum,
    questionnaireId: viewid.value
  }).then((res) => {
    list.value = res.rows;
    total.value = res.total;
  });
}
function handleGetMain(id: string) {
  getQuestionnaireAnswerMain(id).then((res) => {
    form.value = res.data;
    form.value.answerContent = (JSON.parse(res.data.answerContent) as QuestionComponentItem[]) ?? [];
    form.value.content = (JSON.parse(res.data.content) as QuestionComponentItem[]) ?? [];
    form.value.content.forEach((item) => {
      const find = form.value.answerContent.find((i) => i.cid === item.cid);
      if (find) {
        item.value = find.value;
      }
    });
    dialog.visible = true;
    dialog.title = '问卷调查回答详情';
    console.log(form.value);
  });
}
</script>

<style lang="scss" scoped>
.tabs {
  display: flex;
  flex-direction: row;
  justify-content: start;
  .tab-item {
    font-weight: bold;
    padding: 10px 10px;
    cursor: pointer;
    margin-right: 10px;
    letter-spacing: 3px;
    &:hover {
      color: #409eff;
    }
    &.active {
      color: #409eff;
      border-bottom: 4px solid #409eff;
    }
  }
}

.titlebox {
  height: 50px;
  line-height: 50px;
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
}
.container_box {
  background-color: white;
  font-size: 16px;
  padding: 20px 20px 60px;
}
.contentBox {
  width: 1200px;
  margin: 0 auto;
}
.detail-header {
  margin-bottom: 20px;

  h2 {
    text-align: center;
  }
}

.question-item {
  margin-bottom: 25px;
  padding: 15px;
  border-radius: 8px;
  background: #fafafa;

  .title {
    margin-bottom: 8px;
  }

  .type-tag {
    margin-bottom: 12px;
  }

  .options {
    margin-top: 10px;
    .option-item {
      display: flex;
      align-items: center;
      margin-bottom: 8px;
      color: #666;
      position: relative;
      .option-label {
        padding-left: 20px;
      }
      .radio__type {
        position: absolute;
        top: 6px;
        width: 12px;
        height: 12px;
        border: 1px solid #666;
        border-radius: 50%;
      }
      .checkbox__type {
        position: absolute;
        top: 6px;
        width: 12px;
        height: 12px;
        border: 1px solid #666;
      }
      .el-icon {
        margin-right: 8px;
        color: #909399;
      }
    }
  }

  .input-placeholder {
    margin-top: 10px;
  }
}
</style>
