<template>
  <Dialog
    v-model:show="dialogVisible"
    show-cancel-button
    get-container="body"
    :before-close="onBeforeClose"
    @close="onClose"
    @confirm="onComfirm"
    teleport="body"
    className="vant-confirm-z-index"
    overlayClass="vant-overlay-z-index"
    confirmButtonColor="var(--wl-primary-color)"
  >
    <WlHeader title="分组名称" />
    <div class="form-wrap">
      <div class="form-item-input">
        <input
          v-model="groupNameValue"
          label=""
          placeholder="分组名称不能为空"
          maxlength="50"
          @keydown.enter="onKeyDown"
        />
      </div>
    </div>
  </Dialog>
</template>

<script lang="ts">
export default {
  name: "OperGroupDialog",
};
</script>

<script setup lang="ts">
/**
 * 新增分组名称
 */
import { Dialog } from "vant";
import "vant/es/dialog/style";
import { watch, ref, watchEffect } from "vue";
import useMessage from "@mobileUI/hooks/useMessage";
import WlHeader from "@mobileUI/components/WlHeader";

type Props = {
  show?: boolean;
  groupName?: string;
};
const props = withDefaults(defineProps<Props>(), {
  show: false,
  groupName: ""
});
const { onWarning } = useMessage();

const dialogVisible = ref(false);
const groupNameValue = ref("");

const emit = defineEmits<{
  (e: "update:show", val: boolean);
  (e: "update:groupName", val: string);
  (e: "onConfirm", val: string);
}>();

const onClose = () => {
  emit("update:show", false);
  dialogVisible.value = false;
};

const onComfirm = () => {
  const groupNameTrim = groupNameValue.value.trim();
  if (!groupNameTrim) {
    onWarning("分组名称不能为空");
  } else if (groupNameTrim.length > 30) {
    onWarning("分组名称最大为30个字符");
  } else {
    emit("onConfirm", groupNameTrim);
  };
};

const onBeforeClose = (action) => {
  if (action === 'confirm') {
    if (dialogVisible.value) return false;
  } else {
    return true;
  }
}

const onKeyDown = () => {
  onComfirm();
  onClose();
};

watchEffect(() => {
  //默认要清除输入内容
  if (props.show) groupNameValue.value = "";
  dialogVisible.value = props.show;
  groupNameValue.value = props.groupName;
})

watch(
  () => groupNameValue.value,
  (val) => emit("update:groupName", val)
);

watch(
  () => dialogVisible.value,
  val => emit("update:show", val)
);
</script>

<style lang="scss" scoped>
.form-wrap {
  color: #0e0e0e;
  padding: j(15);

  .form-item {
    &-title {
      margin: j(15) 0 j(6) 0;
    }

    &-input {
      border-radius: j(12);
      overflow: hidden;
      background-color: var(--wl-btn-dashed-bg);
      padding: j(10) j(16);

      >input {
        width: 100%;
      }
    }
  }
}
</style>
