import {
  Button,
  Card,
  Cell,
  Col,
  Empty,
  Icon,
  Row,
  Tabbar,
  TabbarItem,
  Toast,
} from "@antmjs/vantui";
import { OpenData, View, Text, OfficialAccount } from "@tarojs/components";
import react, { useEffect, useState } from "react";
import TabbarCom from "../components/TabbarCom";
import { Image } from "@antmjs/vantui";
// import styles from './index.module.scss'
import "./index.module.scss";
import { Tab, Tabs } from "@antmjs/vantui";
import Taro from "@tarojs/taro";
import ActiveCard from "../components/ActiveCard";
import {
  addTable,
  cloudcall,
  getOpenid,
  getTable,
  getTableid,
  isLogin,
  phoneLogin,
  updateTableid,
} from "@/utils/index";
import { type } from "../../../config";
import { Divider } from "@antmjs/vantui";

const my = (props: any) => {
  //   const [active, setActive] = react.useState(props?.active ?? 0);

  const [userInfo, setuserInfo] = useState({}); //用户信息
  const [openId, setopenId] = useState(""); //用户信息
  const [activeidArr, setactiveidArr] = useState<any>([]); //用户参与的活动

  const [detailsData, setdetailsData] = useState<any>([]); //活动详情
  const [currentIndex, setcurrentIndex] = useState(0);
  const [isin, setisin] = useState(false); //0初始 1未登录 2有手机号
  const [initOK, setinitOK] = useState(false); //是否加载完成

  useEffect(() => {
    getLogin();
  }, []);

  const getLogin = async () => {
    let isLogin: any = await phoneLogin();
    console.log("isLogin", isLogin);
    setisin(isLogin);
    setinitOK(true);
  };

  useEffect(() => {
    if (isin) {
      // 获取当前用户信息
      getUserInfo();
    }
  }, [isin]);

  // 获取用户
  const getUserInfo = () => {
    Taro.cloud.callFunction({
      name: "getOpenid",
      complete: async (res: any) => {
        console.log("callFunction test result: ", res);
        let openid = res?.result?.event?.userInfo?.openId;
        setopenId(openid);
        let objParams = {
          tableName: "userInfo",
          // id: "80516fb66370bcf300b8f43c5f4dd52b",
          keyValue: { openId: openid },
          okFun: (res) => {
            console.log("userinfo--", res);
            setuserInfo(res?.data?.[0] ?? {});
            setactiveidArr(res?.data?.activeidArr ?? []);

            // 获取当前用户参与的活动
            getDetails(openid, "1");
          },
        };
        getTable(objParams);
      },
    });
  };

  // 获取该用户所有活动详情
  const getDetails = (openid: any, status?: string) => {
    const db: any = Taro.cloud.database({});
    const _: any = db.command;
    let newKey: any = status
      ? {
          peopleArr: _.elemMatch({
            openid: _.eq(openid),
            status: _.eq(status), //审核通过的数据
          }),
        }
      : {
          peopleArr: _.elemMatch({
            openid: _.eq(openid),
          }),
        };
    let objParams: any = {
      tableName: "details",
      // id: "80516fb66370bcf300b8f43c5f4dd52b",
      keyValue: {
        ...newKey,
      },
      okFun: (res) => {
        console.log("detailsData/usero--", res);
        setdetailsData(res?.data ?? []);
      },
    };
    getTable(objParams);
  };

  useEffect(() => {
    // 设置标题
    definePageConfig({
      navigationBarTitleText: "我的",
    });
  }, []);

  const CardCom = () => {
    return (
      <View>
        {detailsData?.length > 0 ? (
          <View>
            {detailsData.splice(0, 2).map((item: any, index: any) => {
              return (
                <View
                  onClick={() => {
                    console.log("Card");
                    Taro.navigateTo({
                      url: `/pages/activityList/components/details/index?id=${item?._id}`,
                    });
                  }}
                >
                  {/* 活动卡片 */}
                  <ActiveCard dataSource={item} />
                </View>
              );
            })}
          </View>
        ) : (
          <View>
            <Empty
              className="customImage"
              image="https://img.yzcdn.cn/vant/custom-empty-image.png"
              // description="描述文字"
            />
          </View>
        )}
      </View>
    );
  };

  const updateAuth = async (userRes: any) => {
    let newobj = {
      tableName: "userInfo",
      id: userRes?.data?.[0]?._id,
      objData: {
        authInfo: [...(userRes?.data?.[0]?.authInfo ?? []), ...userRes],
      },
      okFun: async (okFunres: any) => {
        console.log("添加用户认证信息", okFunres);
        setisin(true);
        //
      },
    };
    await updateTableid({ ...newobj });
  };

  return (
    <View className="myContent">
      {/* <View className={styles?.myContent}>  */}

      {/* 头像 */}
      <View className={`myImage`}>
        <Image
          round
          width="100px"
          height="100px"
          src="cloud://citynew-0givkbre03955d8c.6369-citynew-0givkbre03955d8c-1253655588/images/touxiang/images.jpg"
        />

        {!isin && initOK && (
          <View className="loginBtn">
            <Button
              type="primary"
              size="mini"
              // open-type="getPhoneNumber"
              // onGetPhoneNumber={onGetPhoneNumber}
              lang="zh_CN"
              onClick={async () => {
                // 获取收获地址
                Taro.chooseAddress({
                  success: async  (AddressRes) =>{
                    console.log("AddressRes", AddressRes);
                    await cloudcall({
                      path:'/feishu'
                    })
                    Taro.cloud.callFunction({
                      name: "getOpenid",
                      complete: async (opemRes: any) => {
                        let openid = opemRes?.result?.event?.userInfo?.openId;
                        console.log("openid", openid);
                        let postData = {
                          tableName: "userInfo",
                          keyValue: { openId: openid },
                          okFun: async (userRes: any) => {
                            console.log("userRes", userRes);
                            let newobj = {
                              tableName: "userInfo",
                              id: userRes?.data?.[0]?._id,
                              objData: {
                                authInfo: [
                                  ...(userRes?.data?.[0]?.authInfo ?? []),
                                  AddressRes,
                                ],
                              },
                              okFun: async (okFunres: any) => {
                                console.log("添加用户认证信息", okFunres);
                                setisin(true);
                                //
                              },
                            };
                            await updateTableid({ ...newobj });
                          },
                        };

                        // 查询openid
                        await getTable({ ...postData });
                      },
                    });
                    // 手机号
                    console.log(AddressRes.telNumber);
                    // cityName: "深圳市"
                    // countyName: "宝安区"
                    // detailInfo: "西乡街道ghhhh"
                    // detailInfoNew: "ghhhh"
                    // errMsg: "chooseAddress:ok"
                    // nationalCode: "440306"
                    // nationalCodeFull: "440306018"
                    // postalCode: "518101"
                    // provinceName: "广东省"
                    // streetName: "西乡街道"
                    // telNumber: "13135685636"
                    // userName: "cady"
                  },
                });
              }}
            >
              登录
            </Button>
          </View>
        )}
      </View>

      <View>
        <Tabs
          sticky={true}
          active={currentIndex}
          onClick={async (e: any) => {
            console.log("e", e);
            setcurrentIndex(e?.detail?.index);
            await getDetails(openId, e?.detail?.name);
          }}
        >
          {/* <Tab title={`待审核 ${detailsData?.length??0}`} name="1"> */}
          <Tab title={`待审核`} name="1"></Tab>
          {/* <Tab title="未通过" name="5"></Tab> */}
          {/* <Tab title="已报名">
            <View>222</View>
          </Tab> */}
          <Tab title="待参加" name="2"></Tab>
          <Tab title="已取消" name="4"></Tab>

          {/* <Tab title="已结束" name='4'>44</Tab> */}
        </Tabs>
        <View>{CardCom()}</View>
      </View>

      <View className="cellArr">
        <Cell
          icon="star"
          title="打卡记录"
          isLink
          onClick={() => {
            if (isin) {
              // 跳转到目的页面，打开新页面
              Taro.navigateTo({
                url: "/pages/my/components/CheckinDetail/index",
              });
            } else {
              Toast.fail({
                message: "请先登录",
                selector: "#vanToast-demo2",
              });
            }
          }}
        />

        {/* <Cell
          icon="coupon"
          title="个人资料"
          isLink
        /> */}

        {/* <Cell
          icon="star"
          title="我参与的"
          isLink
          onClick={() => {
            if (isin) {
              // 跳转到目的页面，打开新页面
              // Taro.navigateTo({
              //   url: "/pages/my/components/CheckinDetail/index",
              // });
            } else {
              // Toast.fail({
              //   message: "请先登录",
              //   selector: "#vanToast-demo2",
              // });
            }
          }}
        /> */}

        <Cell
          icon="manager"
          title="申请成为领队"
          isLink
          onClick={() => {
            Toast.fail({
              message: "首次参加活动后,可申请成为领队",
              selector: "#vanToast-demo2",
            });
            // 跳转到目的页面，打开新页面
            // Taro.navigateTo({
            //   url: "/pages/formSubmit/index",
            // });
          }}
        />

        {/* <Cell icon="manager" title="个人资料" isLink /> */}

        {/* 个人客服 */}
        <View className="wechat">
          <Icon name="wechat" size="16px" className="icon"></Icon>
          {/* <Text>微信客服</Text> */}
          <Button open-type="contact" className="wecahtBtn">
            联系客服
          </Button>
        </View>

        {type !== "people" && (
          <Cell
            title="微信客服"
            icon="wechat"
            isLink
            value=""
            onClick={() => {
              Taro.openCustomerServiceChat({
                corpId: "wwb04af9a97514271c", //企业id
                extInfo: {
                  url: "https://work.weixin.qq.com/kfid/kfc70f3f112c97a54c5",
                },
                success: function (res) {},
              });
            }}
          />
        )}

        <Cell
          icon="friends"
          title="关于我们"
          isLink
          onClick={() => {
            // 跳转到目的页面，打开新页面
            Taro.navigateTo({
              url: "/pages/my/components/AbountUs/index",
            });
          }}
        />

        <Cell
          icon="setting"
          title="版本日志"
          isLink
          onClick={() => {
            // 跳转到目的页面，打开新页面
            Taro.navigateTo({
              url: "/pages/my/components/Version/index",
            });
          }}
        />
      </View>

      <Toast id="vanToast-demo2" />

      {/* tabbar */}
      <TabbarCom active={2} />
    </View>
  );
};

export default my;
