<template>
  <div>
    <n-card :bordered="false" class="proCard">
      <div class="n-layout-page-header">
        <n-card :bordered="false" title="余额平账" />
      </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"
        @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>
    </n-card>
  </div>
</template>
<script lang="ts">
  export default {
  name: 'recharge-ordersSettle',
  inheritAttrs: false,
}
</script>
<script lang="ts" setup>
  import { ref } from 'vue';
  import { BasicTable } from '@/components/Table';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { OrderSettleList, MsdBalance, MsdSettle } from '@/api/echarts/rechargeList';
  import { columns } from './columns';
  import { userInfoObj } from '@/views/account/accountList/userInfo';
  import { useMessage } 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 message = useMessage();
  const statusValue = ref('1');
  const schemas: FormSchema[] = [
    {
      field: 'user_id',
      component: 'NInputNumber',
      label: '玩家ID',
      componentProps: {
        placeholder: '请输入玩家ID',
        showButton: false,
        onUpdateValue: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'order_sn',
      component: 'NInput',
      label: '平账单号',
      componentProps: {
        placeholder: '请输入平账单号',
        showButton: false,
        onUpdateValue: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'status',
      component: 'NSelect',
      label: '平账状态',
      componentProps: {
        placeholder: '请选择',
        options: [
          {
            value: 1,
            label: '成功',
          },
          {
            value: 2,
            label: '失败',
          },
        ],
        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);
        },
      },
    },
  ];

  const actionRef = ref();

  const params = ref({
    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,
  });

  const formRef = ref({});

  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 OrderSettleList({
      ...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) {
    console.log(values);
    params.value = values;
    reloadTable();
  }

  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,
    };
    params.value.player_id = props.userId > 0 ? props.userId : null;
    console.log(values);
    reloadTable();
  }

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

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

  function msdSettle() {
    formParams.value.userId = null;
    formParams.value.openid = '';
    formParams.value.balance = 0;
    formParams.value.remark = '';
    showModal.value = true;
  }

  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;
        console.log('_res:' + JSON.stringify(res));
      })
      .catch((error) => {
        message.error(error.message);
      });
  }
</script>

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