/*
 * @Author: wufan
 * @Date: 2020-11-30 10:47:38
 * @LastEditors: wufan
 * @LastEditTime: 2020-12-21 19:42:53
 * @Description: web店铺banner页面
 * @@Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */

import React from "react";
import { withRouter } from "react-router-dom";
import _ from "underscore";
import { Table, Modal, message, Button } from "antd";
import { QuestionCircleOutlined } from "@ant-design/icons";
import StoreService from "@/domains/store-domain/storeService";
import {
  sortableContainer,
  sortableElement,
  sortableHandle,
} from "react-sortable-hoc";
import { MenuOutlined } from "@ant-design/icons";
import arrayMove from "array-move";
import "./StoreDecorationPage.less";
import User from "@/common/js/user";
import SelectPrepareFileModal from "@/modules/prepare-lesson/modal/SelectPrepareFileModal";
import './StoreDecorationPage.less';
import Upload from '@/core/upload';

const { confirm } = Modal;
const DragHandle = sortableHandle(() => (
  <MenuOutlined
    style={{ cursor: "pointer", color: "#999" }}
    className="drag-icon"
  />
));
const SortableItem = sortableElement((props) => <tr {...props} />);
const SortableContainer = sortableContainer((props) => <tbody {...props} />);
let cutFlag = false;

class StoreWebDecoration extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      storeDecorationlist: [
        {
          id: "1111",
          bannerPath: "https://image.xiaomaiketang.com/xm/rJeQaZxtc7.png",
          index: 0,
          key: "0",
          name: "https://image.xiaomaiketang.com/xm/rJeQaZxtc7.png",
        },
        {
          id: "222",
          bannerPath: "https://image.xiaomaiketang.com/xm/CMyWNaDxbM.jpg",
          index: 1,
          key: "1",
          name: "校长",
        },
        {
          id: "333",
          bannerPath: "https://image.xiaomaiketang.com/xm/pBcJdYkmNN.jpg",
          index: 2,
          key: "2",
        },
      ],
      query: {
        storeId: User.getStoreId(),
        termType: "WEB_ADMIN",
      },
      showSelectFileModal: false,
      diskList: [],
      photoclip: null,
      preview: "",
    };
  }

  componentDidMount() {
    this.getStoreDecorationList();
  }

  getStoreDecorationList = () => {
    StoreService.getStoreDecorationList(this.state.query).then((res) => {
      this.setState({
        storeDecorationlist: res.result,
      });
    });
  };

  parseColumn = () => {
    return [
      {
        title: "Sort",
        dataIndex: "sort",
        width: 30,
        className: "drag-visible",
        render: () => <DragHandle />,
      },
      {
        title: "sequence",
        dataIndex: "sequence",
        key: "sequence",
        width: 20,
        render: (val, record, index) => {
          return <div className="index-num">{index + 1}</div>;
        },
      },
      {
        title: "banner",
        dataIndex: "bannerPath",
        key: "bannerPath",
        className: "drag-visible",
        render: (val) => {
          return <img src={val} alt="banner" className="banner-thumbnail" />;
        },
      },
      {
        title: "操作",
        dataIndex: "operation",
        width: "20%",
        className: "drag-visible",
        render: (val, record) => {
          return (
            <div className="operation">
              <span
                className="edit"
                onClick={() => this.handleReplaceDecoration(record)}
              >
                替换
              </span>
              <span className="divider-line">{" | "}</span>
              <span
                className="delete"
                onClick={() => this.handleDeleteDecorationConfirm(record)}
              >
                删除
              </span>
            </div>
          );
        },
      },
    ];
  };

  handleToAddStoreDecoration = () => {
    this.setState({
      showSelectFileModal: true,
    });
  };

  handleReplaceDecoration = (record) => {
    this.setState({
      showSelectFileModal: true,
      choosedBannerId: record.id
    });
  };

  handleDeleteDecoration = (record) => {
    StoreService.deleteStoreDecorationList({
      storeBannerId: record.id,
      termType: "WEB_ADMIN",
    }).then((res) => {
      message.success("已删除");
      this.getStoreDecorationList();
    });
  };

  handleDeleteDecorationConfirm = (record) => {
    return confirm({
      title: "你确定要删除这个banner吗？",
      icon: (
        <span className="icon iconfont default-confirm-icon">&#xe834;</span>
      ),
      okText: "删除",
      cancelText: "取消",
      onOk: () => {
        this.handleDeleteDecoration(record);
      },
    });
  };

  onSortEnd = ({ oldIndex, newIndex }) => {
    const { storeDecorationlist } = this.state;
    if (oldIndex !== newIndex) {
      const newData = arrayMove(
        [].concat(storeDecorationlist),
        oldIndex,
        newIndex
      ).filter((el) => !!el);
      console.log("Sorted items: ", newData);
      this.setState({ storeDecorationlist: newData });
    }
  };

  DraggableBodyRow = ({ className, style, ...restProps }) => {
    const { storeDecorationlist } = this.state;
    // function findIndex base on Table rowKey props and should always be a right array index
    const index = storeDecorationlist.findIndex(
      (x) => x.index === restProps["data-row-key"]
    );
    return <SortableItem index={index} {...restProps} />;
  };

  // 选择暖场资源
  handleSelectVideo = (file) => {
    this.setState({
      showSelectFileModal: false,
    });
    const { ossUrl, resourceId, folderName, folderFormat, folderSize } = file;
    const liveCourseWarmMedia = {
      contentType: "WARMUP",
      mediaType: folderFormat === "MP4" ? "VIDEO" : "PICTURE",
      mediaContent: resourceId,
      mediaUrl: ossUrl,
      mediaName: folderName,
      size: folderSize,
    };
    console.log("file", file);
    this.uploadImage(file);
  };

  //上传图片
  uploadImage = (imageFile) => {
    const { folderName } = imageFile;
    const fileName =
      window.random_string(16) + folderName.slice(folderName.lastIndexOf("."));
    this.setState(
      {
        visible: true,
      },
      () => {
        setTimeout(() => {
          const okBtnDom = document.querySelector("#headPicModal");
          const viewImgDom = document.querySelector('#preview-url-box');

          const options = {
            size: [500, 73],
            rotateFree: false,
            ok: okBtnDom,
            view: viewImgDom,
            maxZoom: 3,
            style: {
              jpgFillColor: "transparent",
            },
            done: (dataUrl) => {
              console.log("dataUrl-----", dataUrl);
              const cutImage = this.convertBase64UrlToBlob(dataUrl);
              console.log("cutImage-----",cutImage);
              this.getSignature(cutImage, fileName);
              setTimeout(() => {
                cutFlag = false;
              }, 2000);
            },
            fail: (failInfo) => {
              console.log("failInfo-----", failInfo);

            },
            loadComplete:(img)=>{
              console.log("img---",img,img.src);
              this.setState({
                previewUrl: img.src
              })
            }
          };
          if (!this.state.photoclip) {
            const photoclip = new PhotoClip("#headPicModal", options);
            photoclip.load(imageFile.ossUrl);
            console.log("photoclip-222",photoclip);
            this.setState({
              photoclip,
            });
          } else {
            this.state.photoclip.clear();
            this.state.photoclip.load(imageFile.ossUrl);
          }
        },200);
      }
    );
  };

  //获取resourceId
  getSignature = (blob, fileName) => {
    const { choosedBannerId } = this.state;
    Upload.uploadBlobToOSS(blob, 'avatar' + (new Date()).valueOf()).then((addBannerPath) => {
      this.setState({
        addBannerPath
      })
    });
  };

  editStoreBanner = () => {
    const { previewUrl, addBannerPath, choosedBannerId} = this.state;
    const params = {
      bannerPath: addBannerPath,
      storeBannerId: choosedBannerId,
      termType: "WEB_ADMIN",
    };
    StoreService.editStoreBanner(params).then((res) => {
      message.success("替换成功");
      this.getStoreDecorationList();
      // this.state.photoclip.destroy();
    });
  };

  addStoreBanner = () => {
    const { previewUrl, addBannerPath} = this.state;
    const params = {
      bannerPath: addBannerPath,
      storeId: User.getStoreId(),
      termType: "WEB_ADMIN",
    };
    StoreService.addStoreBanner(params).then((res) => {
      message.success("添加成功");
      this.getStoreDecorationList();
    });
  };

  // base64转换成blob
  convertBase64UrlToBlob = (urlData) => {
    const bytes = window.atob(urlData.split(",")[1]);
    const ab = new ArrayBuffer(bytes.length);
    const ia = new Uint8Array(ab);
    for (let i = 0; i < bytes.length; i++) {
      ia[i] = bytes.charCodeAt(i);
    }
    return new Blob([ab], { type: "image/png" });
  };

  render() {
    const {
      storeDecorationlist,
      showSelectFileModal,
      diskList,
      previewUrl,
      visible,
    } = this.state;
    const DraggableContainer = (props) => (
      <SortableContainer
        useDragHandle
        helperClass="row-dragging"
        onSortEnd={this.onSortEnd}
        {...props}
      />
    );
    return (
      <div className="user-manage-page">
        <div className="box-header">
          <div className="banner-setting">
            <div className="title">banner设置</div>
            <div className="tip">
              图片支持bmp、jpeg、jpg、png、gif格式，最大5M，最多可添加5张，拖动可排序。建议尺寸750x252像素。
            </div>
          </div>
          <Button
            onClick={() => {
              this.handleToAddStoreDecoration();
            }}
            type="primary"
            className="add-show-btn"
          >
            添加Banner
          </Button>
        </div>
        <div className="box-body">
          <Table
            size={"middle"}
            pagination={false}
            dataSource={storeDecorationlist}
            columns={this.parseColumn()}
            rowKey={(item) => item.index}
            components={{
              body: {
                wrapper: DraggableContainer,
                row: this.DraggableBodyRow,
              },
            }}
            bordered
          />
        </div>
        <SelectPrepareFileModal
          operateType="select"
          accept="image/jpeg,image/png,image/jpg"
          selectTypeList={["JPG", "JPEG", "PNG"]}
          tooltip="支持文件类型：jpg、jpeg、png"
          isOpen={showSelectFileModal}
          diskList={diskList}
          onClose={() => {
            this.setState({ showSelectFileModal: false });
          }}
          onSelect={this.handleSelectVideo}
        />
        <Modal
          title="设置图片"
          width={1080}
          visible={visible}
          onCancel={() => {
            this.setState({ visible: false });
          }}
          footer={[
            <Button
              key="back"
              onClick={() => {
                this.setState({ visible: false });
                this.handleToAddStoreDecoration();
              }}
            >
              重新上传
            </Button>,
            <Button
              key="submit"
              type="primary"
              onClick={() => {
                if (!cutFlag) {
                  cutFlag = true;
                  this.refs.hiddenBtn.click();
                }
                this.setState({ visible: false });
                this.state.choosedBannerId ? this.editStoreBanner(): this.addStoreBanner();
              }}
            >
              确定
            </Button>,
          ]}
        >
          <div className="clip-box">
            <div
              id="headPicModal"
              style={{
                width: "500px",
                height: "430px",
                marginBottom: 0,
              }}
            ></div>
            <div id="clipBtn" style={{ display: "none" }} ref="hiddenBtn"></div>
            <div className="preview-img">
              <div className="title">效果预览</div>
              {/* <img src={previewUrl} alt="图片预览" className="preview-url" /> */}
              <div id="preview-url-box"></div>
            </div>
          </div>
        </Modal>
      </div>
    );
  }
}

export default withRouter(StoreWebDecoration);
