import React, { useState, useRef } from "react";
import Taro, { useDidShow } from "@tarojs/taro";
import "./index.scss";
import { View, Text, Input, Image } from "@tarojs/components";
import Tab from "../../compents/tab/index";
import Tags from "../../compents/tags/index";
import request, { uploadFiles } from "../../util/request";
import uploadicon from "../../assets/uploadicon.png";
import IsLogin from "../../layout/IsLogin";
import "taro-ui/dist/style/components/flex.scss";

const batchimport = props => {
  const [pageState, setPageState] = useState("1");
  const [labelList, setLabelList] = useState([]);
  const [imgUrl, setImgUrl] = useState([]);
  const [tagList, setTagList] = useState([]);

  let [arrList, setArrList] = useState({});
  useDidShow(() => {
    getMateTagGroupList();
  });

  const getMateTagGroupList = () => {
    request({
      url: "/taMateTagGroup",
      params: { pageSize: 1, pageSize: 9999 }
    }).then(res => {
      const { records, ...page } = res.data.data;
      setTagList(records);
    });
  };

  const onSave = e => {
    let data = [];

    imgUrl.map(item => {
      labelList.map(x => {
        data.push({ tagId: x.tagId, imageId: item.imageId });
      });
    });

    request({ url: "/taMetaImageTag", data: data, method: "post" }).then(
      res => {
        Taro.showModal({
          title: "上传成功",
          content: "点击确认按钮，返回上级菜单",
          showCancel: false,
          success: function(res) {
            setImgUrl([])
            setPageState("1")
          }
        });
      }
    );
  };

  const onLabelChange = (e, index) => {
    console.log(e, index, "onLabelChange");
    let newArrArrList = {
      ...arrList,
      [index]: e
    };
    setArrList(newArrArrList);
    console.log(newArrArrList, "arrList");
    let newArr = Object.values(newArrArrList).reduce((pre, cur) => {
      return pre.concat(cur);
    }, []);
    setLabelList(newArr);
  };

  const onUpImage = () => {
    Taro.chooseImage({
      sourceType: ["album"],
      count: 9,
      success: res => {
        const tempFilePaths = res.tempFilePaths;

        Taro.showLoading({title: '请稍候...'})

        uploadFiles(tempFilePaths, "/api/mp/taMetaImage").then(res1 => {
          setImgUrl(imgUrl.concat(res1));
          Taro.hideLoading()
        }).catch(err => Taro.hideLoading());
      }
    });
  };

  const handleImageDelete = row => {
    Taro.showModal({
      content: '确认删除当前图片?',
      success: res => {
        if (res.confirm) {
          setImgUrl(imgUrl.filter(x => x.imageId !== row.imageId))
        }
      }
    })
  }

  return (
    <IsLogin>
      <View className="batchimport">
        <View style={{ display: pageState == "1" ? "none" : "block" }}>
          <Text>标签</Text>
          <View style={{ padding: "0 20px" }}>
            <View
              className="at-row  at-row--wrap at-row__justify--center"
              style={{ marginTop: "0.15rem" }}
            >
              {labelList.map(item => {
                return (
                  <View className="at-col at-col-4" key={item.name}>
                    <View className="tags-btn">{item.name}</View>
                  </View>
                );
              })}
              {/* <View className='at-col at-col-4 ' >
                        <View className='tags-btn tags-btn-on' onClick={() => setPageState('1')} >添加</View>
                    </View> */}
            </View>
          </View>

          <Text>照片</Text>
          <View>
            {imgUrl.length === 0 && (
              <Image
                className="guide-view-img"
                style={{ width: "10%", height: "100%" }}
                onClick={() => onUpImage()}
                src={uploadicon}
              ></Image>
            )}
            {imgUrl.length > 0 && (
              <View className="at-row at-row--wrap">
                {imgUrl.map(x => {
                  return (
                    <View
                      className="at-col at-col-3"
                      style={{ padding: "3px", height: "94px" }}
                      key={x.imageId}
                    >
                      <Image
                        className="guide-view-img"
                        style={{
                          width: "100%",
                          height: "100%"
                        }}
                        mode="aspectFit"
                        onClick={() => handleImageDelete(x)}
                        src={x.image}
                      ></Image>
                    </View>
                  );
                })}
                <View
                  className="at-col at-col-3"
                  style={{ padding: "30px", height: "94px" }}
                >
                  <Image
                    className="guide-view-img"
                    style={{
                      width: "100%",
                      height: "100%"
                    }}
                    onClick={() => onUpImage()}
                    src={uploadicon}
                  ></Image>
                </View>
              </View>
            )}
          </View>

          {/* <Tab value={['取消','']}  onClick={() => { Taro.navigateTo({ url: `/pages/label/edit/index` }) }} ></Tab> */}
          <Tab
            pageState="3"
            value={["取消", "上传"]}
            onClick={[
              e => {
                setPageState("1");
              },
              e => onSave(e)
            ]}
          ></Tab>
        </View>

        <View style={{ display: pageState == "2" ? "none" : "block" }}>
          <View style={{ padding: "0 20px" }}>
            {tagList.map((item, index) => {
              return (
                <View className="material-card" key={item.name}>
                  <Text>{item.name}</Text>
                  <Tags
                    list={item.taMateTagList}
                    onChange={e => onLabelChange(e, index)}
                    style={{ marginTop: "90rpx" }}
                  ></Tags>
                </View>
              );
            })}
          </View>
          {/* <Tab value={['取消','']}  onClick={() => { Taro.navigateTo({ url: `/pages/label/edit/index` }) }} ></Tab> */}
          <Tab
            pageState="3"
            value={["取消", "选择"]}
            onClick={[
              e => {
                Taro.navigateBack({
                  delta: 1
                });
              },
              e => {
                if (labelList.length > 0) setPageState("2");
                setImgUrl([])
              }
            ]}
          ></Tab>
        </View>
      </View>
    </IsLogin>
  );
};

export default batchimport;
