import { Component } from "react";
import { View, Text, Image, Input } from "@tarojs/components";
import { AtDivider, AtIcon, AtActivityIndicator } from "taro-ui";
import "./index.less";
import vip from "../../../images/earningsOrder/vip.png";
import Taro from "@tarojs/taro";
import { getEarningsOrderTab, getEarningsOrderList } from "../../../service";

export default class Index extends Component {
  state = {
    current: 0,
    orderType: 2,//默认为推广订单
    value: "", //搜索值
    tabList: [{ title: "全部" }],
    page: 1, //页数
    loading: false, //加载状态
    totalPages: 1, // 添加总页数
    isNoMore: false,
    orderList: [],//订单列表
    userInfo: {},//个人信息
  };
  componentDidShow() {
    const { router } = Taro.getCurrentInstance();
    const params = router.params;
    this.setState({
      orderType: params.type||2,
    },()=>{
      this.getEarningsOrderTab();
    });
  }
  // 获取个人信息
  getUserInfo = async () => {
    const res = await getUserInfo();
    this.setState({ userInfo: res });
  }
  // 获取收益订单列表
  getEarningsOrderList = async (isRefresh) => {
    const { page } = this.state;
    this.setState({ loading: true });

    const res = await getEarningsOrderList({
      tab_name: this.state.tabList[this.state.current].title,
      page,
      page_size: 10,
      search_name: this.state.value,
      user_type:this.state.orderType
    });

    this.setState(
      (prevState) => ({
        orderList: isRefresh
          ? res.income_list
          : [...prevState.orderList, ...res.income_list],
        totalPages: res.total_pages,
        loading: false,
        isNoMore: res.total_pages <= page,
      }));
  };
  // 获取收益订单tab
  getEarningsOrderTab = async () => {
    const res = await getEarningsOrderTab();
    const newTabList = res.tabs.map((item) => ({
      title: item,
    }));
    this.setState({
      tabList: newTabList,
    },()=>{
      this.getEarningsOrderList(true);
    });
  };
  // 订单类型切换
  handleOrderTypeClick = (type) => {
    this.setState({ orderType: type, page: 1, value: '' },()=>{
      this.getEarningsOrderList(true);
    });
  };
  // tab切换
  handleTabClick = (index) => {
    this.setState({ current: index, page: 1, value: '' },()=>{
      this.getEarningsOrderList(true);
    });
  };
  // 输入
  handleChange = (e) => {
    const value = e.detail.value;
    this.setState({ value });
  };
  // 搜索
  handleSearch = () => {
    this.getEarningsOrderList(true);
  };
  // 复制
  handleCopy = async (text) => {
    try {
      await Taro.setClipboardData({
        data: text,
      });
      Taro.showToast({
        title: "内容已复制",
        icon: "success",
        duration: 2000,
      });
    } catch (error) {
      Taro.showToast({
        title: "复制失败",
        icon: "error",
        duration: 2000,
      });
    }
  };
  // 页面上拉触底
  onReachBottom = () => {
    const { page, totalPages, loading } = this.state;
    if (page < totalPages && !loading) {
      this.setState(
        (prevState) => ({ page: prevState.page + 1 }),
        () => this.getEarningsOrderList()
      );
    }
  };
  render() {
    const { current, tabList, value, orderList, loading, isNoMore, orderType } = this.state;
    return (
      <View className="index">
        {/* 订单类型切换 */}
        <View className="order-type-switch">
          <View className={`order-type-item ${orderType == 2 ? "active" : ""}`} onClick={() => this.handleOrderTypeClick(2)}>
            <Text>推广订单</Text>
          </View>
          <View className={`order-type-item ${orderType == 1 ? "active" : ""}`} onClick={() => this.handleOrderTypeClick(1)}>
            <Text>购买订单</Text>
          </View>
        </View>
        {/* tab切换 */}
        <View className="tab-container">
          {tabList.map((tab, index) => (
            <View
              key={index}
              className={`tab-item ${current === index ? "active" : ""}`}
              onClick={() => this.handleTabClick(index)}
            >
              <Text>{tab.title}</Text>
              {/* {tab.num > 0 && <Text className="tag">{tab.num}</Text>} */}
            </View>
          ))}
        </View>
        {/* 搜索 */}
        <View className="search-container">
          <View className="search-bar">
            <AtIcon
              className="search-icon"
              value="search"
              size="20"
              color="#ACACAC"
            ></AtIcon>
            <Input
              type="text"
              className="search-input"
              placeholder=""
              value={value}
              onInput={this.handleChange}
            />
            <View onClick={this.handleSearch} className="search-button">
              搜索
            </View>
          </View>
        </View>
        {/* 订单列表 */}
        <View className="order-list">
          {orderList.map((item, index) => (
            <View className="order-item" key={index}>
              {/* 头部信息 */}
              {/* <View className="order-header">
              <View className="user-info">
                <Image className="avatar" src="" />
                <Text className="username">张三</Text>
              </View>
              <Text className="pay-status">{item.state_text}</Text>
            </View> */}
            {/* 订单信息 */}
            <View className="order-info">
              <View className="order-details">
                <View className="detail-item">
                  <Text className="label">订单编号:</Text>
                  <Text className="value">{item.order_number}</Text>
                  <Text
                    className="copy-text"
                    onClick={() => this.handleCopy(item.order_number)}
                  >
                    复制
                  </Text>
                </View>
                <View className="detail-item">
                  <Text className="label">下单时间:</Text>
                  <Text className="value">{item.pay_time}</Text>
                </View>
              </View>
              {/* <View className="member-info">
                <Image className="member-icon" src={vip} />
                <Text className="member-text">闲鱼会员</Text>
              </View> */}
            </View>

            {/* 产品信息 */}
            <View className="product-info">
              <Image mode="aspectFill" className="product-image" src={item.item_pic_url} />
              <View className="product-details">
                <Text className="product-name">
                  {item.item_title}
                </Text>
                {orderType == 2 && (
                  <View className="promotion-info">
                    <View className="tag">推广收入</View>
                    <Text className="amount">¥{item.assess_amount_text}</Text>
                  </View>
                )}
                <View className="payment-info">
                </View>
                <View className="payment-info">
                  <Text className="label">实付金额:</Text>
                  <Text className="amount">¥{item.actual_paid_fee}</Text>
                </View>
                </View>
              </View>
            </View>
          ))}
        </View>
        {/* 加载中 */}
        {loading && (
          <View className="loading">
            <AtActivityIndicator
              content="加载中..."
              isOpened={loading}
              mode="center"
              color="#fdf764"
            />
          </View>
        )}
        {/* 没有更多 */}
        {isNoMore && (
          <View className="no-more">
            <AtDivider fontSize={18} fontColor="#949494" content="我是有底线的" />
          </View>
        )}
      </View>
    );
  }
}

