<template>
  <a-card class="general-card" title="账户管理">
    <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="accountNumber" label="账号">
                <a-input
                  v-model="formModel.accountNumber"
                  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="margin-bottom: 16px">
      <a-col :span="12">
        <a-space>
          <a-button
            type="primary"
            size="small"
            @click="showAddRandomAccountModal"
          >
            <template #icon>
              <icon-plus />
            </template>
            批量创建
          </a-button>
        </a-space>
      </a-col>
      <a-col
        :span="12"
        style="display: flex; align-items: center; justify-content: end"
      >
        <a-space>
          <span>
            {{ state.tMallExpiredAt }}
          </span>
          <a-button
            :status="state.tMallAuthStatus ? 'success' : 'danger'"
            @click="openTMallAuthorizePage"
          >
            天猫授权
          </a-button>
        </a-space>
      </a-col>
    </a-row>
    <a-table
      :loading="loading"
      :pagination="pagination"
      :columns="columns"
      :data="renderData"
      :bordered="false"
      @page-change="onPageChange"
    >
      <template #status="{ record }">
        <a-tag
          :color="record.status === 'enable' ? 'green' : 'red'"
          size="small"
        >
          {{ record.status === 'enable' ? '正常' : '停用' }}
        </a-tag>
      </template>

      <template #operation="{ record }">
        <a-space size="small">
          <!-- <a-button
            status="success"
            size="mini"
            @click="showPaymentDrawer(record)"
          >
            详情
          </a-button> -->
          <a-button
            status="warning"
            size="mini"
            @click="stopAccountNumber(record)"
          >
            停用
          </a-button>
          <a-tooltip content="删除">
            <a-button
              status="danger"
              size="mini"
              @click="deleteItem(record.id)"
            >
              <template #icon>
                <icon-delete />
              </template>
            </a-button>
          </a-tooltip>
        </a-space>
      </template>
    </a-table>
  </a-card>
  <add-account-modal v-model:visible="state.visible" />
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, watchEffect } from 'vue';
import useLoading from '@/hooks/loading';
import { Pagination } from '@/types/global';
import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
import {
  TMallAccountAddRecord,
  TMallAccountParams,
  TMallAccountRecord,
  checkTMallAuthStatus,
  deleteTMallAccountItem,
  getTMallAuthorizeAppKey,
  queryTMallAccountList,
  stopTMallAccountItem
} from '@/api/t-mall-game-account.ts';
import addAccountModal from './components/add-account-modal.tsx';
import { openWindow } from '@/utils/index.ts';

const generateFormModel = () => {
  return {
    accountNumber: ''
  };
};
const { loading, setLoading } = useLoading(true);
const renderData = ref<TMallAccountRecord[]>([]);
const formModel = ref(generateFormModel());
const basePagination: Pagination = {
  current: 1,
  pageSize: 50
};
const pagination = reactive({
  ...basePagination
});
const state = reactive({
  visible: false,
  tMallAuthStatus: false,
  tMallExpiredAt: ''
});
const columns: TableColumnData[] = [
  {
    title: '序号',
    render(data) {
      return data.rowIndex + 1;
    }
  },
  {
    title: '账号',
    dataIndex: 'accountNumber'
  },
  {
    title: '已充值金额',
    dataIndex: 'balance'
  },
  {
    title: '充值次数',
    dataIndex: 'rechargeTimes'
  },
  {
    title: '状态',
    dataIndex: 'status',
    slotName: 'status'
  },
  {
    title: '操作',
    dataIndex: 'operation',
    slotName: 'operation'
  }
];
const fetchData = async (
  params: TMallAccountParams = { current: 1, pageSize: 50 }
) => {
  setLoading(true);
  try {
    const { data } = await queryTMallAccountList(params);
    renderData.value = data.list;
    pagination.current = params.current;
    pagination.total = data.total;
  } catch (err) {
    console.error(err);
  } finally {
    setLoading(false);
  }
};
const search = () => {
  fetchData({
    ...basePagination,
    ...formModel.value
  });
};
const onPageChange = (current: number) => {
  fetchData({ ...basePagination, current });
};
onMounted(() => {
  fetchData();
  checkTmallAuthStatus();
});
const reset = () => {
  formModel.value = generateFormModel();
};
const deleteItem = async (id: string) => {
  await deleteTMallAccountItem({ id });
  search();
};
const stopAccountNumber = async (record: TMallAccountAddRecord) => {
  await stopTMallAccountItem({ id: record.id });
  search();
};
const showAddRandomAccountModal = async () => {
  state.visible = true;
};
const openTMallAuthorizePage = async () => {
  const {
    data: { code, redirectUri }
  } = await getTMallAuthorizeAppKey();
  openWindow(
    `https://oauth.taobao.com/authorize?response_type=code&client_id=${code}&redirect_uri=${redirectUri}&state=12351&view=web`
  );
};
const checkTmallAuthStatus = async () => {
  const { data } = await checkTMallAuthStatus();
  state.tMallAuthStatus = data.status;
  state.tMallExpiredAt = data.expiredAt;
};
watchEffect(() => {
  state.visible && fetchData();
});
</script>

<style scoped lang="less">
:deep(.arco-table-th) {
  &:last-child {
    .arco-table-th-item-title {
      margin-left: 16px;
    }
  }
}

.action-icon {
  margin-left: 12px;
  cursor: pointer;
}

.active {
  color: #0960bd;
  background-color: #e3f4fc;
}

.setting {
  display: flex;
  align-items: center;
  width: 200px;

  .title {
    margin-left: 12px;
    cursor: pointer;
  }
}
</style>
