/*
 * @Author: wufan
 * @Date: 2020-11-30 10:47:38
 * @LastEditors: wufan
 * @LastEditTime: 2021-06-21 11:16:31
 * @Description: web学院banner页面
 * @@Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */

import React from "react";
import { withRouter } from "react-router-dom";
import _ from "underscore";
import { Modal, message, Button } from "antd";
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 User from "@/common/js/user";
import SelectPrepareFileModal from "@/modules/prepare-lesson/modal/SelectPrepareFileModal";
import "./StoreDecorationPage.less";
import Upload from "@/core/upload";
import { XMTable } from '@/components';
import college from '@/common/lottie/college';

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: "WEB_ADMIN",
      },
      showSelectFileModal: false,
      diskList: [],
      photoclip: null,
      preview: "",
      cutImageBlob: null,
      hasImgReady: false // 图片是否上传成功
    };
  }

  timer = null

  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",
        className: "drag-visible",
        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="web-banner-thumbnail" />;
        },
      },
      {
        title: "操作",
        dataIndex: "operation",
        width: "20%",
        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 = () => {
    const { choosedBannerId } = this.state;
    if (this.state.storeDecorationlist.length >= 5 && !choosedBannerId) {
      message.info("最多可添加5条");
      return;
    }

    this.setState({
      showSelectFileModal: true,
      choosedBannerId: ""
    });
  };

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

  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">&#xe839; </span>
      ),
      okText: "删除",
      okType: 'danger',
      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} />;
  };

  // 选择云盘资源
  handleSelectImg = (file) => {
    this.setState({
      showSelectFileModal: false,
    });
    this.uploadImage(file);
  };

  //上传图片
  uploadImage = (imageFile) => {
    const self = this;
    this.setState(
      {
        visible: true,
      },
      () => {
        setTimeout(() => {
          const okBtnDom = document.querySelector("#headPicModal");
          const options = {
            size: [500, 73],
            ok: okBtnDom,
            maxZoom: 3,
            style: {
              jpgFillColor: "transparent",
            },
            done: function (dataUrl) {
              clearTimeout(self.timer);
              self.timer = setTimeout(() => {
                if ((self.state.rotate != this.rotate()) || (self.state.scale != this.scale())) {
                  console.log(this.scale(), 'scale')
                  const _dataUrl = this.clip()
                  const cutImageBlob = self.convertBase64UrlToBlob(_dataUrl);
                  self.setState({
                    cutImageBlob,
                    dataUrl: _dataUrl,
                    rotate: this.rotate(),
                    scale: this.scale()
                  })
                }

              }, 500)

              const cutImageBlob = self.convertBase64UrlToBlob(dataUrl);
              self.setState({
                cutImageBlob,
                dataUrl
              })
              setTimeout(() => {
                cutFlag = false;
              }, 2000);
            },
            fail: (failInfo) => {
              message.error("图片上传失败了，请重新上传");
            },
            loadComplete: function (img) {
              setTimeout(() => {
                const _dataUrl = this.clip()
                self.setState({
                  dataUrl: _dataUrl,
                  hasImgReady: true
                })
              }, 100)

            },
          };
          const imgUrl = `${imageFile.ossUrl}?${new Date().getTime()}`

          if (!this.state.photoclip) {
            const _photoclip = new PhotoClip("#headPicModal", options);
            _photoclip.load(imgUrl);
            this.setState({
              photoclip: _photoclip,
            });
          } else {
            this.state.photoclip.clear();
            this.state.photoclip.load(imgUrl);
          }

        }, 200);
      }
    );
  };

  //获取resourceId
  getSignature = (blob) => {
    Upload.uploadBlobToOSS(blob, "avatar" + new Date().valueOf()).then(
      (addBannerPath) => {
        this.setState({
          addBannerPath,
          visible: false
        }, () => {
          this.state.choosedBannerId
            ? this.editStoreBanner()
            : this.addStoreBanner();
        });
      }
    );
  };

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

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

  addStoreBanner = () => {
    const { 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,
      visible,
      cutImageBlob,
      hasImgReady
    } = this.state;
    const DraggableContainer = (props) => (
      <SortableContainer
        useDragHandle
        helperClass="row-dragging"
        onSortEnd={this.onSortEnd}
        {...props}
      />
    );
    return (
      <div className="store-decoration-web-page">
        <div className="box-header">
          <div className="banner-setting">
            <div className="title">banner设置</div>
            <div className="tip">
              图片支持bmp、jpeg、jpg、png、gif格式，最大5M，最多可添加5张，拖动可排序。建议尺寸1232*212px。
             </div>
          </div>
          <Button
            onClick={() => {
              this.handleToAddStoreDecoration();
            }}
            type="primary"
            className="add-show-btn"
          >
            添加Banner
          </Button>
        </div>
        <div className="box-body">
        <XMTable 
            renderEmpty={{
              image: college,
              description: '暂无数据'
            }}
            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.handleSelectImg}
        />
        <Modal
          title="设置图片"
          width={1080}
          visible={visible}
          onCancel={() => {
            this.setState({ visible: false });
          }}
          maskClosable={false}
          closeIcon={<span className="icon iconfont modal-close-icon">&#xe6ef;</span>}
          footer={[
            <Button
              key="back"
              onClick={() => {
                this.setState({ visible: false });
                this.state.choosedBannerId ? this.handleReplaceDecoration(this.state.choosedBannerItem):this.handleToAddStoreDecoration();
              }}
            >
              重新上传
            </Button>,
            <Button
              key="submit"
              type="primary"
              disabled={!hasImgReady}
              onClick={() => {
                if (!cutFlag) {
                  cutFlag = true;
                  this.refs.hiddenBtn.click();
                }
                this.getSignature(cutImageBlob);
              }}
            >
              确定
            </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">
                <img src={this.state.dataUrl} style={{ width: '100%' }} alt="" />
              </div>
              <div className="tip-box">
                <div className="tip">温馨提示</div>
                <div className="tip">①预览效果图时可能存在延迟，单击左侧图片刷新即可</div>
                <div className="tip">②设置图片时双击可旋转图片，滚动可放大或缩小图片</div>
              </div>
            </div>
          </div>
        </Modal>
      </div>
    );
  }
}

export default withRouter(StoreWebDecoration);
