<template>
  <a-modal
    :visible="visible"
    :title="cookieId ? '编辑Cookie' : '添加Cookie'"
    width="600px"
    :loading="loading"
    :footer="false"
    @cancel="handleCancel"
  >
    <a-form ref="formRef" :model="formModel" :rules="rules" layout="vertical">
      <a-form-item field="cookieValue" label="Cookie内容" required>
        <a-textarea
          v-model="formModel.cookieValue"
          placeholder="请输入完整的Cookie内容"
          :auto-size="{ minRows: 3, maxRows: 6 }"
        />
      </a-form-item>
      <a-form-item field="accountName" label="账户昵称" required>
        <a-input v-model="formModel.accountName" placeholder="请输入账户昵称" />
      </a-form-item>
      <a-form-item field="remark" label="备注">
        <a-textarea
          v-model="formModel.remark"
          placeholder="请输入备注信息"
          :auto-size="{ minRows: 2, maxRows: 4 }"
        />
      </a-form-item>
    </a-form>

    <!-- 校验结果区域 -->
    <div v-if="validateResult" class="validate-result">
      <a-alert
        :type="validateResult.isValid ? 'success' : 'error'"
        :title="validateResult.isValid ? 'Cookie有效' : 'Cookie无效'"
        show-icon
        :closable="false"
      >
        <template #icon>
          <icon-check-circle v-if="validateResult.isValid" />
          <icon-close-circle v-else />
        </template>
        {{ validateResult.message }}
      </a-alert>
    </div>

    <!-- 底部操作区域 -->
    <div class="modal-footer">
      <div class="validate-section">
        <a-button
          type="outline"
          :loading="validating"
          :disabled="!formModel.cookieValue.trim()"
          @click="handleValidate"
        >
          <template #icon>
            <icon-check-circle />
          </template>
          校验Cookie
        </a-button>
      </div>
      <div class="action-section">
        <a-space>
          <a-button @click="handleCancel">取消</a-button>
          <a-button
            type="primary"
            :loading="loading"
            @click="handleManualSubmit"
          >
            {{ cookieId ? '修改' : '添加' }}
          </a-button>
        </a-space>
      </div>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, reactive, watch } from 'vue';
import { Message, type FormInstance } from '@arco-design/web-vue';
import { IconCheckCircle, IconCloseCircle } from '@arco-design/web-vue/es/icon';
import { jdCookieClient } from '@/api';
import type {
  KamiApiJdCookieV1CookieAccountInfo,
  KamiApiJdCookieV1CreateAccountReq,
  KamiApiJdCookieV1UpdateAccountReq
} from '@/api/generated';

interface Props {
  visible: boolean;
  cookieId: string;
  cookieData: KamiApiJdCookieV1CookieAccountInfo | null;
}

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

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

const formRef = ref<FormInstance>();
const loading = ref(false);
const validating = ref(false);
const validateResult = ref<{
  isValid: boolean;
  message: string;
  cookieId?: string;
} | null>(null);

// 表单数据
const formModel = reactive({
  cookieValue: '',
  accountName: '',
  status: 1,
  remark: ''
});

// 表单验证规则
const rules: Record<string, any[]> = {
  cookieValue: [
    { required: true, message: '请输入Cookie内容', trigger: 'blur' }
  ],
  accountName: [{ required: true, message: '请输入账户昵称', trigger: 'blur' }]
};

// 监听props变化，更新表单数据
watch(
  () => props.visible,
  async newVal => {
    if (newVal && props.cookieId) {
      // 编辑模式 - 需要获取完整的 cookie 数据
      try {
        const response = await jdCookieClient.apiJdCookieAccountGetGet({
          cookieId: props.cookieId
        });
        const account = response.data.account;
        if (account) {
          Object.assign(formModel, {
            cookieValue: account.cookieValue || '', // 使用正确的cookieValue字段
            accountName: account.accountName || '',
            status: account.status || 1,
            remark: account.remark || ''
          });
        }
      } catch (error) {
        // 如果获取失败，使用传入的数据作为后备
        if (props.cookieData) {
          Object.assign(formModel, {
            cookieValue: props.cookieData.cookieValue || '',
            accountName: props.cookieData.accountName || '',
            status: props.cookieData.status || 1,
            remark: props.cookieData.remark || ''
          });
        }
      }
    } else if (newVal) {
      // 添加模式
      Object.assign(formModel, {
        cookieValue: '',
        accountName: '',
        status: 1,
        remark: ''
      });
    }
    // 重置校验结果
    validateResult.value = null;
  }
);

// 监听Cookie内容变化，清除校验结果
watch(
  () => formModel.cookieValue,
  () => {
    validateResult.value = null;
  }
);

// 处理单个Cookie校验
const handleValidate = async (): Promise<void> => {
  if (!formModel.cookieValue.trim()) {
    Message.warning('请输入Cookie内容');
    return;
  }

  validating.value = true;
  try {
    const response = await jdCookieClient.apiJdCookieAccountValidatePost({
      kamiApiJdCookieV1ValidateCookieReq: {
        cookieValue: formModel.cookieValue.trim()
      }
    });

    validateResult.value = {
      isValid: response.data.isValid || false,
      message: response.data.message || '',
      cookieId: response.data.cookieId
    };

    if (response.data.isValid) {
      Message.success('Cookie校验成功，状态有效');
    } else {
      Message.error('Cookie校验失败，状态无效');
    }
  } catch (error) {
    console.error('校验失败:', error);
    Message.error('校验失败，请检查网络连接或联系管理员');
  } finally {
    validating.value = false;
  }
};

// 手动提交表单（用于底部按钮）
const handleManualSubmit = (): void => {
  formRef.value?.validate().then((res: any) => {
    if (res) return;
    // 调用原有的提交逻辑，但不关闭模态框
    handleSubmit(closed => {
      if (closed) {
        emit('update:visible', false);
      }
    });
  });
};

// 提交表单
const handleSubmit = (done: (closed: boolean) => void) => {
  formRef.value?.validate().then(async (res: any) => {
    if (res) return done(false);
    try {
      loading.value = true;

      if (props.cookieId) {
        // 编辑模式
        const updateData: KamiApiJdCookieV1UpdateAccountReq = {
          cookieId: props.cookieId,
          cookieValue: formModel.cookieValue,
          accountName: formModel.accountName,
          status: formModel.status,
          remark: formModel.remark
        };
        await jdCookieClient.apiJdCookieAccountUpdatePut({
          kamiApiJdCookieV1UpdateAccountReq: updateData
        });
      } else {
        // 添加模式
        const createData: KamiApiJdCookieV1CreateAccountReq = {
          cookieValue: formModel.cookieValue,
          accountName: formModel.accountName,
          remark: formModel.remark
        };
        await jdCookieClient.apiJdCookieAccountCreatePost({
          kamiApiJdCookieV1CreateAccountReq: createData
        });
      }

      Message.success(props.cookieId ? '修改成功' : '添加成功');
      emit('success');
      done(true);
    } catch (error) {
      console.error('提交失败:', error);
      Message.error(props.cookieId ? '修改失败' : '添加失败');
      done(false);
    } finally {
      loading.value = false;
    }
  });
};

// 取消
const handleCancel = (): void => {
  emit('update:visible', false);
  validateResult.value = null;
  validating.value = false;
};
</script>

<style scoped>
.validate-result {
  margin: 16px 0;
}

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

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

.action-section {
  display: flex;
  align-items: center;
}
</style>
