<template>
  <div class="container">
    <Breadcrumb :items="['京东Cookie管理', 'ck管理']" />
    <a-space direction="vertical" fill>
      <a-card class="general-card" title="京东Cookie管理">
        <a-row>
          <a-col :flex="1">
            <a-form
              :model="formModel"
              :label-col-props="{ span: 6 }"
              :wrapper-col-props="{ span: 18 }"
              label-align="left"
            >
              <a-row :gutter="16">
                <a-col :span="8">
                  <a-form-item field="cookie" label="cookie">
                    <a-input
                      v-model="formModel.cookie"
                      placeholder="请输入Cookie"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item field="name" label="名称">
                    <a-input
                      v-model="formModel.name"
                      placeholder="请输入名称"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </a-col>
          <a-divider style="height: 42px" direction="vertical" />
          <a-col flex="172px" style="text-align: right">
            <a-space direction="horizontal" :size="18">
              <a-button type="primary" @click="search">
                <template #icon>
                  <icon-search />
                </template>
                搜索
              </a-button>
              <a-button @click="reset">
                <template #icon>
                  <icon-refresh />
                </template>
                重置
              </a-button>
            </a-space>
          </a-col>
        </a-row>
        <a-divider style="margin-top: 0" />
        <a-row style="justify-content: space-between; margin-bottom: 16px">
          <a-space>
            <a-button
              type="primary"
              size="small"
              @click="showAddModel({ ...generateFormModel() })"
            >
              <template #icon>
                <icon-plus />
              </template>
              添加
            </a-button>
            <batchImportModel @close="() => search()" />
          </a-space>
        </a-row>
        <a-table
          :loading="loading"
          :pagination="{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            pageSizeOptions: [10, 20, 50, 100],
            showPageSize: true
          }"
          :columns="columns"
          :data="renderData"
          :scroll="{ x: 1080 }"
          @page-change="onPageChange"
          @page-size-change="onPageSizeChange"
        >
          <template #status="{ record }">
            <a-space size="small">
              <a-switch
                v-if="[0, 1].includes(record.status)"
                v-model="record.status"
                size="small"
                :checked-value="1"
                :unchecked-value="0"
                :beforeChange="
                  newValue =>
                    updateCurrentStatus(
                      record,
                      newValue as KamiApiCardRedeemJdV1AccountAddReqStatusEnum
                    )
                "
              />
              <a-tag
                v-else
                size="small"
                :color="statusMapper(record.status).color"
              >
                {{ statusMapper(record.status).text }}
              </a-tag>
            </a-space>
          </template>
          <template #operations="{ record }">
            <a-space size="small">
              <a-tooltip content="修改">
                <a-button
                  size="small"
                  status="warning"
                  @click="showAddModel(record)"
                >
                  <template #icon>
                    <icon-pen />
                  </template>
                </a-button>
              </a-tooltip>
              <a-tooltip content="详情">
                <a-button size="small" @click="showDetailModel(record)">
                  <template #icon>
                    <icon-list />
                  </template>
                </a-button>
              </a-tooltip>
              <a-tooltip content="删除">
                <a-button
                  size="small"
                  status="danger"
                  @click="deleteOne(record.id)"
                >
                  <template #icon>
                    <icon-delete />
                  </template>
                </a-button>
              </a-tooltip>
            </a-space>
          </template>
        </a-table>
      </a-card>
    </a-space>
    <add-modal
      :id="state.accountId"
      v-model:visible="state.addModalVisible"
      :account="state.account"
    />
  </div>
</template>

<script lang="ts" setup>
import useLoading from '@/hooks/loading';
import { Pagination } from '@/types/global';
import { onMounted, reactive, ref, watchEffect } from 'vue';
import { Notification, TableColumnData } from '@arco-design/web-vue';
import AddModal from './components/add-modal.vue';
import { batchImportModel } from './components/component.tsx';
import {
  ApiCookieInfoJdAccountListGetPageSizeEnum,
  KamiApiCardRedeemJdV1AccountAddReqStatusEnum,
  KamiApiCardRedeemJdV1AccountStatusReqStatusEnum,
  KamiApiCardRedeemJdV1CookieInfo
} from '@/api/generated/index.ts';
import { apiCkClient } from '@/api/index.ts';

const basePagination: Pagination = {
  current: 1,
  pageSize: 50
};
const pagination = reactive({
  ...basePagination
});
const columns: TableColumnData[] = [
  {
    title: '序号',
    dataIndex: 'index',
    render: ({ rowIndex }) => {
      return rowIndex + 1 + (pagination.current - 1) * pagination.pageSize;
    }
  },
  {
    title: '名称',
    dataIndex: 'name'
  },
  {
    title: '拉单次数',
    dataIndex: 'amountTotalCount'
  },
  {
    title: '成功订单',
    dataIndex: 'amountTotalCount'
  },
  {
    title: '支付总金额',
    dataIndex: 'amountTotalSum'
  },
  {
    title: '今日支付金额',
    dataIndex: 'amountTodaySum'
  },
  {
    title: 'ck',
    dataIndex: 'cookie',
    ellipsis: true,
    tooltip: true
  },
  {
    title: '状态',
    dataIndex: 'status',
    slotName: 'status'
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    slotName: 'createdAt'
  },
  {
    title: '最近拉单时间',
    dataIndex: 'updatedAt'
  },
  {
    title: '操作',
    dataIndex: 'operations',
    slotName: 'operations',
    fixed: 'right',
    width: 220
  }
];
const generateFormModel = (): KamiApiCardRedeemJdV1CookieInfo => {
  return {
    name: '',
    cookie: ''
  };
};
const { loading, setLoading } = useLoading(false);
const renderData = ref<KamiApiCardRedeemJdV1CookieInfo[]>([]);
const formModel = ref(generateFormModel());
const state = reactive({
  addModalVisible: false,
  deployModalVisible: false,
  accountDetailVisible: false,
  accountId: null,
  account: null
});

const fetchData = async () => {
  setLoading(true);
  try {
    const res = await apiCkClient.apiCookieInfoJdAccountListGet({
      current: pagination.current,
      pageSize: pagination.pageSize as ApiCookieInfoJdAccountListGetPageSizeEnum
    });
    renderData.value = res.data.list;
    pagination.total = res.data.total;
  } catch (err) {
  } finally {
    setLoading(false);
  }
};
const onPageChange = (current: number) => {
  pagination.current = current;
  fetchData();
};
const onPageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize;
  fetchData();
};
const search = () => {
  fetchData();
};

const reset = () => {
  formModel.value = generateFormModel();
};

const deleteOne = async (id: number) => {
  try {
    await apiCkClient.apiCookieInfoJdAccountDeleteDelete({
      id: id
    });
  } catch {
    Notification.error({
      id: 'walmartAccountNotice',
      content: '删除京东ck失败',
      closable: true
    });
  } finally {
    fetchData();
  }
};

const showAddModel = (record: KamiApiCardRedeemJdV1CookieInfo) => {
  state.addModalVisible = true;
  state.accountId = record.id;
  state.account = record;
  if (state.account.groupId === 0) {
    state.account.groupId = null;
  }
};
const showDetailModel = (record: KamiApiCardRedeemJdV1CookieInfo) => {
  state.accountDetailVisible = true;
  state.accountId = record.id;
};
watchEffect(() => {
  // 目标账户和存储用户不能相同
  if (!state.addModalVisible) {
    search();
  }
});
const updateCurrentStatus = async (
  record: KamiApiCardRedeemJdV1CookieInfo,
  newValue: KamiApiCardRedeemJdV1AccountAddReqStatusEnum
) => {
  await apiCkClient.apiCookieInfoJdAccountStatusPut({
    kamiApiCardRedeemJdV1AccountStatusReq: {
      id: record.id,
      status:
        newValue as unknown as KamiApiCardRedeemJdV1AccountStatusReqStatusEnum
    }
  });
};

const statusMapper = (
  status: KamiApiCardRedeemJdV1AccountAddReqStatusEnum
): { text: string; color: string } => {
  switch (status) {
    case KamiApiCardRedeemJdV1AccountAddReqStatusEnum.Normal:
      return { text: '正常', color: 'green' };
    case KamiApiCardRedeemJdV1AccountAddReqStatusEnum.Disable:
      return { text: '禁用', color: 'red' };
    default:
      return { text: '未知', color: 'gray' };
  }
};
onMounted(() => {
  fetchData();
});
</script>
