<template>
  <div
    class="question-content p-2 pl-4"
    :class="{
      'show-indicator': props.showIndicator,
      'hide-survey-title': props.hideSurveyTitle
    }"
  >
    <div>
      <div class="text-base text-gray-800 mb-2">{{ item?.title }}</div>
      <div class="text-gray-400 text-sm">{{ item?.remark }}</div>
    </div>
    <!-- 单选 -->
    <template v-if="item.type === 'radio'">
      <!-- 常规显示 -->
      <div class="text-left padding-top-10 padding-bottom-10">
        <el-radio-group v-model="item.value">
          <div>
            <div
              v-for="(sub, idx) in item.choices"
              :key="idx"
              class="sub-title margin-top-5 hide"
            >
              <el-radio :label="idx">
                <span
                  class="cursor-copy"
                  @click.stop="emitText(`&quot;${sub.label}&quot;`)"
                  >{{ sub.label }}</span
                >
              </el-radio>
              <!-- <el-tag type="info" class="cursor-copy" @click="emitText(sub.attr)">{{
                sub.attr
              }}</el-tag> -->
              <div
                v-if="idx == item.value && item.choices[idx]?.isInput"
                class="text-sm pl-6"
              >
                <span class="text-xs text-gray-500">输入内容：</span>
                <span>{{ item.choices[idx]?.extra }}</span>
              </div>
            </div>
          </div>
        </el-radio-group>
      </div>
    </template>
    <!-- 多选 -->
    <template v-else-if="item.type === 'checkbox'">
      <!-- 常规显示 -->
      <div class="text-left padding-top-10 padding-bottom-10">
        <div
          v-for="(sub, idx) in item.choices"
          :key="idx"
          class="sub-title margin-top-5"
        >
          <el-checkbox :checked="(item.value || []).includes(idx)">
            <span
              class="cursor-copy"
              @click.stop="emitText(`&quot;${sub.label}&quot;`)"
              >{{ sub.label }}</span
            >
          </el-checkbox>

          <div
            v-if="
              (item.value || []).includes(idx) && item.choices[idx]?.isInput
            "
            class="text-sm pl-6"
          >
            <span class="text-xs text-gray-500">输入内容：</span>
            <span>{{ item.choices[idx]?.extra }}</span>
          </div>
        </div>
      </div>
    </template>
    <!-- 单行文本题 -->
    <template v-else-if="item.type === 'input' || item.type === 'textarea'">
      <!-- 常规显示 -->
      <div class="text-left padding-top-10 padding-bottom-10">
        <div>
          <el-input
            v-model="item.value"
            :type="item.type === 'textarea' ? 'textarea' : 'text'"
            :rows="3"
          />
        </div>
      </div>
    </template>
    <!-- 量表题 -->
    <template v-else-if="item.type === 'scale'">
      <!-- 常规显示 -->
      <div class="text-left padding-top-10 padding-bottom-10">
        <div class="row pt-4">
          <div class="flex">
            <div class="flex items-center flex-col">
              <span class="whitespace-nowrap mx-4">{{
                item.choices[0].label
              }}</span>
              <div>{{ item.min }}</div>
            </div>
            <el-slider
              v-model="item.value"
              :show-tooltip="true"
              :min="item.min"
              :max="item.max"
              :step="1"
            />
            <div class="flex items-center flex-col">
              <span class="whitespace-nowrap mx-4">{{
                item.choices[1].label
              }}</span>
              <div>{{ item.max }}</div>
            </div>
          </div>
        </div>
      </div>
    </template>
    <template v-else-if="item.type === 'rating_scale'">
      <!-- 常规显示 -->
      <div class="text-left padding-top-10 padding-bottom-10">
        <div class="row">
          <span class="mr-4">{{ item.choices[0].label }}</span>
          <el-radio-group>
            <el-radio-button
              :value="false"
              v-for="(sub, idx) in item.max"
              :key="idx"
              >{{ idx + item.min }}</el-radio-button
            >
          </el-radio-group>
          <span class="ml-2">{{ item.choices[1].label }}</span>
        </div>
      </div>
    </template>
    <!-- 评分题 -->
    <template v-else-if="item.type === 'rating'">
      <!-- 常规显示 -->
      <div class="text-left py-2">
        <div v-for="(sub, idx) in item.choices" :key="idx" class="mt-1">
          <template v-if="item.isMultiple">
            <el-checkbox :value="false"
              >{{ sub.label }}({{ sub.score }})</el-checkbox
            >
          </template>
          <template v-else>
            <el-radio :value="false">{{ sub.label }}({{ sub.score }})</el-radio>
          </template>
        </div>
      </div>
    </template>
    <!-- 文本描述 -->
    <div class="pt-4 pb-8" v-else-if="item.type === 'text'">
      <el-input
        class="input"
        v-model="item.title"
        v-if="edit || item.edit"
        placeholder="请输入文本"
      />
      <p v-else class="text-center">
        <span @click.stop="emitText(`&quot;${item.title}&quot;`)"
          >{{ item.title
          }}<el-tag v-if="item.isRepeat" type="danger" size="mini"
            >可多答</el-tag
          ></span
        >
      </p>
    </div>
    <!-- 时间选择题 -->
    <template v-else-if="item.type === 'date'">
      <!-- 常规显示 -->
      <div class="text-left padding-top-10 padding-bottom-10">
        <div class="row">
          <el-date-picker
            v-model="item.value"
            type="date"
            :placeholder="item.remark || '选择时间'"
          />
        </div>
      </div>
    </template>
    <!-- 矩阵题 -->
    <template v-else-if="item.type === 'matrix_checkbox'">
      <!-- 常规显示 -->
      <div class="text-left py-2">
        <div class="row">
          <el-table :data="item.matrix">
            <el-table-column>
              <template #default="{ $index }">
                <div class="survey-sub-title">
                  {{ item.rows[$index]?.label }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              v-for="(col, colIdx) in item.columns"
              :key="colIdx"
              :label="col.label"
              align="center"
            >
              <template #header="{ $index }">
                {{ col.label }}
              </template>
              <template #default="{ $index }">
                <el-checkbox
                  readonly
                  :checked="
                    (item.value || []).includes(
                      `${item.rows[$index]?.label}${item.columns[colIdx]?.label}`
                    )
                  "
                />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </template>
    <!-- 疾病下拉题 -->
    <template v-else-if="item.type === 'disease' || item.type === 'medicine'">
      <!-- 常规显示 -->
      <div class="text-left py-2">
        <div class="row">
          <p>推荐展示值</p>
          <div
            v-for="(recommend, recommendIndex) in item.cacheSearchList"
            :key="recommendIndex"
          >
            {{ recommend.name }}({{ recommend.sn }})
          </div>
        </div>
      </div>
    </template>
    <!-- 下拉题 -->
    <template v-else-if="item.type === 'select'">
      <!-- 常规显示 -->
      <div class="text-left py-2">
        <div class="row">
          <p>推荐展示值</p>
          <div
            v-for="(recommend, recommendIndex) in item.cacheSearchList"
            :key="recommendIndex"
          >
            {{ recommend.name }}({{ recommend.sn }})
          </div>
        </div>
      </div>
    </template>
    <!-- 组合题 -->
    <template v-else-if="item.type === 'group'">
      <!-- 常规显示 -->
      <div class="text-left py-2">
        <div
          v-for="(sub, subIdx) in item.children"
          :key="subIdx"
          class="template-question-child"
        >
          <TempQuestionItem
            v-model:info="item.children[subIdx]"
            :indicator="item.belongIndicator"
            :show-indicator="true"
            :edit="item.edit"
            :is-child="true"
            :target-prefix="targetPrefix"
            @text="emitText"
          />
        </div>
      </div>
    </template>
    <template v-else-if="item.type === 'combination'">
      <!-- 常规显示 -->
      <div class="text-left py-2">
        <div v-for="(sub, subIdx) in item.children" :key="subIdx">
          <TempQuestionItem
            v-model:info="item.children[subIdx]"
            :indicator="item.belongIndicator"
            :show-indicator="true"
            :edit="item.edit"
            :target-prefix="targetPrefix"
            @text="emitText"
          />
        </div>
      </div>
    </template>
    <template v-else-if="item.type === 'upload'">
      <template />
    </template>
    <ComponentRegex
      v-model:visible="state.regexVisible"
      ref="regexRef"
      @success="onRegexSave"
    />
  </div>
</template>
<script setup>
import { defineOptions, onMounted, computed, reactive, ref } from "vue";
import { randomString, request } from "@/utils";
import {
  simpleTypes,
  typeLabelByKey as typeLabel
} from "@/enumerated/questionEnum";

import { copyTextToClipboard } from "@pureadmin/utils";
import { Rank, Close, CircleClose } from "@element-plus/icons-vue";
import ComponentRegex from "@/components/Question/Regex.vue";
const QUESTION_TYPE_TEMP_CHECK = "temp_check";
const QUESTION_TYPE_ANSWER = "answer";
const QUESTION_TYPE_INPUT = "input";
const QUESTION_TYPE_TEXT = "text";
const QUESTION_TYPE_CHECKBOX = "checkbox";
const QUESTION_TYPE_RADIO = "radio";
const QUESTION_TYPE_SELECT = "select";
const QUESTION_TYPE_RATING_SCALE = "rating_scale";
const QUESTION_TYPE_RATING = "rating";
const QUESTION_TYPE_DATE = "date";
const QUESTION_TYPE_UPLOAD = "upload";
const QUESTION_TYPE_MATRIX = "matrix_checkbox";
const QUESTION_TYPE_COMBINATION = "combination";
const QUESTION_TYPE_GROUP = "group"; // 组合题
defineOptions({
  name: "TempQuestionItem"
});
const props = defineProps([
  "info",
  "id",
  "edit",
  "showIndicator",
  "isChild",
  "hideSurveyTitle",
  "indicator",
  "targetPrefix"
]);
const emits = defineEmits(["update:info", "text"]);
const item = computed({
  get() {
    const info = props.info;
    if (props.showIndicator && props.indicator) {
      info.number = `${props.indicator.var}["${info.attr}"]`;
    } else if (props.showIndicator && info.belongIndicator) {
      info.number = `${info.belongIndicator.var}["${info.attr}"]`;
    }
    return info;
  },
  set(v) {
    emits("update:info", v);
  }
});

const state = reactive({
  regexVisible: false,
  isParentRegex: false,
  subIndex: -1,
  childType: "",
  tags: []
});
const getTags = async (params = {}) => {
  // const { data } = await request.get("/mechanism/systemTag/list", { params });
  // state.tags = data.list;
  // return data.list;
  return [];
};
const searchChange = () => {
  item.value.cacheSearchList = item.value.recommend
    .map(id => {
      return item.value.searchList.find(v => v.id == id);
    })
    .filter(v => v);
};
const searchDiseaseOrMedicine = (key = "") => {
  const urls = {
    disease: "/api/disease/list",
    medicine: "/api/medicine/list"
  };
  const url = urls[props.info.type];
  url &&
    request
      .get(url, {
        params: { key }
      })
      .then(({ data }) => {
        item.value.searchList = data.list;
      });
};
const regexRef = ref();
const setRegex = (subItem, subIndex, flag = false) => {
  console.log(regexRef.value);
  regexRef.value.setTpl(subItem.regexRule);
  if (!flag) {
    state.subIdx = subIndex;
  }
  state.regexVisible = true;
  state.isParentRegex = flag;
};
const onRegexSave = data => {
  console.log(data);
  console.log(state.isParentRegex);
  if (state.isParentRegex) {
    item.value.config.regexRuleName = data.name;
    item.value.config.regexRule = data;
  } else {
    if (item.value.choices[state.subIdx]) {
      item.value.choices[state.subIdx].regexRuleName = data.name;
      item.value.choices[state.subIdx].regexRule = data;
    }
  }
};
const emitText = e => {
  if (!e) return;
  const rText = props.targetPrefix || "tar";
  const str = e.replace(/target/, rText).replace(/\./, "");
  console.log(rText, str);
  copyTextToClipboard(str);
  emits("text", str);
};
const addGroupChild = () => {
  const line = {
    type: state.childType,
    edit: true,
    title: "",
    value: "",
    attr: randomString(5),
    sn: "",
    remark: "",
    combination: "",
    isRepeat: false,
    config: {
      desc: "",
      rule: "",
      type: "",
      regexRule: "",
      regexRuleName: ""
    },
    choices: [],
    children: []
  };
  switch (line.type) {
    case "radio":
      line.choices = [
        {
          label: "选项1",
          isInput: false,
          extra: "",
          inputPlaceholder: "",
          regexRule: "",
          regexRuleName: "",
          attr: randomString(6)
        },
        {
          label: "选项2",
          isInput: false,
          extra: "",
          inputPlaceholder: "",
          regexRule: "",
          regexRuleName: "",
          attr: randomString(6)
        }
      ];
      break;
    case "checkbox":
      line.choices = [
        {
          label: "选项1",
          mutuallyExclusive: false,
          isInput: false,
          extra: "",
          inputPlaceholder: "",
          regexRule: "",
          regexRuleName: "",
          attr: randomString(6)
        },
        {
          label: "选项2",
          mutuallyExclusive: false,
          isInput: false,
          extra: "",
          inputPlaceholder: "",
          regexRule: "",
          regexRuleName: "",
          attr: randomString(6)
        }
      ];
      line.isMultiple = true;
      break;
    case "rating_scale":
      line.min = 1;
      line.max = 5;
      line.choices = [
        {
          label: "不满意"
        },
        {
          label: "非常满意"
        }
      ];
      break;
    case "rating":
      line.choices = [
        {
          label: "选项1",
          score: 0
        },
        {
          label: "选项2",
          score: 0
        }
      ];
      line.isMultiple = false;
      break;
    case "date":
      break;
    case "disease":
    case "medicine":
      line.config.isInput = false;
      line.config.attr = "extra";
      line.recommend = [];
      line.searchList = [];
      line.cacheSearchList = [];
      line.systemTagIds = [];
      break;
    case "matrix_checkbox":
      line.columns = [
        {
          label: "选项1",
          mutuallyExclusive: false
        },
        {
          label: "选项2",
          mutuallyExclusive: false
        }
      ];
      line.rows = [
        {
          label: "问题1"
        },
        {
          label: "问题2"
        }
      ];
      line.matrix = [];
      line.isMultiple = false;
      break;
  }
  item.value.children.push(line);
};
const updateMatrix = () => {
  props.info.matrix = Array(props.info.rows.length)
    .fill(0)
    .map(() => Array(props.info.columns.length).fill(false));
};

const formatResultList = arr => {
  const list = [];
  const repeatKey = [];
  arr.forEach(v => {
    if (v.isRepeat) {
      if (!repeatKey.includes(v.sn)) {
        const temp = {
          ...v,
          value: []
        };
        repeatKey.push(v.sn);
        const cur = arr.filter(v2 => v2.sn === v.sn);
        console.log("cur", cur);

        temp.value = cur.map(formatItemVal);

        temp.rawValue = cur.map(v2 => {
          if (v.type == QUESTION_TYPE_GROUP) {
            return v2.children.map(v3 => v3.value);
          } else {
            return v2.value;
          }
        });
        console.log(temp.value, temp.rawValue);
        list.push(temp);
      }
    } else {
      console.log(v.type == QUESTION_TYPE_GROUP && "出现组合题", v);
      if (v.type == QUESTION_TYPE_GROUP) {
        list.push({
          ...v,
          rawValue: v.children.map(child => child.value),
          value: formatItemVal(v)
        });
      } else {
        list.push({
          ...v,
          rawValue: v.value,
          value: formatItemVal(v)
        });
      }
    }
  });
  return list;
};

onMounted(() => {
  if (
    props.info &&
    (!props.info.matrix ||
      !props.info.matrix.length ||
      props.info.matrix.flat().length !=
        props.info.rows.length * props.info.columns.length) &&
    props.info.type === "matrix_checkbox"
  ) {
    props.info.matrix = Array(props.info.rows.length)
      .fill(0)
      .map(() => Array(props.info.columns.length).fill(false));
  } else if (props.info.type === "group") {
    props.info.children.forEach(v => {
      v.edit = props.info.edit;
    });
  }
  if (props.edit || props.info.edit) {
    searchDiseaseOrMedicine();
    getTags();
  }
});
</script>
<style lang="scss">
.q-attr {
  cursor: copy;
  user-select: none;
  margin-left: 10px;
}
.cursor-copy {
  cursor: copy;
}
.show-indicator {
  .survey-title,
  .sub-title {
    &:before {
      display: none;
      //   cursor: copy;
      //   display: inline-block;
      //   margin-bottom: 6px;
    }
    span {
      display: inline-block;
      margin: 5px auto;
    }
    &.hide {
      &:before {
        display: none;
      }
    }
  }
  .survey-title {
    // left: -60px;
    cursor: copy;

    &:before {
      // font-size: 14px !important;
      // padding: 6px 15px !important;
      // left: 0 !important;
      // top: -3em !important;
      display: none;
    }
  }

  .el-checkbox__input.is- + span.el-checkbox__label {
    cursor: copy;
  }
}
.template-question-child {
  position: relative;
  background: #f5f5f5;
  border-radius: 4px;
  margin-bottom: 10px;
  padding-top: 10px;
  .template-question-child-close {
    position: absolute;
    top: 10px;
    right: 10px;
    font-size: 24px;
    color: #999;
    cursor: pointer;
  }
}
.hide-survey-title {
  .survey-title {
    &:before {
      display: none;
    }
  }
}
</style>
