<template>
  <div
    class="diagram-content-wrapper"
    v-loading.fullscreen.lock="spinning"
    element-loading-text="Loading..."
    element-loading-background="rgba(255, 255, 255, 0.8)"
    v-infinite-scroll="load"
    :infinite-scroll-disabled="disabled"
    :infinite-scroll-distance="100"
  >
    <div class="search-wrapper">
      <div class="top">
        <sub-title>基础分析</sub-title>
        <!-- <a-button type="primary" size="small" @click="handleExportAllData"
          >导出</a-button
        > -->
      </div>
      <newSearch
        ref="newSearchRef"
        @onSearch="onSearch"
        @openModal="openModal"
        @searchPlan="searchPlan"
        @saveVisOpen="saveVisOpen"
        :versions="versions"
        :logics="logics"
        :questions="questions"
        :count="dataCount"
        :publish_types="publish_types"
        :filterData="filterData"
        :isArt="isArt"
        :nowPlanVal="nowPlanVal"
      ></newSearch>
    </div>
    <div v-if="diagramList.length > 0">
      <!-- add by zhangweiwei 20250331_ai AI 洞察 start  -->
      <ai-insight-result-overall
        v-if="aiInsightResult || (typeof aiInsightLoading !== 'undefined')"
        :result="aiInsightResult"
        :loading="aiInsightLoading"
      />
      <!-- add by zhangweiwei 20250331_ai AI 洞察 end  -->
      <div class="diagram-container">
        <BasicDiagramItem
          @remove-chart="onRemove"
          @onFull="onFullScreen"
          v-for="(item, index) in diagramList"
          :key="index"
          :data="item"
          :sn="sn"
          :tableSearchInfo="tableSearchInfo"
          :permission="permission"
          :isLoading="isLoading"
        >
        </BasicDiagramItem>
      </div>
    </div>
  </div>
  <div v-if="!spinning && diagramList.length === 0" class="no-data">
    <img :src="require('@/assets/img/publish/no-data.png')" alt="" class="empty-img" />
    <div class="empty-text">您的问卷暂无数据</div>
  </div>

  <FullScreenModal
    v-model:visible="fullScreenVisible"
    :tableSearchInfo="tableSearchInfo"
    :data="fullData"
    :question-list="questionList"
    :sn="sn"
  ></FullScreenModal>
  <newModal
    ref="newModalRef"
    :isFilterInfo="isFilterInfo"
    :operType="operType"
    :filterNewData="filterNewData"
    @modalOk="modalOk"
    @isUse="isUseFun"
    @isSave="isSaveFun"
    @resetPlan="resetPlan"
    @getNewData="getDiagramData"
    @resShowFlag="resShowFlag"
  />
</template>
<script setup>
import 'element-plus/theme-chalk/el-loading.css';
import { onMounted, ref, computed, provide, nextTick, watch } from 'vue';
import { useRoute } from 'vue-router';
import BasicDiagramItem from '@/views/DataAnalyse/diagram/components/diagram-item-new.vue';
import SubTitle from '../components/SubTitle.vue';
import search from '../components/diagram/search.vue';
import AiInsightResultOverall from '@views/DataAnalyse/diagram/components/AiInsightResultOverall.vue';
import FullScreenModal from '@views/DataAnalyse/diagram/components/FullScreenModal';
import newSearch from '@/views/DataAnalyse/components/diagram/newSearch';

import { aiInsight, getDiagramAnalysis } from '@/api/data-analyse';
import { getAuthRoles } from '@/api/role';
import { convertQueryToString } from '@/utils/httpFormat';
import { useStore } from 'vuex';
import useEmitter from '@/composables/useEmitter';
import { chartList } from '@/views/DataAnalyse/diagram/composables/useInstance';
import newModal from '@/views/DataAnalyse/components/diagram/newModal';
import taskManager from '@/utils/ai/ai-task-manager';
import { TASK_TYPE } from '@/utils/ai/ai-task';

const store = useStore();
const emitter = useEmitter();

const route = useRoute();
const sn = route.query.sn;
// 获取权限信息
const permission = ref([]);
const spinning = ref(false);

const isLoading = computed(() => spinning.value);
const loadAllData = ref(false);

const exportList = ref([]);
provide('exportList', exportList);

const diagramItem = ref(null);

/** add by zhangweiwei 20250331_ai AI 洞察 start */
const aiInsightResult = ref('');
const aiInsightLoading = ref(undefined);
// const tasks = taskManager.tasks.value;
/** add by zhangweiwei 20250331_ai AI 洞察 end */

function getPermissionInfo() {
  getAuthRoles({
    flag: 2,
    sn
  }).then((res) => {
    try {
      const analysePermisson = res.data.find((item) => item.id === 183) || {}; // 183: 数据分析
      const chartPermisson = analysePermisson.second_level_list.find((item) => item.id === 193) || {}; // 193 图表分析
      const result = chartPermisson.three_level_list.map((item) => item.display_name);
      permission.value = result;
    } catch (e) {
      console.log(e);
    }
  });
}
// 搜索
const tableSearchInfo = ref({});
function onSearch(payload) {
  payload.type = 0;
  tableSearchInfo.value = payload;
  diagramList.value = [];
  current_page.value = 1;
  getDiagramData();
}

function onRemove() {
  current_page.value = 1;
  diagramList.value = [];
  getDiagramData();
}

// 获取列表数据
const diagramList = ref([]);
const current_page = ref(1);
const total = ref(0);
const per_page = ref(6);
const hasElementAfterRemove = ref(false);

const disabled = computed(
  () =>
    hasElementAfterRemove.value
    || loadAllData.value
    || spinning.value
    || (diagramList.value.length > 0 && diagramList.value.length === total.value)
);
const questionList = computed(() => diagramList.value.map((item) => item.question_index));
function getDiagramData() {
  const params = {
    ...tableSearchInfo.value,
    page: current_page.value,
    per_page: per_page.value
  };
  spinning.value = true;
  return getDiagramAnalysis(sn, params)
    .then((res) => {
      console.log('res', res);
      const _total = +res.meta.total || 0;
      total.value = _total;
      per_page.value = res.meta.per_page;
      dataCount.value = res.other.answerCount;
      aiInsightResult.value = res.other.overall_conclusion;
      hasElementAfterRemove.value = _total === 0 ? true : false;

      let response_data = res.data
        .filter((item) => item !== null)
        .map((item, index) => {
          item.option.forEach((i) => {
            i.groupTitle = i.groupTitle || ''; // fix: 全部数据的 groupTitle 都为 null 时，图表不显示
          });

          return {
            ...item,
            index,
            type: item.question_type,
            is_quick: item.config.quick_type ? true : false,
            question_type: item.config.quick_type ? item.config.quick_type : item.question_type
          };
        });
      diagramList.value.push(...response_data);
      console.log('diagramList--------', diagramList.value);

      // 当前页面题型总数
      // 当前页面题型总数
      store.dispatch('tableAnalysis/changeNowCount', diagramList.value.length);
      store.dispatch('tableAnalysis/diagramList', diagramList.value);
    })
    .finally(() => {
      spinning.value = false;
      emitter.emit('reset-chart-type');
    });
}

const fullData = ref();
const fullScreenVisible = ref(false);

function onFullScreen(data) {
  fullData.value = data;
  fullScreenVisible.value = true;
}
const versions = ref([]);
const questions = ref([]);
const dataCount = ref(0);
const logics = ref([]);
const publish_types = ref([]);
const getSurveysHead = async () => {
  try {
    questions.value = [];
    versions.value = [];
    const res = await store.dispatch('dataFilter/getSurveysHead', { sn });
    // 版本
    versions.value = res.filters.versions;
    // 投放方式
    publish_types.value = res.filters.publish_types;
    // 配额
    logics.value = res.filters.logics;
    // 完成
    // answer_count.value = res.answer_count;
    // 投放数量
    // publish_number.value = res.publish_number;
    // 今日
    // today_answer_count.value = res.today_answer_count;
    // 配置
    // answer_columns.value = res.answer_columns;3
    // columns.value = res.columns;
    // 筛选条件

    questions.value = res?.filters?.answer_questions;
  } catch (error) {
    console.error(error);
  }
};
async function handleExportAllData() {
  loadAllData.value = true;
  if (!total.value) return;
  if (diagramList.value.length < total.value) {
    current_page.value = 1;
    per_page.value = total.value;
    diagramList.value = [];
    // exportList.value = [];
    chartList.value = [];
    await getDiagramData();
    const list = chartList.value.map((item) => {
      const question_index = item.question_index;
      const imageUrl = item.instance?.chart?.ImageUrl || 'nothing';
      return {
        question_index,
        imageUrl
      };
    });
  }
}
async function load() {
  if (total.value == 0 || total.value > current_page.value) {
    current_page.value = current_page.value + 1;
    try {
      await getDiagramData();
    } catch (error) {
      spinning.value = false;
    }
  }
}
// 弹窗操作
const newModalRef = ref(null);
const newBtnListRef = ref(null);
const fullFlag = ref(false);
const modalOk = (e) => {
  console.log('modalOk', e);
  if (e === 'confirmDel') {
    newBtnListRef.value.delSurveysAnswers(fullFlag.value);
  }
  if (e === 'confirmDelAll') {
    newBtnListRef.value.delSurveysAnswers(fullFlag.value);
  }
};
const operType = ref(0);

// 打开方案管理
const openModal = () => {
  newModalRef.value.modalVis = true;
};
// 控制显示筛选数目
const resShowFlag = (flag) => {
  newSearchRef.value.resShowFlag = flag;
};
// 根据方案筛选信息
const nowPlanVal = ref(-1);
const newSearchRef = ref(null);
const isUseFun = async (e) => {
  onSearch(e);
  searchPlan(e, 'isUseFun');
  console.log('当前使用条件', e);
  if (e.id) {
    await newSearchRef.value.getSurveysAnswerFilter();
    nowPlanVal.value = e.id;
  }
};
const isSaveFun = async (e) => {
  searchPlan(e, 'isSaveFun');
  console.log('当前使用条件', e);
  if (e.id) {
    await newSearchRef.value.getSurveysAnswerFilter();
    nowPlanVal.value = e.id;
  }
};
const resetPlan = async (e) => {
  await newSearchRef.value.getSurveysAnswerFilter();
  if (!e) {
    await newSearchRef.value.clearInfo();
    nowPlanVal.value = '-1';
  }
};
// 修改方案信息
const filterData = ref({});
const isArt = ref(false);
const searchPlan = (e, isType) => {
  console.log('修改方案信息', e);
  if (isType && isType == 'isSaveFun') {
    if (newSearchRef.value.filterPlan.filterListVal == e.id) {
      filterData.value = e;
    }
  } else {
    filterData.value = e;
  }
  isArt.value = false;
  if (e) {
    isArt.value = true;
  }
};
onMounted(async () => {
  try {
    nextTick(() => {
      newSearchRef.value.isOpen = false;
    });
    await getSurveysHead();
    await newSearchRef.value.getSurveysAnswers();
    // await getDiagramData()
    getPermissionInfo();
  } catch (error) {
    spinning.value = false;
  }
});

watch(
  () => taskManager.tasks.value,
  (newTasks) => {
    console.log('任务列表发生变化:', newTasks);
    aiInsightLoading.value = taskManager.findTask(TASK_TYPE.INSIGHT, sn)?.isPolling;
    if (aiInsightLoading.value) {
      aiInsightResult.value = '';
    }
  },
  { immediate: true, deep: true }
);
</script>

<style lang="scss">
.diagram-content-wrapper {
  // height:100%;
  overflow: hidden;
  padding-bottom: 20px;
}
.diagram-toolip-img {
  display: inline-block;
  width: 40px;
  height: 40px;
  img {
    display: inline-block;
    width: 40px;
    height: 40px;
  }
}
.search-wrapper {
  padding: 24px 32px 32px 32px;
  // box-shadow: 0px 0px 6px 0px rgba(0,0,0,0.1);
  background: #fff;
  .top {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
.diagram-wrapper {
  display: flex;
  flex-wrap: wrap;
}

.diagram-container {
  display: grid;
  grid-template-columns: repeat(2, minmax(400px, 50%));
  grid-row-gap: 24px;
  grid-column-gap: 24px;
  width: 100%;
  padding: 0 32px 30px;
  .ant-popover {
    width: 300px;
  }
}

.page-container {
  position: absolute;
  bottom: 10px;
  right: 8px;
  margin-top: 20px;
  text-align: right;
}

.no-data {
  height: 400px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.empty-img {
  display: block;
  width: 160px;
  height: 160px;
  margin-bottom: 8px;
}

.empty-text {
  color: #70b936;
  font-size: 14px;
}

//设置图标颜色
.el-loading-spinner .path {
  stroke: #70b936;
}
//设置文字颜色
.el-loading-spinner .el-loading-text {
  color: #70b936;
}
</style>
