/*
 * Author: 黎永顺
 * name: 水印内容设置
 * Description:
 * Date: 2023/6/14
 */
import React, { Component } from "react";
import {
  WeaFormItem,
  WeaHelpfulTip,
  WeaInputNumber,
  WeaInputSearch,
  WeaLocaleProvider,
  WeaRichText,
  WeaSearchGroup,
  WeaSlideModal,
  WeaTransfer
} from "ecCom";
import { Button, Col, message, Row } from "antd";
import { commonVariables } from "./config";
import "./index.less";

const getLabel = WeaLocaleProvider.getLabel;
const WeaTransferList = WeaTransfer.list;

class WmContentSetModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      wmWidth: 100,
      wmHeight: 100,
      wmOriginText: "",
      searchV: ""
    };
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.visible !== this.props.visible) {
      this.setState({
        wmWidth: nextProps.textSet.wmWidth || 100,
        wmHeight: nextProps.textSet.wmHeight || 100,
        wmOriginText: nextProps.textSet.wmOriginText || ""
      });
    } else {
      this.setState({
        wmWidth: 100,
        wmHeight: 100,
        wmOriginText: "",
        searchV: ""
      });
    }
  }

  handleSaveWMContent = () => {
    const html = this.refs.TextContentRichText.getData().replace(/\n/ig, "");
    if (!html) {
      message.warning(getLabel(111, "请输入水印内容!"));
      return;
    }
    const { wmWidth, wmHeight } = this.state;
    this.props.onClose({
      wmWidth, wmHeight,
      wmSelectedFieldIds: this.getHtmlAttrVal(html),
      pureWmText: this.convertToPlain(html),
      wmOriginText: html, wmText: this.convertToWMText(html)
    });
  };

  convertToWMText = (html) => {
    _.map(commonVariables, item => {
      const { id, name } = item;
      const reg = eval("/" + name + "/g");
      html = html.replace(reg, `$${id}`).replace(/ data-id=\"(.*?)\"/g, "");
    });
    return html.replace(/ contenteditable="false"/g, "");
  };
  getHtmlAttrVal = (html) => {
    let attrAndValueArr = html.match(/ data-id=\"(.*?)\"/g);
    let valueArr = []; // 放所有该属性的值
    if (!_.isEmpty(attrAndValueArr)) {
      for (let i = 0; i < attrAndValueArr.length; i++) {
        valueArr.push(attrAndValueArr[i].replace(/ data-id=/g, "").replace(/\"/g, ""));
      }
    }
    return valueArr;
  };
  convertToPlain = (html) => {
    let tempDivElement = document.createElement("div");
    tempDivElement.innerHTML = html;
    return tempDivElement.textContent || tempDivElement.innerText || "";
  };

  renderItem = (item = {}) => {
    return <span>{item.name}</span>;
  };

  selectHeader() {
    return (
      <div className={"waterMark-select-header"}>
        <WeaInputSearch onSearchChange={(v) => {
          this.setState({ searchV: v });
        }}/>
      </div>
    );
  }

  render() {
    const { wmWidth, wmHeight, wmOriginText, searchV } = this.state;
    const ckConfig = {
      toolbar: [
        { name: "paragraph", items: ["JustifyLeft", "JustifyCenter", "JustifyRight"] },
        { name: "styles", items: ["Font", "FontSize"] },
        { name: "colors", items: ["TextColor"] }
      ],
      removePlugins: "resize",
      height: 280
    };
    const tempOptions = _.filter(commonVariables, (item) => {
      const { name } = item;
      let flag = true;
      if (searchV && name) {
        flag = name.indexOf(searchV) > -1;
      }
      return flag;
    });
    return (
      <WeaSlideModal
        {...this.props} className="wmContentWrapper" onClose={() => this.props.onClose(this.props.textSet)}
        title={<span className="wmTitle">{getLabel(111, "水印内容设置")}</span>}
        direction="right" top={0} width={800} height={100}
        measureT="%" measureX="px" measureY="%"
        content={
          <React.Fragment>
            <WeaSearchGroup
              title={<span><span style={{ marginRight: 10 }}>{getLabel(111, "水印格式设置")}</span><WeaHelpfulTip
                title={getLabel(111, "水印最小100px*100px")} placement="topLeft"/></span>}
              showGroup needTigger={false} className="waterMarkWrapper wmContGroup">
              <WeaFormItem label={getLabel(111, "水印宽度") + "（px）"} labelCol={{ span: 5 }} wrapperCol={{ span: 10 }}>
                <WeaInputNumber
                  min={100} precision={3} value={wmWidth}
                  onChange={wmWidth => this.setState({ wmWidth })}
                />
              </WeaFormItem>
              <WeaFormItem label={getLabel(111, "水印高度") + "（px）"} labelCol={{ span: 5 }} wrapperCol={{ span: 10 }}>
                <WeaInputNumber
                  min={100} precision={3} value={wmHeight}
                  onChange={wmHeight => this.setState({ wmHeight })}
                />
              </WeaFormItem>
            </WeaSearchGroup>
            <WeaSearchGroup
              title={getLabel(111, "内容")}
              showGroup needTigger={false} className="waterMarkWrapper wmContGroup mt16">
              <Row className="content-box" gutter={10}>
                <Col span={18}>
                  <WeaRichText ckConfig={ckConfig} value={wmOriginText} ref={"TextContentRichText"}/>
                </Col>
                <Col span={6}>
                  <WeaTransferList
                    header={this.selectHeader()}
                    data={tempOptions}
                    renderItem={this.renderItem}
                    checkedCb={(keys) => {
                      let result = _.filter(commonVariables, (item) => item.id === keys[0]);
                      if (result && result.length > 0) {
                        this.refs.TextContentRichText.insertHTML(`&nbsp;<span contenteditable="false" data-id="${result[0].id}">${result[0].name}</span>&nbsp;`);
                      }
                    }}
                    height={280}
                    checkedKeys={[]}
                  />
                </Col>
              </Row>
            </WeaSearchGroup>
            <div className="slideBottom">
              <Button type="primary"
                      onClick={this.handleSaveWMContent}>{getLabel(111, "保存")}</Button>
              <Button type="ghost"
                      onClick={() => this.props.onClose(this.props.textSet)}>{getLabel(111, "取消")}</Button>
            </div>
          </React.Fragment>
        }
      />
    );
  }
}

export default WmContentSetModal;
