import dayjs from "dayjs";
import {
  // MpSplashDetail,
  // UpUserNick,
  // UserInfoUp,
  // WCUserLogin,
  UpdateUser,
  UpdateUserUploadFile,
  GetProvince,
  GetAreaListByPid,
} from "../../utils/Interface";
import { Component, PropsWithChildren, useEffect, useState } from "react";
import Taro from "@tarojs/taro";
// 引入 Swiper, SwiperItem 组件
import { Block, View, Text, Image, Input, Button } from "@tarojs/components";
import { Toast, Popup, Picker, DatetimePicker } from "@antmjs/vantui";

import "taro-ui/dist/style/components/button.scss"; // 按需引入
import "./userInfo.less";

/*** redux ***/
import { connect } from "react-redux";
import { userRefresh } from "../../store/features/userInfo";
/*** redux end ***/

/** 自定义组件 **/
import Navbar from "../../components/navbar/navbar";
import PopupAlert from "../../components/popup/popup-alert";
/** 自定义组件 **/

import { loading, msg, go } from "../../utils/traoAPI";
import FormData from "../../utils/wxFormdata/formData";

// 仅注册成功后进入此页面

class UserInfo extends Component<any, any> {
  constructor(props) {
    super(props);
    this.state = {
      name: "用户信息",
      style: "font-size: 26rpx; font-weight: 400; color: #ccc",
      userInfo: {
        ...this.props.userInfo,
      },
      isShowIntegralText: false,
      cityShow: false,
      timeShow: false,
      columns: [
        {
          values: [],
          className: "column1",
          defaultIndex: 0,
        },
        {
          values: [],
          className: "column2",
          defaultIndex: 0,
        },
        {
          values: [],
          className: "column3",
          defaultIndex: 0,
        },
      ],
      leve1region: [],
      leve2region: [],
      leve3region: [],
      loading: true,
      form: {
        nickname: "", // 昵称
        province: "",
        city: "", // 市
        area: "", // 县区
        provinceId: "", // 省份
        cityId: "", // 市
        areaId: "", // 县区
        headimg: null,
      },
      // maxDate: new Date().getTime(),
      // minDate: new Date("1949-10-01").getTime(),
      minDate: new Date("1949-10-01").getTime(),
      birthday: this.props.userInfo.birthday
        ? dayjs(this.props.userInfo.birthday).valueOf()
        : dayjs().valueOf(),
      isSubmit: false, // 是否允许提交
    };
  }

  async onLoad() {
    if (!Taro.getStorageSync("token")) {
      // await this.WCUserLogin();
    }

    this.initData();
  }
  componentDidMount() {}

  componentWillUnmount() {}

  componentDidShow() {}

  componentDidHide() {}

  async initData() {
    await this.getProvince();
  }

  getProvince = async () => {
    let res = await GetProvince();
    if (res.data.code === 200) {
      let { columns } = this.state;
      let values = res.data.data.map((item: any) => item.name);
      columns[0].values = values;
      this.setState({ leve1region: res.data.data, columns });

      this.GetAreaListByPid_level2(res.data.data[0].id);
    }
  };

  GetAreaListByPid_level2 = async (level2) => {
    let res = await GetAreaListByPid({ pid: level2 });
    if (res.data.code === 200) {
      let { columns } = this.state;
      let values = res.data.data.map((item: any) => item.name);
      columns[1].values = values;
      this.setState({ leve2region: res.data.data, columns });

      this.GetAreaListByPid_level3(res.data.data[0].id);
    }
  };

  GetAreaListByPid_level3 = async (level3) => {
    let res = await GetAreaListByPid({ pid: level3 });
    if (res.data.code === 200) {
      let { columns } = this.state;
      let values = res.data.data.map((item: any) => item.name);
      columns[2].values = values;
      this.setState({ leve3region: res.data.data, columns });
    }
  };

  UpdateUser = async () => {
    let { form, userInfo } = this.state;
    let isTmpFile = userInfo.headimg.indexOf("//tmp") > -1;
    let isWXFile = userInfo.headimg.indexOf("wxfile://") > -1;
    if (isTmpFile || isWXFile) {
      let formData = {
        province: form.province,
        city: form.city,
        area: form.area,
        provinceId: form.provinceId,
        cityId: form.cityId,
        areaId: form.areaId,
        birthday: userInfo.birthday,
        nickname: userInfo.nickname,
        headimg: userInfo.headimg,
        file: userInfo.headimg || null,
      };
      let res = await UpdateUserUploadFile(formData);
      console.log("Res", res);
      if (res.code === 200) {
        userInfo.province = res.data.province;
        userInfo.city = res.data.city;
        userInfo.area = res.data.area;
        userInfo.provinceId = res.data.provinceId;
        userInfo.cityId = res.data.cityId;
        userInfo.areaId = res.data.areaId;
        userInfo.nickname = res.data.nickname;
        userInfo.headimg = res.data.headimg;
        userInfo.integralText = res.data.integralText;
        this.props.userRefresh(userInfo);
        this.setState({ userInfo: userInfo });
        if (res.data.integralText) {
          this.setState({ isShowIntegralText: true });
        } else {
          msg("更新成功");
          this.onSkip();
        }
      }
    } else {
      let formData = new FormData();
      formData.append("province", form.province);
      formData.append("city", form.city);
      formData.append("area", form.area);
      formData.append("provinceId", form.provinceId);
      formData.append("cityId", form.cityId);
      formData.append("areaId", form.areaId);
      formData.append("birthday", userInfo.birthday);
      formData.append("nickname", userInfo.nickname);
      formData.append("headimg", userInfo.headimg);
      formData.append("file", null);
      let data = formData.getData();
      let res = await UpdateUser(data);
      if (res.data.code === 200) {
        userInfo.province = res.data.data.province;
        userInfo.city = res.data.data.city;
        userInfo.area = res.data.data.area;
        userInfo.provinceId = res.data.data.provinceId;
        userInfo.cityId = res.data.data.cityId;
        userInfo.areaId = res.data.data.areaId;
        userInfo.nickname = res.data.data.nickname;
        userInfo.headimg = res.data.data.headimg;
        userInfo.integralText = res.data.data.integralText;
        this.props.userRefresh(userInfo);
        this.setState({ userInfo: userInfo });

        if (res.data.data.integralText) {
          this.setState({ isShowIntegralText: true });
        } else {
          msg("更新成功");
          this.onSkip();
        }
      }
    }
  };

  getChooseAvatar = (event) => {
    console.log("getChooseAvatar", event);

    let { userInfo } = this.state;
    userInfo.headimg = event.detail.avatarUrl;
    this.setState({ userInfo });

    this.isSubmitCheck();
  };

  onSubmit = async () => {
    const { userInfo, form } = this.state;
    if (!userInfo.headimg) return msg("请点击授权头像");
    if (!userInfo.nickname) return msg("请输入昵称");
    if (!form.provinceId) return msg("请选择您所在的地区");
    if (!userInfo.birthday) return msg("请选择您的生日");
    loading("提交中");

    // @ts-ignore
    await this.UpdateUser();

    // // @ts-ignore
    // UpUserNick({
    //   headimg: userInfo.headimg,
    //   nickname: userInfo.nickname,
    // }).then((res) => {
    //   loading("请稍等");
    //   const data = {
    //     birthday,
    //     province: form.provinceId,
    //     city: form.cityId,
    //     area: form.areaId,
    //   };
    //   // @ts-ignore
    //   UserInfoUp(data).then((res) => {
    //     msg(res.data.msg);
    //     this.onSkip();
    //   });
    // });
  };

  onSkip = () => {
    // 仅注册账号进入个人信息完善页。此时判断是否扫码进入的小程序，如果是扫码进入，提交与跳过都是回到主页
    const isScan = Taro.getStorageSync("isScan");
    if (isScan) {
      // Taro.setStorageSync("isScanNotRegisterSkip", true);
      Taro.switchTab({
        url: "/pages/index/index",
      });
      return;
    }
    let isInstrumentJump = Taro.getStorageSync("isInstrumentJump");
    if (isInstrumentJump === "true") {
      go("/pages/instrument/instrument");
    } else {
      Taro.switchTab({
        url: "/pages/user/user",
      });
    }
  };

  pickerChange = (event) => {
    console.log("pickerChange", event);
  };

  onPickerColumnChange = (event) => {
    console.log("onPickerColumnChange", event);
  };

  onCityChange = async (picker) => {
    console.log("onCityChange", picker);
    if (picker.detail.index === 0) {
      this.setState({ loading: true });

      let { leve1region } = this.state;
      let obj = leve1region.find(
        (item: any) => item.name === picker.detail.value[0]
      );
      await this.GetAreaListByPid_level2(obj.id);
      this.setState({ loading: false });
      return false;
    }
    if (picker.detail.index === 1) {
      this.setState({ loading: true });
      let { leve2region } = this.state;
      let obj = leve2region.find(
        (item: any) => item.name === picker.detail.value[1]
      );
      await this.GetAreaListByPid_level3(obj.id);
      this.setState({ loading: false });
    }
  };

  onCityConfirm = (picker) => {
    const index = picker.detail.index;
    let { form } = this.state;
    form.province = picker.detail.value[0];
    form.provinceId = this.state.leve1region[index[0]].id;
    form.city = picker.detail.value[1];
    form.cityId = this.state.leve2region[index[1]].id;
    form.area = picker.detail.value[2];
    form.areaId = this.state.leve3region[index[2]].id;
    this.setState({ form });
    this.onCityCancel();

    this.isSubmitCheck();
  };

  onCityCancel = () => {
    this.setState({ cityShow: false });
  };

  onCityShow = () => {
    this.setState({ cityShow: true });
  };
  closeShow = () => {
    this.setState({ cityShow: false });
  };

  onTimeShow = () => {
    this.setState({ timeShow: true });
  };
  closeTime = () => {
    this.setState({ timeShow: false });
  };
  onTimePickerCancel = () => {
    console.log("onTimePickerCancel");
    this.closeTime();
  };
  onTimePickerConfirm = (picker) => {
    let { userInfo } = this.state;
    userInfo.birthday = dayjs(picker.detail.value).format("YYYY-MM-DD");
    if (picker.detail.value) {
      this.setState({ userInfo });
    }
    this.closeTime();

    this.isSubmitCheck();
  };

  onNicknameChange = (event) => {
    let { userInfo } = this.state;
    userInfo.nickname = event.detail.value;
    this.setState({ userInfo });

    this.isSubmitCheck();
  };
  onNickNameReview = (event) => {
    console.log("onNickNameReview", event);
  };

  isSubmitCheck() {
    let { userInfo, form } = this.state;

    if (
      userInfo.nickname &&
      userInfo.headimg &&
      form.province &&
      form.city &&
      form.area &&
      userInfo.birthday
    ) {
      this.setState({ isSubmit: true });
    } else {
      this.setState({ isSubmit: false });
    }
  }

  closeIntegralText = () => {
    this.setState({ isShowIntegralText: false });
    setTimeout(() => {
      this.onSkip();
    }, 600);
  };

  onDateChange = (e) => {
    console.log("onDateChange", e);
  };

  render() {
    let {
      style,
      userInfo,
      columns,
      cityShow,
      timeShow,
      form,
      minDate,
      isSubmit,
      isShowIntegralText,
      birthday,
    } = this.state;
    const formatter = (type, value) => {
      if (type === "year") {
        return `${value}年`;
      }
      if (type === "month") {
        return `${value}月`;
      }
      return `${value}日`;
    };

    return (
      <Block>
        <PopupAlert
          isShow={isShowIntegralText}
          isClose={true}
          title="提示"
          content={userInfo.integralText}
          confirmButtonText="确定"
          textAlgin="center"
          close={this.closeIntegralText}
          confirm={this.closeIntegralText}
        />
        <Navbar></Navbar>
        <View className="main">
          <View className="title">个人信息</View>
          <View className="txt">请完善您的个人信息</View>
          <View className="txt">为您提供针对性的服务内容和指引</View>
          <Button
            className="avatar_box"
            open-type="chooseAvatar"
            onChooseAvatar={this.getChooseAvatar}
          >
            {!userInfo.headimg ? (
              <Block>
                <Image
                  className="avatar"
                  src={require("../../img/welcome/avatar.png")}
                />
                <View className="btn_avatar">点击授权头像</View>
              </Block>
            ) : (
              <Image className="avatar" src={userInfo.headimg}></Image>
            )}
          </Button>
          <View className="form">
            <View className="form_item">
              <View className="label">昵称</View>
              <Input
                type="nickname"
                className="ipt nickname"
                placeholder="请填写您的昵称"
                placeholder-style={style}
                value={userInfo.nickname}
                maxlength={20}
                onInput={this.onNicknameChange}
                onNickNameReview={this.onNickNameReview}
              ></Input>
            </View>
            <View className="form_item">
              <View className="label">地区/省市区</View>
              <Input
                onClick={this.onCityShow}
                disabled
                className="ipt"
                placeholder="请选择您所在的地区/省市区"
                value={form.province + form.city + form.area}
              ></Input>
              <Image
                className="arrow"
                src={require("../../img/welcome/arrow-down.png")}
              ></Image>
            </View>
            <View className="form_item">
              <View className="label">生日</View>
              <Input
                onClick={this.onTimeShow}
                disabled
                className="ipt"
                placeholder="请选择您的生日"
                placeholder-style={style}
                value={userInfo.birthday}
              ></Input>
              {/* <Picker
                mode="date"
                value={userInfo.birthday}
                onChange={this.onDateChange}
              >
                <Input
                  // onClick={this.onTimeShow}
                  disabled
                  className="ipt"
                  placeholder="请选择您的生日"
                  placeholder-style={style}
                  value={userInfo.birthday}
                ></Input>
              </Picker> */}
              <Image
                className="arrow"
                src={require("../../img/welcome/arrow-down.png")}
              ></Image>
            </View>
          </View>
        </View>
        <View className="footer">
          {isSubmit ? (
            <View className="btn" onClick={this.onSubmit}>
              确认提交
            </View>
          ) : (
            <View className="btn btn-disable">确认提交</View>
          )}

          <View className="text" onClick={this.onSkip}>
            <Text style="margin-right: 6rpx;">跳过</Text>
            <Image
              src={require("../../img/right.png")}
              style="width: 30rpx;height:30rpx"
              mode="aspectFit"
            />
          </View>
        </View>

        <Popup show={cityShow} position={"bottom"} onClose={this.closeShow}>
          <Picker
            showToolbar
            title="请选择您所在的地区"
            defaultIndex={0}
            columns={columns}
            onChange={this.onCityChange}
            onCancel={this.onCityCancel}
            onConfirm={this.onCityConfirm}
          />
        </Popup>

        <Popup show={timeShow} position={"bottom"} onClose={this.closeTime}>
          <DatetimePicker
            type="date"
            formatter={formatter}
            value={birthday}
            minDate={minDate}
            maxDate={Date.now()}
            onCancel={this.onTimePickerCancel}
            onConfirm={this.onTimePickerConfirm}
          />
        </Popup>
      </Block>
    );
  }
}

const mapStateToProps = (state) => ({
  userInfo: state.userInfo,
});
const mapDispatchToProps = (dispatch) => ({
  userRefresh(data) {
    dispatch(userRefresh(data));
  },
});
export default connect(mapStateToProps, mapDispatchToProps)(UserInfo);
