<template>
  <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="true"
        :unchecked-value="false"
        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 #enable="{ record }">
        <a-switch
          v-model="record.enable"
          size="small"
          :checked-value="1"
          :unchecked-value="0"
          :beforeChange="
            newValue => setAppleCardStealRuleEnable(record, 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>
  <div>
    <AddModal
      v-model:visible="state.addModalVisible"
      :rule="state.targetRule"
    />
  </div>
</template>

<script lang="ts" setup>
import AddModal from './components/add-modal.vue';

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 { AppleCardStealListParams } from '@/api/apple-card-steal-settings';
import { apiClient } from '@/api';
import {
  ApiMerchantConfigStealRuleListGetPageSizeEnum,
  KamiApiRoadV1RoadSimpleInfo,
  KamiApiMerchantV1MerchantHiddenConfigEntity,
  KamiInternalModelEntityV1MerchantInfo
} from '@/api/generated';

const basePagination: Pagination = {
  current: 1,
  pageSize: 50
};
const pagination = reactive({
  ...basePagination
});
const columns: TableColumnData[] = [
  {
    title: '序号',
    dataIndex: 'index',
    render: (data: { rowIndex: number }) => {
      return data.rowIndex + 1;
    }
  },
  {
    title: '名称',
    dataIndex: 'name'
  },
  {
    title: '商户',
    dataIndex: 'merchantUid',
    render: ({ record }) => {
      const merchantInfo = state.merchantInfos.find(
        item => item.merchantUid === record.merchantUid
      );
      return merchantInfo?.merchantName || '未知';
    }
  },
  {
    title: '通道',
    dataIndex: 'roadUid',
    render: ({ record }) => {
      const roadInfo = state.roadInfos.find(
        item => item.roadUid === record.roadUid
      );
      return roadInfo?.roadName || '未知';
    }
  },
  {
    title: '间隔金额',
    dataIndex: 'amount'
  },
  {
    title: '面额',
    dataIndex: 'faceAmount'
  },
  {
    title: '延迟时间',
    render: ({ record }) => {
      return `${record.delayDurationMin}秒-${record.delayDurationMax}秒`;
    }
  },
  {
    title: '是否启用',
    dataIndex: 'enable',
    slotName: 'enable'
  },
  {
    title: '策略',
    dataIndex: 'strategy',
    render: ({ record }) => {
      switch (record.strategy) {
        case 1:
          return '策略1：创建空白订单';
        case 2:
          return '策略2：创建延迟订单';
        case 3:
          return '策略3：随机';
        default:
          return '未知';
      }
    }
  },
  {
    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<KamiApiMerchantV1MerchantHiddenConfigEntity[]>([]);
const formModel = ref(generateFormModel());
const state = reactive<{
  addModalVisible: boolean;
  deployModalVisible: boolean;
  accountDetailVisible: boolean;
  targetRule: Required<KamiApiMerchantV1MerchantHiddenConfigEntity> | null;
  switchValue: boolean;
  roadInfos: KamiApiRoadV1RoadSimpleInfo[];
  merchantInfos: KamiInternalModelEntityV1MerchantInfo[];
}>({
  addModalVisible: false,
  deployModalVisible: false,
  accountDetailVisible: false,
  targetRule: null,
  switchValue: false,
  roadInfos: [],
  merchantInfos: []
});

const fetchData = async (
  params: AppleCardStealListParams = { current: 1, pageSize: 50 }
) => {
  setLoading(true);
  try {
    const {
      data: { list, total }
    } = await apiClient.apiMerchantConfigStealRuleListGet({
      current: params.current,
      pageSize: params.pageSize as ApiMerchantConfigStealRuleListGetPageSizeEnum
    });
    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: KamiApiMerchantV1MerchantHiddenConfigEntity
) => {
  try {
    await apiClient.apiMerchantConfigStealRuleUpdateDelete({
      id: record.id
    });
  } catch {
    Notification.error({
      id: 'stealRuleNotice',
      content: '删除失败',
      closable: true
    });
  } finally {
    fetchData({ ...pagination });
  }
};

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

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

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

// 设置是否开启偷卡
const setAppleCardStealSetting = async (value: boolean) => {
  state.switchValue = value;
  await apiClient.apiMerchantConfigStealRuleStatusPost({
    kamiApiMerchantV1StealStatusSetReq: {
      status: value
    }
  });
  return true;
};

onMounted(() => {
  fetchData();
  getAppleCardStealSetting();
  apiClient.apiRoadSimpleGetAllGet().then(res => {
    state.roadInfos = res.data.list;
  });
  apiClient
    .apiMerchantListAllGet()
    .then(res => (state.merchantInfos = res.data.list));
});
watch(
  () => state.addModalVisible,
  () => {
    if (!state.addModalVisible) {
      search();
    }
  }
);

const setAppleCardStealRuleEnable = async (
  record: KamiApiMerchantV1MerchantHiddenConfigEntity,
  enable: string | number | boolean
) => {
  try {
    await apiClient.apiMerchantConfigStealRuleUpdateStatusPost({
      kamiApiMerchantV1StealUpdateStatusReq: {
        id: record.id,
        enable: enable as number
      }
    });
    search();
  } catch {
    Notification.error({
      id: 'stealRuleNotice',
      content: '操作失败',
      closable: true
    });
  }
};
</script>

<style lang="less" scoped></style>
