import React, { Fragment } from "react";
import { Icon, message, Modal, Button} from "antd";
import { WeaCheckbox, WeaHelpfulTip, WeaTable } from "ecCom";
import { slideStep3Columns } from "../columns";
import AddSalaryItemModal from "./AddSalaryItemModal";
import { inject, observer } from "mobx-react";
import { toJS } from "mobx";
import FormalFormModal from "../../salaryItem/formalFormModal";
import AddCategoryModal from "../step3/AddCategoryModal";

const helpContent = () => {
  return <span>
    <span>1、新建薪资账套时，核算公式与【薪资项目管理】菜单一致；</span><br/>
    <span>2、取值方式为公式的薪资项目，核算公式显示为具体公式；点击公式可编辑公式，核算时，按照当前薪资项目的公式进行核算；</span><br/>
    <span>3、薪资账套内的薪资项目的公式或SQL的修改或公式的修改，都不影响【薪资项目管理】菜单的薪资项目取值方式或公式，只对当前账套生效；</span><br/>
  </span>;
};

@inject("ledgerStore")
@observer
export default class CanMoveItem extends React.Component {
  constructor(props) {
    super(props);
    let columns = slideStep3Columns.map(item => {
      item = { ...item };
      if (item.key === "formulaContent") {
        item.title = <span>
          <span style={{ marginRight: 8 }}>{item.title}</span>
          <WeaHelpfulTip
            title={helpContent()}
            placement="bottom"
            width={200}
          />
        </span>;
        item.render = (text, record) => {
          if (record.canEdit) {
            return (
              <span className="linkWapper">
                <a
                  onClick={() => {
                    this.handleFormulaClick(record.formulaId, record);
                  }}>
                  {text}
                </a>
              </span>
            );
          } else {
            return (
              <span>
                {text}
              </span>
            );
          }
        };
      }
      return item;
    });
    this.state = {
      addItemVisible: false,
      showContent: true,
      selectedRowKeys: [],
      columns,
      formalModalVisible: false,
      addCategoryVisible: false
    };

    this.formulaId = "";
    this.record = {};
    this.title = "";
  }

  handleChangeItem = (value, id) => {
    const { dataSource } = this.props;
    let result = [...dataSource];
    this.props.onChange(
      _.map(result, item => {
        if (id === item.id) {
          return {
            ...item,
            itemHide: String(value)
          };
        }
        return { ...item };
      })
    );
  };
  handleChangeAllItem = (value) => {
    const { dataSource } = this.props;
    let result = [...dataSource];
    this.props.onChange(
      _.map(result, item => {
        return {
          ...item,
          itemHide: String(value)
        };
      })
    );
  };

  // 编辑公式
  handleFormulaClick(formulaId, record) {
    this.formulaId = formulaId;
    this.record = record;
    this.setState({
      formalModalVisible: true
    });
  }

  handleTiggleContent() {
    this.setState({ showContent: !this.state.showContent });
  }

  onSelectChange = selectedRowKeys => {
    this.setState({ selectedRowKeys });
  };

  // 删除
  handleDelete = () => {
    const { selectedRowKeys } = this.state;
    if (selectedRowKeys.length == 0) {
      message.warning("未选择任何条目");
      return;
    }
    Modal.confirm({
      title: "信息确认",
      content: "确认删除",
      onOk: () => {
        const { dataSource } = this.props;
        let result = [...dataSource];
        this.props.onChange(
          result.filter(item => selectedRowKeys.indexOf(item.key) < 0)
        );
      },
      onCancel: () => {
      }
    });
  };

  // 保存
  handleSaveFormal(data) {
    let record = { ...this.record };
    record.formulaId = data.id;
    let dataSource = [...this.props.dataSource];
    dataSource.map(item => {
      if (item.id == record.id) {
        item.formulaId = data.id;
        item.formulaContent = data.formula;
      }
    });
    this.props.onDataSourceChange(dataSource);
  }

  // 编辑分类名称
  handleUpdateCategorySave(name) {
    this.props.onTitleChange && this.props.onTitleChange(name);
    this.setState({
      addCategoryVisible: false
    });
  }

  // 修改分类名称，弹出修改弹出
  handleEditGroupIconClick(title) {
    this.title = title;
    this.setState({ addCategoryVisible: true });
  }

  // 删除分类回调
  handleDeleteGroupIconClick() {
    Modal.confirm({
      title: "信息确认",
      content: "确认删除",
      onOk: () => {
        this.props.onGroupDelete && this.props.onGroupDelete();
      },
      onCancel: () => {
      }
    });
  }

  render() {
    const {
      disabled,
      sortedIndex,
      ledgerStore: { setAddItemVisible, addItemVisible, itemGroups = [] }
    } = this.props;
    const checkValue = _.every(this.props.dataSource, it => it.itemHide && it.itemHide === "1") ? "1" : "0";
    const {
      selectedRowKeys,
      formalModalVisible,
      addCategoryVisible,
      columns
    } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      getCheckboxProps: record => ({
        disabled: !record.canDelete
      })
    };

    const newColumns = [...columns, {
      title: <span>
          <WeaCheckbox
            value={checkValue}
            onChange={value => {
              this.handleChangeAllItem(value);
            }}
          />
          <span style={{ marginLeft: 8 }}>隐藏</span>
        </span>,
      dataIndex: "itemHide",
      key: "itemHide",
      render: (text, record) => <WeaCheckbox
        value={text ? String(text) : !text ? "0" : "1"}
        onChange={value => {
          this.handleChangeItem(value, record.id);
        }}
      />
    }];

    return (
      <div className="tableItemWrapper">
        <div style={{ padding: "10px" }}>
          <span className="itemTitle">
            {this.props.title}
            {this.props.title !== "未分类" &&
              <span>
                {!disabled &&
                  <Fragment>
                    <i
                      className="icon-coms-edit"
                      style={{
                        marginLeft: "10px",
                        marginRight: "10px",
                        cursor: "pointer"
                      }}
                      title="编辑"
                      onClick={() => {
                        this.handleEditGroupIconClick(this.props.title);
                      }}
                    />
                    <i
                      className="icon-coms-Delete"
                      style={{ cursor: "pointer" }}
                      title="删除"
                      onClick={() => {
                        this.handleDeleteGroupIconClick();
                      }}
                    />
                  </Fragment>}
              </span>}
            <span style={{
              marginLeft: 10,
              cursor: "pointer"
            }}>
              {
                sortedIndex !== 0 &&
                <i className="icon-coms-Reverse"
                   onClick={() => this.props.onUpgo(sortedIndex)}
                   title="向上移动"
                   style={{
                     marginRight: 10,
                     cursor: "pointer"
                   }}
                />
              }
              {
                sortedIndex !== toJS(itemGroups).length - 1 &&
                <i className="icon-coms-positive-sequence"
                   onClick={() => this.props.onDowngo(sortedIndex)}
                   title="向下移动"
                   style={{
                     cursor: "pointer"
                   }}
                />
              }
            </span>
          </span>
          <span className="rightBtnsWrapper">
            {
              !disabled &&
              <React.Fragment>
                <Button type="primary"
                        size="small"
                        onClick={() => {
                          this.handleDelete();
                        }}
                ><span className="icon-coms-form-delete-hot" title="删除"></span></Button>
                <Button type="primary"
                        size="small"
                        style={{ marginRight: 10 }}
                        onClick={() => {
                          this.setState({ addItemVisible: true });
                        }}
                ><span className="icon-coms-Add-to-hot" title="添加"></span></Button>
              </React.Fragment>
            }
            <i
              className={this.state.showContent ? "icon-coms-down2" : "icon-coms-up2"}
              style={{ cursor: "pointer",fontSize: 18 }}
              onClick={() => {
                this.handleTiggleContent();
              }}
            />
          </span>
        </div>
        {this.state.showContent &&
          <WeaTable
            rowSelection={rowSelection}
            dataSource={this.props.dataSource}
            columns={newColumns}
            onRow={(record, index) => ({
              index,
              moveRow: record
            })}
            pagination={false}
            onDrop={datas => this.props.onDataSourceChange(datas)}
            draggable={true}
          />}
        {this.state.addItemVisible &&
          <AddSalaryItemModal
            visible={this.state.addItemVisible}
            title={this.props.title}
            onCancel={() => {
              this.setState({ addItemVisible: false });
            }}
          />}

        {formalModalVisible &&
          <FormalFormModal
            formulaId={this.formulaId}
            valueType={this.record.valueType}
            visible={formalModalVisible}
            onSaveFormal={data => {
              this.handleSaveFormal(data);
            }}
            onCancel={() =>
              this.setState({
                formalModalVisible: false
              })}
          />}

        {/* 编辑分类名称 */}
        {addCategoryVisible &&
          <AddCategoryModal
            title={this.title}
            onSave={value => {
              this.handleUpdateCategorySave(value);
            }}
            visible={addCategoryVisible}
            onCancel={() => {
              this.setState({ addCategoryVisible: false });
            }}
          />}
      </div>
    );
  }
}
