<template>
  <div>
    <n-card :bordered="false" class="proCard">
      <div class="n-layout-page-header">
        <n-card :bordered="false" title="异常订单记录"></n-card>
      </div>
      <BasicForm
        @register="register"
        @submit="handleSubmit"
        @reset="handleReset"
        @keyup.enter="handleSubmit"
        ref="formRef"
      >
        <template #statusSlot="{ model, field }">
          <n-input v-model:value="model[field]" />
        </template>
      </BasicForm>
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="actionRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
        :scroll-x="1090"
        :flex-height="false"
        :pagination="{ pageSize: Number(userId) > 0 ? 10 : 15 }"
        :resizeHeightOffset="-500"
      >
        <template #tableTitle>
          <n-button type="primary" @click="exportOrders" :loading="loadingRef" class="mx-1">
            导出数据
          </n-button>
          <n-button type="primary" ghost @click="getBalance">查询余额</n-button>
          <n-space :style="{'margin-left':'10px'}" v-model:value="balance" :disabled="balance <= 0"> {{ balance/useUserStore.config.amount_multiple }} 元</n-space>
        </template>
      </BasicTable>
    </n-card>
  </div>
</template>
<script lang="ts">
  export default {
  name: 'recharge-abnormalOrder',
  inheritAttrs: false,
}
</script>
<script lang="ts" setup>
  import { h, reactive, ref } from 'vue';
  import { BasicTable, TableAction } from '@/components/Table';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { getAbnormalOrderList,reissueOrder,GetBalance} from '@/api/echarts/rechargeList';
  import { columns} from './columns';
  import { delNullProperty, encodeParams } from '@/utils/array';
  import { userInfoObj } from '@/views/account/accountList/userInfo';
  import { useUserStoreWidthOut } from '@/store/modules/user';
  import { useMessage, useDialog } from 'naive-ui';
  import { defRangeShortcuts } from '@/utils/dateUtil';

  interface Props {
    userId?: number | string;
    userInfo?: any;
  }

  const props = withDefaults(defineProps<Props>(), { userId: 0, userInfo: userInfoObj });
  const useUserStore = useUserStoreWidthOut();
  const message = useMessage();
  const dialog = useDialog();
  //const statusValue = ref('1');
  const params = ref<any>({
    goods_id: 0,
    player_id: Number(props.userId) > 0 ? props.userId : null,
    created_at: null,
    order_id: null,
    server_id: 1,
  });

  const schemas: FormSchema[] = [
    {
      field: 'server_id',
      component: 'NSelect',
      label: '服务器',
      componentProps: {
        placeholder: '请选择服务器',
        defaultValue: params.value.server_id,
        options: useUserStore.config.server_simple_option,
        onUpdateValue: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'player_id',
      component: 'NInputNumber',
      label: '玩家ID',
      defaultValue: Number(props.userId) > 0 ? props.userId : null,
      componentProps: {
        disabled: Number(props.userId) > 0,
        placeholder: '请输入玩家ID',
        showButton: false,
        onUpdateValue: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'created_at',
      component: 'NDatePicker',
      label: '创建时间',
      componentProps: {
        type: 'datetimerange',
        clearable: true,
        shortcuts: defRangeShortcuts(),
        onUpdateValue: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'order_id',
      component: 'NInputNumber',
      label: '订单ID',
      componentProps: {
        placeholder: '请输入订单ID',
        showButton: false,
        onUpdateValue: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'goods_id',
      component: 'NInputNumber',
      label: '商品ID',
      componentProps: {
        placeholder: '请输入商品ID',
        showButton: false,
        onUpdateValue: (e: any) => {
          console.log(e);
        },
      },
    },
  ];

  const actionRef = ref();
  const formRef = ref<any>({});
  const dataSource = ref();

  const [register, {}] = useForm({
    gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
    labelWidth: 80,
    schemas,
  });

  const loadDataTable = async (res) => {
    dataSource.value = await getAbnormalOrderList({
      ...params.value,
      ...res,
      ...formRef.value.formModel,
      is_export: 0,
    });
    return dataSource.value;
  };

  const balance = ref(0);

  function getBalance() {
    console.log(formRef.value.formModel);
    if (formRef.value.formModel.player_id == null) {
      message.error('请输入玩家ID');
      return;
    }
    GetBalance(formRef.value.formModel)
      .then((res) => {
        balance.value = res.balance;
    }).catch((error) => {
        message.error(error.message);
      });
  }

  function onCheckedRow(rowKeys) {
    console.log(rowKeys);
  }

  function reloadTable() {
    actionRef.value.reload();
  }

  function handleSubmit(_values: Recordable) {
    reloadTable();
  }

  const loadingRef = ref(false);
  function exportOrders() {
    console.log(formRef.value.formModel);
    loadingRef.value = true;
    window.location.href =
      '/api/gm/abnormalOrderList?' +
      encodeParams(
        delNullProperty({ ...formRef.value.formModel, is_export: 1, ...{ authorization: useUserStore.token } })
      );
    setTimeout(() => {
      loadingRef.value = false;
    }, 2000);
  }

  function handleReset(values: Recordable) {
    params.value = {
      goods_id: 0,
      player_id: null,
      created_at: null,
      order_id: null,
      server_id: null,
    };
    params.value.player_id = Number(props.userId) > 0 ? props.userId : null;
    console.log(values);
    reloadTable();
  }

  const actionColumn = reactive({
    width: 120,
    title: '操作',
    key: 'action',
    // fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            type: 'default',
            label: '一键补发',
            onClick: handleEdit.bind(null, record),
            ifShow: () => {
              return (record.state == 0 || record.state == 2 || record.state == 8);
            },
          },
        ],
        select: (key) => {
          message.info(`您点击了，${key} 按钮`);
        },
      });
    },
  });

function handleEdit(record: Recordable) {
  dialog.warning({
        title: '警告',
        content: '你确定要一件补发吗？补发后会在下次上线后邮件发放给玩家，是否确定',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: () => {
          reissueOrder(record).then((_res) => {
            message.success('操作成功');
            reloadTable();
          });
        },
        onNegativeClick: () => {
          //message.error('取消')
        }
      })
}
</script>

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