<template>
  <a-modal
    v-bind="$attrs"
    title="打回"
    :maskClosable="false"
    :footer="false"
    :zIndex="6000"
  >
    <div ref="modalContenBox">
      <a-form
        autocomplete="off"
        :model="reasonOption"
        :labelCol="{span: 5}"
        @keydown.stop=""
        @keypress.stop=""
        @finish="onConfirm"
      >
        <a-form-item label="打回原因" name="reason" required>
          <a-select
            v-model:value="reasonOption.reason"
            placeholder="选择打回原因"
            :virtual="false"
            :getPopupContainer="() => modalContenBox!"
            :options="reasonOptions"
          >
          </a-select>
        </a-form-item>
        <a-form-item label="详情描述" name="desc">
          <a-textarea
            v-model:value="reasonOption.desc"
            placeholder="详情描述(限制50字以内)"
            :maxlength="50"
          ></a-textarea>
        </a-form-item>
        <a-form-item>
          <a-row justify="center">
            <a-col>
              <a-button type="primary" htmlType="submit">打回</a-button>
            </a-col>
            <a-col :offset="2">
              <a-button type="ghost" @click="onCancel">取消</a-button>
            </a-col>
          </a-row>
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { reactive, useAttrs, watch, ref } from "vue";

interface ReturnInfo {
  reason?: string;
  desc: string;
}

/** select 定位层级较低, 所以在弹窗中使用一个div容器, 将select 组件的 dorpdown 挂载在div中, 避免dropdown被modal挡住 */
const modalContenBox = ref<HTMLElement>();

const emit = defineEmits(["confirmReturn"]);

/** 打回原因元数据 */
const reasonOptions = ["给分较高", "给分较低", "判分错误", "其它"].map((v) => ({
  value: v,
}));

/** 初始化表单数据 */
const getInitialFormData = (): ReturnInfo => {
  return {
    reason: undefined,
    desc: "",
  };
};

const reasonOption = reactive<ReturnInfo>(getInitialFormData());

watch(
  () => modalContenBox,
  () => {
    console.log(modalContenBox);
  }
);

/** 弹窗关闭时 重置form表单数据 */
const attrs = useAttrs();
watch(
  () => attrs.visible,
  (v) => {
    if (!v) {
      Object.assign(reasonOption, getInitialFormData());
    }
  }
);

/** 确定打回 */
const onConfirm = () => {
  emit(
    "confirmReturn",
    Object.values(reasonOption)
      .map((s) => s || "")
      .join(":")
  );
  onCancel();
};

/** 取消打回 */
const onCancel = (e?: MouseEvent) => {
  (attrs["onUpdate:visible"] as (e: boolean) => void)?.(false);
  (attrs.onChange as (e: boolean) => void)?.(false);
  (attrs.onCancel as (e?: MouseEvent) => void)?.(e);
};
</script>

<style scoped></style>
