<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="number" label="用户名">
              <a-input v-model="formModel.number" 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="addUserItem">
          <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-col>
  </a-row>
  <a-table
    :loading="loading"
    :pagination="pagination"
    :columns="columns"
    :data="renderData"
    :bordered="false"
    @page-change="onPageChange"
  >
    <template #userStatus="{ record }">
      <a-space size="small">
        <a-switch
          v-if="[1, 0].includes(record.userStatus)"
          v-model="record.userStatus"
          size="small"
          :checked-value="1"
          :unchecked-value="0"
          checked-text="正常"
          unchecked-text="停用"
          @change="
            async () => {
              await pauseOrRestartAccount({ id: record.id });
              search();
            }
          "
        />
        <a-tag v-if="record.payment?.balance <= 1000" size="small" color="red">
          余额不足
        </a-tag>
      </a-space>
    </template>
    <template #operation="{ record }">
      <a-space size="small">
        <a-button status="warning" size="mini" @click="modifyItem(record)">
          修改密码
        </a-button>
        <a-button
          status="warning"
          size="mini"
          @click="showRechargeToUser(record)"
        >
          调整余额
        </a-button>
        <a-tooltip content="详情">
          <a-button size="mini" @click="showPaymentDrawer(record)">
            <template #icon>
              <icon-list />
            </template>
          </a-button>
        </a-tooltip>
        <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>
  <add-update-modal
    v-model:visible="state.addModalVisible"
    :item="currentItem"
  />
  <payment-list-drawer
    v-model:visible="state.paymentDrawerVisible"
    :item="currentItem?.payment"
  />
  <recharge-modal
    v-model:visible="state.rechargeModalVisible"
    :userId="currentItem?.id"
  />
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, watchEffect } from 'vue';
import useLoading from '@/hooks/loading';
import {
  deleteUserItem,
  queryUserList,
  UserListParams,
  UserRecord
} from '@/api/list';
import { Pagination } from '@/types/global';
import AddUpdateModal from './components/add-update-modal.tsx';
import PaymentListDrawer from './components/payment-list-drawer.tsx';
import RechargeModal from './components/recharge-modal.tsx';
import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
import { pauseOrRestartAccount } from '@/api/user.ts';

const generateFormModel = () => {
  return {
    number: '',
    name: '',
    contentType: '',
    filterType: '',
    status: ''
  };
};
const { loading, setLoading } = useLoading(true);
const renderData = ref<UserRecord[]>([]);
const formModel = ref(generateFormModel());
const state = ref<{
  addModalVisible: boolean;
  rechargeModalVisible: boolean;
  paymentDrawerVisible: boolean;
}>({
  addModalVisible: false,
  rechargeModalVisible: false,
  paymentDrawerVisible: false
});
const currentItem = ref<UserRecord | null>(null);
const basePagination: Pagination = {
  current: 1,
  pageSize: 50
};
const pagination = reactive({
  ...basePagination
});
const columns: TableColumnData[] = [
  {
    title: '序号',
    render(data) {
      return data.rowIndex + 1;
    }
  },
  {
    title: '用户名',
    dataIndex: 'username'
  },
  {
    title: '余额',
    dataIndex: 'payment.balance'
  },
  {
    title: '总充值金额',
    dataIndex: 'payment.totalDeposits'
  },
  {
    title: '充值次数',
    dataIndex: 'payment.totalDepositCount'
  },
  {
    title: '充值时间',
    dataIndex: 'payment.lastDepositTime'
  },
  {
    title: '总消耗金额',
    dataIndex: 'payment.totalConsumption'
  },
  {
    title: '总消耗金额',
    dataIndex: 'payment.totalConsumptionCount'
  },
  {
    title: '消耗时间',
    dataIndex: 'payment.lastConsumptionTime'
  },
  {
    title: '状态',
    dataIndex: 'userStatus',
    slotName: 'userStatus'
  },
  {
    title: '操作',
    dataIndex: 'operation',
    slotName: 'operation'
  }
];
const fetchData = async (
  params: UserListParams = { current: 1, pageSize: 50 }
) => {
  setLoading(true);
  try {
    const { data } = await queryUserList(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();
});

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

const addUserItem = () => {
  state.value.addModalVisible = true;
  currentItem.value = null;
};
const modifyItem = (item: UserRecord) => {
  state.value.addModalVisible = true;
  currentItem.value = item;
};
const deleteItem = async (id: string) => {
  await deleteUserItem({ id });
  search();
};
const showPaymentDrawer = (item: UserRecord) => {
  state.value.paymentDrawerVisible = true;
  currentItem.value = item;
};
const showRechargeToUser = (item: UserRecord) => {
  state.value.rechargeModalVisible = true;
  currentItem.value = item;
};
watchEffect(() => {
  if (
    !state.value.addModalVisible &&
    !state.value.rechargeModalVisible &&
    !state.value.paymentDrawerVisible
  ) {
    currentItem.value = null;
    search();
  }
});
</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>
