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

import React, { useEffect, useState } from "react";
import { withRouter } from "react-router-dom";
import _ from "underscore";
import PageControl from "@/components/PageControl";
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';

const { confirm } = Modal;

function StoreH5Decoration(props) {
  const [storeDecorationlist, setStoreDecorationlist] = useState([
    {
      id: 1111,
      bannerPath: "https://image.xiaomaiketang.com/xm/rJeQaZxtc7.png",
      sequence: 0,
    },
    {
      id: 1111,
      bannerPath: "https://image.xiaomaiketang.com/xm/CMyWNaDxbM.jpg",
      sequence: 1,
    },
    {
      id: 1111,
      bannerPath: "https://image.xiaomaiketang.com/xm/pBcJdYkmNN.jpg",
      sequence: 2,
    },
    {
      id: 1111,
      bannerPath: "https://image.xiaomaiketang.com/xm/p7hG4exMFf.png",
      sequence: 3,
    },
  ]);
  const [query, setQuery] = useState({
    storeId: User.getStoreId(),
    termType: "H5_ADMIN",
  });
  const [showSelectFileModal, setShowSelectFileModal] = useState(false);
  const [diskList, setDiskList] = useState([]);
  const [visible, setVisible] = useState(false);

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

  useEffect(() => {
    getStoreDecorationList();
  }, [query]);

  function getStoreDecorationList() {
    StoreService.getStoreDecorationList(query).then((res) => {
      setStoreDecorationlist(res.result);
    });
  }

  function handleReplaceDecoration(record) {}

  function handleDeleteDecoration(record) {
    StoreService.deleteStoreDecorationList({
      storeBannerId: record.id,
      termType: "H5_ADMIN",
    }).then((res) => {
      message.success("已删除");
    });
  }
  function handleDeleteDecorationConfirm(record) {
    return confirm({
      title: "你确定要删除这个banner吗？",
      icon: <QuestionCircleOutlined />,
      okText: "删除",
      cancelText: "取消",
      onOk: () => {
        handleDeleteDecoration(record);
      },
    });
  }

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

  function DraggableBodyRow({ className, style, ...restProps }) {
    const index = storeDecorationlist.findIndex(
      (x) => x.index === restProps["data-row-key"]
    );
    return <SortableItem index={index} {...restProps} />;
  }

  function 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: "bannerPath",
        dataIndex: "bannerPath",
        key: "bannerPath",
        render: (val) => {
          return <img src={val} alt="banner" className="banner-thumbnail" />;
        },
      },
      {
        title: "操作",
        dataIndex: "operation",
        width: "20%",
        render: (val, record) => {
          return (
            <div className="operation">
              <span
                className="edit"
                onClick={() => handleReplaceDecoration(record)}
              >
                替换
              </span>
              <span className="divider-line">{" | "}</span>
              <span
                className="delete"
                onClick={() => handleDeleteDecorationConfirm(record)}
              >
                删除
              </span>
            </div>
          );
        },
      },
    ];
  }

  function handleToAddStoreDecoration() {
    setShowSelectFileModal(true);
  }

  // 选择暖场资源
  function handleSelectVideo(file) {
    setShowSelectFileModal(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("liveCourseWarmMedia", liveCourseWarmMedia);
    
  }

  const DraggableContainer = (props) => (
    <SortableContainer
      useDragHandle
      helperClass="row-dragging"
      onSortEnd={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={() => {
            handleToAddStoreDecoration();
          }}
          type="primary"
          className="add-show-btn"
        >
          添加Banner
        </Button>
      </div>
      <div className="box-body">
        <Table
          size={"middle"}
          pagination={false}
          dataSource={storeDecorationlist}
          columns={parseColumn()}
          rowKey={(item) => item.index}
          components={{
            body: {
              wrapper: DraggableContainer,
              row: DraggableBodyRow,
            },
          }}
          bordered
        />
      </div>
      <SelectPrepareFileModal
        operateType="select"
        accept="image/jpeg,image/png,image/jpg"
        selectTypeList={["JPG", "JPEG", "PNG"]}
        tooltip="支持文件类型：jpg、jpeg、png、mp4"
        isOpen={showSelectFileModal}
        diskList={diskList}
        onClose={() => {
          setShowSelectFileModal(false);
        }}
        onSelect={handleSelectVideo}
      />
       <Modal
          title="设置图片"
          width={1080}
          visible={visible}
          onCancel={() => { setVisible(false)}}
          footer={[
            <Button key="reUpload" onClick={() => { setShowSelectFileModal(true);
            }}>重新上传</Button>,
            <Button key="submit" type="primary" onClick={() => {
              if (!cutFlag) {
                cutFlag = true;
                this.refs.hiddenBtn.click();
              }
            }}>
              确定
            </Button>,
          ]}>
          <div id="headPicModal" style={{
            width: '502px',
            height: '283px',
            'marginBottom': 0
          }}></div>
          <div id="clipBtn" style={{ display: 'none' }} ref="hiddenBtn"></div>
        </Modal>
    </div>
  );
}

export default withRouter(StoreH5Decoration);
