import { h, ref, nextTick } from "vue";
import editForm from "./form.vue";
import { ElMessageBox } from "element-plus";
import ExportForm from '@/components/exportDialog/index.vue';
import { utils, writeFile } from "xlsx";
import detailView from './detail.vue';
import banUserView from './banUser.vue';
import changePassView from './password.vue';
import setFundView from './fundSetting.vue';
import searchMoreView from './searchMore.vue';
import { message } from "@/utils/message";
import {
  queryList,
  editUserInfo,
  getUserInfo,
  removeUserData,
  changePassWordByUser,
  setMoneyByUser,
  officialUserData,
  banUserData
} from "@/api/modules/newuserList";
import { addDialog } from "@/components/ReDialog";
export function useData() {
  const formRef = ref();
  const searchFormMore = ref({
    user_code: '',
    login_device: '',
    nickname: '',
    status: '',
    coin1: '',
    coin2: '',
    createtime: ''
  })
  const loading = ref(true);
  const tableList = ref([]);
  const isShow = ref(false);
  const pagination = ref({
    total: 0,
    pageSize: 10,
    pageSizes: [10, 20, 50, 100],
    currentPage: 1,
    background: true
  });
  const searchForm = ref({
    search: "",
    is_sys_tester: "",
    is_real: ""
  });
  const searchLabel = ref([
    { label: "昵称/手机号查询", prop: "search", type: "input" },
    {
      label: "官方账号",
      prop: "is_sys_tester",
      type: "select",
      optionList: [
        { label: "全部", value: "" },
        { label: "是", value: 1 },
        { label: "否", value: 0 }
      ]
    },
    {
      label: "实名状态",
      prop: "is_real",
      type: "select",
      optionList: [
        { label: "全部", value: "" },
        { label: "是", value: 1 },
        { label: "否", value: 0 }
      ]
    }
  ]);
  const indexMethod = (index: number) => {
    return index + 1;
  };
  const tableLabel = ref([
    {
      type: "index",
      index: indexMethod
    },
    {
      label: "Id",
      prop: "user_code"
    },
    {
      label: "靓号",
      prop: "special_num"
    },
    {
      label: "头像",
      prop: "avatar",
      cellRenderer: ({ row }) => (
        <el-image
          fit="cover"
          preview-teleported={true}
          src={row.avatar}
          preview-src-list={Array.of(row.avatar)}
          class="w-[50px] h-[50px]  align-middle"
        />
      )
    },
    {
      label: "手机号",
      prop: "mobile"
    },
    {
      label: "昵称",
      prop: "nickname"
    },
    {
      label: "性别",
      prop: "sex",
      cellRenderer: ({ row }) => (
        <div>{row.sex === 1 ? '男' : row.sex === 0 ? '未知' : '女'}</div>
      )
    },
    {
      label: "设备号",
      prop: "login_device"
    },
    {
      label: "IP地址",
      prop: "loginip"
    },
    {
      label: "金币",
      prop: "coin"
    },
    {
      label: "钻石",
      prop: "earnings"
    },
    {
      label: "实名状态",
      prop: "is_real_str",
    },
    {
      label: "邀请码",
      prop: "init_code"
    },
    {
      label: "登录状态",
      prop: "status",
      cellRenderer: ({ row }) => (
        <el-tag type={row.status == 2 ? 'error' : 'success'}>{row.status_str}</el-tag>
      )
    },
    {
      label: "操作",
      fixed: "right",
      width: 510,
      slot: "operation"
    }
  ]);
  const onSearch = async (formData) => {
    loading.value = true;
    searchForm.value = { ...formData }
    // console.log(searchForm.value, formData, 111)
    if (!formData) {
      resetFieldsSearch()
    }
    const { data, code } = await queryList({
      ...formData,
      // coin1: searchForm.value.coin1 ? searchForm.value.coin1 : '',
      // coin2: searchForm.value.coin2 ? searchForm.value.coin2 : '',
      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 userInfoRes = await getUserInfo({ user_id: rowData.id })
    nextTick(() => {
      if (userInfoRes.code) {
        const { user_info, follow_num } = userInfoRes.data
        addDialog({
          title: `${title}会员信息`,
          props: {
            formInline: {
              mobile: user_info?.mobile ?? "",
              nickname: user_info?.nickname ?? "",
              real_name: follow_num?.real_name ?? "",
              card_id: follow_num?.card_id ?? "",
              birthday: user_info?.birthday ?? "",
              status: Number(user_info?.status) ?? "",
              profile: user_info?.profile ?? "",
              init_code: user_info?.init_code ?? "",
              red_status: user_info?.red_status ?? "",
              sex: user_info?.sex ?? user_info.sex === '男' ? 1 : user_info.sex === '女' ? 2 : '',
              is_real: follow_num?.is_real ?? follow_num.is_real === '未实名' ? 0 : 1
            }
          },
          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 updateUserData = async form => {
              const { code, msg } = await editUserInfo({
                ...form,
                user_id: rowData.id
              });
              if (code) {
                message("修改成功", { type: "success" });
                onSearch(searchForm.value);
                done();
              } else {
                message(msg, { type: "error" });
              }
            };
            FormRef.validate(valid => {
              if (valid) {
                // 表单规则校验通过
                if (title === "新增") {
                } else {
                  updateUserData(curData);
                }
              }
            });
          }
        });
      }
    })
  };
  // 查看会员详情
  const viewDetail = async (rowData) => {
    const userInfoRes = await getUserInfo({ user_id: rowData.id })
    nextTick(() => {
      if (userInfoRes.code) {
        const userData = userInfoRes.data
        addDialog({
          title: `查看会员详情`,
          props: {
            userInfo: { userId: rowData.id, ...userData }
          },
          width: "50%",
          closeOnClickModal: false,
          contentRenderer: () => h(detailView),
          beforeSure: (done) => {
            done()
          }
        });
      }
    })
  }
  // 删除会员
  const handleDelete = async rowData => {
    const { code } = await removeUserData({ user_id: rowData.id });
    if (code) {
      message(`删除成功`, {
        type: "success"
      });
      onSearch(searchForm.value);
    }
  };
  // 禁用
  const handleBanData = async rowData => {
    addDialog({
      title: `禁用`,
      props: {
        formInline: {
          type: 1
        },
        userData: { ...rowData }
      },
      width: "40%",
      closeOnClickModal: false,
      contentRenderer: () => h(banUserView, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline;
        const updateUserDataStatus = async form => {
          const paramData = { ...form, user_id: rowData.id }
          if (form.status === 2) {
            // 解封
            paramData.time = ''
            paramData.status = 2
          } else {
            if (!form.timeType) {
              // 永久解封
              paramData.time = ''
            }
          }
          delete paramData.timeType
          const { code, msg } = await banUserData(paramData);
          if (code) {
            message("设置成功", { type: "success" });
            onSearch(searchForm.value);
            done();
          } else {
            message(msg, { type: "error" });
          }
        };
        FormRef.validate(valid => {
          if (valid) {
            updateUserDataStatus(curData)
          }
        });
      }
    });
  };
  // 设置成官方账号
  const setOfficialUser = async rowData => {
    const { code } = await officialUserData({ user_id: rowData.id });
    if (code) {
      message(`设置成功`, {
        type: "success"
      });
      onSearch(searchForm.value);
    }
  };
  const onSeniorSearch = () => {
    addDialog({
      title: `高级搜索筛选`,
      props: {
        formInline: { ...searchFormMore.value }
      },
      width: "50%",
      closeOnClickModal: false,
      contentRenderer: () => h(searchMoreView, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline;
        FormRef.validate(valid => {
          if (valid) {
            searchFormMore.value = { ...curData }
            onSearch({ ...searchForm.value, ...curData });
          }
        });
        done()
      }
    });
  }
  const resetFieldsSearch = () => {
    searchFormMore.value = {
      user_code: '',
      login_device: '',
      nickname: '',
      status: '',
      coin1: '',
      coin2: '',
      createtime: ''
    }
    searchForm.value = {
      search: "",
      is_sys_tester: "",
      is_real: ""
    }
    onSearch({ ...searchForm.value, ...searchFormMore.value });
  }
  // 设置资金
  const setUserFund = async (rowData: any) => {
    addDialog({
      title: `账户资金设置`,
      props: {
        formInline: {
          money_type: "",
          change_value: "",
          secondary_password: "",
          remarks: ""
        }
      },
      width: "50%",
      closeOnClickModal: false,
      contentRenderer: () => h(setFundView, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline;
        const setMoneyData = async form => {
          const { code, msg } = await setMoneyByUser({
            ...form,
            user_id: rowData.id
          });
          if (code) {
            message("设置成功", { type: "success" });
            onSearch(searchForm.value);
            done();
          } else {
            message(msg, { type: "error" });
          }
        };
        FormRef.validate(valid => {
          if (valid) {
            setMoneyData(curData)
          }
        });
      }
    });
  };
  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 queryList({
    //         ...searchForm.value,
    //         coin1: searchForm.value.coin1 ? searchForm.value.coin1 : '',
    //         coin2: searchForm.value.coin2 ? searchForm.value.coin2 : '',
    //         page: pagination.value.currentPage,
    //         page_limit: pagination.value.pageSize
    //       });
    //       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.start_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({ start_time: curData.time[0] || '', end_time: curData.time[1] || '' })
    //         }
    //       }
    //     });
    //   }
    // });

  }
  // 修改密码
  const changePassword = async (rowData: any) => {
    addDialog({
      title: `修改密码`,
      props: {
        formInline: {
          new_pwd: ""
        }
      },
      width: "40%",
      closeOnClickModal: false,
      contentRenderer: () => h(changePassView, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline;
        const changePassData = async form => {
          const { code, msg } = await changePassWordByUser({
            ...form,
            user_id: rowData.id
          });
          if (code) {
            message("修改成功", { type: "success" });
            onSearch(searchForm.value);
            done();
          } else {
            message(msg, { type: "error" });
          }
        };
        FormRef.validate(valid => {
          if (valid) {
            // 表单规则校验通过
            changePassData(curData);
          }
        });
      }
    });
  };

  return {
    searchForm,
    searchLabel,
    onSearch,
    isShow,
    tableList,
    tableLabel,
    pagination,
    handleSizeChange,
    handleCurrentChange,
    loading,
    openDialog,
    handleDelete,
    viewDetail,
    handleBanData,
    setOfficialUser,
    changePassword,
    setUserFund,
    onSeniorSearch,
    resetFieldsSearch,
    exportExcel
  };
}