/*
 * @Author: wufan
 * @Date: 2020-11-30 10:47:38
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-07-08 19:35:17
 * @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';
import ImgClipModal from '@/components/ImgClipModal'

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 StoreH5Decoration extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      storeDecorationlist: [],
      query: {
        storeId: User.getStoreId(),
        termType: "H5_ADMIN",
      },
      showSelectFileModal: false,
      diskList: [],
      photoclip: null,
      preview: "",
      cutImageBlob: null,
      hasImgReady: false, // 图片是否上传成功
      imageFile: null // 需要被截取的图片
    };
  }

  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="banner-thumbnail" />;
        },
      },
      {
        title: "操作",
        dataIndex: "operation",
        width: "20%",
        render: (val, record, index) => {
          return (
            <div className="operation">
              <span
                className="edit"
                onClick={() => this.handleReplaceDecoration(record,index)}
              >
                替换
              </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, index) => {
    this.setState({
      showSelectFileModal: true,
      choosedBannerId: record.id,
      choosedBannerItem:record
    });
  };

  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">&#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) => {
    if(file){
      this.setState({
        visible: true,
        imageFile:file
      });
    }
    
  };


  //获取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: "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();
    });
  };


  render() {
    const {
      storeDecorationlist,
      showSelectFileModal,
      diskList,
      visible,
      cutImageBlob,
      hasImgReady,
      imageFile,
    } = this.state;
    const DraggableContainer = (props) => (
      <SortableContainer
        useDragHandle
        helperClass="row-dragging"
        onSortEnd={this.onSortEnd}
        {...props}
      />
    );
    return (
      <div className="store-decoration-h5-page">
        <div className="box-header">
          <div className="banner-setting">
            <div className="title">banner设置</div>
            <div className="tip">
              图片支持bmp、jpeg、jpg、png、gif格式，最大5M，最多可添加5张，拖动可排序。建议尺寸750*252px。
            </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}
        />
        { visible &&
          <ImgClipModal visible={visible} imgUrl={imageFile.ossUrl}  aspectRatio='500/172' cropBoxHeight='172' onConfirm={this.getSignature} onClose={()=>{this.setState({ visible: false });}}/>
        }
      </div>
    );
  }
}

export default withRouter(StoreH5Decoration);
