<template>
  <div>
    <n-card :bordered="false" class="proCard">
      <div class="n-layout-page-header">
        <n-card :bordered="false" title="订单记录">
          每30秒同步一次游戏服务器充值订单，截止目前共查询到
          {{ dataSource.successful_order }} 个已支付订单，累计交易金额
          {{ dataSource.transaction_money }} 元。
        </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: userId > 0 ? 10 : 15 }"
        :resizeHeightOffset="-500"
      >
        <template #tableTitle>
          <n-button type="primary" @click="exportOrders" :loading="loadingRef" class="mx-1">
            导出数据
          </n-button>
          <!--          <n-button type="success" @click="msdSettle" class="mx-1"> 米大师平账 </n-button>-->
        </template>
      </BasicTable>

      <n-modal
        v-model:show="showModal"
        :show-icon="false"
        preset="dialog"
        title="米大师平账"
        :style="{
          width: '720px',
        }"
      >
        <n-form
          :rules="rules"
          :model="formParams"
          ref="formRef2"
          label-placement="left"
          :label-width="80"
          class="py-4"
        >
          <n-form-item label="玩家ID" path="userId">
            <n-input-group>
              <n-input placeholder="请输入玩家ID" v-model:value="formParams.userId" />
              <n-button type="primary" @click="getMsdBalance" :disabled="formParams.userId <= 0">
                查余额
              </n-button>
            </n-input-group>
          </n-form-item>
          <n-form-item label="微信openid" path="openid">
            <n-input placeholder=" " v-model:value="formParams.openid" disabled />
          </n-form-item>
          <n-form-item label="平账金额" path="balance">
            <n-input-number
              :required="true"
              :max="maxBalance"
              v-model:value="formParams.balance"
              :disabled="formParams.balance <= 0"
              :button-placement="undefined"
            >
              <template #suffix> 单位：分 </template>
            </n-input-number>
          </n-form-item>
          <n-form-item label="平账理由" path="remark">
            <n-input
              :required="true"
              type="textarea"
              rows="5"
              placeholder="请输入平账理由"
              v-model:value="formParams.remark"
            />
          </n-form-item>
        </n-form>

        <template #action>
          <n-space>
            <n-button @click="() => (showModal = false)">取消</n-button>
            <n-button
              type="info"
              :loading="formBtnLoading"
              @click="confirmForm"
              :disabled="formParams.balance <= 0"
              >平账</n-button
            >
          </n-space>
        </template>
      </n-modal>

      <UserModal ref="userModalRef" :userId="userId" />
    </n-card>
  </div>
</template>

<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 { getOrderList, MsdBalance, MsdSettle } from '@/api/echarts/rechargeList';
  import { columns, payStatusMap } from './columns';
  import { delNullProperty, encodeParams } from '@/utils/array';
  import { userInfoObj } from '@/views/account/accountList/userInfo';
  import { useUserStoreWidthOut } from '@/store/modules/user';
  import { useMessage } from 'naive-ui';
  import UserModal from '@/views/account/accountList/modal.vue';
  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 statusValue = ref('1');
  const params = ref<any>({
    platform: 0,
    goods_id: 0,
    status: statusValue.value,
    player_id: props.userId > 0 ? props.userId : null,
    created_at: null,
    order_sn: null,
    out_trade_no: null,
    server_id: null,
    channel_id: '',
    flag: -1,
  });

  const schemas: FormSchema[] = [
    {
      field: 'server_id',
      component: 'NSelect',
      label: '服务器',
      componentProps: {
        placeholder: '请选择服务器',
        defaultValue: params.value.server_id,
        options: useUserStore.config.server_option,
        onUpdateValue: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'channel_id',
      component: 'NTreeSelect',
      label: '推广渠道',
      componentProps: {
        placeholder: '请选择推广渠道',
        clearFilterAfterSelect: true,
        clearable: true,
        filterable: true,
        defaultExpandAll: true,
        options: useUserStore.config.channel_tree_option,
        onUpdateValue: (e: any) => {
          console.log(e);
          params.value.channel_id = e;
        },
      },
    },
    {
      field: 'flag',
      component: 'NSelect',
      label: '玩家分类',
      componentProps: {
        placeholder: '请选择玩家分类',
        options: useUserStore.config.flag_option,
        onUpdateValue: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'platform',
      component: 'NSelect',
      label: '下单渠道',
      componentProps: {
        placeholder: '请选择下单渠道',
        options: [
          {
            label: '全部',
            value: 0,
          },
          {
            label: '安卓平台',
            value: 1,
          },
          {
            label: '苹果平台',
            value: 2,
          },
        ],
        onUpdateValue: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'player_id',
      component: 'NInputNumber',
      label: '玩家ID',
      defaultValue: props.userId > 0 ? props.userId : null,
      componentProps: {
        disabled: props.userId > 0,
        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);
        },
      },
    },
    {
      field: 'status',
      component: 'NSelect',
      label: '订单状态',
      componentProps: {
        defaultValue: statusValue,
        placeholder: '请选择',
        options: payStatusMap(),
        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: 'out_trade_no',
      component: 'NInput',
      label: '外部单号',
      componentProps: {
        placeholder: '请输入外部订单号',
        showButton: false,
        onUpdateValue: (e: any) => {
          console.log(e);
        },
      },
    },
  ];

  const actionRef = ref();
  const formRef = ref<any>({});
  const dataSource = ref({
    successful_order: 0,
    transaction_money: 0,
  });

  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 getOrderList({
      ...params.value,
      ...res,
      ...formRef.value.formModel,
      is_export: 0,
    });
    return dataSource.value;
  };

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

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

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

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

  function handleReset(values: Recordable) {
    params.value = {
      platform: 0,
      goods_id: 0,
      status: statusValue.value,
      player_id: null,
      created_at: null,
      order_sn: null,
      out_trade_no: null,
      server_id: null,
      channel_id: '',
      flag: -1,
    };
    params.value.player_id = props.userId > 0 ? props.userId : null;
    console.log(values);
    reloadTable();
  }

  const rules = {
    userId: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入玩家ID',
    },
    remark: {
      required: true,
      trigger: ['blur', 'change'],
      message: '请输入平账理由',
    },
  };

  const formRef2 = ref<any>();
  const showModal = ref(false);
  const formBtnLoading = ref(false);
  const formParams = ref<any>({
    userId: null,
    openid: '',
    balance: 0,
    remark: '',
  });

  function confirmForm(e) {
    e.preventDefault();
    formRef2.value.validate((errors) => {
      if (!errors) {
        console.log('confirmForm formParams:' + JSON.stringify(formParams.value));
        formBtnLoading.value = true;
        formParams.value.userId = Number(formParams.value.userId);
        MsdSettle(formParams.value).then((_res) => {
          message.success('操作成功');
          setTimeout(() => {
            showModal.value = false;
            reloadTable();
          });
        });
      } else {
        message.error('请填写完整信息');
      }
      formBtnLoading.value = false;
    });
  }

  const maxBalance = ref(0);
  function getMsdBalance() {
    MsdBalance(formParams.value)
      .then((res) => {
        formParams.value.openid = res.openid;
        formParams.value.balance = res.balance;
        maxBalance.value = res.balance;
      })
      .catch((error) => {
        message.error(error.message);
      });
  }

  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 true;
            },
          },
        ],
        select: (key) => {
          message.info(`您点击了，${key} 按钮`);
        },
      });
    },
  });

  function handleEdit(record: Recordable) {
    openUserModal(record.player_id);
  }

  const userModalRef = ref();
  const userId = ref(0);
  function openUserModal(id) {
    userId.value = id;
    const { openDrawer } = userModalRef.value;
    openDrawer();
  }
</script>

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