<template>
  <a-modal
    :visible="visible"
    :title="isFullscreen ? '' : '批量添加Cookie'"
    :width="modalWidth"
    :fullscreen="isFullscreen"
    :footer="false"
    :mask-closable="false"
    :esc-to-close="!isFullscreen"
    @cancel="handleCancel"
  >
    <template v-if="!isFullscreen" #title>
      <div class="modal-title">
        <span>批量添加Cookie</span>
        <a-button
          type="text"
          size="small"
          class="fullscreen-btn"
          @click="toggleFullscreen"
        >
          <icon-fullscreen />
        </a-button>
      </div>
    </template>

    <div class="batch-import-container">
      <!-- 全屏模式下的头部 -->
      <div v-if="isFullscreen" class="fullscreen-header">
        <div class="header-left">
          <a-button
            type="text"
            size="small"
            class="exit-fullscreen-btn"
            @click="toggleFullscreen"
          >
            <icon-fullscreen-exit />
            退出全屏
          </a-button>
          <h2>批量添加Cookie</h2>
        </div>
        <div class="header-actions">
          <a-button
            type="primary"
            :loading="loading"
            :disabled="!hasValidData"
            @click="handleSubmit"
          >
            <icon-import />
            确认导入 ({{ parsedData.length }})
          </a-button>
          <a-button @click="handleCancel">
            <icon-close />
            取消
          </a-button>
        </div>
      </div>

      <!-- 主要内容区域 -->
      <div class="content-wrapper">
        <!-- 左侧输入区域 -->
        <div class="input-section">
          <div class="section-header">
            <h3>
              <icon-edit />
              输入数据
            </h3>
            <div class="input-tips">
              <a-tag size="small" color="blue">格式：每行一个Cookie</a-tag>
            </div>
          </div>

          <!-- Cookie批量输入 -->
          <a-textarea
            v-model="formModel.cookieData"
            placeholder="请输入Cookie数据，每行一个&#10;示例：&#10;pt_key=AAJo8JBBADCehYF-0KP6YtweybQUPaGlc16tyfEAS7JIh81ncH9J4Fz8hckodXgnrGKk4YCxV64;pt_pin=jd_UGRblnTjugEH;&#10;pt_key=xxx;pt_pin=yyy;"
            :auto-size="{
              minRows: isFullscreen ? 15 : 6,
              maxRows: isFullscreen ? 25 : 12
            }"
            class="batch-textarea"
            @input="handleInputChange"
            @change="handleInputChange"
            @keyup="handleInputChange"
          />

          <!-- 账户前缀设置 -->
          <div class="form-item">
            <div class="form-label">
              <icon-user />
              账户前缀
            </div>
            <a-input
              v-model="formModel.accountPrefix"
              placeholder="请输入账户前缀，如：京东账号"
              class="form-input"
              @input="handleInputChange"
            />
          </div>

          <!-- 统一备注设置 -->
          <div class="form-item">
            <div class="form-label">
              <icon-message />
              统一备注
            </div>
            <a-input
              v-model="formModel.unifiedRemark"
              placeholder="请输入统一备注（可选）"
              class="form-input"
              @input="handleInputChange"
            />
          </div>

          <div class="input-stats">
            <span>Cookie数量：{{ lineCount }}</span>
            <span>有效数据：{{ parsedData.length }}</span>
          </div>
        </div>

        <!-- 右侧预览区域 -->
        <div class="preview-section">
          <div class="section-header">
            <h3>
              <icon-eye />
              数据预览
            </h3>
            <div class="preview-stats">
              <a-tag
                size="small"
                :color="parsedData.length > 0 ? 'green' : 'gray'"
              >
                {{ parsedData.length }} 条数据
              </a-tag>
            </div>
          </div>

          <div class="preview-content">
            <div v-if="parsedData.length === 0" class="empty-preview">
              <icon-eye />
              <p>暂无数据预览</p>
              <span>请在左侧输入数据后，数据将自动预览</span>
            </div>

            <div v-else class="preview-table-wrapper">
              <a-table
                :data="parsedData"
                :pagination="false"
                size="small"
                :scroll="{ y: isFullscreen ? 400 : 300 }"
                class="preview-table"
                :columns="[
                  {
                    title: 'Cookie',
                    dataIndex: 'cookieValue',
                    ellipsis: true,
                    tooltip: true,
                    width: 280
                  },
                  {
                    title: '账号',
                    dataIndex: 'accountName',
                    width: 120
                  },
                  {
                    title: '备注',
                    dataIndex: 'remark',
                    ellipsis: true,
                    tooltip: true,
                    width: 160
                  },
                  {
                    title: '校验状态',
                    dataIndex: 'isValid',
                    width: 100,
                    slotName: 'validateStatus'
                  },
                  {
                    title: '状态',
                    dataIndex: 'valid',
                    width: 60,
                    slotName: 'status'
                  }
                ]"
              >
                <template #validateStatus="{ record }">
                  <a-tag
                    v-if="record.isValid === true"
                    color="green"
                    size="small"
                  >
                    有效
                  </a-tag>
                  <a-tag
                    v-else-if="record.isValid === false"
                    color="red"
                    size="small"
                  >
                    无效
                  </a-tag>
                  <a-tag v-else color="gray" size="small">未校验</a-tag>
                </template>
                <template #status="{ record }">
                  <a-tag v-if="record.valid" color="green">有效</a-tag>
                  <a-tag v-else color="red">无效</a-tag>
                </template>
                <template #cookieValue="{ record }">
                  <div class="cookie-cell">
                    <a-tooltip :content="record.cookieValue">
                      <span class="cookie-text">
                        {{ record.cookieValue }}
                      </span>
                    </a-tooltip>
                  </div>
                </template>
              </a-table>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部操作区域 -->
      <div v-if="!isFullscreen" class="footer-actions">
        <div class="footer-content">
          <div class="validate-section">
            <a-button
              type="outline"
              :loading="validating"
              :disabled="!hasValidData"
              @click="handleValidate"
            >
              <template #icon>
                <icon-check-circle />
              </template>
              校验Cookie
            </a-button>
            <div v-if="validationSummary" class="validation-summary">
              <a-tag
                :color="
                  validationSummary.allValid
                    ? 'green'
                    : validationSummary.hasValid
                      ? 'orange'
                      : 'red'
                "
                size="small"
              >
                {{ validationSummary.text }}
              </a-tag>
            </div>
          </div>
          <div class="action-buttons">
            <a-space>
              <a-button
                type="primary"
                :loading="loading"
                :disabled="!hasValidData"
                @click="handleSubmit"
              >
                <template #icon>
                  <icon-import />
                </template>
                确认导入 ({{ parsedData.length }})
              </a-button>
              <a-button @click="handleCancel">取消</a-button>
            </a-space>
          </div>
        </div>
      </div>
    </div>
  </a-modal>

  <!-- 失败详情弹窗 -->
  <a-modal
    v-model:visible="showErrorModal"
    title="批量添加失败详情"
    :footer="false"
    width="800px"
    @cancel="showErrorModal = false"
  >
    <div class="error-modal-content">
      <a-alert
        type="error"
        message="部分Cookie添加失败"
        :description="`共 ${failedItemsList.length} 个Cookie添加失败，请查看具体原因`"
        show-icon
        :closable="false"
        style="margin-bottom: 16px"
      />

      <a-table
        :data="failedItemsList"
        :pagination="{ pageSize: 10 }"
        size="small"
        :columns="[
          {
            title: '行号',
            dataIndex: 'lineNumber',
            width: 80
          },
          {
            title: '账户名称',
            dataIndex: 'accountName',
            width: 150,
            ellipsis: true,
            tooltip: true
          },
          {
            title: '失败原因',
            dataIndex: 'errorMsg',
            ellipsis: true,
            tooltip: true
          }
        ]"
      >
        <template #lineNumber="{ record }">
          第{{ record.lineNumber }}行
        </template>
        <template #errorMsg="{ record }">
          <a-tag color="red" size="small">
            {{ record.errorMsg }}
          </a-tag>
        </template>
      </a-table>

      <div class="error-actions">
        <a-button type="primary" @click="showErrorModal = false">
          我知道了
        </a-button>
      </div>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from 'vue';
import { Message } from '@arco-design/web-vue';
import {
  IconFullscreen,
  IconFullscreenExit,
  IconEye,
  IconImport,
  IconClose,
  IconEdit,
  IconUser,
  IconMessage,
  IconCheckCircle
} from '@arco-design/web-vue/es/icon';
import { jdCookieClient } from '@/api';

interface ParsedCookieItem {
  cookieValue: string;
  accountName: string;
  remark: string;
  valid: boolean;
  lineNumber: number;
  isValid?: boolean; // 校验结果：是否有效
  validateMessage?: string; // 校验消息
  cookieId?: string; // 校验成功后返回的Cookie ID
}

interface Props {
  visible: boolean;
}

interface Emits {
  (e: 'update:visible', value: boolean): void;
  (e: 'success'): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const loading = ref(false);
const validating = ref(false);
const isFullscreen = ref(false);
const validationSummary = ref<{
  allValid: boolean;
  hasValid: boolean;
  text: string;
} | null>(null);
const showErrorModal = ref(false);
const failedItemsList = ref<any[]>([]);

// 表单数据
const formModel = reactive({
  cookieData: '',
  accountPrefix: '',
  unifiedRemark: ''
});

// 解析后的数据
const parsedData = ref<ParsedCookieItem[]>([]);

// 计算属性
const modalWidth = computed(() => (isFullscreen.value ? '100vw' : '1200px'));
const lineCount = computed(() => {
  if (!formModel.cookieData.trim()) return 0;
  return formModel.cookieData.split('\n').filter(line => line.trim()).length;
});
const hasValidData = computed(() => parsedData.value.length > 0);

// 解析Cookie数据
const parseCookieData = (): void => {
  const lines = formModel.cookieData
    .trim()
    .split('\n')
    .filter(line => line.trim());

  const parsed: ParsedCookieItem[] = lines.map((line, index) => {
    // 提取Cookie值（整行作为Cookie）
    let cookieValue = line.trim();
    let accountName = '';
    let remark = '';
    let isValid = false;

    // 生成账户名称：前缀 + 数字序号
    if (formModel.accountPrefix.trim()) {
      accountName = `${formModel.accountPrefix.trim()}${index + 1}`;
    } else {
      accountName = `账号${index + 1}`;
    }

    // 使用统一备注
    remark = formModel.unifiedRemark.trim() || '';

    // 所有输入的Cookie都认为是有效的
    isValid = true;

    return {
      cookieValue,
      accountName,
      remark,
      valid: isValid,
      lineNumber: index + 1
    };
  });

  parsedData.value = parsed;

  // 调试输出
  console.log('解析的数据:', parsedData.value);
};

// 处理输入变化
const handleInputChange = (): void => {
  parseCookieData();
};

// 切换全屏
const toggleFullscreen = (): void => {
  isFullscreen.value = !isFullscreen.value;
};

// 处理批量校验
const handleValidate = async (): Promise<void> => {
  if (!formModel.cookieData.trim()) {
    Message.warning('请输入Cookie数据');
    return;
  }

  // 重新解析数据
  parseCookieData();

  if (parsedData.value.length === 0) {
    Message.warning('没有可校验的数据');
    return;
  }

  validating.value = true;
  try {
    // 准备批量校验请求
    const validateCookies = parsedData.value.map(item => ({
      index: item.lineNumber - 1, // 从0开始
      cookieValue: item.cookieValue,
      accountName: item.accountName
    }));

    const response = await jdCookieClient.apiJdCookieAccountBatchValidatePost({
      kamiApiJdCookieV1BatchValidateCookieReq: {
        cookies: validateCookies
      }
    });

    const results = response.data.results || [];
    const validCount = response.data.validCount || 0;
    const invalidCount = response.data.invalidCount || 0;

    // 更新解析数据的校验结果
    results.forEach(result => {
      const item = parsedData.value.find(
        p => p.lineNumber === (result.index || 0) + 1
      );
      if (item) {
        item.isValid = result.isValid;
        item.validateMessage = result.message;
        item.cookieId = result.cookieId;
      }
    });

    // 更新校验摘要
    validationSummary.value = {
      allValid: validCount === parsedData.value.length,
      hasValid: validCount > 0,
      text:
        validCount === parsedData.value.length
          ? `全部有效 (${validCount})`
          : validCount > 0
            ? `${validCount}个有效, ${invalidCount}个无效`
            : `全部无效 (${invalidCount})`
    };

    // 显示校验结果统计
    if (validCount === parsedData.value.length) {
      Message.success(`校验完成，全部 ${validCount} 个Cookie都有效`);
    } else if (validCount > 0) {
      Message.warning(`校验完成，${validCount} 个有效，${invalidCount} 个无效`);
    } else {
      Message.error(`校验完成，全部 ${invalidCount} 个Cookie都无效`);
    }

    // 输出详细的校验结果到控制台
    const validCookies = results.filter(r => r.isValid);
    const invalidCookies = results.filter(r => !r.isValid);

    if (validCookies.length > 0) {
      console.log(
        '有效的Cookie:',
        validCookies.map(r => `${r.accountName}: ${r.message}`)
      );
    }

    if (invalidCookies.length > 0) {
      console.warn(
        '无效的Cookie:',
        invalidCookies.map(r => `${r.accountName}: ${r.message}`)
      );
    }
  } catch (error) {
    console.error('批量校验失败:', error);
    Message.error('校验失败，请检查网络连接或联系管理员');
  } finally {
    validating.value = false;
  }
};

const handleCancel = (): void => {
  emit('update:visible', false);
  formModel.cookieData = '';
  formModel.accountPrefix = '';
  formModel.unifiedRemark = '';
  parsedData.value = [];
  isFullscreen.value = false;
  validating.value = false;
  validationSummary.value = null;
  showErrorModal.value = false;
  failedItemsList.value = [];
};

const handleSubmit = async (): Promise<boolean> => {
  if (!formModel.cookieData.trim()) {
    Message.warning('请输入Cookie数据');
    return false;
  }

  if (!formModel.accountPrefix.trim()) {
    Message.warning('请输入账户前缀');
    return false;
  }

  // 重新解析数据
  parseCookieData();

  const validCookies = parsedData.value.filter(item => item.valid);
  if (validCookies.length === 0) {
    Message.warning('没有有效的Cookie数据');
    return false;
  }

  loading.value = true;
  try {
    const cookieAccounts = validCookies.map(item => ({
      cookieValue: item.cookieValue,
      accountName: item.accountName,
      remark: item.remark
    }));

    // 调用批量创建API
    const response = await jdCookieClient.apiJdCookieAccountBatchCreatePost({
      kamiApiJdCookieV1BatchCreateReq: {
        cookies: cookieAccounts
      }
    });

    // 处理新的返回结果结构
    const successCount = response.data.successIds?.length || 0;
    const failedCount = response.data.failedCount || 0;
    const failedItems = response.data.failedItems || [];

    // 构建详细的成功/失败消息
    let message = '';

    if (successCount > 0) {
      message = `成功添加 ${successCount} 个Cookie`;
    }

    if (failedCount > 0) {
      if (message) {
        message += `，${failedCount} 个添加失败`;
      } else {
        message = `${failedCount} 个Cookie添加失败`;
      }

      // 如果有具体的失败原因，准备显示详细信息
      if (failedItems.length > 0) {
        // 准备失败详情数据
        failedItemsList.value = failedItems.map(item => ({
          lineNumber: (item.index || 0) + 1,
          accountName: item.accountName || `账号${(item.index || 0) + 1}`,
          errorMsg: item.errorMsg || '未知错误'
        }));

        // 修改提示消息，引导用户查看详情
        message += `，点击查看失败详情`;
      }
    }

    if (message) {
      if (successCount > 0 && failedCount === 0) {
        Message.success(message);
      } else if (successCount === 0 && failedCount > 0) {
        // 全部失败，显示错误消息并引导查看详情
        Message.error({
          content: message,
          duration: 5000,
          closable: true
        });
        // 显示失败详情弹窗
        showErrorModal.value = true;
      } else {
        // 部分成功，显示警告消息
        Message.warning(message);
      }

      // 如果有失败项，显示详情弹窗
      if (failedItems.length > 0) {
        showErrorModal.value = true;
      }
    }

    // 只要有成功的就触发success事件
    if (successCount > 0) {
      emit('success');
    }

    handleCancel();
    return true;
  } catch (error) {
    console.error('批量添加失败:', error);
    Message.error('批量添加失败，请检查网络连接或联系管理员');
    return false;
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
/* 响应式设计 */
@media (width <= 768px) {
  .content-wrapper {
    flex-direction: column;
    gap: 16px;
  }

  .modal-title {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .header-actions {
    flex-wrap: wrap;
  }

  .header-left {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .fullscreen-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .input-stats {
    flex-direction: column;
    gap: 4px;
    text-align: center;
  }
}

.modal-title {
  display: flex;
  align-items: center;
  width: 100%;
}

.modal-title span {
  flex: 1;
}

.fullscreen-btn {
  color: var(--color-text-2);
  padding: 4px 8px;
  min-width: auto;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  flex-shrink: 0;
  margin-right: 8px;
}

.fullscreen-btn:hover {
  color: var(--color-text-1);
  background-color: var(--color-fill-2);
}

.batch-import-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.fullscreen-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 0;
  border-bottom: 1px solid var(--color-border-2);
  margin-bottom: 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.exit-fullscreen-btn {
  color: var(--color-text-2);
  display: flex;
  align-items: center;
  gap: 4px;
}

.exit-fullscreen-btn:hover {
  color: var(--color-text-1);
  background-color: var(--color-fill-2);
}

.fullscreen-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.content-wrapper {
  display: flex;
  gap: 20px;
  flex: 1;
  min-height: 400px;
}

.input-section,
.preview-section {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid var(--color-border-2);
}

.section-header h3 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 6px;
}

.input-tips {
  display: flex;
  gap: 6px;
}

.preview-stats {
  display: flex;
  gap: 6px;
}

.batch-textarea {
  font-family: Consolas, Monaco, 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.5;
  border: 1px solid var(--color-border-2);
  border-radius: 6px;
  transition: border-color 0.2s;
}

.batch-textarea:focus {
  border-color: rgb(var(--primary-6));
}

.form-item {
  margin-top: 16px;
}

.form-label {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  font-weight: 500;
  color: var(--color-text-2);
  margin-bottom: 6px;
}

.form-input {
  width: 100%;
}

.cookie-input-item {
  margin-bottom: 0;
}

.input-stats {
  display: flex;
  justify-content: space-between;
  margin-top: 8px;
  font-size: 12px;
  color: var(--color-text-3);
  padding: 8px 12px;
  background-color: var(--color-fill-1);
  border-radius: 4px;
}

.preview-content {
  flex: 1;
  border: 1px solid var(--color-border-2);
  border-radius: 6px;
  background-color: var(--color-bg-2);
}

.empty-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  color: var(--color-text-3);
  text-align: center;
}

.empty-preview svg {
  font-size: 48px;
  margin-bottom: 12px;
  opacity: 0.5;
}

.empty-preview p {
  margin: 8px 0 4px;
  font-size: 14px;
  font-weight: 500;
}

.empty-preview span {
  font-size: 12px;
}

.preview-table-wrapper {
  height: 100%;
}

.preview-table {
  height: 100%;
}

.cookie-cell {
  max-width: 200px;
}

.cookie-text {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-family: Consolas, Monaco, 'Courier New', monospace;
  font-size: 12px;
}

.footer-actions {
  display: flex;
  justify-content: flex-end;
  padding: 16px 0 0;
  border-top: 1px solid var(--color-border-2);
  margin-top: 20px;
}

.footer-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.validate-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.validation-summary {
  display: flex;
  align-items: center;
}

.action-buttons {
  display: flex;
}

.error-modal-content {
  padding: 16px 0;
}

.error-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  padding-top: 16px;
  border-top: 1px solid var(--color-border-2);
}

/* 全屏模式样式调整 */
:deep(.arco-modal-fullscreen) .batch-import-container {
  height: calc(100vh - 100px);
}

:deep(.arco-modal-fullscreen) .content-wrapper {
  min-height: calc(100vh - 300px);
}

:deep(.arco-modal-fullscreen) .preview-content {
  height: 100%;
}

:deep(.arco-modal-fullscreen) .empty-preview {
  height: 100%;
}

/* 表格样式优化 */
:deep(.preview-table .arco-table-th) {
  background-color: var(--color-fill-1);
  font-weight: 600;
  font-size: 12px;
}

:deep(.preview-table .arco-table-td) {
  font-size: 12px;
}

:deep(.preview-table .arco-table-cell) {
  padding: 8px 12px;
}

/* 按钮组样式 */
.footer-actions :deep(.arco-space) {
  width: 100%;
  justify-content: flex-end;
}

/* 加载状态样式 */
:deep(.arco-btn-loading) {
  position: relative;
}

/* 无效数据样式 */
:deep(.arco-tag-red) {
  background-color: var(--color-danger-light-1);
  color: var(--color-danger-6);
  border-color: var(--color-danger-light-3);
}
</style>
