<template>
  <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-col :span="8">
            <a-form-item field="nickname" label="沃尔玛昵称">
              <a-input
                v-model="formModel.nickname"
                placeholder="请输入沃尔玛账户昵称"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item field="createdUserName" label="创建人">
              <a-select v-model="formModel.createdUserName" allow-clear>
                <a-option
                  v-for="item in userList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.userName"
                />
              </a-select>
            </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
        v-if="checkTokenFromLogin()"
        type="primary"
        size="small"
        @click="showAddModel({ id: '', ...generateFormModel() })"
      >
        <template #icon>
          <icon-plus />
        </template>
        添加
      </a-button>
      <a-button @click="download">
        <template #icon>
          <icon-download />
        </template>
        导出
      </a-button>
      <batchImportModel @close="() => search()" />
    </a-space>
    <a-tabs
      default-active-key=""
      type="capsule"
      :onChange="onChangeRadio"
      animation
    >
      <a-tab-pane key="" title="全部" />
      <a-tab-pane
        v-for="item in groupList"
        :key="item.id"
        :title="item.name"
        :value="item.id"
      />
    </a-tabs>
  </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)"
        />
        <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-popconfirm
          type="warning"
          content="确认刷新账号状态嘛？"
          @ok="refreshButton(record)"
        >
          <a-tooltip content="刷新">
            <a-button v-if="record.status === 3" size="small" status="success">
              <template #icon>
                <icon-refresh />
              </template>
            </a-button>
          </a-tooltip>
        </a-popconfirm>
        <a-tooltip content="检查账号状态">
          <a-button size="small" status="warning" @click="checkOne(record.id)">
            <template #icon>
              <icon-check-circle />
            </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>
  <add-modal
    :id="state.accountId"
    v-model:visible="state.addModalVisible"
    :account="state.account"
  />
  <account-detail
    v-model:visible="state.accountDetailVisible"
    :accountId="state.accountId"
  />
</template>

<script lang="ts" setup>
import useLoading from '@/hooks/loading';
import { Pagination } from '@/types/global';
import { checkTokenFromLogin } from '@/utils/auth';
import { onMounted, reactive, ref, watchEffect } from 'vue';
import { Notification, TableColumnData } from '@arco-design/web-vue';
import AddModal from './components/add-modal.vue';
import AccountDetail from './components/detail.vue';
import {
  deleteWalmartCard,
  downloadDataList,
  refreshWalmartCardStatus,
  updateWalmartCardStatus,
  WalmartCardParams,
  walmartCardUpdateRecord
} from '@/api/card-walmart-account';
import { batchImportModel } from './components/component.tsx';
import {
  ApiCardInfoWalmartAccountGetListGetPageSizeEnum,
  KamiApiCardInfoWalmartV1AccountListRecord,
  KamiApiSysUserV1UserGetAllSimpleUser,
  KamiInternalModelEntityV1CardRedeemAccountGroup
} from '@/api/generated/index.ts';
import { apiClient } 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: 'nickname'
  },
  {
    title: '余额',
    dataIndex: 'balance'
  },
  {
    title: '今日充值金额',
    dataIndex: 'amountTodaySum'
  },
  {
    title: '今日充值次数',
    dataIndex: 'amountTodayCount'
  },
  {
    title: '充值限制(金额)',
    dataIndex: 'maxAmountLimit'
  },
  {
    title: '充值限制(次数)',
    dataIndex: 'maxCountLimit'
  },
  {
    title: '累计充值金额',
    dataIndex: 'amountTotalSum'
  },
  {
    title: '累计充值次数',
    dataIndex: 'amountTotalCount'
  },
  {
    title: 'ck',
    dataIndex: 'cookie',
    ellipsis: true,
    tooltip: true
  },
  {
    title: '创建人',
    dataIndex: 'uploadUser.username'
  },
  {
    title: '状态',
    dataIndex: 'status',
    slotName: 'status'
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    slotName: 'createdAt'
  },
  {
    title: '操作',
    dataIndex: 'operations',
    slotName: 'operations',
    fixed: 'right',
    width: 220
  }
];
const generateFormModel = () => {
  return {
    remark: '',
    name: '',
    cookie: '',
    nickname: '',
    maxAmountLimit: 0,
    status: 1,
    createdUserName: '',
    groupId: null
  };
};
const { loading, setLoading } = useLoading(true);
const renderData = ref<KamiApiCardInfoWalmartV1AccountListRecord[]>([]);
const formModel = ref(generateFormModel());
const state = reactive({
  addModalVisible: false,
  deployModalVisible: false,
  accountDetailVisible: false,
  accountId: '',
  account: null
});

const groupList = ref<KamiInternalModelEntityV1CardRedeemAccountGroup[]>([]);

const fetchData = async (
  params: WalmartCardParams = { current: 1, pageSize: 50 }
) => {
  setLoading(true);
  try {
    const res = await apiClient.apiCardInfoWalmartAccountGetListGet({
      current: params.current,
      pageSize:
        params.pageSize as ApiCardInfoWalmartAccountGetListGetPageSizeEnum,
      name: formModel.value.name,
      nickName: formModel.value.nickname,
      cookie: formModel.value.cookie,
      createdUserName: formModel.value.createdUserName,
      groupId: formModel.value.groupId
    });
    renderData.value = res.data.list;
    pagination.current = params.current;
    pagination.pageSize = params.pageSize;
    pagination.total = res.data.total;
  } catch (err) {
  } finally {
    setLoading(false);
  }
};
const onPageChange = (current: number) => {
  fetchData({ ...pagination, current });
};
const onPageSizeChange = (pageSize: number) => {
  fetchData({ ...pagination, pageSize });
};
const search = () => {
  fetchData({
    ...basePagination,
    ...formModel.value
  } as unknown as WalmartCardParams);
};
const reset = () => {
  formModel.value = generateFormModel();
};

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

const deleteOne = async (id: string) => {
  try {
    await deleteWalmartCard({ id });
  } catch {
    Notification.error({
      id: 'walmartAccountNotice',
      content: '删除沃尔玛卡失败',
      closable: true
    });
  } finally {
    fetchData({ ...pagination });
  }
};

const checkOne = async (id: string) => {
  try {
    const result = await apiClient.apiCardInfoWalmartAccountStatusDetectGet({
      id
    });
    if (result.data.status) {
      Notification.info({
        id: 'walmartAccountNotice',
        content: 'ck有效',
        closable: true
      });
    } else {
      Notification.error({
        id: 'walmartAccountNotice',
        content: 'ck无效',
        closable: true
      });
    }
  } catch (err) {
    Notification.error({
      id: 'walmartAccountNotice',
      content: '检测沃尔玛卡失败',
      closable: true
    });
  }
};

const showAddModel = (record: walmartCardUpdateRecord) => {
  state.addModalVisible = true;
  state.accountId = record.id;
  state.account = record;
  if (state.account.groupId === 0) {
    state.account.groupId = null;
  }
};

const showDetailModel = (record: walmartCardUpdateRecord) => {
  state.accountDetailVisible = true;
  state.accountId = record.id;
};

watchEffect(() => {
  // 目标账户和存储用户不能相同
  if (!state.addModalVisible) {
    search();
  }
});

const updateCurrentStatus = async (
  record: walmartCardUpdateRecord,
  newValue: string | number | boolean
) => {
  await updateWalmartCardStatus({ id: record.id, status: newValue as number });
  record.status = newValue as number;
};

const statusMapper = (status: number): { text: string; color: string } => {
  switch (status) {
    case 0:
      return { text: '失效', color: 'red' };
    case 1:
      return { text: '正常', color: 'green' };
    case 2:
      return { text: '充值过快', color: 'orange' };
    case 3:
      return { text: '充值限制(用户设置)', color: 'red' };
    case 4:
      return { text: '充值限制(其他)', color: 'red' };
    case 5:
      return { text: '充值限制(低额)', color: 'red' };
    case 6:
      return { text: '充值限制(安全原因)', color: 'red' };
    case 7:
      return { text: '充值限制(暂时限制)', color: 'red' };
    case 8:
      return { text: '充值限制(平台原因)', color: 'red' };
    default:
      return { text: '未知', color: 'gray' };
  }
};
const refreshButton = (record: walmartCardUpdateRecord) => {
  refreshWalmartCardStatus({ id: record.id }).then(() => {
    fetchData();
  });
};

const onChangeRadio = (value: string | number | boolean) => {
  formModel.value.groupId = value as number;
  // fetchData();
};
const download = () => {
  downloadDataList();
};

const userList = ref<KamiApiSysUserV1UserGetAllSimpleUser[]>([]);

// 获取所有分组
const getAllUserList = () => {
  apiClient.apiUserGetSimpleAllGet().then(res => {
    userList.value = res.data.list;
  });
};

onMounted(() => {
  fetchData();
  getAllGroupList();
  getAllUserList();
});
</script>
