<template>
  <a-radio-group
    v-if="customRadio"
    v-model:value="value"
    :disabled="disabled"
    @change="changeValue"
  >
    <div class="radio-group">
      <div v-for="(group, groupIndex) in optionGroups" :key="groupIndex" class="group">
        <div
          v-if="group.title && !config.option_groups?.is_hide"
          v-show="showGroupTitle(group.options)"
          class="group-title answer-color"
        >
          {{ group.title }}
        </div>
        <div
          v-for="option in group.options"
          v-show="!hideOptions.includes(option.option_key)"
          :key="option.option_key"
          class="radio theme-hover-default"
          :class="group.title && !config.option_groups?.is_hide ? 'margin-left' : ''"
          :style="
            isMobile ? 'width: 100%' : `width: calc(100% / ${config.each_number || 1} - 33px)`
          "
          @click="onChangeValue(option.option_key)"
        >
          <a-radio :value="option.option_key" @click.stop />
          <div class="option scrollbar answer-color">
            <rich-text :nodes="option.option" isPreview />
          </div>
          <a-input
            v-if="option.is_other"
            v-model:value="option.value"
            :disabled="disabled"
            @change="changeInput($event, option.option_key)"
          />
        </div>
      </div>
    </div>
  </a-radio-group>
  <choice v-else :element="question" />
</template>

<script setup>
import Choice from '@/views/Design/components/Questions/Choice.vue';
</script>

<script>
import RichText from '@/components/RichText.vue';
import { computed, defineComponent, ref, watch } from 'vue';
import { compareArrayByField, randomOptions } from '@/utils/utils.js';

const customRadio = true;

export default defineComponent({
  components: { RichText /* AnswerViewer */ },
  props: {
    // 题干
    stem: {
      type: String,
      default: ''
    },
    // 列表
    list: {
      type: Array,
      default: () => []
    },
    // 配置
    config: {
      type: Object,
      default: () => {
        /* 占位 */
      }
    },
    // 答案
    answer: {
      type: Object,
      default: () => {
        /* 占位 */
      }
    },
    // 答案索引
    answerIndex: {
      type: String,
      default: ''
    },
    // 隐藏选项
    hideOptions: {
      type: Array,
      default: () => []
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false
    },
    // 是否移动端
    isMobile: {
      type: Boolean,
      default: false
    },
    // 样本SN
    answerSn: {
      type: String,
      default: ''
    },
    answerSurveySn: {
      type: String,
      default: ''
    },
    question: {
      type: Object,
      default: () => ({})
    }
  },
  setup(props, context) {
    // 值
    const value = ref('');
    // 选项
    const options = ref([]);
    // 分组
    const optionGroups = ref([]);

    // console.log(`radio input question: `, props.question);

    // 初始化
    function init() {
      props.list.forEach((list) => {
        options.value = [...options.value, ...list.options];
      });
      if (props.answer) {
        value.value = Object.keys(props.answer)[0];
        options.value.forEach((option) => {
          if (option.is_other && option.option_key === value.value) {
            option.value = props.answer[value.value];
          }
        });
      }
    }

    init();

    // 选项分组
    function setOptionGroups() {
      optionGroups.value = [];
      const copyOptions = JSON.parse(JSON.stringify(options.value));
      props.config.option_groups?.option_group.forEach((optionGroup) => {
        const group = {
          title: optionGroup.title,
          options: []
        };
        optionGroup.groups.forEach((groups) => {
          const index = copyOptions.findIndex((option) => option.option_key === groups.option_key);
          if (index === -1) return;
          group.options.push(copyOptions.splice(index, 1)[0]);
        });
        group.options = sortOptions(
          group.options,
          props.question.config.select_random && props.question.config.option_group_random_inside
        );
        optionGroups.value.push(group);
      });
      optionGroups.value = sortOptions(
        optionGroups.value,
        props.question.config.select_random && props.question.config.option_group_random_outside
      );
      // 若是 group 是undefined ，默认给一个空对象
      const group = optionGroups.value.find((group) => !group.title) ?? {};
      // console.log(group);
      group.options = sortOptions(copyOptions, props.question.config.select_random);
    }

    // 排序(固定项和其他项不参与随机)
    function sortOptions(oldOptions, isRandom) {
      const sorts = [];
      const fixed = [];
      const others = [];
      const removeOther = [];
      oldOptions.forEach((option) => {
        if (option.is_remove_other) {
          removeOther.push(option);
        } else if (option.is_other) {
          others.push(option);
        } else if (option.is_fixed) {
          fixed.push(option);
        } else {
          sorts.push(option);
        }
      });
      return [...randomOptions(sorts, isRandom), ...fixed, ...others, ...removeOther];
    }

    // 选择回调
    function changeValue(e) {
      // 更新答案
      const option = options.value.find((option) => option.option_key === e.target.value);
      context.emit('update:answer', {
        [e.target.value]: option.value || (option.is_other ? '' : '1')
      });
      // 清空未选中项输入框值
      options.value.forEach((option) => {
        if (option.is_other && option.option_key !== e.target.value) {
          option.value = '';
        }
      });
    }

    function onChangeValue(key) {
      value.value = key;
      changeValue({ target: { value: key } });
    }

    // 输入回调
    function changeInput(e, key) {
      const option = options.value.find((option) => option.option_key === key);
      option.value = e.target.value;
      value.value = key;
      // 更新答案
      context.emit('update:answer', { [key]: e.target.value });
    }

    // 监听答案
    watch(
      () => props.answer,
      () => {
        context.emit('changeAnswer', {
          options: optionGroups.value.flatMap((group) => group.options || []),
          value: value.value
        });
        // 质量控制
        const timer = setTimeout(() => {
          if (value.value) {
            const index = optionGroups.value
              .flatMap((group) => group.options.map((option) => option))
              .findIndex((option) => option.option_key === value.value);
            context.emit('update:answerIndex', `${index}`);
          } else if (props.answerIndex) {
            context.emit('update:answerIndex', '');
          }
          clearTimeout(timer);
        });
      },
      {
        deep: true,
        immediate: true
      }
    );

    // 监听list，更新关联选项
    watch(
      () => props.list,
      () => {
        // 更新关联题选项
        let newOptions = [];
        props.list.forEach((list) => {
          newOptions = [...newOptions, ...list.options];
        });
        // 其他项
        newOptions.forEach((option) => {
          if (option.is_other && option.option_key === value.value) {
            const timer = setTimeout(() => {
              option.value = props.answer[value.value];
              clearTimeout(timer);
            });
          }
        });

        if (
          !compareArrayByField(options.value, newOptions, 'option_key') ||
          !compareArrayByField(options.value, newOptions, 'option')
        ) {
          options.value = newOptions;
        }

        // 清空值和答案
        if (
          value.value &&
          options.value.findIndex((option) => option.option_key === value.value) === -1
        ) {
          // 清空值
          value.value = '';
          // 清空答案
          context.emit('update:answer', null);
        }
      },
      {
        deep: true
      }
    );

    // 监听list，更新关联选项
    watch(
      () => options.value,
      (val, oldVal) => {
        if (
          compareArrayByField(val, oldVal || [], 'option_key') &&
          compareArrayByField(val, oldVal || [], 'option')
        ) {
          return;
        }
        setOptionGroups();
      },
      {
        deep: true,
        immediate: true
      }
    );

    const onHoldToCart = (target) => {
      value.value = target.option_key;

      changeValue({
        target: {
          value: target.option_key
        }
      });
    };

    const cartWaresLength = computed(() => {
      if (!props.answer) return 0;
      return Object.keys(props.answer).length;
    });

    // console.log(`car wares length:`, cartWaresLength.value);

    // 显示分组标题
    function showGroupTitle(groupOptions) {
      const option = groupOptions.find((option) => !props.hideOptions.includes(option.option_key));
      return !!option;
    }

    return {
      value,
      options,
      optionGroups,
      changeValue,
      onChangeValue,
      changeInput,
      onHoldToCart,
      cartWaresLength,
      showGroupTitle
    };
  }
});
</script>

<style lang="scss" scoped>
.radio-group {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: -18px;

  .group {
    display: flex;
    flex-wrap: wrap;
    width: 100%;

    .group-title {
      margin-bottom: 18px;
    }
  }

  .radio {
    display: flex;
    align-items: center;
    margin-right: 32px;
    margin-bottom: 6px;
    padding: 6px 8px;
    border-radius: 3px;

    :deep(.ant-radio-wrapper) {
      margin-right: 0;
    }

    .option {
      overflow: auto;
      margin-right: 8px;
      padding-left: 8px;
    }
  }

  .margin-left {
    padding-left: 32px;
  }

  .ant-input {
    width: 225px;
  }
}

.ant-radio-group {
  width: 100%;
}
</style>
