import { getSurveysPage, deleteSurveys, saveTemplates } from '@/api/home';
import { ref } from 'vue';
import { showDialog, showConfirmDialog, showFailToast, showToast } from 'vant';
import { getSurveysDetail } from '@/api/design';
import { getQuestionList } from '@/api/survey';
import { questionTypeMap } from '@/utils/question/typeMapping';

const searchValue = ref('');
const survey = ref<SurveyItem[]>([]);
const total = ref(0);
const loading = ref(false);
const requestLoading = ref(false);
const finished = ref(false);
const currentSurvey = ref<SurveyItem>();

const requestSingle = ref(true);

async function fetchSingleSurvey(sn: string) {
  const res = await getSurveysDetail(sn);
  // const res = await getSetting({sn})
  // console.log(res);
  if (res.data.code === 0) {
    currentSurvey.value = res.data.data;
  }
}

async function fetchSurveys(form: any) {
  if (!requestSingle.value) return;
  requestSingle.value = false;
  requestLoading.value = true;
  const params = {
    page: form.page,
    per_page: form.pageSize,
    group_id: 0,
    // project_name: searchValue.value
    key_word: form.key_word
  };
  const res = await getSurveysPage(params);
  if (res.data.code === 0) {
    survey.value = survey.value.concat(res.data.data);
    total.value = res.data.meta.total;
    loading.value = false;
    // 数据全部加载完成
    if (survey.value.length >= total.value) {
      finished.value = true;
    }
  } else {
    // Toast()
  }
  requestLoading.value = false;
  requestSingle.value = true;
}

function deleteItem(item: SurveyItem, form: any) {
  showDialog({
    title: `确认删除问卷 "${item.project_name}" ?`,
    showCancelButton: true,
    confirmButtonColor: '#03B03C'
  })
    .then(async () => {
      const res = await deleteSurveys(item.sn);
      if (res.data.message) {
        showToast(res.data.message);
      } else {
        showToast('删除成功！');
      }
      form.page = 1;
      clearSurveys();
      await fetchSurveys(form);
    })
    .catch(() => {
      // on cancel
    });
}

// 保存为模板
async function saveTemplate(item: SurveyItem) {
  const data = JSON.parse(JSON.stringify(item));

  // 如果没有通过校验， 弹出提示窗不进行下一步
  if (!(await validateSurvey(data))) {
    showDialog({
      title: '无法保存模板',
      message: '问卷内包含移动端暂未兼容题型/逻辑设置，请至PC端编辑后重新保存。'
    });
    return;
  }
  const res = await saveTemplates(item.sn, data);
  if (res.data.code === 200 || res.data.code === 201) {
    showConfirmDialog({
      message: '模板保存成功，请前往更多模板页面查看',
      showCancelButton: false
    });
  } else {
    showFailToast(res.data);
  }
}
function clearSurveys() {
  survey.value = [];
}

/**
 * 校验问卷是否可以保存为模板
 * @param data
 */
async function validateSurvey(survey: SurveyItem): Promise<boolean> {
  const { data } = await getQuestionList(survey.sn);
  const { questions, logics } = data.data;
  const questionValid = questions.every((question: any) => {
    if (!questionTypeMap.has(question.question_type)) {
      return false;
    }
    return true;
  });
  // 2 自动填写， 3 是逻辑配额
  const logicValid = logics.every((logic: any) => {
    if ([0, 1].includes(logic.skip_type)) {
      return true;
    }
  });
  //  判断是否是随机题组/循环题组
  const surveyValid = !data.data.survey.group_pages?.length > 0;
  const cycleValid = !data.data?.cycle_pages?.length > 0;
  return questionValid && logicValid && surveyValid && cycleValid;
}

export {
  fetchSurveys,
  loading,
  finished,
  survey,
  total,
  searchValue,
  deleteItem,
  saveTemplate,
  currentSurvey,
  requestLoading,
  fetchSingleSurvey,
  clearSurveys
};
