<template>
  <div class="pb-10">
    <!-- <AutoCompleteStep @confirm="stepConfirm" /> -->
    <div v-for="(item, index) in list" :key="index" class="mb-6">
      <div
        v-for="(child, childIdx) in item.currentData.question"
        :key="childIdx"
        class="m-2 my-4 flex item-start"
      >
        <div class="w-12 h-12 rounded-full select-none mr-4">
          <img src="@/assets/icon-ai-avatar.png" alt="" />
        </div>
        <div
          class="drop-shadow p-4 w-fit max-w-[70%] bg-white dialog-content rounded-xl"
        >
          <div class="overflow-hidden">
            <QuestionItem
              v-model:info="item.currentData.question[childIdx]"
              class="animate__faster animate__animated animate__slideInRight py-0"
              :class="{
                'pointer-events-none filter grayscale':
                  item.currentData.state < currentState || isEnd
              }"
              :style="`transition-delay:${75 * childIdx}ms;`"
              @checkMatrix="checkMatrix"
              @reply="reply"
            ></QuestionItem>
          </div>
        </div>
      </div>
    </div>
    <div
      v-if="!isEnd  && !msgLoading"
      class="flex justify-start mt-6 px-1"
    >
      <el-button type="primary" size="large" class="px-16 ml-16" @click="next"
        >保存</el-button
      >
    </div>
    <div v-if="msgLoading" class="mb-6">
      <div class="m-2 flex item-start">
        <div class="w-12 h-12 rounded-full select-none mr-4">
          <img src="@/assets/icon-ai-avatar.png" alt="" />
        </div>
        <div
          class="drop-shadow p-4 w-fit max-w-[70%] bg-gray-50 dialog-content rounded-xl"
        >
          <div class="overflow-hidden">
            <span
              class="px-2 animate__faster animate__animated animate__slideInRight"
              >分析中...</span
            >
          </div>
        </div>
      </div>
    </div>
    <div v-if="isEnd">
      <!-- <p>结论：</p> -->

      <div class="m-2 flex item-start">
        <div class="w-12 h-12 rounded-full select-none mr-4">
          <img src="@/assets/icon-ai-avatar.png" alt="" />
        </div>
        <div
          class="drop-shadow p-4 w-fit max-w-[70%] bg-gray-50 dialog-content rounded-xl"
        >
          <div class="pb-4">
            <div class="mb-4">
              <div class="text-gray-700 text-sm mb-2">分析结果：</div>
              <div>{{ assessmentInfo.result }}</div>
            </div>
            <div v-if="assessmentInfo.accordance">
              <div class="text-gray-700 text-sm mb-2">分析依据：</div>
              <div
                v-for="(item, index) in assessmentInfo.accordance"
                :key="index"
              >
                {{ item }}
              </div>
            </div>
          </div>
          <div class="flex justify-start py-2">
            <el-button type="warning" plain size="large" @click="reset">
              重新分析</el-button
            >
            <el-button
              type="primary"
              plain
              class="relative bg-white hover:bg-blue-50 hover:text-blue-500"
              size="large"
              @click="confirm"
            >
              <span class="relative flex h-3 w-3 mr-2">
                <span
                  class="animate-ping absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-75"
                ></span>
                <span
                  class="relative inline-flex rounded-full h-3 w-3 bg-blue-600"
                ></span>
              </span>
              <span>查看分析结果</span>
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import {
  request,
  parseJSON,
  formatResultList,
  formatItemVal,
  formatData,
  sleep
} from "@/utils";
import QuestionItem from "@/views/dataCenter/components/QuestionItem.vue";
import AutoCompleteStep from "./AutoCompleteStep.vue";
import { nextTick } from "vue";
import { ElMessage } from "element-plus";

const props = defineProps({
  userId: {
    type: String,
    default: ""
  },
  diseaseId: {
    type: String,
    default: ""
  }
});
const emit = defineEmits(["confirm"]);
const msgLoading = ref(false);
const basicData = ref({
  scenes: "0",
  userId: props.userId,
  diseaseId: props.diseaseId,
  evaluationsNum: 0
});
const processData = ref([]);
const currentState = ref(0);
const datas = ref();
const isEnd = ref(false);
const assessmentInfo = ref();
const list = ref([]);

const next = () => {
  const cur = list.value.find(v => v.currentData.state == currentState.value);
  console.log(cur, cur.currentData.question, currentState.value);
  if (
    cur.currentData.question.find(v => {
      if (v.type == "group") {
        return v.children.find(v2 =>
          Array.isArray(v2.value)
            ? !v2.value.length
            : !v2.value && v2.value !== 0
        );
      } else {
        return (
          v.type != "chat" &&
          (Array.isArray(v.value) ? !v.value.length : !v.value && v.value !== 0)
        );
      }
    })
  ) {
    return ElMessage.warning("请作答后保存");
  }
  msgLoading.value = true;
  nextTick(() => {
    const req = {
      state: currentState.value,
      question: cur.currentData.question.map(JSON.stringify),
      surveys: undefined
    };
    const answers = formatData(formatResultList(cur.currentData.question), {
      type: 2
    });
    const surveys = {};
    answers.forEach(v => {
      surveys[v.answer.questionNo] = v.answer;
    });
    req.surveys = surveys;
    console.log(req);
    processData.value.push(req);
    qa();
  });
};
const qa = async () => {
  const { data } = await request.post("/algorServer/api/execute/qa", {
    basicData: basicData.value,
    processData: processData.value,
    currentState: currentState.value,
    datas: datas.value
  });
  const { result } = data;
  if (result) {
    datas.value = result.datas;
    if (result.currentData) {
      result.currentData.question = result.currentData.question
        ? result.currentData.question?.map(v => parseJSON(v))
        : [];
      // result.currentData.question[0].value = ["AwHWXC"];
      // result.currentData.question[0].value = [0];
    }
    if (currentState.value) {
      await sleep(3e2);
    }
    msgLoading.value = false;
    nextTick(() => {
      if (!result.isEnd) {
        if (currentState.value == result.currentData?.state) {
          list.value.splice(
            list.value.findIndex(
              v => currentState.value == v.currentData.state
            ),
            1,
            result
          );
        } else {
          currentState.value = result.currentData?.state;
          list.value.push(result);
        }
      } else {
        assessmentInfo.value = result.assessmentInfo;
      }
      isEnd.value = result.isEnd;
    });
  }
  console.log(data.result);
};

const reply = item => {
  formatItemVal(item);
};

const checkMatrix = (item, rowIdx, colIdx) => {
  console.log(item);

  let curState = item.matrix[rowIdx][colIdx];
  let isMultiple = item.isMultiple;
  let mutuallyExclusive = item.columns[colIdx].mutuallyExclusive;
  // 单选
  if (!isMultiple) {
    item.matrix[rowIdx].forEach((v, k) => {
      item.matrix[rowIdx][k] = k === colIdx ? !curState : false;
    });
  } else {
    // 多选
    // 该列有互斥
    if (mutuallyExclusive) {
      if (curState) {
        item.matrix[rowIdx][colIdx] = !curState;
      } else {
        item.matrix[rowIdx].forEach((v, k) => {
          item.matrix[rowIdx][k] = k === colIdx;
        });
      }
    } else {
      item.matrix[rowIdx].forEach((v, k) => {
        if (item.columns[k].mutuallyExclusive) {
          item.matrix[rowIdx][k] = false;
        }
      });
      item.matrix[rowIdx][colIdx] = !item.matrix[rowIdx][colIdx];
    }
  }
  const res = [];
  item.matrix?.forEach((cols, k1) => {
    cols &&
      cols.forEach &&
      cols?.forEach((c, k2) => {
        c && res.push(item.rows[k1].label + "" + item.columns[k2].label);
      });
  });
  item.value = res;
};

const init = async () => {
  qa();
};
init();
const reset = () => {
  datas.value = undefined;
  processData.value = [];
  currentState.value = 0;
  isEnd.value = false;
  list.value = [];
  qa();
};
const confirm = () => {
  emit("confirm", assessmentInfo.value);
};
</script>

<style lang="scss">
/* 隐藏浏览器默认的滚动条 */
textarea::-webkit-scrollbar {
  width: 12px;
}

/* 轨道 */
textarea::-webkit-scrollbar-track {
  background: #f1f1f1;
}

/* 滑块 */
textarea::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 20px;
  cursor: pointer;
}

/* 滑块悬停状态 */
textarea::-webkit-scrollbar-thumb:hover {
  background: #555;
}

/* 滚动条的角落 */
textarea::-webkit-scrollbar-corner {
  background: #f1f1f1;
}
.dialog-content {
  position: relative;
  &::before {
    content: "";
    position: absolute;
    top: 20px;
    left: -10px;
    transform: translateX(-50%);
    border-width: 10px;
    border-style: solid;
    border-color: transparent #fff transparent transparent;
  }
}
</style>
