<template>
  <a-modal
    :visible="props.visible"
    :ok-loading="loading"
    draggable
    @cancel="handleCancel"
  >
    <template #title>{{ props.id === '' ? '新增' : '编辑' }}Cookie</template>
    <a-form ref="formDataRef" :model="formData">
      <a-form-item field="name" label="名称" required>
        <a-input v-model="formData.name" />
      </a-form-item>
      <a-form-item
        field="cookie"
        label="cookie"
        :disabled="props.id !== ''"
        required
      >
        <a-space
          direction="vertical"
          fill
          style="width: -webkit-fill-available"
        >
          <a-textarea
            v-model="formData.cookie"
            :autoSize="{ minRows: 3, maxRows: 10 }"
          />
        </a-space>
      </a-form-item>
      <a-form-item
        field="maxAmountLimit"
        label="充值限制(金额)"
        tooltip="0表示没有限制"
        required
      >
        <a-input-number v-model="formData.maxAmountLimit" />
      </a-form-item>
      <a-form-item
        field="maxCountLimit"
        label="充值限制(次数)"
        tooltip="0表示没有限制"
        required
      >
        <a-input-number v-model="formData.maxCountLimit" />
      </a-form-item>
      <a-form-item
        field="status"
        label="状态"
        :disabled="![0, 1].includes(formData.status)"
      >
        <a-switch
          v-model="formData.status"
          :checked-value="1"
          :unchecked-value="0"
        />
      </a-form-item>
      <a-form-item field="remark" label="备注">
        <a-textarea v-model="formData.remark" />
      </a-form-item>
    </a-form>
    <template #footer>
      <div class="footer">
        <a-button
          v-if="props.id === ''"
          type="secondary"
          status="warning"
          :loading="renderData.loading"
          @click="checkCookie"
        >
          检测Cookie
        </a-button>
        <div style="float: right">
          <a-space>
            <a-button @click="handleCancel">取消</a-button>
            <a-button
              type="primary"
              :loading="loading"
              :disabled="!renderData.cookieStatus && props.id === ''"
              @click="handleOk"
            >
              确定
            </a-button>
          </a-space>
        </div>
      </div>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
import useLoading from '@/hooks/loading';
import { FormInstance } from '@arco-design/web-vue';
import { ref, PropType, watch, reactive } from 'vue';
import { isNull } from '@/utils/is.ts';
import { notification } from './component.tsx';
import { apiClient } from '@/api/index.ts';
import { KamiApiCardInfoJdV1JDAccountCreateReq } from '@/api/generated/index.ts';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  id: {
    type: String,
    default: ''
  },
  account: {
    type: Object as PropType<Required<KamiApiCardInfoJdV1JDAccountCreateReq>>,
    default: null
  }
});

const generateFormData = () => {
  return {
    status: 1,
    maxAmountLimit: 0,
    maxCountLimit: 0,
    cookie: '',
    remark: '',
    name: ''
  };
};
const formData = ref<KamiApiCardInfoJdV1JDAccountCreateReq>(generateFormData());
const formDataRef = ref<FormInstance>();

const { loading, setLoading } = useLoading(false);
const renderData = reactive<{ cookieStatus: boolean; loading: boolean }>({
  cookieStatus: false,
  loading: false
});

const emit = defineEmits(['update:visible']);

const handleOk = () => {
  if (formData.value) {
    formDataRef.value.validate().then(async res => {
      if (res) return;
      setLoading(true);
      try {
        if (props.id === '') {
          await apiClient.apiCardInfoJDCardAccountCreatePost({
            kamiApiCardInfoJdV1JDAccountCreateReq: formData.value
          });
        } else {
          await apiClient.apiCardInfoJDCardAccountUpdatePut({
            kamiApiCardInfoJdV1JDAccountUpdateReq: {
              id: props.id,
              ...formData.value
            }
          });
        }
        emit('update:visible', false);
        formData.value = generateFormData();
      } catch (error) {
      } finally {
        setLoading(false);
      }
    });
  }
};
watch(
  () => props.account,
  val => {
    if (!isNull(val)) {
      formData.value = { ...val };
    }
  }
);
const handleCancel = () => {
  emit('update:visible', false);
  formData.value = generateFormData();
};

watch(
  () => formData.value.cookie,
  val => {
    renderData.cookieStatus = false;
  }
);

const checkCookie = async () => {
  renderData.loading = true;
  try {
    const cookieResp = await apiClient.apiCardInfoJDCardAccountCheckCookiePost({
      kamiApiCardInfoJdV1JDAccountCookieCheckReq: {
        cookie: formData.value.cookie.trim()
      }
    });
    if (cookieResp.data.isAvailable) {
      notification(
        true,
        cookieResp.data.nickname,
        cookieResp.data.balance,
        cookieResp.data.isExist
      );
      renderData.cookieStatus = true;
      if (props.id === '') {
        renderData.cookieStatus = !cookieResp.data.isExist;
      }
    } else {
      notification(false);
    }
  } finally {
    renderData.loading = false;
  }
};
</script>

<style lang="less" scoped>
.footer {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}
</style>
