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

import "./userInfoDetail.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 } from "../../utils/traoAPI";
import FormData from "../../utils/wxFormdata/formData";

class UserInfoDetail 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,
      isSubmit: false,
      columns: [
        {
          values: [],
          classNameName: "column1",
          defaultIndex: 0,
        },
        {
          values: [],
          classNameName: "column2",
          defaultIndex: 0,
        },
        {
          values: [],
          classNameName: "column3",
          defaultIndex: 0,
        },
      ],
      leve1region: [],
      leve2region: [],
      leve3region: [],
      loading: true,
      form: {
        nickname: this.props.userInfo.nickname, // 昵称
        provinceId: this.props.userInfo.provinceId, // 省份
        province: this.props.userInfo.province, // 省份
        cityId: this.props.userInfo.cityId, // 市
        city: this.props.userInfo.city, // 市
        areaId: this.props.userInfo.areaId, // 县区
        area: this.props.userInfo.area, // 县区
        file: null,
      },
      pickerCityValue: [],
      // maxDate: new Date().getTime(),
      // minDate: new Date("1949-10-01").getTime(),
      currentDate: new Date().getTime(),
      birthday: this.props.userInfo.birthday
        ? dayjs(this.props.userInfo.birthday).valueOf()
        : dayjs().valueOf(),
      minDate: new Date("1949-10-01").getTime(),
    };
  }

  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, form } = this.state;
      let values = res.data.data.map((item: any) => item.name);
      columns[0].values = values;

      if (form.province) {
        let objIndex = values.findIndex((ele) => ele === form.province);
        if (objIndex > -1) {
          columns[0].defaultIndex = objIndex;
          this.setState({ leve1region: res.data.data, columns });
          this.GetAreaListByPid_level2(form.provinceId, true);
        }
      } else {
        this.setState({ leve1region: res.data.data, columns });
        this.GetAreaListByPid_level2(res.data.data[0].id);
      }
    }
    this.isSubmitCheck();
  };

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

      if (isInit) {
        let objIndex = values.findIndex((name) => name === form.city);
        if (objIndex > -1) {
          columns[1].defaultIndex = objIndex;
          this.setState({ leve2region: res.data.data, columns });
          this.GetAreaListByPid_level3(form.cityId, true);
        }
      } else {
        this.setState({ leve2region: res.data.data, columns });
        this.GetAreaListByPid_level3(res.data.data[0].id);
      }
    }
  };

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

      if (isInit) {
        let objIndex = values.findIndex((name) => name === form.area);
        if (objIndex > -1) {
          columns[2].defaultIndex = objIndex;
          this.setState({ leve3region: res.data.data, columns });
        }
      } else {
        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);
      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("更新成功");
          setTimeout(() => {
            this.goUser();
          }, 600);
        }
      }
    } 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("更新成功");
          setTimeout(() => {
            this.goUser();
          }, 600);
        }
      }
    }
  };

  goUser = () => {
    Taro.switchTab({
      url: "/pages/user/user",
    });
  };

  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();
  };

  onSkip = () => {
    this.goUser();
  };

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

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

  onCityChange = async (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 = () => {
    this.closeTime();
    this.isSubmitCheck();
  };
  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) => {
    // console.log("onNicknameChange", event);
    let { userInfo } = this.state;
    userInfo.nickname = event.detail.value;
    this.setState({ userInfo });
    this.isSubmitCheck();
  };
  onNickNameReview = (event) => {
    // console.log("onNickNameReview", event);
    this.isSubmitCheck();
  };

  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.goUser();
    }, 600);
  };

  render() {
    let {
      userInfo,
      columns,
      cityShow,
      timeShow,
      form,
      minDate,
      isShowIntegralText,
      isSubmit,
      birthday,
    } = this.state;

    const formatter = (type, value) => {
      if (type === "year") {
        return `${value}年`;
      }
      if (type === "month") {
        return `${value}月`;
      }
      return `${value}日`;
    };
    return (
      <Block>
        <Navbar isBack={true} titleSlot="个人信息"></Navbar>
        <PopupAlert
          isShow={isShowIntegralText}
          isClose={true}
          title="提示"
          content={userInfo.integralText}
          confirmButtonText="确定"
          textAlgin="center"
          close={this.closeIntegralText}
          confirm={this.closeIntegralText}
        />
        <View className="user-info-detail">
          <View className="infobox1">
            <View className="avatar_box">
              <Button
                style="width: 100rpx;height:100rpx;"
                open-type="chooseAvatar"
                onChooseAvatar={this.getChooseAvatar}
                hover-className="none"
              >
                {userInfo.headimg ? (
                  <Image className="headimg" src={userInfo.headimg}></Image>
                ) : (
                  <Image
                    className="headimg"
                    src={require("../../img/welcome/avatar.png")}
                  ></Image>
                )}
              </Button>
            </View>
            <Input
              type="nickname"
              className="ipt nickname"
              placeholder="请填写您的昵称"
              value={userInfo.nickname}
              maxlength={20}
              onInput={this.onNicknameChange}
              onNickNameReview={this.onNickNameReview}
            ></Input>
          </View>

          <View className="infobox2">
            <View className="title border">绑定手机</View>
            <View className="block_list flex aitems sb">
              <View className="label">
                手机号<Text>*</Text>
              </View>
              <View className="value">{userInfo.mobile}</View>
            </View>
          </View>

          <View className="infobox3">
            <View className="title border">基础信息</View>
            <View className="block_list" onClick={this.onCityShow}>
              <View className="label">
                地区(省市区)<Text>*</Text>
              </View>
              <View className="value">
                <View>
                  {form.province}
                  {form.city}
                  {form.area}
                </View>
                <View className="righticon">
                  <Image
                    src={require("../../img/user/right.png")}
                    mode="aspectFill"
                  ></Image>
                </View>
              </View>
            </View>
            <View className="block_list" onClick={this.onTimeShow}>
              <View className="label">
                生日<Text>*</Text>
              </View>
              <View className="value">
                {/* <picker className="picker" mode="date" bindchange="bindbirthdayPickerChange" end="{{dateend}}" value="{{ageindex}}" range="{{age}}">picker</picker> */}

                <View>{userInfo.birthday}</View>
                <View className="righticon">
                  <Image
                    src={require("../../img/user/right.png")}
                    mode="aspectFill"
                  ></Image>
                </View>
              </View>
            </View>
          </View>
        </View>

        <View className="btn_box flex jcenter">
          {isSubmit ? (
            <View className="btn" onClick={this.onSubmit}>
              保存
            </View>
          ) : (
            <View className="btn btn-disable">保存</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={dayjs(birthday).valueOf()}
            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)(UserInfoDetail);
