<template>
  <div class="dsion-step1">
    <div style="padding: 24px" class="flex">
      <div class="ml-4">
        <div class="flex mt-8">
          <Checkbox.Group v-model:value="state.checkboxItem" :options="state.checkedOptions" />
        </div>
        <div class="flex mt-2">
          <Radio.Group v-model:value="state.radioItem" :options="state.radioOptions" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { Checkbox, Radio, CheckboxOptionType } from 'ant-design-vue';
  import { CheckboxValueType } from 'ant-design-vue/lib/checkbox/interface';
  import { onMounted, reactive, watch } from 'vue';

  import {
    getBandingTaskRuleList,
    postBandingTaskSetRule,
  } from '/@/services/apis/BandingTaskController';

  const props = defineProps({
    taskId: { type: String, default: '' },
  });

  const state = reactive<{
    gradeId: String;
    enrollType: String;
    checkboxItem: CheckboxValueType[];
    radioItem: CheckboxValueType;
    checkedOptions: CheckboxOptionType[];
    radioOptions: CheckboxOptionType[];
  }>({
    gradeId: '',
    enrollType: '',
    checkboxItem: [],
    radioItem: '',
    checkedOptions: [],
    radioOptions: [],
  });

  watch(
    () => props.taskId,
    async (newVal) => {
      if (newVal) {
        await getRule(newVal);
      }
    },
  );

  const getRule = async (taskId) => {
    const data = await getBandingTaskRuleList({ id: taskId });
    const checkboxItem: CheckboxValueType[] = [];
    let radioItem = '';

    state.checkedOptions = data
      .filter((item: any) => item.chooseType === 'multi')
      .map((item: any) => {
        if (item.isSelected === 1) {
          checkboxItem.push(item.id);
        }
        return { value: item.id, label: item.name };
      });

    state.radioOptions = data
      .filter((item: any) => item.chooseType === 'radio')
      .map((item: any) => {
        if (item.isSelected === 1) {
          radioItem = item.id;
        }
        return { value: item.id, label: item.name };
      });

    state.checkboxItem = checkboxItem;
    state.radioItem = radioItem;
  };

  const validateStep = async () => {
    try {
      const bandingRuleIds = [...state.checkboxItem];
      if (state.radioItem) {
        bandingRuleIds.push(state.radioItem);
      }
      await postBandingTaskSetRule({ bandingRuleIds: bandingRuleIds, bandingTaskId: props.taskId });
      return true;
    } catch {
      return false;
    }
  };

  onMounted(async () => {});

  defineExpose({ validateStep });
</script>

<style lang="less" scoped>
  .dsion-step1 {
    margin: 24px auto;
    background-color: @component-background;
    border-radius: 16px;
    width: 1000px;
  }

  :deep(.ant-checkbox-wrapper) {
    display: flex !important;
    margin-bottom: 4px;
  }

  :deep(.ant-radio-wrapper) {
    display: flex !important;
    margin-bottom: 4px;
  }
</style>
