import { ref, h, nextTick } from "vue";
import editForm from "./form.vue";
import { message } from "@/utils/message";
import { utils, writeFile } from "xlsx";
import {
  queryRedEnvelopeList,
  getRedEnvelopeDetail
} from "@/api/modules/room";
import ExportForm from '@/components/exportDialog/index.vue';
import { addDialog } from "@/components/ReDialog";
export function useData() {
  const formRef = ref();
  const loading = ref(true);
  const tableList = ref([]);
  const isShow = ref(false);
  const searchForm = ref({
    room_id: "",
    status: "",
    stime: "",
    etime: ""
  });
  // //状态:0=未开始,1=进行中,2=已结束,3=已退回',
  const searchLabel = ref([
    { label: "房间ID", prop: "room_id", type: "input" },
    {
      label: "红包状态", prop: "status", type: "select",
      optionList: [
        { label: "未开始", value: 0 },
        { label: "进行中", value: 1 },
        { label: "已结束", value: 2 },
        { label: "已退回", value: 3 }
      ]
    },
    { label: "开始时间", prop: "stime", type: "date" },
    { label: "结束时间", prop: "etime", type: "date" }
  ]);
  const pagination = ref({
    total: 0,
    pageSize: 10,
    pageSizes: [10, 20, 50, 100, 500, 1000, 2000],
    currentPage: 1,
    background: true
  });
  const tableLabel = ref([
    {
      label: "房间ID",
      prop: "room_id"
    },
    {
      label: "房间名字",
      prop: "room_name"
    },
    {
      label: "发放人ID",
      prop: "user_code"
    },
    {
      label: "发放人昵称",
      prop: "nickname"
    },
    {
      label: "红包类型",
      prop: "type_text"
    },
    {
      label: "口令",
      prop: "password"
    },
    {
      label: "多少秒后开抢",
      prop: "countdown"
    },
    {
      label: "币种",
      prop: "coin_type_text"
    },
    {
      label: "总金额",
      prop: "total_amount"
    },
    {
      label: "总数量",
      prop: "total_count"
    },
    {
      label: "剩余金额",
      prop: "left_amount"
    },
    {
      label: "剩余数量",
      prop: "left_count"
    },
    {
      label: "状态",
      prop: "status_text"
    },
    {
      label: "红包备注",
      prop: "remark"
    },
    {
      label: "创建时间",
      prop: "createtime"
    },
    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation"
    }
  ]);
  const onSearch = async (formData) => {
    loading.value = true;
    searchForm.value = { ...formData }
    const { data, code } = await queryRedEnvelopeList({
      ...formData,
      page: pagination.value.currentPage,
      page_limit: pagination.value.pageSize
    });
    if (code) {
      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 openDialog = async (title = "审核", rowData: any) => {
    const { code, data } = await getRedEnvelopeDetail({ redpacket_id: rowData.id })
    if (!code) return
    nextTick(() => {
      addDialog({
        title: `${title}`,
        props: {
          rowData: data
        },
        width: "40%",
        hideFooter: true,
        closeOnClickModal: false,
        contentRenderer: () => h(editForm, { ref: formRef, formInline: null })
      });
    })

  };
  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 queryRedEnvelopeList({
            stime: formData.search_status_time,
            etime: formData.search_end_time,
            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.search_status_time} - ${formData.search_end_time}.xlsx`);
            message("导出成功", {
              type: "success"
            });
            done()
          } else {
            message("获取数据失败，请重试！", {
              type: "error"
            });
          }
        }
        FormRef.validate(valid => {
          if (valid) {
            if (curData.time && curData.time.length) {
              exportData({ search_status_time: curData.time[0] || '', search_end_time: curData.time[1] || '' })
            }
          }
        });
      }
    });

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