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, loading, msg, showModal } from "../../utils/traoAPI";
import { isVideo } from "../../utils/util";
import utilHtml from "../../utils/utilhtml";

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: "",
        image: "",
        serial: "",
        bind_intro_Video: "",
      },
      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.serial = value;

    this.setState({ channelInfo });
  };

  onScanCode() {
    Taro.scanCode({
      scanType: ["qrCode"],
      success: (res) => {
        let { channelInfo } = this.state;
        channelInfo.serial = 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);
          this.setState({
            bindCode,
          });
        }

        this.bindingInstrument();
        // this.getBindCodeInfo();
      },
      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"],
      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.image = compressTempFilePath;
        this.setState({ channelInfo });
      },
    });
  };

  onSubmit = () => {
    const that = this;
    const { serial, image, buy_id, id } = this.state.channelInfo;
    if (!serial?.trim()) return msg("请输入设备序列号");
    if (!image) return msg("请上传序列号照片");
    // if (!buy_id) return msg('请选择购买渠道');
    // loading("绑定中");
    // InstrumentBindingAdd({ serial, image, buy_id, instrument_id: id })
    //   .then((res) => {
    //     this.setState({ succeedShow: true });
    //   })
    //   .catch((err) => {
    //     if (err.data.code != 400) {
    //       that.setState({
    //         errorMsg: err.data.msg,
    //         bindPopup: "errorMsg",
    //       });
    //     }
    //   });
  };

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

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

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

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

  // 绑定仪器
  bindingInstrument = async () => {
    Taro.showLoading({
      title: "请求中...",
      mask: true,
    });
    let { instrumentInfo } = this.state;
    let { data } = await InstrumentInfo.binding({
      serial: instrumentInfo.serial,
    });
    console.log("bindingInstrument", data);
    Taro.hideLoading();
    if (data.code === 200) {
      // this.setState({ isVisibleBinding: false });
      msg("绑定成功");
    } 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,
      isVideo,
      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">
            {isVideo && channelInfo.bind_intro_Video ? (
              <Video
                className="banner_item"
                autoplay
                objectFit="cover"
                enablePlayGesture
                showFullscreenBtn={false}
                playBtnPosition="center"
                src={utilHtml.getHttpsUrl(channelInfo.bind_intro_Video)}
              />
            ) : (
              <Image
                className="banner_item"
                src={utilHtml.getHttpsUrl(channelInfo.bind_intro_Video)}
                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"
                >
                  需要绑定的仪器
                </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={utilHtml.getHttpsUrl(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>
                <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">填写序列号</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.serial}
                      ></Input>
                    </View>
                  </View>
                  <View className="form_item">
                    <View className="label_box">
                      <View className="label">上传序列号照片</View>
                    </View>
                    <View className="photo_box" onClick={this.onChangeImg}>
                      {channelInfo.image && (
                        <Image
                          src={channelInfo.image}
                          mode="aspectFill"
                        ></Image>
                      )}
                      {!channelInfo.image && (
                        <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>
    );
  }
}
