import { ref, h } from "vue";
import {
  queryBoxTypeList,
  queryBlindBoxList,
  resetBlindBoxRule,
  removeBlindBoxData,
  addBlindBoxData,
  editBlindBoxData,
  getBlindBoxRule,
  settingBlindBoxRule
} from "@/api/modules/blindBox";
import TurntableView from './Turntable.vue';
import editForm from "./form.vue";
import settingRuleView from './settingRule.vue'
import { addDialog } from "@/components/ReDialog";
import { message } from "@/utils/message";
export function useData() {
  const formRef = ref();
  const loading = ref(true);
  const tableList = ref([]);
  const isShow = ref(false);
  const pagination = ref({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    pageSizes: [10, 20, 50, 100],
    background: true
  });
  const searchForm = ref({
    gift_id: "",
    gift_name: "",
  });
  const activeName = ref(0)
  const typeList = ref([])
  const statisticsList = ref([
    { label: "每期总次数", prop: "total_count" },
    { label: "每期总礼物价值(收入)", prop: "total_price" },
    {
      label: "每期总抽奖花费(支出)", prop: "total_cost"
    },
    { label: "每期统计(收入/支出)", prop: "profit_loss_ratio", tip: "%" },
    // { label: "今日抽奖人数", prop: "today_count_user" },
    // { label: "今日抽奖次数", prop: "today_total_count" },
    // { label: "今日抽奖收入", prop: "today_total_price" },
  ])
  const statisticsData = ref({})
  const searchLabel = ref([
    { label: "礼物ID", prop: "gift_id", type: "input" },
    { label: "礼物名称", prop: "gift_name", type: "input" }
  ]);
  const tableLabel = ref([
    {
      label: "礼物ID",
      prop: "gift_id"
    },
    {
      label: "礼物名称",
      prop: "gift_name"
    },
    {
      label: "封面图",
      prop: "base_image",
      cellRenderer: ({ row }) => (
        <el-image
          fit="cover"
          preview-teleported={true}
          src={row.base_image}
          preview-src-list={Array.of(row.base_image)}
          class="w-[50px] h-[50px]  align-middle"
        />
      )
    },
    {
      label: "价格",
      prop: "gift_price"
    },
    {
      label: "每期数量",
      prop: "quantity"
    },
    {
      label: "未开数量",
      prop: "remaining_number"
    },
    {
      label: "多少次后可参与开奖",
      prop: "weight"
    },
    {
      label: "公屏",
      prop: "is_public_screen",
      cellRenderer: ({ row }) => (
        <el-tag type={row.is_public_screen === 1 ? 'success' : 'error'}>{row.is_public_screen === 1 ? '是' : '否'}</el-tag>
      )
    },
    {
      label: "全服播报",
      prop: "is_public_server",
      cellRenderer: ({ row }) => (
        <el-tag type={row.is_public_server === 1 ? 'success' : 'error'}>{row.is_public_server === 1 ? '是' : '否'}</el-tag>
      )
    },
    {
      label: "添加时间",
      prop: "createtime"
    },
    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation"
    }
  ]);
  const onSearch = async (formData) => {
    loading.value = true;
    searchForm.value = { ...formData }
    const { data, code } = await queryBlindBoxList({
      ...formData,
      gift_bag_id: activeName.value,
      page: pagination.value.currentPage,
      page_limit: pagination.value.pageSize,

    });
    if (code) {
      tableList.value = data.lists.map(ele => {
        return {
          ...ele, ...data.total
        }
      });
      statisticsData.value = data.total_data
      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 getType = async () => {
    const { code, data } = await queryBoxTypeList({ activities_id: 5 })
    typeList.value = code ? data.map(ele => {
      return {
        label: ele.name,
        value: ele.id
      }
    }) : []
    if (code) handleClick(data[0].id)
  }
  const handleClick = (id) => {
    activeName.value = id
    onSearch(searchForm.value);
  }
  // 
  const resetSetting = async () => {
    const { data, code } = await resetBlindBoxRule({
      gift_bag_id: activeName.value
    })
    if (code) {
      message(`重置成功`, {
        type: "success"
      });
      handleClick(activeName.value);
    }

  }
  const handleDelete = async rowData => {
    const { code } = await removeBlindBoxData({ id: rowData.id });
    if (code) {
      message(`您删除了这条数据`, {
        type: "success"
      });
      onSearch(searchForm.value);
    }
  };
  const openDialog = async (title = "新增", rowData: any) => {
    addDialog({
      title: `${title}盲盒礼物`,
      props: {
        formInline: {
          gift_id: rowData?.gift_id ?? "",
          quantity: rowData?.quantity ?? 1,
          weight: rowData?.weight ?? 1,
          is_world_show: rowData?.is_world_show ?? ""
        }
      },
      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 saveData = async form => {
          const { code } = await addBlindBoxData({
            ...form,
            gift_bag_id: activeName.value,
          });
          if (code) {
            message("新增成功", { type: "success" });
            onSearch(searchForm.value);
            done();
          } else {
            message("新增失败", { type: "error" });
          }
        };
        const updateData = async form => {
          const { code, msg } = await editBlindBoxData({
            ...form,
            gift_bag_id: activeName.value,
            id: rowData.id
          });
          if (code) {
            message("修改成功", { type: "success" });
            onSearch(searchForm.value);
            done();
          } else {
            message(msg, { type: "error" });
          }
        };
        FormRef.validate(valid => {
          if (valid) {
            console.log("curData", curData);
            // 表单规则校验通过
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              saveData(curData);
            } else {
              // 实际开发先调用修改接口，再进行下面操作
              updateData(curData);
            }
          }
        });
      }
    });
  };
  const setting = async () => {
    const { data, code } = await getBlindBoxRule({ gift_bag_id: activeName.value })
    addDialog({
      title: `设置盲盒规则`,
      props: {
        formInline: {
          ...data
        }
      },
      width: "40%",
      closeOnClickModal: false,
      contentRenderer: () => h(settingRuleView, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline;
        const saveData = async form => {
          const { code } = await settingBlindBoxRule({ ...form });
          if (code) {
            message("设置成功", { type: "success" });
            onSearch(searchForm.value);
            done();
          } else {
            message("设置失败", { type: "error" });
          }
        };
        FormRef.validate(valid => {
          if (valid) {
            // console.log("curData", curData);
            saveData(curData)
          }
        });
      }
    });
  }
  // 开奖记录
  const openLotteryRecord = () => {
    addDialog({
      title: `盲盒转盘开奖记录`,
      fullscreen: true,
      hideFooter: true,
      closeOnClickModal: false,
      contentRenderer: () => h(TurntableView, { ref: formRef, formInline: null })
    });
  }
  return {
    searchForm,
    searchLabel,
    onSearch,
    isShow,
    tableList,
    tableLabel,
    pagination,
    handleSizeChange,
    handleCurrentChange,
    loading,
    getType,
    activeName,
    typeList,
    statisticsList,
    statisticsData,
    handleClick,
    openDialog,
    resetSetting,
    handleDelete,
    setting,
    openLotteryRecord
  };
}