<script setup>
import { computed, reactive, watch } from 'vue';

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  mode: {
    type: String,
    default: 'single', // single | batch
  },
});

const emit = defineEmits(['update:modelValue', 'submit']);

const form = reactive({
  type: 'account', // account | tk | account_tk
  account: '',
  password: '',
  token: '',
  batchText: '',
  remark: '',
});

const isBatch = computed(() => props.mode === 'batch');

const dialogTitle = computed(() => {
  return isBatch.value ? '批量添加账号' : '添加账号';
});

const formatExample = computed(() => {
  if (form.type === 'account') {
    return 'account,password';
  }
  if (form.type === 'account_tk') {
    return 'account,password,token';
  }
  return 'token';
});

watch(
  () => props.modelValue,
  (visible) => {
    if (!visible) return;
    resetForm();
  }
);

function closeDialog() {
  emit('update:modelValue', false);
}

function resetForm() {
  form.type = 'account';
  form.account = '';
  form.password = '';
  form.token = '';
  form.batchText = '';
  form.remark = '';
}

function parseBatchRows() {
  const rows = form.batchText
    .split(/\r?\n/)
    .map((line) => line.trim())
    .filter(Boolean);

  const parsed = [];
  const errors = [];

  rows.forEach((line, index) => {
    if (form.type === 'account') {
      const [account, password] = line.split(',').map((x) => (x || '').trim());
      if (!account || !password) {
        errors.push(`第 ${index + 1} 行格式错误，应为 account,password`);
        return;
      }
      parsed.push({
        type: 'account',
        account,
        password,
        token: '',
        remark: form.remark,
      });
      return;
    }

    if (form.type === 'account_tk') {
      const [account, password, token] = line
        .split(',')
        .map((x) => (x || '').trim());
      if (!account || !password || !token) {
        errors.push(`第 ${index + 1} 行格式错误，应为 account,password,token`);
        return;
      }
      parsed.push({
        type: 'account_tk',
        account,
        password,
        token,
        remark: form.remark,
      });
      return;
    }

    parsed.push({
      type: 'tk',
      account: '',
      password: '',
      token: line,
      remark: form.remark,
    });
  });

  return { parsed, errors };
}

function handleSubmit() {
  if (!isBatch.value) {
    if (form.type === 'account') {
      if (!form.account || !form.password) {
        return;
      }
      emit('submit', {
        mode: 'single',
        rows: [
          {
            type: 'account',
            account: form.account.trim(),
            password: form.password.trim(),
            token: '',
            remark: form.remark.trim(),
          },
        ],
      });
      closeDialog();
      return;
    }

    if (form.type === 'account_tk') {
      if (!form.account || !form.password || !form.token) {
        return;
      }
      emit('submit', {
        mode: 'single',
        rows: [
          {
            type: 'account_tk',
            account: form.account.trim(),
            password: form.password.trim(),
            token: form.token.trim(),
            remark: form.remark.trim(),
          },
        ],
      });
      closeDialog();
      return;
    }

    if (!form.token) return;
    emit('submit', {
      mode: 'single',
      rows: [
        {
          type: 'tk',
          account: '',
          password: '',
          token: form.token.trim(),
          remark: form.remark.trim(),
        },
      ],
    });
    closeDialog();
    return;
  }

  const { parsed, errors } = parseBatchRows();
  if (errors.length || parsed.length === 0) {
    return;
  }
  emit('submit', {
    mode: 'batch',
    rows: parsed,
  });
  closeDialog();
}
</script>

<template>
  <el-dialog
    :model-value="modelValue"
    :title="dialogTitle"
    width="640px"
    @close="closeDialog"
    @update:model-value="(v) => emit('update:modelValue', v)"
  >
    <el-form label-width="96px">
      <el-form-item label="账号类型">
        <el-radio-group v-model="form.type">
          <el-radio value="account">账号密码</el-radio>
          <el-radio value="account_tk">账号密码+Token</el-radio>
          <el-radio value="tk">Token</el-radio>
        </el-radio-group>
      </el-form-item>

      <template v-if="!isBatch">
        <template v-if="form.type === 'account' || form.type === 'account_tk'">
          <el-form-item label="账号">
            <el-input v-model="form.account" placeholder="请输入账号" clearable />
          </el-form-item>
          <el-form-item label="密码">
            <el-input v-model="form.password" placeholder="请输入密码" clearable />
          </el-form-item>
          <el-form-item v-if="form.type === 'account_tk'" label="Token">
            <el-input
              v-model="form.token"
              type="textarea"
              :rows="4"
              placeholder="请输入 token"
              clearable
            />
          </el-form-item>
        </template>
        <el-form-item v-else label="Token">
          <el-input
            v-model="form.token"
            type="textarea"
            :rows="4"
            placeholder="请输入 token"
            clearable
          />
        </el-form-item>
      </template>

      <el-form-item v-else label="批量内容">
        <el-input
          v-model="form.batchText"
          type="textarea"
          :rows="12"
          :placeholder="`每行一条，格式：${formatExample}`"
          clearable
        />
      </el-form-item>

      <el-form-item label="备注">
        <el-input v-model="form.remark" placeholder="可选备注" clearable />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确认</el-button>
    </template>
  </el-dialog>
</template>
