<script setup lang="ts">
import { computed, ref, watch } from "vue";
import { jsonClone } from "@sa/utils";
import {
  fetchCreatePlatformUser,
  fetchUpdatePlatformUser,
} from "@/service/api/client/platform-user";
import { useFormRules, useNaiveForm } from "@/hooks/common/form";
import { $t } from "@/locales";

defineOptions({
  name: "PlatformUserOperateDrawer",
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.Client.PlatformUser | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: "submitted"): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>("visible", {
  default: false,
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { createRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: "新增平台用户关联（微信/抖音小程序用户信息）",
    edit: "编辑平台用户关联（微信/抖音小程序用户信息）",
  };
  return titles[props.operateType];
});

type Model = Api.Client.PlatformUserOperateParams;

const model = ref<Model>(createDefaultModel());

function createDefaultModel(): Model {
  return {
    id: null,
    userId: null,
    platformType: null,
    platformOpenid: "",
    platformUnionid: "",
    platformSessionKey: "",
    platformExtra: "",
    lastLoginTime: null,
  };
}

type RuleKey = Extract<
  keyof Model,
  "id" | "userId" | "platformType" | "platformOpenid"
>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  id: createRequiredRule("平台用户ID（自增）不能为空"),
  userId: createRequiredRule("关联t_user.id不能为空"),
  platformType: createRequiredRule(
    "平台类型：1-微信小程序，2-抖音小程序，3-支付宝小程序不能为空",
  ),
  platformOpenid: createRequiredRule(
    "平台唯一标识（微信openid/抖音open_id）不能为空",
  ),
};

function handleUpdateModelWhenEdit() {
  model.value = createDefaultModel();

  if (props.operateType === "edit" && props.rowData) {
    Object.assign(model.value, jsonClone(props.rowData));
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();

  const {
    id,
    userId,
    platformType,
    platformOpenid,
    platformUnionid,
    platformSessionKey,
    platformExtra,
    lastLoginTime,
  } = model.value;

  // request
  if (props.operateType === "add") {
    const { error } = await fetchCreatePlatformUser({
      userId,
      platformType,
      platformOpenid,
      platformUnionid,
      platformSessionKey,
      platformExtra,
      lastLoginTime,
    });
    if (error) return;
  }

  if (props.operateType === "edit") {
    const { error } = await fetchUpdatePlatformUser({
      id,
      userId,
      platformType,
      platformOpenid,
      platformUnionid,
      platformSessionKey,
      platformExtra,
      lastLoginTime,
    });
    if (error) return;
  }

  window.$message?.success($t("common.updateSuccess"));
  closeDrawer();
  emit("submitted");
}

watch(visible, () => {
  if (visible.value) {
    handleUpdateModelWhenEdit();
    restoreValidation();
  }
});
</script>

<template>
  <NDrawer
    v-model:show="visible"
    :title="title"
    display-directive="show"
    :width="800"
    class="max-w-90%"
  >
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules">
        <NFormItem label="关联t_user.id" path="userId">
          <NInput
            v-model:value="model.userId"
            placeholder="请输入关联t_user.id"
          />
        </NFormItem>
        <NFormItem
          label="平台类型：1-微信小程序，2-抖音小程序，3-支付宝小程序"
          path="platformType"
        >
          <NSelect
            v-model:value="model.platformType"
            placeholder="请选择平台类型：1-微信小程序，2-抖音小程序，3-支付宝小程序"
            :options="[{ value: '0', label: '请选择字典生成' }]"
            clearable
          />
        </NFormItem>
        <NFormItem
          label="平台唯一标识（微信openid/抖音open_id）"
          path="platformOpenid"
        >
          <NInput
            v-model:value="model.platformOpenid"
            placeholder="请输入平台唯一标识（微信openid/抖音open_id）"
          />
        </NFormItem>
        <NFormItem
          label="平台统一标识（微信unionid，多小程序互通用）"
          path="platformUnionid"
        >
          <NInput
            v-model:value="model.platformUnionid"
            placeholder="请输入平台统一标识（微信unionid，多小程序互通用）"
          />
        </NFormItem>
        <NFormItem
          label="平台会话密钥（微信session_key，加密存储）"
          path="platformSessionKey"
        >
          <NInput
            v-model:value="model.platformSessionKey"
            placeholder="请输入平台会话密钥（微信session_key，加密存储）"
          />
        </NFormItem>
        <NFormItem
          label="平台扩展字段（如抖音的user_name、微信的city等）"
          path="platformExtra"
        >
          <NInput
            v-model:value="model.platformExtra"
            placeholder="请输入平台扩展字段（如抖音的user_name、微信的city等）"
          />
        </NFormItem>
        <NFormItem label="最后登录时间" path="lastLoginTime">
          <NDatePicker
            v-model:formatted-value="model.lastLoginTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            clearable
          />
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t("common.cancel") }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{
            $t("common.confirm")
          }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
