import { Component } from "react";
import { View, Text, Image } from "@tarojs/components";
import { AtInput } from "taro-ui";
import "./index.less";
import aliPayIcon from "../../../images/aliPayIcon.png";
import { get_my_worker_info, worker_register, card_ocr } from "../../../service/money_api";
import Taro from '@tarojs/taro';


export default class Index extends Component {
  state = {
    name: "", // 账户姓名
    account: "", // 支付宝账户
    phone: "", // 手机号
    idCard: "", // 身份证号
    bankCard: "", // 银行卡号
    idCardFront: "https://video-img.fyshark.com/1735011631991upload-background-front.11d37038.png", // 身份证正面
    idCardBack: "https://video-img.fyshark.com/1735011647149upload-background-back.5b42ae0e.png", // 身份证反面
    type: "bank", // 类型
    phoneError: false, // 手机号格式错误标志
    isLoading: false, // 是否加载中
    isAlipay: false, // 是否已绑定支付宝
    isBank: false, // 是否已绑定银行卡
    signImg: "https://video-img.fyshark.com/1735033624483%E5%B7%B2%E7%AD%BE%E7%BA%A6.png", // 签约码
  };

  componentDidMount () {
    this.getWorkerInfo(); // 页面加载时请求签约信息
  }

  // 获取签约信息
  getWorkerInfo = async () => {
    const res = await get_my_worker_info();
    if (res.data.length > 0) {
      res.data.forEach(item => {
        if (item.rsv_account_type === 1) {
          this.setState({
            name: item.name,
            idCard: item.card_no,
            phone: item.phone,
            idCardFront: item.portrait_page,
            idCardBack: item.national_emblem_page,
            account: item.bank_no,
            isAlipay: true
          });
        } else {
          this.setState({
            name: item.name,
            idCard: item.card_no,
            phone: item.phone,
            idCardFront: item.portrait_page,
            idCardBack: item.national_emblem_page,
            bankCard: item.bank_no,
            isBank: true
          });
        }
      });
    }
    console.log(res, 'res');
  }
  // 账户姓名
  handleChangeName (value) {
    this.setState({ name: value });
  }
  // 支付宝账户
  handleChangeAccount (value) {
    this.setState({ account: value });
  }
  // 手机号
  handleChangePhone (value) {
    this.setState({ phone: value });
  }
  // 身份证号
  handleChangeIdCard (value) {
    this.setState({ idCard: value });
  }
  // 银行卡号
  handleChangeBankCard (value) {
    this.setState({ bankCard: value });
  }



  handleChooseImage (type) {
    if (this.isBind()) return;
    Taro.chooseImage({
      count: 1, // 选择一张图片
      sizeType: ['compressed'], // 可以指定是原图还是压缩图
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机
      success: (res) => {
        const filePath = res.tempFilePaths[0];
        Taro.showLoading({
          title: '上传中...',
          mask: true
        });
        Taro.uploadFile({
          url: 'https://api.yushixcx.com/money/upload', // 上传接口地址
          filePath: filePath,
          name: 'file',
          header: {
            'accept': 'application/json',
            'Content-Type': 'multipart/form-data'
          },
          formData: {
            'type': 'image/png' // 根据需要设置文件类型
          },
          success: async (uploadRes) => {
            const data = JSON.parse(uploadRes.data);
            if (type === 'front') {
              this.setState({ idCardFront: data.url });
              let that = this;
              await card_ocr({
                img_url: data.url
              }).then(res => {
                console.log(res, 'res111');
                let info = JSON.parse(res.data);
                that.setState({ idCard: info.card_no, name: info.name });
              })
            } else if (type === 'back') {
              this.setState({ idCardBack: data.url });
            }
            // 隐藏加载提示
            Taro.hideLoading();
          }

        });
      }
    });
  }
  // 提交
  handleSubmit () {
    const { name, account, phone, idCard, bankCard, idCardFront, idCardBack, type, phoneError } = this.state;
    const defaultFront = "https://video-img.fyshark.com/1735011631991upload-background-front.11d37038.png";
    const defaultBack = "https://video-img.fyshark.com/1735011647149upload-background-back.5b42ae0e.png";
    switch (true) {
      case name.length === 0:
        Taro.showToast({
          title: '请填写账户姓名',
          icon: 'none',
          duration: 2000
        });
        return;
      case phone.length === 0 || phoneError:
        Taro.showToast({
          title: phone.length === 0 ? '请填写手机号' : phoneError ? '手机号格式错误' : '请填写手机号',
          icon: 'none',
          duration: 2000
        });
        return;
      case idCard.length === 0:
        Taro.showToast({
          title: '请填写身份证号',
          icon: 'none',
          duration: 2000
        });
        return;
      case type === 'alipay' && account.length === 0:
        Taro.showToast({
          title: '请填写支付宝账户',
          icon: 'none',
          duration: 2000
        });
        return;
      case type === 'bank' && bankCard.length === 0:
        Taro.showToast({
          title: '请填写银行卡号',
          icon: 'none',
          duration: 2000
        });
        return;
      case idCardFront === defaultFront || idCardBack === defaultBack:
        Taro.showToast({
          title: '请上传身份证照片',
          icon: 'none',
          duration: 2000
        });
        return;
    }
    Taro.showLoading({
      title: '签约中...',
      mask: true
    });
    worker_register({
      name,
      card_no: idCard,
      bank_no: type === 'alipay' ? account : bankCard,
      phone,
      rsv_account_type: type === 'alipay' ? "1" : "0",
      portrait_page: idCardFront,
      national_emblem_page: idCardBack
    }).then(res => {
      console.log(res, 'res');
      if (res.code === 200) {
        this.getWorkerInfo()
        Taro.showToast({
          title: '签约成功',
          icon: 'success',
          mask: true,
          duration: 2000
        });
      } else {
        Taro.showToast({
          title: `签约失败:${res.msg}`,
          icon: 'none',
          mask: true,
          duration: 3000
        });
      }
    }).finally(() => {
      Taro.hideLoading();
    })
  }

  // 选择类型
  handleChooseType (type) {
    this.setState({ type });
  }

  // 手机号
  handleBlurPhone (value) {
    const phonePattern = /^1[3-9]\d{9}$/; // 简单的中国大陆手机号验证
    if (phonePattern.test(value)) {
      this.setState({ phoneError: false });
    } else {
      this.setState({ phoneError: true });
    }
  }
  // 是否已绑定
  isBind () {
    return (this.state.isAlipay && this.state.type === 'alipay') || (this.state.isBank && this.state.type === 'bank')
  }
  render () {
    return (
      <View className="index">
        {/* 支付宝信息 */}

        <View className="alipay-info">
          <View className="alipay-info-item">
            <View className="type-box">
              {/* <View className={["type-title", this.state.type === 'alipay' ? 'active' : '']} onClick={() => this.handleChooseType('alipay')}>支付宝</View> */}
              <View className={["type-title", this.state.type === 'bank' ? 'active' : '']} onClick={() => this.handleChooseType('bank')}>银行卡</View>
            </View>
          </View>
          <View className="upload-box">
            <View className="upload-title" style={{ color: this.isBind() ? '#999' : '#333' }}>请上传身份证照片</View>
            <View className="upload-image">
              <View className="upload-image-item" onClick={() => this.handleChooseImage('front')}>
                <Image src={this.state.idCardFront} className="upload-image-item-image" />
              </View>
              <View className="upload-image-item" onClick={() => this.handleChooseImage('back')}>
                <Image src={this.state.idCardBack} className="upload-image-item-image" />
              </View>
            </View>
          </View>

          <AtInput
            name="value"
            title="账户姓名"
            type="text"
            disabled={this.isBind()}
            placeholder="请输入账户姓名"
            value={this.state.name}
            onChange={this.handleChangeName.bind(this)}
          />
          <AtInput
            name="value"
            title="身份证号"
            disabled={this.isBind()}
            type="text"
            placeholder="请输入身份证号"
            value={this.state.idCard}
            onChange={this.handleChangeIdCard.bind(this)}
          />
          <AtInput
            name="value"
            title="手机号"
            disabled={this.isBind()}
            type='phone'
            placeholder="请输入手机号"
            value={this.state.phone}
            onChange={this.handleChangePhone.bind(this)}
            onBlur={this.handleBlurPhone.bind(this)}
            error={this.state.phoneError}
            errorMessage={this.state.phoneError ? '请输入正确的手机号' : ''}
          />
          {
            this.state.type === 'bank' && (
              <AtInput
                name="value"
                disabled={this.isBind()}
                title="银行卡号"
                type="text"
                placeholder="请输入银行卡号"
                value={this.state.bankCard}
                onChange={this.handleChangeBankCard.bind(this)}
              />
            )
          }
          {
            this.state.type === 'alipay' && (
              <AtInput
                border={false}
                disabled={this.isBind()}
                name="value"
                title="支付宝账户"
                type="text"
                placeholder="请输入支付宝账户"
                value={this.state.account}
                onChange={this.handleChangeAccount.bind(this)}
              />
            )
          }
        </View>
        {
          this.isBind() &&
          <View className="alipay-info-tips">
            <View className="alipay-info-tips-item">
              <Image src={this.state.signImg} className="alipay-info-tips-item-icon" />
              <View className="alipay-info-tips-item-text">
                如需更改，请联系客服
              </View>
            </View>
          </View>
        }
        {/* 注意 */}
        {
          !this.isBind() && (
            <View className="attention">
              <View className="attention-top">
                <Image src={aliPayIcon} className="attention-icon" />
                注意：
              </View>
              <View className="attention-bottom">
                所维护的信息需要与提现认证提交的自然人为同一人，非同一人会提现失败
              </View>
            </View>
          )
        }
        {/* 提交 */}
        {
          !this.isBind() &&
          <View className="submit" onClick={this.handleSubmit.bind(this)}>提交</View>
        }
        {
          !this.isBind() &&
          <View className="submit" onClick={this.handleSubmit.bind(this)}>提交</View>
        }
      </View>
    );
  }
}
