<script setup lang="tsx">
import { computed, onMounted, ref } from 'vue';
import { useRoute } from 'vue-router';
import { NButton } from 'naive-ui';
// import dayjs from 'dayjs';
// import { fetchGetStoreList } from '@/service/api/xsb-manage/store-info';
import {
  fetchDetail,
  fetchGetChannelList,
  fetchList,
  fetchReversal
} from '@/service/api/reconciliation-center/points-details';
import { useAuth } from '@/hooks/business/auth';
import { commonExport } from '@/utils/common';
import { useTable } from '@/components/zt/Table/hooks/useTable';
import { useModalFrom } from '@/components/zt/ModalForm/hooks/useModalForm';
import { useModal } from '@/components/zt/Modal/hooks/useModal';
const route = useRoute();
const detailData = ref<any>(null);
const columns: NaiveUI.TableColumn<Api.goods.ShopSku>[] = [
  {
    key: 'updateTime',
    title: '更新时间',
    align: 'center',
    width: 200
  },
  {
    key: 'realName',
    title: '姓名',
    align: 'center'
  },
  {
    key: 'mobile',
    title: '用户手机号',
    align: 'center'
  },
  {
    key: 'channelName',
    title: '企业',
    align: 'center'
  },
  {
    key: 'businessScene',
    title: '业务场景',
    align: 'center'
  },
  {
    key: 'pointsActionType',
    title: '类型',
    align: 'center'
  },
  {
    key: 'variablePoints',
    title: '变动积分',
    align: 'center'
  },
  {
    key: 'currentlyAvailablePoints',
    title: '变动后积分',
    align: 'center'
  },
  {
    key: 'orderNumber',
    title: '关联订单',
    align: 'center'
  }
];

const [registerTable, { refresh, getTableData, setFieldsValue, getSeachForm, setTableLoading }] = useTable({
  searchFormConfig: {
    schemas: [
      {
        label: '手机号',
        component: 'NInput',
        field: 'mobile'
      },

      {
        field: 'businessScene',
        label: '业务场景',
        component: 'dictSelect',
        componentProps: {
          dictCode: 'sys_business_type',
          immediate: true,
          extraOptions: [
            {
              label: '充值',
              value: 'CZ'
            },
            {
              label: '过期',
              value: 'GQ'
            }
          ]
        }
      },

      {
        label: '更新时间',
        component: 'NDatePicker',
        field: 'createTime',
        componentProps: {
          type: 'datetimerange',
          defaultTime: ['00:00:00', '23:59:59']
        }
      },
      {
        label: '企业',
        component: 'ApiSelect',
        field: 'channelId',
        componentProps: {
          api: fetchGetChannelList,
          resultFeild: 'data',
          labelFeild: 'channelName',
          valueFeild: 'channelId'
        }
      }
    ],
    inline: false,
    size: 'small',
    labelPlacement: 'left',
    isFull: false
  },
  tableConfig: {
    keyField: 'skuId',
    title: '积分明细',
    showAddButton: false,
    scrollX: 1800,
    fieldMapToTime: [['createTime', ['startTime', 'endTime']]]
  }
});

const [registerModal, { openModal, setModalLoading }] = useModal({
  title: '查看',
  width: 500,
  height: 400,
  isShowHeaderText: false
});

const [
  registerModalForm,
  {
    openModal: openModalForm,
    setFieldsValue: setModalFormValue,
    getFieldsValue: getModalFormValue,
    closeModal: closeModalForm,
    setSubLoading
  }
] = useModalFrom({
  modalConfig: {
    title: '优惠券',
    isShowHeaderText: true
  },
  formConfig: {
    schemas: [
      {
        field: 'id',
        label: 'ID',
        show: false,
        component: 'NInput'
      },
      {
        field: 'type',
        label: '差额冲正',
        component: 'NRadioGroup',
        required: true,
        componentProps: {
          options: [
            {
              label: '增加',
              value: 0
            },
            {
              label: '扣除',
              value: 1
            }
          ]
        },
        defaultValue: 0
      },
      {
        field: 'variablePoints',
        component: 'NInput',
        label: '积分数量',
        required: true,
        componentProps: {
          placeholder: '请输入积分数量'
        }
      },
      {
        field: 'remark',
        component: 'NInput',
        label: '备注',
        required: true,
        componentProps: {
          type: 'textarea',
          rows: 3
        }
      }
    ],
    labelWidth: 120,
    layout: 'horizontal',
    gridProps: {
      cols: '1',
      itemResponsive: true
    }
  }
});

const tableData = computed(() => {
  return getTableData();
});

function handle(row: any) {
  console.log(row);
  openModalForm();
  setModalFormValue({
    id: row.id
  });
}

async function handleDetail(row: any) {
  openModal();
  setModalLoading(true);
  const { data, error } = await fetchDetail(row.id);
  if (!error) {
    setModalLoading(false);
    detailData.value = data;
  }
}
async function handleExport() {
  setTableLoading(true);
  try {
    await commonExport('/smqjh-system/app-api/v1/claim/export', getSeachForm(), '积分明细列表.xlsx');
  } finally {
    setTableLoading(false);
  }
}

async function handleSubmit() {
  const form = await getModalFormValue();
  setSubLoading(false);
  const { error } = await fetchReversal(form);
  if (error) {
    return;
  }
  closeModalForm();
  refresh();
}

onMounted(async () => {
  if (route.query.transactionDate) {
    await setFieldsValue({
      channelId: Number(route.query.channelId),
      createTime: [`${route.query.transactionDate} 00:00:00`, `${route.query.transactionDate} 23:59:59`]
    });
  }
  refresh();
});
</script>

<template>
  <LayoutTable>
    <ZTable :columns="columns" :api="fetchList" :immediate="false" @register="registerTable">
      <template #prefix="{ loading }">
        <NSpace>
          <NButton v-if="false" size="small" :disabled="tableData.length == 0" :loading="loading" @click="handleExport">
            导出全部
          </NButton>
        </NSpace>
      </template>
      <template v-if="useAuth().hasAuth('points-details:reversal') && route.query.mode == 'reversal'" #op="{ row }">
        <NButton v-if="row.isAdjust" size="small" ghost type="primary" @click="handleDetail(row)">查看</NButton>
        <NButton v-else size="small" ghost type="primary" @click="handle(row)">冲正</NButton>
      </template>
    </ZTable>
    <BasicModal @register="registerModal">
      <div class="text-14px font-600">处理结果</div>
      <div>处理方式：{{ detailData?.type === 0 ? '增加' : '扣除' }}{{ detailData?.variablePoints || 0 }}</div>
      <div>备注：{{ detailData?.remark }}</div>

      <div>处理人：{{ detailData?.username }}</div>
      <div>处理时间：{{ detailData?.updateTime }}</div>
    </BasicModal>
    <BasicModelForm @register-modal-form="registerModalForm" @submit-form="handleSubmit"></BasicModelForm>
  </LayoutTable>
</template>

<style scoped></style>
