<script setup>
import { reactive, ref, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { extractAccountPool } from '@/api/accountPool';

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  /** cursor / windsurf / krio */
  module: {
    type: String,
    required: true,
  },
  platformMap: {
    type: Object,
    default: () => ({}),
  },
  /** 打开弹窗时的默认账号类型（与列表 Tab 对齐：全部时用 account） */
  defaultAccountType: {
    type: String,
    default: 'account',
  },
});

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

const confirmLoading = ref(false);
const copiedText = ref('');
const form = reactive({
  platform: 'local',
  type: 'account',
  remark: '',
});

function normalizeRow(raw) {
  const pick = (...keys) => {
    for (const key of keys) {
      if (raw?.[key] !== undefined && raw?.[key] !== null) return raw[key];
    }
    return '';
  };
  const pickNullable = (...keys) => {
    for (const key of keys) {
      if (raw?.[key] !== undefined) return raw[key] ?? null;
    }
    return null;
  };
  const formatTime = (val) => {
    if (!val) return '';
    const d = new Date(val);
    if (isNaN(d)) return val;
    const p = (v) => String(v).padStart(2, '0');
    return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
  };
  const st = Number(pick('is_extracted', 'isExtracted', 'IsExtracted'));
  const extractStatus = Number.isFinite(st) ? st : 0;
  return {
    id: pick('id', 'Id', 'ID'),
    type: pick('data_type', 'dataType', 'type'),
    account: pick('account', 'Account'),
    password: pick('password', 'Password'),
    token: pick('token', 'Token'),
    remark: pick('remark', 'Remark'),
    extractStatus,
    extracted: extractStatus !== 0,
    extractedAt: formatTime(pickNullable('extracted_time', 'extractedAt')),
    extractedPlatform: pickNullable('extracted_platform', 'extractedPlatform'),
    createdAt: formatTime(pick('create_time', 'createdAt')),
  };
}

function buildCopyTextByRow(row) {
  const parts = [];
  if (row?.account) parts.push(row.account);
  if (row?.password) parts.push(row.password);
  if (row?.token) parts.push(row.token);
  return parts.join('\n');
}

async function copyToClipboard(text) {
  if (!text) {
    ElMessage.warning('无可复制内容');
    return false;
  }
  try {
    await navigator.clipboard.writeText(text);
    ElMessage.success('已复制');
    return true;
  } catch (e) {
    ElMessage.error('复制失败，请检查浏览器权限');
    return false;
  }
}

function resetWhenOpen() {
  form.platform = 'local';
  form.type = props.defaultAccountType || 'account';
  form.remark = '';
  copiedText.value = '';
}

watch(
  () => props.modelValue,
  (visible) => {
    if (visible) resetWhenOpen();
  }
);

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

async function handleConfirm() {
  confirmLoading.value = true;
  try {
    const res = await extractAccountPool(props.module, {
      id: 0,
      type: form.type,
      platform: form.platform,
      remark: form.remark || '',
    });
    if (res?.code !== 200) {
      ElMessage.error(res?.msg || '补卡失败');
      return;
    }
    const extractedRow = normalizeRow(res?.data || {});
    const text = buildCopyTextByRow(extractedRow);
    copiedText.value = text;
    const copied = await copyToClipboard(text);
    emit('success');
    if (copied) close();
  } finally {
    confirmLoading.value = false;
  }
}
</script>

<template>
  <el-dialog
    :model-value="modelValue"
    title="补卡"
    width="520px"
    :close-on-click-modal="false"
    @update:model-value="emit('update:modelValue', $event)"
  >
    <el-form label-width="92px">
      <el-form-item label="账号类型">
        <el-select v-model="form.type" placeholder="请选择账号类型" class="field-full">
          <el-option label="账号密码" value="account" />
          <el-option label="账号密码+Token" value="account_tk" />
          <el-option label="Token" value="tk" />
        </el-select>
      </el-form-item>
      <el-form-item label="提取平台">
        <el-select v-model="form.platform" placeholder="请选择平台" class="field-full">
          <el-option
            v-for="(meta, key) in platformMap"
            :key="key"
            :label="meta.label"
            :value="key"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注">
        <el-input
          v-model="form.remark"
          class="field-full"
          type="textarea"
          :rows="3"
          placeholder="可选"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
      <el-form-item v-if="copiedText" label="复制内容">
        <el-input v-model="copiedText" type="textarea" :rows="4" readonly />
        <div class="patch-copy-actions">
          <el-button @click="copyToClipboard(copiedText)">复制</el-button>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取消</el-button>
      <el-button type="primary" :loading="confirmLoading" @click="handleConfirm">
        确定并复制
      </el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.field-full {
  width: 100%;
}

.patch-copy-actions {
  margin-top: 8px;
  width: 100%;
  display: flex;
  justify-content: flex-end;
}
</style>
