import { ref, h } from "vue";
import {
  queryGiftRankList
} from "@/api/modules/statistics";
import { utils, writeFile } from "xlsx";
import ExportForm from '@/components/exportDialog/index.vue';
import { addDialog } from "@/components/ReDialog";
import { message } from "@/utils/message";
export function useData() {
  const loading = ref(true);
  const tableList = ref([]);
  const isShow = ref(false);
  const pagination = ref({
    total: 0,
    pageSize: 10,
    pageSizes: [10, 20, 50, 100, 500, 1000, 2000],
    currentPage: 1,
    background: true
  });
  const searchForm = ref({
    search_uid: "",
    begin_time: "",
    end_time: "",
    username: "",
    type: 1
  });
  const total_price = ref(0)
  const searchLabel = ref([
    { label: "用户ID", prop: "search_uid", type: "input" },
    { label: "用户昵称", prop: "username", type: "input" },
    { label: "开始时间", prop: "begin_time", type: "date" },
    { label: "结束时间", prop: "end_time", type: "date" },
  ]);
  const tableLabel = ref([
    // {
    //   label: "用户ID",
    //   prop: "user_id"
    // },
    {
      label: "用户名称",
      prop: "user_name"
    },
    {
      label: "头像",
      prop: "avatar",
      cellRenderer: ({ row }) => (
        <el-image
          fit="cover"
          preview-teleported={true}
          src={row.avatar}
          preview-src-list={Array.of(row.avatar)}
          class="w-[30px] h-[30px]  align-middle"
        />
      )
    },
    {
      label: "礼物总充值",
      prop: "total_price"
    },
    {
      label: "礼物总量",
      prop: "number"
    },
    // {
    //   label: "生成时间",
    //   prop: "createtime"
    // }
  ]);
  const onSearch = async (formData) => {
    loading.value = true;
    searchForm.value = { ...formData }
    const { data, code } = await queryGiftRankList({
      ...formData,
      page: pagination.value.currentPage,
      page_limit: pagination.value.pageSize,

    });
    if (code) {
      total_price.value = data.total.total_price || 0;
      tableList.value = data.lists
      pagination.value.total = data.count;
      pagination.value.currentPage = data.page;
    }
    loading.value = false;
  };
  const handleSizeChange = (val: number) => {
    pagination.value.pageSize = val;
    onSearch(searchForm.value);
  };
  const handleCurrentChange = (val: number) => {
    pagination.value.currentPage = val;
    onSearch(searchForm.value);
  };
  const exportFormRef = ref(null)
  const exportExcel = () => {
    let exportTableList = []
    addDialog({
      title: `导出数据`,
      props: {
        formInline: {
          time: ''
        }
      },
      width: "40%",
      closeOnClickModal: false,
      contentRenderer: () => h(ExportForm, { ref: exportFormRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = exportFormRef.value.getRef();
        const curData = options.props.formInline;
        const exportData = async (formData) => {
          const { data, code } = await queryGiftRankList({
            ...formData,
            page: 1,
            page_limit: 20000
          });
          if (code) {
            exportTableList = data.lists;
            const res = exportTableList.map(item => {
              const arr = [];
              tableLabel.value.forEach(column => {
                arr.push(item[column.prop as string]);
              });
              return arr;
            });
            const titleList = [];
            tableLabel.value.forEach(column => {
              titleList.push(column.label);
            });
            res.unshift(titleList);
            const workSheet = utils.aoa_to_sheet(res);
            const workBook = utils.book_new();
            utils.book_append_sheet(workBook, workSheet, "数据报表");
            writeFile(workBook, `送礼排行统计${formData.begin_time} - ${formData.end_time}.xlsx`);
            message("导出成功", {
              type: "success"
            });
            done()
          } else {
            message("获取数据失败，请重试！", {
              type: "error"
            });
          }
        }
        FormRef.validate(valid => {
          if (valid) {
            if (curData.time && curData.time.length) {
              exportData({ begin_time: curData.time[0] || '', end_time: curData.time[1] || '' })
            }
          }
        });
      }
    });

  }

  return {
    searchForm,
    searchLabel,
    onSearch,
    isShow,
    tableList,
    tableLabel,
    total_price,
    pagination,
    exportExcel,
    handleSizeChange,
    handleCurrentChange,
    loading
  };
}
