import classnames from "classnames";
import { Component, PropsWithChildren, useEffect, useState } from "react";

// import { InstrumentInfo } from "../../utils/Interface";

import Taro from "@tarojs/taro";
// 引入 Swiper, SwiperItem 组件
import {
  Block,
  View,
  Text,
  Image,
  Input,
  // Button,
  Video,
  ScrollView,
  Canvas,
} from "@tarojs/components";

import { InstrumentInfo } from "@/utils/Interface";
import { go, back, msg, setStorageSync, getStorageSync } from "@/utils/traoAPI";

import { getImgInfo, contraction } from "@/utils/compressImage";

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

import "./instrument.less";

export default class Instrument extends Component<any, any> {
  constructor(props) {
    super(props);
    this.state = {
      name: "instrument",
      isBindingError: false,
      isBindingCheckError: false,
      style: "font-size: 28rpx; color: #ccc;",
      succeedShow: false,
      tipShow: false,
      loading: true,
      channelList: [],
      channelInfo: {
        id: "",
        serialImage: "",
        serialCode: "",
      },
      equipmentList: [
        {
          id: 1,
          banner: "",
          titile: "测试",
        },
      ],
      isVideo: false,
      inputType: 1, //1.手写 2.扫码绑定
      bindCode: "",
      bindCodeInfo: null,
      bindPopup: "",
      userinfo: null,
      showLoginPopup: "",
      fromUrl: "",
    };
  }

  async onLoad() {
    this.unbindingInstrumentInfoList();
  }
  componentDidMount() {}

  componentWillUnmount() {}

  componentDidShow() {}

  componentDidHide() {}

  async initData() {}

  onSerial = (event) => {
    const { value } = event.detail;
    let { channelInfo } = this.state;
    channelInfo.serialCode = value;

    this.setState({ channelInfo });
  };

  // onScanCode() {
  //   Taro.scanCode({
  //     scanType: ["qrCode"],
  //     success: (res) => {
  //       let { channelInfo } = this.state;
  //       channelInfo.serialCode = res.result;

  //       this.setState({ channelInfo });
  //     },
  //   });
  // }

  onTipShow = () => {
    this.setState({ tipShow: true });
  };

  onTabTap = (type) => {
    this.setState({
      inputType: type,
    });
  };

  onScanTap = () => {
    /*
    // 本地测试
    const result = decodeURIComponent('https%3A%2F%2Fi.flossom.com%2Fa%3Ffr200test12');
    const bindCode = result.split('?')[1];
    that.setData({
        bindCode
    })
    that.getBindCodeInfo();
    return*/
    Taro.scanCode({
      scanType: ["barCode", "qrCode"],
      success: (res) => {
        const result = decodeURIComponent(res.result);
        if (result.indexOf("?") > -1) {
          const bindCode = result.split("?")[1];
          console.log("bindCode", bindCode);
          const { channelInfo } = this.state;
          channelInfo.serialCode = bindCode;
          this.setState({
            channelInfo,
          });
        }

        setTimeout(() => {
          this.scanCodeBinding();
        }, 10);
      },
      fail(err) {},
      complete(res) {},
    });
  };

  // getBindCodeInfo = async () => {
  //   const { bindCode, instrumentList, channelInfo } = this.state;
  //   // // 1.查询资料
  //   // try {
  //   //   const { data } = await InstrumentCodeCheck({
  //   //     code: bindCode,
  //   //   });
  //   //   const bindCodeInfo = { ...data.data.bindCodeInfo };
  //   //   // 2.判断是否是选中的仪器, 如果不是, 直接弹出scanErrorPopup
  //   //   if (channelInfo.id != bindCodeInfo.instrument_id) {
  //   //     this.setState({
  //   //       bindPopup: "scanErrorPopup",
  //   //     });
  //   //     return;
  //   //   }
  //   //   const match = instrumentList.find((item) => {
  //   //     if (item.id == bindCodeInfo.instrument_id && item.serial) {
  //   //       // 找到同一个仪器
  //   //       bindCodeInfo.hadBindSame = true;
  //   //       if (item.serial == bindCodeInfo.antifakeCode) {
  //   //         // 找到同一个序列号
  //   //         bindCodeInfo.hadBindSameCode = true;
  //   //       } else {
  //   //         bindCodeInfo.hadBindSameCode = false;
  //   //       }
  //   //       return item;
  //   //     }
  //   //     if (item.id == bindCodeInfo.instrument_id) {
  //   //       const { channelInfo } = this.state;
  //   //       if (channelInfo.id === item.id) return;
  //   //       this.setState({
  //   //         channelInfo: item,
  //   //         isVideo: isVideo(item.bind_intro_video),
  //   //       });
  //   //     }
  //   //   });
  //   //   if (match) {
  //   //     bindCodeInfo.hadBind = true;
  //   //   } else {
  //   //     bindCodeInfo.hadBindSame = false;
  //   //   }
  //   //   this.setState({
  //   //     bindCodeInfo,
  //   //   });
  //   //   this.judgeBindCode();
  //   // } catch (e) {
  //   //   this.judgeBindCode();
  //   // }
  // };

  // judgeBindCode = () => {
  //   const { bindCode, bindCodeInfo } = this.state;
  //   const opts: any = {};
  //   if (bindCode && !bindCodeInfo) {
  //     // 有仪器码, 但是没有找到信息时
  //     opts.bindPopup = "noFoundPopup";
  //   } else if (bindCode && bindCodeInfo && bindCodeInfo.isLabelCode) {
  //     opts.bindPopup = "labelPopup";
  //   } else if (
  //     bindCode &&
  //     bindCodeInfo.hadBindSame &&
  //     bindCodeInfo.hadBindSameCode
  //   ) {
  //     // 有仪器码, 如果有登录, 判断是绑定了同样的仪器和仪器的序列号是一致 -- 不弹弹窗, 回到首页
  //     opts.bindCode = ""; // 重置bindCode
  //     opts.bindPopup = ""; // 隐藏bindPopup
  //   } else if (
  //     bindCode &&
  //     bindCodeInfo.hadBindSame &&
  //     !bindCodeInfo.hadBindSameCode
  //   ) {
  //     // 有仪器码, 如果有登录, 判断是绑定了同样的仪器, 但仪器的序列号不一致 -- 判断换绑
  //     opts.bindPopup = "switchBindCodePopup";
  //   } else if (bindCode && !bindCodeInfo.hadBindSame) {
  //     // 有仪器码, 如果有登录, 判断不是绑定了同样的仪器 -- 绑定
  //     opts.bindPopup = "toBindPopup";
  //   }
  //   if (Object.keys(opts).length) {
  //     this.setState(opts);
  //   }
  // };

  onCustomerTap = () => {
    this.onCancelBind2Tap();
    go("/pages/consultant/consultant");
  };

  onCancelBind2Tap = () => {
    this.setState({
      bindPopup: "",
      bindCode: "",
    });
  };

  onChangeImg = async () => {
    Taro.chooseMedia({
      count: 1,
      mediaType: ["image"],
      sourceType: ["album", "camera"],
      sizeType: ["compressed"],
      camera: "back",
      success: async (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        let img = await getImgInfo(tempFilePath);
        let compressImage = await contraction(img, "compressImage");
        // 压缩后文件地址
        let compressTempFilePath = compressImage.tempFilePath;
        let { channelInfo } = this.state;
        channelInfo.serialImage = compressTempFilePath;
        this.setState({ channelInfo });
      },
    });
  };

  onSubmit = () => {
    const { serial, serialImage, id } = this.state.channelInfo;
    if (!serial?.trim()) return msg("请输入设备序列号");
    if (!serialImage) return msg("请上传序列号照片");
    this.manualCodeBinding();
  };

  onSelectChange(item) {
    const { channelInfo } = this.state;
    if (channelInfo.id === item.id) return;
    channelInfo.serialCode = "";
    this.setState({
      channelInfo: item,
      isVideo: this.isVideo(item.banner),
    });
  }

  public back = () => {
    back();
  };

  closeDev = () => {
    // go("/pages/user/user");
    let isInstrumentJump = Taro.getStorageSync("isInstrumentJump");
    if (isInstrumentJump === "true") {
      Taro.switchTab({
        url: "/pages/user/user",
      });
    }
  };

  isVideo = (str) => {
    if (str.includes(".mp4")) {
      return true;
    }
    return false;
  };

  // 未绑定列表
  unbindingInstrumentInfoList = async () => {
    let { data } = await InstrumentInfo.unbindingInstrumentInfoList();
    if (data.code === 200) {
      if (data.data.length) {
        let item = data.data[0];
        item.serialCode = "";
        this.setState({
          equipmentList: data.data,
          channelInfo: item,
          isVideo: this.isVideo(item.banner),
        });
      }
    }
  };

  // 绑定仪器
  manualCodeBinding = async () => {
    Taro.showLoading({
      title: "请求中...",
      mask: true,
    });
    let { channelInfo } = this.state;

    let res = await InstrumentInfo.manualCodeBinding({
      serial: channelInfo.serialCode,
      serialImage: channelInfo.serialImage,
      instrumentId: channelInfo.id,
    });
    console.log("bindingInstrument", res);
    Taro.hideLoading();
    if (res.code === 200) {
      this.binding();
    } else if (res.code === 204) {
      this.setState({ isBindingCheckError: false });
    } else {
      this.setState({ isBindingError: true });
    }
  };
  scanCodeBinding = async () => {
    Taro.showLoading({
      title: "请求中...",
      mask: true,
    });
    let { channelInfo } = this.state;
    let res = await InstrumentInfo.scanCodeBinding({
      serial: channelInfo.serialCode,
      instrumentId: channelInfo.id,
    });
    Taro.hideLoading();
    if (res.data.code === 200) {
      // this.setState({ isVisibleBinding: false });
      this.binding();
    } else if (res.data.code === 204) {
      this.setState({ isBindingCheckError: false });
    } else {
      this.setState({ isBindingError: true });
    }
  };

  binding = async () => {
    Taro.showLoading({
      title: "请求中...",
      mask: true,
    });

    let { channelInfo } = this.state;
    let res = await InstrumentInfo.binding({
      serial: channelInfo.serialCode,
    });
    Taro.hideLoading();
    if (res.data.code === 200) {
      // this.setState({ isVisibleBinding: false });
      msg("绑定成功");
      setStorageSync("instrument_item", JSON.stringify(channelInfo));
      go("/pages/instrument/intro?id=" + channelInfo.id);
    } else if (res.data.code === 204) {
      this.setState({ isBindingCheckError: false });
    } else {
      this.setState({ isBindingError: true });
    }
  };
  onBindErrorClose = () => {
    this.setState({ isBindingError: false });
  };
  onBindErrorConfirm = () => {
    this.onBindErrorClose();
    go("/pages/consultant/consultant");
  };

  onBindCheckErrorClose = () => {
    this.setState({ isBindingCheckError: false });
  };

  render() {
    let {
      isBindingError,
      isBindingCheckError,
      channelInfo,
      inputType,
      style,
      equipmentList,
    } = this.state;
    return (
      <Block>
        {/* <PopupAlert
          isShow={true}
          isClose={true}
          title="提示"
          content="页面正在开发中"
          confirmButtonText="确定"
          textAlgin="center"
          close={this.closeDev}
          confirm={this.closeDev}
        /> */}
        <Navbar titleSlot="仪器绑定" isBack={true} />
        <PopupAlert
          isShow={isBindingError}
          title="提示"
          content="序列号库仍在更新，请联系微信助手"
          confirmButtonText="知道了"
          textAlgin="center"
          isClose={false}
          close={this.onBindErrorClose}
          confirm={this.onBindErrorClose}
        ></PopupAlert>
        <PopupAlert
          isShow={isBindingCheckError}
          title="提示"
          content="您选择的仪器有误，请重新选择确认"
          confirmButtonText="知道了"
          textAlgin="center"
          isClose={false}
          close={this.onBindCheckErrorClose}
          confirm={this.onBindCheckErrorClose}
        ></PopupAlert>
        <Canvas
          style="height: 0"
          id="compressImage"
          canvasId="compressImage"
          type="2d"
        ></Canvas>

        <View></View>
        <View className="main">
          <View className="top">
            <View className="top_title">仪器绑定</View>
            <View className="top_tips">
              请参考图片指引，扫描或输入产品序列号
            </View>
            <View className="top_tips">完成花至美容仪绑定</View>
          </View>
          <View className="banner_list">
            {inputType === 1 ? (
              <Video
                className="banner_item"
                autoplay
                objectFit="cover"
                enablePlayGesture
                showFullscreenBtn={false}
                playBtnPosition="center"
                src={channelInfo.manualCodeBinding}
              />
            ) : (
              <Image
                className="banner_item"
                src={channelInfo.scanCodeBinding}
                mode="aspectFill"
              ></Image>
            )}
          </View>
          <View className="form">
            <View className="form_item is-instrument">
              <View className="label_box">
                <View
                  className="label"
                  style="font-size: 32rpx; margin: 0 0 0rpx 2rpx"
                >
                  需要绑定的仪器
                  <Text style={{ color: "#EB5858", marginLeft: "20rpx" }}>
                    *
                  </Text>
                </View>
              </View>

              <ScrollView
                scrollX={true}
                className="instrument_list"
                style="width: 100%; white-space: nowrap;"
                scrollIntoView={"scroll" + channelInfo.id}
              >
                {equipmentList.map((item, index) => {
                  return (
                    <View
                      className={classnames("cover", {
                        active_cover: channelInfo.id === item.id,
                      })}
                      id={"scroll" + item.id}
                      key={index}
                      onClick={this.onSelectChange.bind(this, item)}
                    >
                      <Image
                        className="instrument_img"
                        src={item.banner}
                        mode="aspectFill"
                        // mode="aspectFit"
                      ></Image>
                      <View className="desc">{item.name}</View>
                    </View>
                  );
                })}
              </ScrollView>
            </View>
            <View className="form_item is-tab">
              <View className="tab_list">
                <View
                  className={classnames("tab_item", {
                    "is-active": inputType === 1,
                  })}
                  onClick={this.onTabTap.bind(this, 1)}
                >
                  <Text>手写输入绑定</Text>
                  <View className="tab_active_line"></View>
                </View>
                {channelInfo.isScanCode === 1 && (
                  <View
                    className={classnames("tab_item", {
                      "is-active": inputType === 2,
                    })}
                    onClick={this.onTabTap.bind(this, 2)}
                  >
                    <Text>扫码绑定</Text>
                    <View className="tab_active_line"></View>
                  </View>
                )}
              </View>
            </View>

            {inputType == 1 && (
              <Block>
                <View className="inputCode_box">
                  <View className="form_item is-inputCode">
                    <View className="label_box">
                      <View className="label">
                        填写序列号
                        <Text style={{ color: "#EB5858", marginLeft: "20rpx" }}>
                          *
                        </Text>
                      </View>
                      <View className="label_text" onClick={this.onTipShow}>
                        <Text className="label-tips">查看序列号位置</Text>
                        <Image
                          className="right_icon"
                          src={require("../../img/index-right.png")}
                          mode="aspectFill"
                        />
                      </View>
                    </View>
                    <View className="ipt_box">
                      <Input
                        maxlength={50}
                        className="ipt"
                        placeholder="例如：FR10*********1"
                        placeholder-style={style}
                        onInput={this.onSerial}
                        value={channelInfo.serialCode}
                      ></Input>
                    </View>
                  </View>
                  <View className="form_item">
                    <View className="label_box">
                      <View className="label">
                        上传序列号照片
                        <Text style={{ color: "#EB5858", marginLeft: "20rpx" }}>
                          *
                        </Text>
                      </View>
                    </View>
                    <View className="photo_box" onClick={this.onChangeImg}>
                      {channelInfo.serialImage && (
                        <Image
                          src={channelInfo.serialImage}
                          mode="aspectFill"
                        ></Image>
                      )}
                      {!channelInfo.serialImage && (
                        <Image
                          className="add"
                          src={require("../../img/welcome/add.png")}
                          mode="aspectFit"
                        ></Image>
                      )}
                    </View>
                  </View>
                </View>
              </Block>
            )}
          </View>
        </View>
        <View className="footer">
          {inputType == 1 && (
            <View className="btn" onClick={this.onSubmit}>
              确认绑定
            </View>
          )}

          {inputType == 2 && (
            <View className="btn footer-btn-scan" onClick={this.onScanTap}>
              <Image
                className="footer-btn-scan-img"
                src={require("../../img/icon-scan.png")}
              ></Image>
              扫码绑定
            </View>
          )}
        </View>
      </Block>
    );
  }
}
