import React, { Component, createRef } from "react";
import { View, Picker, Image, Text } from "@tarojs/components";
import { AtTabs, AtCheckbox } from "taro-ui";
import Taro from "@tarojs/taro";
import "./index.less";
import {
  getMyShopList,
  deleteShopProduct,
  updateProductSort,
  getAllTags,
} from "../../../service";
import { getShareContent } from "../../../common/share";
import ProductList from "../../../components/index/ProductList"; //商品列表
import add from "../../../images/productManagement/add.png";
import back from "../../../images/productManagement/back.png";
import manger from "../../../images/productManagement/manger.png";
import selectIcon from "../../../images/productManagement/selectIcon.png";
import deleteIcon from "../../../images/productManagement/delete.png";
import toTop from "../../../images/productManagement/toTop.png";
export default class Index extends Component {
  childComponentRef = React.createRef(); // 创建 ref
  state = {
    isManagementStatus: false, //是否是管理状态
    current: 0, //tabs坐标
    isSelectAll: false, //是否全选
    selectedOption: "", //商品默认名称
    tabList: [{ title: "在售中 (0)" }], //tabs标题
    options: [""], //商品下拉选项
    checkedList: [""], //全选
    checkboxOption: [
      {
        value: "allValue",
        label: "全选",
      },
    ], //全选
    productList: [], // 商品列表
    page: 1, //页数
    loading: false, //加载状态
    totalPages: 1, // 添加总页数
    selectedProducts: [], // 删除商品选中id数组
    tags: [], // 所有闲鱼tags
    isNoMore: false, // 是否没有更多
  };
  componentDidShow() {
    this.getAllTags();
  }
  // 获取所有闲鱼tags
  getAllTags = async () => {
    const res = await getAllTags();
    const arr = Object.values(res).map((item) => item.name);
    this.setState(
      {
        options: arr,
        selectedOption: res[0].name,
      },
      () => {
        this.getMyShopList(true);
      }
    );
  };
  // 获取商品列表
  getMyShopList = async (isDelete) => {
    const { page } = this.state;
    this.setState({ loading: true });

    const res = await getMyShopList({
      tag_name: this.state.selectedOption,
      page,
      page_size: 10,
    });

    this.setState(
      (prevState) => ({
        productList: isDelete
          ? res.goods_list
          : [...prevState.productList, ...res.goods_list],
        totalPages: res.total_pages,
        loading: false,
        isNoMore: res.total_pages <= page,
      }),
      () => {
        this.setState((prevState) => ({
          tabList: [{ title: `在售中 (${res.total_count})` }],
        }));
      }
    );
  };
  // 商品下拉选项
  handleSelectOption = (e) => {
    const selectedOption = this.state.options[e.detail.value];
    this.setState({ selectedOption, page: 1, isNoMore: false }, () => {
      Taro.pageScrollTo({
        scrollTop: 0,
        duration: 300,
      });
      this.getMyShopList(true);
    });
  };
  // 切换管理状态
  changeManagement = (type) => {
    if (type === "management") {
      this.setState({
        isManagementStatus: true,
      });
    } else {
      this.setState(
        {
          isManagementStatus: false,
          isSelectAll: false, // 重置全选状态
          checkedList: [], // 重置选中状态
        },
        () => {
          // 在清空后通过回调清除子组件中的选中状态
          this.childComponentRef.current.clearSelectedItems();
        }
      );
    }
  };
  // 全选
  handleChange(value) {
    this.setState({
      checkedList: value,
      isSelectAll: !this.state.isSelectAll,
    });
  }
  // 删除商品
  onDeleteProduct = async () => {
    if (this.state.selectedProducts.length == 0) {
      Taro.showToast({
        title: "请选择商品",
        icon: "none",
      });
      return;
    }
    const res = await deleteShopProduct({
      goods_ids: this.state.selectedProducts,
    });
    if (res.success == true) {
      this.setState(
        (prevState) => ({
          productList: prevState.productList.filter(
            (item) => !this.state.selectedProducts.includes(item.id)
          ),
          isSelectAll: false, // 重置全选状态
          checkedList: [], // 重置选中状态
        }),
        () => {
          // 在清空后通过回调清除子组件中的选中状态
          this.childComponentRef.current.clearSelectedItems();
          this.setState((prevState) => ({
            tabList: [{ title: `在售中 (${prevState.productList.length})` }],
          }));
        }
      );
      Taro.showToast({
        title: "删除成功",
        icon: "none",
      });
    }
  };
  // 更新商品排序
  updateProductSort = async () => {
    if (this.state.selectedProducts.length === 0) {
      Taro.showToast({
        title: "请选择商品",
        icon: "none",
      });
      return;
    } else if (this.state.selectedProducts.length > 1) {
      Taro.showToast({
        title: "只能选择一个商品",
        icon: "none",
      });
      return;
    }
    const res = await updateProductSort({
      goods_id: this.state.selectedProducts.join(","),
    });

    if (res.success === "排序完成") {
      this.setState(
        (prevState) => {
          // 从 productList 中移除选中的商品
          const remainingProducts = prevState.productList.filter(
            (item) => !this.state.selectedProducts.includes(item.id)
          );
          // 将选中的商品添加到列表的开头
          const sortedProducts = this.state.selectedProducts.map((id) =>
            prevState.productList.find((item) => item.id === id)
          );
          return {
            productList: [...sortedProducts, ...remainingProducts],
            selectedProducts: [],
          };
        },
        () => {
          // 在清空后通过回调清除子组件中的选中状态
          this.childComponentRef.current.clearSelectedItems();
        }
      );

      Taro.showToast({
        title: "排序完成",
        icon: "none",
      });
    }
  };
  // 配置分享内容
  onShareAppMessage() {
    return getShareContent();
  }
  // 页面上拉触底
  onReachBottom = () => {
    const { page, totalPages, loading } = this.state;
    if (page < totalPages && !loading) {
      this.setState(
        (prevState) => ({ page: prevState.page + 1 }),
        () => this.getMyShopList()
      );
    }
  };
  // 添加处理选中商品的方法
  onDeleteProductSelect = (selectedProducts) => {
    // 可以将选中的商品保存到父组件的状态中
    this.setState({ selectedProducts });
  };
  render() {
    return (
      <View
        className={`index ${
          this.state.isManagementStatus ? "management-active" : ""
        }`}
      >
        {/* tab分类 */}
        <View className="tabs-list">
          <AtTabs
            tabList={this.state.tabList}
            current={this.state.current}
            scroll
          ></AtTabs>
          {/* 内容 */}
          <View className="tabs-content">
            {/* 商品下拉分类 */}
            <View className="product-category">
              <Picker
                mode="selector"
                range={this.state.options}
                onChange={this.handleSelectOption}
              >
                <View className="product-category-left">
                  {this.state.selectedOption}
                  <Image
                    className="selectIcon"
                    src={selectIcon}
                    mode="aspectFit"
                  />
                </View>
              </Picker>
              <View className="product-category-right">
                前6款商品将推荐给直属会员
              </View>
            </View>
            {/* 商品列表 */}
            {this.state.productList && (
              <ProductList
                ref={this.childComponentRef} // 将 ref 传递给子组件
                productList={this.state.productList}
                isSelectAll={this.state.isSelectAll}
                isManagement={true}
                isManagementStatus={this.state.isManagementStatus}
                loading={this.state.loading}
                onDeleteProductSelect={this.onDeleteProductSelect}
                isNoMore={this.state.isNoMore}
              />
            )}
          </View>
        </View>
        {/* 底部购买模块 */}
        {!this.state.isManagementStatus ? (
          <View className="bottom-buy">
            <View
              onClick={() => Taro.navigateBack()}
              className="bottom-buy-left"
            >
              <Image src={back} mode="aspectFit" />
              <Text className="bottom-buy-text">返回店铺</Text>
            </View>
            <View className="bottom-buy-right">
              <View
                onClick={() => this.changeManagement("management")}
                className="bottom-buy-right-self"
              >
                <Image src={manger} mode="aspectFit" />
                <Text className="bottom-buy-text">批量管理</Text>
              </View>
              <View
                onClick={() =>
                  Taro.navigateTo({
                    url: "/pages/memberSub/productClassify/index",
                  })
                }
                className="bottom-buy-right-share"
              >
                <Image src={add} mode="aspectFit" />
                <Text className="bottom-buy-text">添加商品</Text>
              </View>
            </View>
          </View>
        ) : (
          <View className="operation-product">
            <View className="operation-product-top">
              <View className="left">
                <AtCheckbox
                  options={this.state.checkboxOption}
                  selectedList={this.state.checkedList}
                  onChange={this.handleChange.bind(this)}
                />
              </View>
              <View className="right">
                <View className="item" onClick={this.updateProductSort}>
                  <Image src={toTop} mode="aspectFit" />
                  <Text>移至顶部</Text>
                </View>
                <View onClick={this.onDeleteProduct} className="item">
                  <Image src={deleteIcon} mode="aspectFit" />
                  <Text>删除</Text>
                </View>
              </View>
            </View>
            <View
              onClick={() => this.changeManagement("finish")}
              className="operation-product-bottom"
            >
              完成
            </View>
          </View>
        )}
      </View>
    );
  }
}
