<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" 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="groupId" label="分组">
        <a-select
          v-model="formData.groupId"
          placeholder="请选择分组"
          :showSearch="true"
          :filter-option="false"
          :allowClear="true"
        >
          <a-option
            v-for="(item, index) in groupList"
            :key="index"
            :value="item.id"
            :label="item.name"
          />
        </a-select>
      </a-form-item>
      <a-form-item field="remark" label="备注">
        <a-textarea v-model="formData.remark" />
      </a-form-item>
    </a-form>
    <template #footer>
      <!-- <a-button
          v-if="props.id === ''"
          type="secondary"
          status="warning"
          :loading="renderData.loading"
          @click="checkCookie"
        >
          检测Cookie
        </a-button> -->
      <a-space>
        <a-button @click="handleCancel">取消</a-button>
        <a-button type="primary" :loading="loading" @click="handleOk">
          确定
        </a-button>
        <!-- <a-button
              type="primary"
              :loading="loading"
              :disabled="!renderData.cookieStatus && props.id === ''"
              @click="handleOk"
            >
              确定
            </a-button> -->
      </a-space>
    </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 { apiClient } from '@/api/index.ts';
import {
  addWalmartCard,
  detectCookie,
  updateWalmartCard
} from '@/api/card-walmart-account';
import { notification } from './component.tsx';
import {
  KamiApiCardInfoWalmartV1AccountCreateReq,
  KamiApiCardInfoWalmartV1AccountListRecord
} from '@/api/generated/index.ts';
import type { KamiInternalModelEntityV1CardRedeemAccountGroup } from '@/api/generated/index.ts';

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

const generateFormData = () => {
  return {
    status: 1,
    maxAmountLimit: 0,
    maxCountLimit: 0,
    cookie: '',
    remark: '',
    name: ''
  };
};
const formData =
  ref<KamiApiCardInfoWalmartV1AccountCreateReq>(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 groupList = ref<KamiInternalModelEntityV1CardRedeemAccountGroup[]>([]);

const handleOk = () => {
  if (formData.value) {
    formDataRef.value.validate().then(async res => {
      if (res) return;
      setLoading(true);
      try {
        if (props.id === '') {
          await addWalmartCard(formData.value);
        } else {
          await updateWalmartCard({ 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 = false;
  try {
    const cookieResp = await detectCookie({
      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;
  }
};

const getAllGroupList = () => {
  apiClient.apiCardInfoWalmartGroupAllListGet().then(res => {
    groupList.value = res.data.list;
  });
};
getAllGroupList();
</script>

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