import {
  Button,
  Cell,
  Dialog,
  Icon,
  ShareSheet,
  Skeleton,
  Toast,
} from "@antmjs/vantui";
import { Input, RichText, View } from "@tarojs/components";
import Taro, { getCurrentInstance, useShareTimeline } from "@tarojs/taro";
import react, { useEffect, useState } from "react";
import {
  addTable,
  getTable,
  getTableid,
  isLogin,
  phoneLogin,
  updateTableid,
} from "../../../../utils/index";
import "./index.scss";
import { Image } from "@antmjs/vantui";
import _ from "lodash";
import moment from "moment";

const details = () => {
  const [dataSource, setdataSource] = 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 [status, setstatus] = useState<any>("0");
  const [detailStatus, setdetailStatus] = useState<any>();
  const [disable, setdisable] = useState<any>(false); //按钮禁用状态
  const [statusName, setstatusName] = useState("");

  const [bottomheight, setbottomheight] = useState(0);
  let $instance: any = getCurrentInstance();
  const { id } = $instance?.router?.params ?? {}; //活动id
  const [isCheckin, setisCheckin] = useState(false); // 是否报名
  const [openId, setopenId] = useState("");

  const [show, setShow] = react.useState(false);
  const [canelshow, setcanelshow] = react.useState(false);
  const [showShare, setshowShare] = react.useState(false)

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

  Taro.useShareAppMessage((res) => {
    if (res.from === "button") {
      // 来自页面内转发按钮
      console.log(res.target);
    }
    return {
      title: "活动详情",
      path: `/pages/activityList/components/details/index?id=${id}`,
    };
  });

  useEffect(() => {
    if (status === "1" || detailStatus !== "1" || status === "5") {
      setdisable(true);
    } else {
      setdisable(false);
    }
  }, [status, detailStatus]);

  useEffect(() => {
    // 设置标题
    definePageConfig({
      navigationBarTitleText: "活动详情",
    });
  }, []);

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

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

  useEffect(() => {
    // (dataSource?.useridArr ?? []).length > 0 &&
    Taro.cloud.callFunction({
      name: "getOpenid",
      complete: async (res: any) => {
        console.log("callFunction test result: ", res);
        let newopenId: any = res?.result?.event?.userInfo?.openId;
        setopenId(newopenId);
      },
    });
  }, []);

  useEffect(() => {
    const { screenHeight, safeArea = {} } = Taro.getSystemInfoSync();
    // @ts-ignore
    let newBottom = screenHeight - safeArea?.bottom ?? 0;
    setbottomheight(newBottom);
  }, []);

  useEffect(() => {
    if (openId) {
      getDetail();
    }
  }, [openId]);

  // 获取详情
  const getDetail = () => {
    let objParams = {
      tableName: "details",
      id: id,
      okFun: (res) => {
        console.log("res", res);
        // setdataSource(res?.data ?? {});
        console.log("dataSource ", dataSource);

        setdetailStatus(res?.data?.Status ?? "");
        let newpeopleArr = res?.data?.peopleArr ?? [];

        if (newpeopleArr?.length > 0) {
          newpeopleArr.forEach((item: any) => {
            if (item?.openid === openId) {
              setstatus(item?.status ?? "0");
            }
          });
        } else {
          setstatus("0");
        }
        // 检查是否已报名
        if ((res?.data?.useridArr ?? []).includes(openId)) {
          setisCheckin(true);
        } else {
          setisCheckin(false);
        }
      },
    };
    getTableid(objParams); //指定活动详情id
    // getTable(objParams)
  };

  // console.log('SafeAreaResult',Taro.getSystemInfoSync())

  const btnStatus = [
    {
      label: "活动待开放",
      value: "0",
    },
    // {
    //   label: "立即报名", //开放中
    //   value: "1",
    // },
    {
      label: "活动已取消",
      value: "2",
    },
    {
      label: "活动进行中",
      value: "3",
    },
    {
      label: "活动已结束",
      value: "4",
    },
    {
      label: "活动已关闭",
      value: "5",
    },
  ];

  // 按钮文本
  const btnContent = () => {
    console.log("detailStatus,status,openid", detailStatus, status, openId);
    let newstatusName = "立即报名";
    // 开放中
    if (detailStatus === "1") {
      if (status === "0") {
        newstatusName = "立即报名";
      }
      if (status === "4") {
        newstatusName = "再次报名";
      }
      if (status === "2") {
        newstatusName = "取消报名";
      }
      if (status === "1") {
        newstatusName = "待审核";
      }
      if (status === "5") {
        newstatusName = "审核不通过";
      }
    } else {
      btnStatus.forEach((item: any) => {
        let status: any = dataSource?.Status;
        if (item?.value === status) {
          newstatusName = item?.label;
        }
      });
    }
    // setstatusName(newstatusName);
    return newstatusName;
  };

  const canelActive = () => {
    // 取消报名
    let peopleArrItem = (dataSource?.peopleArr ?? []).map(
      (item, index, arr) => {
        if (item?.openid === openId) {
          return {
            ...item,
            status: "4", //报名后取消
          };
        } else {
          return {
            ...item,
          };
        }
      }
    );
    updateTableid({
      tableName: "details",
      id: id,
      objData: {
        // 删除用户报名记录
        // useridArr: [
        //   ...(dataSource?.useridArr ?? []).filter(
        //     (value, index, arr) => {
        //       return value !== openId;
        //     }
        //   ),
        // ],
        // peopleArr: [
        //   ...(dataSource?.peopleArr ?? []).filter(
        //     (item, index, arr) => {
        //       return item?.openid !== openId;
        //     }
        //   ),
        // ],
        peopleArr: [...peopleArrItem],
      },
      okFun: (res: any) => {
        Toast.success({
          message: "取消成功",
          selector: "#vanToast-demo2",
          onClose: () => {
            // 刷新数据
            getDetail();
            // 返回首页 [上一页]
            // Taro.navigateBack({
            //   // url: "/pages/home/index",
            //   delta: 1,
            // });
          },
        });
      },
    });
  };

  const detailPost = () => {
    // 立即报名
    let postData = {
      // env: "any",
      id: id,
      tableName: "details",
      objData: {
        // ..._.cloneDeep(dataSource),
        useridArr: [..._.cloneDeep(dataSource?.useridArr ?? []), openId],
        peopleArr: [
          ..._.cloneDeep(dataSource?.peopleArr ?? []),
          {
            openid: openId,
            status: "1", //待审核
          },
        ],
      },
      okFun: (res: any) => {
        console.log("res333", res);

        // 报名成功
        Toast.success({
          message: "报名成功,审核中",
          selector: "#vanToast-demo2",
          onClose: () => {
            // 更新用户信息
            userinfoPost();
            setShow(true);
            // 刷新数据
            getDetail();

            // 返回首页 [上一页]
            // Taro.navigateBack({
            //   // url: "/pages/home/index",
            //   delta: 1,
            // });
          },
        });
      },
    };

    console.log("postData", postData);
    updateTableid({ ...postData });
  };

  // 更新用户参与活动记录
  const userinfoPost = () => {
    let postData = {
      tableName: "userInfo",
      keyValue: { openId: openId },
      okFun: (res: any) => {
        let newobj = {
          tableName: "userInfo",
          id: res?.data?.[0]?._id,
          objData: {
            activeidArr: [...(res?.data?.activeidArr ?? []), openId],
          },
          okFun: (okFunres: any) => {
            console.log("添加用户记录", okFunres);
            //
          },
        };
        updateTableid({ ...newobj });
      },
    };

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

  return (
    <View>
      {Object.keys(dataSource)?.length > 0 ? (
        <View className={`detailContent`}>
          <View>
            <View>{dataSource?.title}</View>
            <Image
              width="100%"
              height="180px"
              fit="cover"
              // src="https://img.yzcdn.cn/vant/cat.jpeg"
              src={dataSource?.images?.[0]?.url}
            />
            <View>
              <Cell
                icon="clock"
                title={`开始时间 ${
                  dataSource?.startTime
                    ? moment(dataSource?.startTime).format(
                        "YYYY-MM-DD HH:mm:ss"
                      )
                    : ""
                }`}
                // isLink
                // linkType="navigateTo"
                // url="/pages/dashboard/index"
              />
              <Cell
                icon="clock"
                title={`结束时间 ${
                  dataSource?.endTime
                    ? moment(dataSource?.endTime).format("YYYY-MM-DD HH:mm:ss")
                    : ""
                }`}
                // isLink
                // linkType="navigateTo"
                // url="/pages/dashboard/index"
              />
              <Cell
                isLink
                icon="location"
                title={`${dataSource?.address}`}
                linkType="navigateTo"
                url="/pages/dashboard/index"
                onClick={() => {
                  Taro.openLocation({
                    latitude: dataSource?.latitude,
                    longitude: dataSource?.longitude,
                    scale: 18,
                  });
                }}
              />

              <Cell
                icon="friends"
                // title={`已报名人数 ${dataSource?.useridArr?.length ?? 0}`}
                title={`已报名人数 ${
                  (dataSource?.peopleArr ?? []).filter((item: any) => {
                    return item?.status === "2" || item?.status === "1";
                  })?.length >> 0
                }`}

                // isLink
                // linkType="navigateTo"
                // url="/pages/dashboard/index"
              />
            </View>

            {/* 头像列表 */}
            {/* <View className="imagesArr">
          {[1, 2, 3, 4].map((item: any) => {
            return (
              <Image
                round
                width="30px"
                height="30px"
                src="https://img.yzcdn.cn/vant/cat.jpeg"
                style={{ marginRight: "5px" }}
              />
            );
          })}
        </View> */}
          </View>
          {/* 富文本 */}
          <View onClick={() => {}} className="RichText">
            {/* <View>{dataSource?.[0]?.actTitle}</View> */}

            <RichText nodes={dataSource?.richText} />
          </View>

          <View>
            <Dialog
              id="vanDialog3"
              title="长按二维码识别"
              showCancelButton={false}
              showConfirmButton={false}
              // confirmButtonOpenType="getUserInfo"
              show={show}
              onClose={() => setShow(false)}
            >
              <View className="wechatCode">
                <Image
                  showMenuByLongpress={true}
                  width={300}
                  height={300}
                  src={dataSource?.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>

          <View>
            <Dialog
              id="vanDialog4"
              title="取消后,再次报名,会严格审核"
              showCancelButton={true}
              // showConfirmButton={false}
              // confirmButtonOpenType="getUserInfo"
              show={canelshow}
              onClose={() => setShow(false)}
              cancelButtonColor={'green'}
              confirmButtonColor={'red'}
              onConfirm={() => {
                // 取消报名
                canelActive();
              }}
            >
              <View className="wechatCode">
                {/*       
              <Button
                style={{ width: "130px", marginTop: "20px" }}
                type="primary"
                round
                size="small"
                onClick={() => {
                  setcanelshow(false);
                  canelActive()
                }}
              >
                我想好了
              </Button> */}
              </View>
            </Dialog>
          </View>

          {/* 调试按钮 */}
          {/* <Cell title="组件调用" onClick={() => setShow(true)} /> */}

          <View className="share" onClick={() => setshowShare(true)}>
            <Icon name="share" size="32px" className="icon"></Icon>
          </View>
          <View>
            <ShareSheet
              show={showShare}
              description="一起来玩吧 ~"
              title="立即分享给好友"
              options={[
                {
                  name: "好友",
                  icon: "wechat",
                  openType:"share"
                },
                // {
                //   name: "朋友圈",
                //   icon: "weibo",
                //   openType:"weibo"
                // },
              ]}
              onClose={() => setshowShare(false)}
            />
          </View>

          <View
            className={`detailBtn`}
            style={{ bottom: `${bottomheight ?? 0}px` }}
          >
            {/* style={{width:'375px'}} */}
            <Button
              type={disable ? "warning" : "primary"}
              block
              // disabled={disable}
              onClick={async () => {
                if (disable) {
                  setShow(true);
                  return false;
                }
                // if (isCheckin) {
                if (status === "2") {
                  setcanelshow(true);
                  return false;
                }

                // 放鸽子
                if (status === "4") {
                  Toast.fail({
                    message: "再次报名需审核!",
                    selector: "#vanToast-demo2",
                    duration: 2000,
                    onClose: () => {
                      // 跳转到目的页面，打开新页面
                      setShow(true);
                    },
                  });
                  return false;
                }

                let isin: any = await phoneLogin();
                if (!isin) {
                  //重新登录- 跳转到我的页面
                  Toast.fail({
                    message: "请先登录",
                    selector: "#vanToast-demo2",
                    duration: 2000,
                    onClose: () => {
                      // 跳转到目的页面，打开新页面
                      Taro.navigateTo({
                        url: "/pages/my/index",
                      });
                    },
                  });
                } else {
                  console.log("id", id);
                  //  立即报名
                  detailPost();
                }
              }}
            >
              {/* 立即参加 */}
              {btnContent()}
              {/* {`立即报名`} */}
            </Button>

            <Toast id="vanToast-demo2" />
          </View>
        </View>
      ) : (
        <View>
          {/* 骨架屏 */}
          <Skeleton title={true} row={16} />
        </View>
      )}
    </View>
  );
};

export default details;
