import { ref, h } from "vue";
import editForm from "./form.vue";
import { utils, writeFile } from "xlsx";
import { message } from "@/utils/message";
import {
  querySubsidyList,
  grantSubsidyData,
  grantSubsidyBybatch
} from "@/api/modules/union";
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({
    search_user_id: "",
    search_guild_id: "",
    search_status_time: "",
    search_end_time: ""
  });
  const multipleSelection = ref([])
  const searchLabel = ref([
    { label: "用户ID", prop: "search_user_id", type: "input" },
    { label: "公会号", prop: "search_guild_id", type: "input" },
    { label: "开始时间", prop: "search_status_time", type: "date" },
    { label: "结束时间", prop: "search_end_time", type: "date" }
  ]);
  const pagination = ref({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const tableLabel = ref([
    {
      type: "selection",
      align: "left"
    },
    {
      label: "补贴ID",
      prop: "id"
    },
    {
      label: "公会长昵称",
      prop: "user_name"
    },
    {
      label: "公会ID",
      prop: "guild_id"
    },
    {
      label: "公会昵称",
      prop: "guild_name"
    },
    {
      label: "公会周流水（金币）",
      prop: "total_transaction"
    },
    {
      label: "公会周补贴（钻石）",
      prop: "subsidy_amount"
    },
    {
      label: "是否发放",
      prop: "status_str",
      cellRenderer: ({ row }) => (
        <el-tag type={row.status === 1 ? 'success' : row.status === 2 ? 'error' : 'info'}>{row.status === 1 ? '已发放' : row.status === 2 ? '已拒绝' : '未发放'}</el-tag>
      ),
    },
    {
      label: "时间",
      prop: "time"
    },
    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation"
    }
  ]);
  const onSearch = async (formData) => {
    loading.value = true;
    searchForm.value = { ...formData }
    const { data, code } = await querySubsidyList({
      ...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 = (title = "审核", rowData: any) => {
    addDialog({
      title: `${title}`,
      props: {
        formInline: {
          id: rowData?.id ?? "",
          status: "",
          remark: rowData?.remark ?? ""
        }
      },
      width: "40%",
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline;
        const examineData = async form => {
          const { code } = await grantSubsidyData({
            ...form,
            id: rowData.id
          });
          if (code) {
            message("审核成功", { type: "success" });
            onSearch(searchForm.value);
            done();
          } else {
            message("审核失败", { type: "error" });
          }
        };
        FormRef.validate(valid => {
          if (valid) {
            // 表单规则校验通过
            if (title === "审核") {
              examineData(curData);
            }
          }
        });
      }
    });
  };
  const handleSelectionChange = val => {
    multipleSelection.value = val;
  };
  // 批量发放
  const batchDistribution = async () => {
    const ids = multipleSelection.value.map(ele => { return ele.id })
    const statusList = multipleSelection.value.map(ele => { return ele.status })
    if (statusList.length && statusList.includes(1)) {
      message("内含已发放状态的数据，请重新勾选！", { type: "error" });
    } else {
      if (ids.length) {
        const form = {
          ids: ids.join(','),
          status: 1,
          remark: ""
        }
        const { data, code, msg } = await grantSubsidyBybatch(form)
        if (code) {
          message("批量发放成功", { type: "success" });
          onSearch(searchForm.value);
        } else {
          message(msg, { type: "error" });
        }
      }
    }
  }
  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 querySubsidyList({
            ...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.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,
    handleSelectionChange,
    multipleSelection,
    batchDistribution
  };
}
