import {
  Button,
  Card,
  Cell,
  Col,
  Divider,
  Grid,
  GridItem,
  Row,
  Skeleton,
  Tab,
  Tabs,
  Tag,
  Toast,
} from "@antmjs/vantui";
import {
  Input,
  OfficialAccount,
  Swiper,
  View,
  WebView,
  // ChannelVideo,
  SwiperItem,
  Ad,
} from "@tarojs/components";
import React, { useCallback, useEffect, useState } from "react";
import { Image } from "@antmjs/vantui";
import react from "react";
import { NoticeBar } from "@antmjs/vantui";
import Taro, { useShareTimeline } from "@tarojs/taro";
import { Tabbar, TabbarItem } from "@antmjs/vantui";
import TabbarCom from "../components/TabbarCom";
import {
  cloudcall,
  getTable,
  getTableid,
  phoneLogin,
  updateTableid,
} from "@/utils/index";
import { Icon } from "@antmjs/vantui";
import "./index.scss";
import { Search } from "@antmjs/vantui";
import ActiveCard from "../components/ActiveCard";
import { Dialog } from "@antmjs/vantui";
import { Loading } from "@antmjs/vantui";
import InfoCard from "./components/InfoCard";
import WeGroup from "./components/WeGroup";

import QRcode from "../../images/QRcode.png";
import mylife from "../../images/mylife.jpg";

import { Radio, RadioGroup } from "@antmjs/vantui";
import { Steps } from "@antmjs/vantui";

const Home = () => {
  // const { images } = COMMON
  const [value, setValue] = react.useState("1");

  const [initPage1, setInitPage1] = react.useState(0);
  const [active, setActive] = react.useState(0);

  const [show, setShow] = react.useState(false);
  const [isEnded, setisEnded] = react.useState(false);

  // const [value, setValue] = react.useState("");

  const [SearchValue, setSearchValue] = useState<any>("");

  const [details, setdetails] = useState<any>([
    {
      title: "自由职业交流会",
      address: "深圳莲花山",
      date: "20231123",
      tagName: "报名中",
      tagCode: "ut ipsum esse Excepteur velit",
      Status: "dolor",
      images: [],
      peopleArr: [],
      detailsId: "laboris pariatur commodo",
      startTime: -83917740.70315647,
      endTime: -52170253.25949725,
      rules: [],
      isDelete: false,
      useridArr: [],
      latitude: "velit ea do i",
      longitude: "voluptate sint dolore ",
    },
  ]); //活动详情
  // 系统配置
  const [systemConfig, setsystemConfig] = useState<any>({});

  const [openid, setopenid] = useState();
  const [isIn, setisIn] = useState(false);
  const [addData, setaddData]: any = useState(null);

  const onChange = (e) => {};

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

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

  Taro.useShareAppMessage((res) => {
    if (res.from === "button") {
      // 来自页面内转发按钮
      console.log(res.target);
    }
    return {
      title: "cityNew",
      path: `/pages/home/index`,
    };
  });

  // 分享到朋友圈
  useShareTimeline(() => {
    return {
      title: "一起来玩吧", //字符串  自定义标题
      // query: `id=${this.data.shop.shop_id}`,  //页面携带参数
      // imageUrl: moments   //图片地址
    };
  });

  // 云托管测试
  const testCloud = async () => {
    const res = await cloudcall({
      path: "/feishu",
      method: "GET",
    });
    console.log("业务返回结果", res);
  };

  // 云托管本地测试
  const testPost = async () => {
    const res = await cloudcall({
      path: "/nihao",
      method: "POST",
    });
    console.log("业务返回结果", res);
  };
  useEffect(() => {
    // testCloud();
    // testPost()
  }, []);

  useEffect(() => {
    // 设置标题
    definePageConfig({
      navigationBarTitleText: "首页",
    });
    // 设置允许分享
    Taro.showShareMenu({
      withShareTicket: true,
    });
    // 其他分享
    Taro.updateShareMenu({
      withShareTicket: true,
      success() {},
    });
  }, []);

  const steps = [
    {
      text: "步骤一",
      // desc: '描述信息',
    },
    {
      text: "步骤二",
      // desc: '描述信息',
    },
    {
      text: "步骤三",
      // desc: '描述信息',
    },
    {
      text: "步骤四",
      // desc: '描述信息',
    },
  ];

  useEffect(() => {
    getsystemConfig(); //获取系统配置
    // getdetails(); //获取活动详情

    // setTimeout(() => {
    //   getdetails(); //获取活动详情
    // }, 1000);

    // getAd();
  }, []);

  // useEffect(() => {
  //   Taro.cloud.callFunction({
  //     name: "getOpenid",
  //     complete: async (res: any) => {
  //       console.log("callFunction test result: ", res);
  //       let newopenid = res?.result?.event?.userInfo?.openId;
  //       setopenid(newopenid);
  //     },
  //   });
  // }, [isIn]);
  const listener = function (res) {
    console.log("isEnded", res.isEnded);
    setisEnded(res.isEnded);
    if (!!res.isEnded) {
      setShow(true);
    } else {
      setShow(false);
    }
  };

  const listenerErr = function (err) {
    console.log("err", err);
  };

  const getAd = async () => {
    // 激励视频广告
    let res = await Taro.createRewardedVideoAd({
      adUnitId: "adunit-406f7f94d37c2243", //小程序广告位 ID
    });

    res.onClose(listener);
    res.onClose(listenerErr);

    //  加载激励广告数据
    await res
      .load()
      .then(async () => {
        await res.show();
      })
      .catch((err) => {
        console.log("err", err);
      });
    // 设置激励广告变量
    setaddData(res);
  };

  const gotoMylife=()=>{
        // 跳转到目的页面，打开新页面
        Taro.navigateTo({
          url: "/pages/mylife/index",
        });
  }

  const getdetails = async () => {
    let objParams = {
      tableName: "details",
      // id: "80516fb66370bcf300b8f43c5f4dd52b",
      okFun: async (res: any) => {
        console.log("details11--", res);
        // await setdetails(res?.data ?? []);
      },
    };
    await getTable(objParams);
  };

  const getsystemConfig = async () => {
    let objParams = {
      tableName: "systemConfig",
      // id: "80516fb66370bcf300b8f43c5f4dd52b",
      okFun: async (res: any) => {
        console.log("systemConfig--", res);
        await setsystemConfig(res?.data ?? []);

        // setTimeout(() => {
        //   getdetails();
        // }, 800);
      },
    };
    await getTable(objParams);
  };

  // 上传到云存储
  const uploadTaro = (tempFilePaths: any, lbsInfo: any) => {
    // 云开发存储文件 [/自动创建文件路径]
    Taro.cloud.uploadFile({
      cloudPath: `images/checkIn/${new Date()?.getTime()}.png`,
      filePath: tempFilePaths?.[0], // 文件路径
      success: (res: any) => {
        // get resource ID
        console.log("res", res?.fileID);
        checkIn({ imageUrl: res?.fileID, lbsInfo: lbsInfo });

        //  跳转到目的页面，打开新页面
        // Taro.navigateTo({
        //   url: `/pages/home/components/CheckIn/index?fileID=${res?.fileID}`,
        // });
      },
      fail: (err: any) => {
        // handle error
        console.log("err", err);
      },
    });
  };
  const onSearch = (e: any) => {
    console.log("e---", e);
    // Toast.show(`search: ${e.detail}`);
    // setSearchValue(e?.detail);
    setSearchValue("");

    // 跳转到目的页面，打开新页面
    Taro.navigateTo({
      url: "/pages/activityList/index",
    });
  };
  const onCancel = (e: any) => {
    // Toast.show(`onCancel`);
  };

  // 签到
  const checkIn = async (data: any) => {
    console.log("data=====", data);
    let postData = {
      tableName: "userInfo",
      keyValue: { openId: openid },
      okFun: (res: any) => {
        console.log("提交打卡,res", res);

        let newobj = {
          tableName: "userInfo",
          id: res?.data?.[0]?._id,
          objData: {
            checkInArr: [
              ...(res?.data?.[0]?.checkInArr ?? []),
              {
                imageUrl: data?.imageUrl,
                checkTime: new Date().valueOf(), //打卡时间
                latitude: data?.lbsInfo?.latitude,
                longitude: data?.lbsInfo?.longitude,
                // remark: fieldValues?.remark,
                // location: address,
              },
            ],
          },
          okFun: (okFunres: any) => {
            console.log("提交打卡,res", okFunres);
            Toast.success({
              message: "打卡成功",
              selector: "#vanToast-demo2",
              duration: 2000,
              onClose: () => {
                // 跳转到打卡页面
                // 返回首页 [上一页]
                // Taro.navigateBack({
                //   delta: 1,
                // });
              },
            });
          },
        };
        updateTableid({ ...newobj });
      },
    };

    // 查询openid
    getTable({ ...postData });
  };

  // 获取地理位置
  const getLocation = async () => {
    // 获取地理位置
    Taro.getLocation({
      type: "wgs84",
      success: function (res: any) {
        // 地理位置信息-经纬度
        console.log("lbsres---", res);
        const latitude = res.latitude;
        const longitude = res.longitude;
        const speed = res.speed;
        const accuracy = res.accuracy;
      },
    });
  };

  const chooseImage = (lbsInfo: any) => {
    // 相机拍照
    Taro.chooseImage({
      count: 1, // 默认9
      // , 'compressed'
      sizeType: ["original"], // 可以指定是原图还是压缩图，默认二者都有
      // 'album',
      sourceType: ["camera"], // 可以指定来源是相册还是相机，默认二者都有，在H5浏览器端支持使用 `user` 和 `environment`分别指定为前后摄像头
      success: function (res: any) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        let tempFilePaths = res.tempFilePaths;
        console.log("tempFilePaths===", tempFilePaths);
        // 跳转页面
        // Taro.navigateTo({
        //   url: `/pages/home/components/CheckIn/index?fileID=${tempFilePaths?.[0]}`,
        // });

        uploadTaro(tempFilePaths, lbsInfo);
      },
      complete: () => {
        // 刷新页面数据
        getsystemConfig(); //获取系统配置
        setTimeout(() => {
          getdetails(); //获取活动详情
        }, 800);
      },
    });
  };

  const showAd = () => {
    // addData.show();
    getAd();
  };

  return (
    <View className="homeContent">
      {/* <View className="text">请选择正确的给微信公众号名称</View>
      <RadioGroup value={value} onChange={(e) => setValue(e.detail)}>
        <Radio name="1">异度世界</Radio>
        <Radio name="2">hackrobot</Radio>
        <Radio name="3">极客小助手</Radio>
      </RadioGroup> */}
      <View className="textcontent">
        {" "}
        <Icon name={"star-o"} size="32px" />
        我的生活日记
      </View>
      <View className="text">对事物的看法</View>
      {/* <View className="text">设置了视频弹窗广告</View> */}
      <View className="text">读书笔记</View>
      <View className="text">参加的线上线下活动</View>
      <View className="text">旅游过的城市</View>
      {/* <View className="text">{String(show)}</View> */}
      {/* <View className="text">{String(isEnded)}</View> */}
      <View className="wechatCode">
        <Image
          showMenuByLongpress={true}
          width={300}
          height={300}
          src={mylife}
          // src='cloud://citynew-0givkbre03955d8c.6369-citynew-0givkbre03955d8c-1253655588/images/touxiang/download-1.jpg'
        ></Image>
      </View>
      <View className="addfried">
        <Button onClick={() => gotoMylife()} type="primary">
          查看我的分享
        </Button>
      </View>
      {/* <View className="QRcode">二维码</View> */}
      {/* banner广告 */}
      {/* <View className="bottomAd">
        <Ad
          unitId="adunit-2cca76d14094da03"
          adIntervals={60}
          onLoad={() => console.log("ad onLoad")}
          onError={() => console.log("ad onError")}
          onClose={() => console.log("ad onClose")}
        />
      </View> */}
      <View>
        <Dialog
          id="vanDialog3"
          title="长按二维码识别"
          showCancelButton={false}
          showConfirmButton={false}
          // confirmButtonOpenType="getUserInfo"
          show={show}
          onClose={() => {
            setShow(false);
            setisEnded(false);
          }}
        >
          <View className="wechatCode">
            <Image
              showMenuByLongpress={true}
              width={300}
              height={300}
              src={QRcode}
              // src='cloud://citynew-0givkbre03955d8c.6369-citynew-0givkbre03955d8c-1253655588/images/touxiang/download-1.jpg'
            ></Image>

            <Button
              style={{ width: "130px", marginTop: "20px" }}
              type="primary"
              round
              size="small"
              onClick={() => {
                setShow(false);
              }}
            >
              关闭
            </Button>
          </View>
        </Dialog>
      </View>
      {/* <Loading type="spinner" /> */}
      {/* 通知条 */}
      {/* {systemConfig?.length > 0 && !systemConfig?.[0]?.notice?.isHidden && (
        <NoticeBar
          leftIcon="volume-o"
          // text="疫情期间,请留意各个景区的开放状态以及时间"
          text={systemConfig?.[0]?.notice?.text}
        />
      )} */}
      {/* 顶部 */}
      {/* <View>
        <Row>
          <Col span="4" className="dark">
            深圳
          </Col>
        </Row>
      </View> */}
      {/* <View className="topHome"> */}
      {/* <Tag type="primary">深圳</Tag> */}
      {/* <View onClick={() => setShow(true)}>
          <Tag plain={true} type="primary" size="large">
            深圳
          </Tag>
        </View> */}
      {/* 搜索框 */}
      {/* <View>
          <Search
            value={SearchValue}
            onChange={(e) => setSearchValue(e.detail)}
            placeholder="请输入搜索关键词"
            style={{ width: "320px" }}
            onSearch={onSearch}
            // onCancel={onCancel}
          />
        </View>
      </View> */}
      {/* 轮播图 */}
      {/* <View className="Swiper-box">
        {systemConfig?.length > 0 && (
          <Swiper
            className="Swiper"
            // indicatorColor='#999'
            indicatorActiveColor="#333"
            // vertical //纵向
            circular
            indicatorDots
            autoplay
          >
            {(systemConfig?.[0]?.imagesArr ?? []).map(
              (item: any, index: any) => (
                <SwiperItem>
                  <Image
                    className="SwiperImg"
                    src={item?.url}
                    fit="cover"
                    width="100%"
                    height="150px"
                  />
                </SwiperItem>
              )
            )}
          </Swiper>
        )}
      </View> */}
      {/* 模块 */}
      {/* <Grid>
        <GridItem
          icon="star"
          text="打卡"
          className="iconStyle"
          onClick={async () => {
            // getLocation();
            if (isIn) {
              // 获取定位信息
              Taro.getLocation({
                type: "gcj02", //返回可以用于 Taro.openLocation的经纬度
                success: function (res: any) {
                  console.log("lbs", res);
                  const latitude = res?.latitude;
                  const longitude = res?.longitude;
                  let lbsInfo = {
                    latitude: res?.latitude,
                    longitude: res?.longitude,
                  };

                  // 拍照上传
                  chooseImage(lbsInfo);
                },
                fail: () => {
                  Toast.fail({
                    message: "定位授权异常,无法签到打卡",
                    selector: "#vanToast-demo2",
                  });
                },
              });
              // chooseImage();
            } else {
              await getdetails();

              Toast.fail({
                message: "请先登录",
                selector: "#vanToast-demo2",
                duration: 2000,
                onClose: () => {
                  // 跳转到目的页面，打开新页面
                  Taro.navigateTo({
                    url: "/pages/my/index",
                  });
                },
              });
            }
          }}
        /> */}
      {/* <GridItem
          icon="like"
          className="iconStyle"
          text="深圳十峰"
          onClick={() => {
            // 跳转到目的页面，打开新页面
            Taro.navigateTo({
              url: "/pages/mountainPeak/index",
            });
          }}
        /> */}
      {/* <GridItem
          icon="eye"
          className="iconStyle"
          text="活动"
          onClick={() => {
            // 跳转到目的页面，打开新页面
            Taro.navigateTo({
              url: "/pages/activityList/index",
            });
          }}
        /> */}
      {/* <GridItem
          icon="manager"
          className="iconStyle"
          text="组队"
          onClick={() => {
            Toast.fail({
              message: "参加1次活动后,可发起组队",
              selector: "#vanToast-demo2",
            });
            // 跳转到目的页面，打开新页面
            // Taro.navigateTo({
            //   url: "/pages/formSubmit/index",
            // });
          }}
        /> */}
      {/* <GridItem
          icon="video"
          className="iconStyle"
          text="视频"
          onClick={() => {
            // 打开视频号-指定视频
            Taro.openChannelsActivity({
              // finderUserName: "sphqzUmI0BlppCI", //视频号id,
              finderUserName:
                systemConfig?.[0]?.videoObj?.finderUserName ??
                "sphqzUmI0BlppCI",
              feedId:
                systemConfig?.[0]?.videoObj?.feedId ??
                "export/UzFfAgtgekIEAQAAAAAAeIIQA5S-0wAAAAstQy6ubaLX4KHWvLEZgBPEj6MUcExXaL37zNPgMJpEUVVnZ9njxR_hb9_u-bQj", //视频 feedId
              success: (res: any) => {
                console.log("res", res);
              },
            });

            // 打开视频号主页 [接口异常]
            // Taro.openChannelsUserProfile({
            //   finderUserName: "sphqzUmI0BlppCI", //视频号id
            //   success: (res: any) => {
            //     console.log("res", res);
            //   },
        //     // });
          }}
        /> */}
      {/* <GridItem
          icon="manager"
          className="iconStyle"
          text="认证"
          onClick={() => {
            // 跳转到目的页面，打开新页面
            Taro.navigateTo({
              url: "/pages/home/components/Certified/index",
            });
          }}
        /> */}
      {/* // </Grid> */}
      {/* 分割线 */}
      {/* <View>
        <Divider />
      </View> */}
      {/* 离我最近/天气/动态展示 */}
      {/* <View>
        <Tag plain={true} type="success">
          离你最近 (5km)
        </Tag>
        <View>
          <View>{`天气晴雨[动画效果]`}</View>
          <View>温度</View>
          <View>是否开放</View>
        </View>
      </View> */}
      {/* 日期页签 */}
      {/* <Tabs onClick={() => {}}>
        <Tab title="今天">今天</Tab>
        <Tab title="明天">明天</Tab>
        <Tab title="后天">后天</Tab>
        <Tab title="周六">周六</Tab>
        <Tab title="周日">周日</Tab>
      </Tabs> */}
      {/* 离我最近 */}
      {/* <View className="homeLbs">
        <Icon name="location" size="20px" className="icon"></Icon>
        <View> 理我最近</View>

        <View className="lbsMount">
          <Tag plain={true} type="primary" className="lbsMountTag">
            梧桐山 5km
          </Tag>
          <Tag plain={true} type="success" className="lbsMountTag">
            七娘山 3km
          </Tag>
          <Tag plain={true} type="danger" className="lbsMountTag">
            莲花山 2km
          </Tag>
        </View>
      </View> */}
      {/* 截取数组2个活动 */}
      {/* {details?.length > 0 ? (
        <View>
          {(details?.reverse()?.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>
      ) : (
        <Skeleton title={true} row={4} />
      )} */}
      {/* 加入微信群 */}
      {/* <WeGroup /> */}
      {/* <View style={{marginTop:'10px'}}>打卡精选</View> */}
      {/* 瀑布流 */}
      {/* <InfoCard /> */}
      {/* 直播live专区 */}
      {/* <View>视频号直播</View> */}
      {/* 小红书图文/视频信息流 */}
      {/* <View> 打开信息流</View> */}
      {/* 扫码的场景(才会显示) */}
      {/* <View style={{ marginTop: "20px" }}> */} {/* 个人版本未生效 */}
      {/* <OfficialAccount
          onLoad={(res: any) => {
            console.log("加载成功", res);
          }}
          onError={(res: any) => {
            console.log("加载失败", res);
          }}
        ></OfficialAccount> */}
      {/* </View> */}
      {/* 打开视频号主页-需要开放平台主主体认证 */}
      {/* <View
        onClick={() => {
          Taro.openChannelsUserProfile({
            finderUserName: "sphqzUmI0BlppCI", //视频号id
            success: (res: any) => {
              console.log("加载成功", res);
            },
            fail: (error: any) => {
              console.log("加载成功", error);
            },
          });
        }}
      >
        {" "}
        打开视频号主页
      </View> */}
      {/* 个人小程序无法打开公众号文章 */}
      {/* <WebView src="https://mp.weixin.qq.com/s/LkjkAWW9VUB90KoyZpI5Fg" onMessage={() => {}} /> */}
      {/* <View onClick={()=>{
        Taro.requestSubscribeMessage({
          tmplIds:["oyY-sN3yBm4JRch1PoT-Cj7049c9vyZAMs1LwnUma4I"], //模板id
          success:(res:any)=>{
            console.log('res',res)
          }
        })
      }}>订阅消息</View> */}
      {/* <Toast id="vanToast-demo2" /> */}
      {/* 打开视频号 */}
      {/* <View
        onClick={() => {
          Taro.openChannelsActivity({
            finderUserName: "sphqzUmI0BlppCI", //视频号id
            feedId:
              "export/UzFfAgtgekIEAQAAAAAAeIIQA5S-0wAAAAstQy6ubaLX4KHWvLEZgBPEj6MUcExXaL37zNPgMJpEUVVnZ9njxR_hb9_u-bQj", //视频 feedId
            success: (res: any) => {
              console.log("res", res);
            },
          });
        }}
      >
        打开视频号
      </View> */}
      {/* @ts-ignore */}
      {/* <channel-video feed-id={'export/UzFfAgtgekIEAQAAAAAAeIIQA5S-0wAAAAstQy6ubaLX4KHWvLEZgBPEj6MUcExXaL37zNPgMJpEUVVnZ9njxR_hb9_u-bQj'} finder-user-name={'sphqzUmI0BlppCI'}></channel-video> */}
      {/* @ts-ignore */}
      {/* <channel-video autoplay = {true} object-fit={'cover'} feed-id={'export/UzFfAgtgekIEAQAAAAAAi2cqMAslgwAAAAstQy6ubaLX4KHWvLEZgBPEgIFoIyNiE9iBzNPgMJpw2GKV9V4VOKQarDhUTo15'} finder-user-name={'sphiBL5kbHuXDRZ'}></channel-video> */}
      {/* 底部tabbar */}
      {/* <TabbarCom active={0} /> */}
    </View>
  );
};

export default Home;
