/*
 * @Author: wufan
 * @Date: 2020-11-30 10:47:38
 * @LastEditors: wufan
 * @LastEditTime: 2020-12-22 13:48:59
 * @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: [],
      query: {
        storeId: User.getStoreId(),
        termType: "H5_ADMIN",
      },
      showSelectFileModal: false,
      diskList: [],
      photoclip: null,
      preview: "",
    };
  }

  componentDidMount() {
    this.getStoreDecorationList();
  }

  getStoreDecorationList = () => {
    StoreService.getStoreDecorationList(this.state.query).then((res) => {
      const data = _.map(res.result, (item, index) => {
        item.index = index;
        item.key = index;
        return item;
      });
      this.setState({
        storeDecorationlist: data,
      });
    });
  };

  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: "H5_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);
      this.setState(
        {
          storeDecorationlist: newData,
          newSequence: storeDecorationlist[newIndex].sequence,
          storeBannerId: storeDecorationlist[oldIndex].id,
        },
        () => {
          this.moveBannerSequence();
        }
      );
    }
  };

  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,
    });
    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("#H5-preview-url-box");

          const options = {
            size: [500, 172],
            rotateFree: false,
            ok: okBtnDom,
            view: viewImgDom,
            maxZoom: 3,
            style: {
              jpgFillColor: "transparent",
            },
            done: (dataUrl) => {
              const cutImage = this.convertBase64UrlToBlob(dataUrl);
              this.getSignature(cutImage, fileName);
              setTimeout(() => {
                cutFlag = false;
              }, 2000);
            },
            fail: (failInfo) => {
              console.log("failInfo-----", failInfo);
            },
            loadComplete: (img) => {
              this.refs.headPicModal.click();
              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) => {
    Upload.uploadBlobToOSS(blob, "avatar" + new Date().valueOf()).then(
      (addBannerPath) => {
        this.setState({
          addBannerPath,
        });
      }
    );
  };

  editStoreBanner = () => {
    const { addBannerPath, choosedBannerId } = this.state;
    const params = {
      bannerPath: addBannerPath,
      storeBannerId: choosedBannerId,
      termType: "H5_ADMIN",
    };
    StoreService.editStoreBanner(params).then((res) => {
      message.success("设置成功");
      this.getStoreDecorationList();
    });
  };

  moveBannerSequence = () => {
    const { newSequence, storeBannerId } = this.state;
    const params = {
      sequence: newSequence,
      storeBannerId: storeBannerId,
      termType: "H5_ADMIN",
    };
    StoreService.moveBannerSequence(params).then((res) => {
      this.getStoreDecorationList();
    });
  };

  addStoreBanner = () => {
    const { addBannerPath } = this.state;
    const params = {
      bannerPath: addBannerPath,
      storeId: User.getStoreId(),
      termType: "H5_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,
      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"
              ref="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>
              <div id="H5-preview-url-box"></div>
            </div>
          </div>
        </Modal>
      </div>
    );
  }
}

export default withRouter(StoreWebDecoration);
