/*
 * @Author: wufan
 * @Date: 2020-11-30 10:47:38
 * @LastEditors: wufan
 * @LastEditTime: 2020-12-17 15:30:52
 * @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';

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} />);

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'
      },
    };
  }

  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={() => handleReplaceDecoration(record)}
              >
                替换
              </span>
              <span className="divider-line">{" | "}</span>
              <span
                className="delete"
                onClick={() => this.handleDeleteDecorationConfirm(record)}
              >
                删除
              </span>
            </div>
          );
        },
      },
    ];
  };

  handleReplaceDecoration = (record) => {};

  handleDeleteDecoration = (record) => {

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

  handleDeleteDecorationConfirm = (record) => {
    return confirm({
      title: "你确定要删除这个banner吗？",
      icon: <QuestionCircleOutlined />,
      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} />;
  };

  render() {
    const { storeDecorationlist } = 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>
      </div>
    );
  }
}

export default withRouter(StoreWebDecoration);
