import React from "react";
import { Icon, message } from "antd";
import { WeaSelect, WeaSortable } from "ecCom";
import { inject, observer } from "mobx-react";
import { toJS } from "mobx";
import CanDeleteItem from "../../../components/canDeleteItem";

@inject("ledgerStore")
@observer
export default class UserInfoSelected extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      list: [],
      showSelect: false
    };
  }

  handleSelectChange(value) {
    const { ledgerStore: { empBrowserList, userSelectedList } } = this.props;
    let list = [...userSelectedList];
    let selectedItem = {};
    empBrowserList.map(item => {
      if (item.key == value) {
        selectedItem = item;
      }
    });
    let flag = false;
    list.map(item => {
      if (item.key == value) {
        flag = true;
      }
    });
    if (!flag) {
      list.push(selectedItem);
    }
    if (flag) {
      message.warning("该信息已存在");
      this.setState({ showSelect: false });
      return;
    }
    const { ledgerStore: { empFields, addEmpFields, setUserSelectedList } } = this.props;
    addEmpFields(value);
    this.setState({ showSelect: false });
  }

  handleItemDelete(item) {
    const { ledgerStore: { userSelectedList, setUserSelectedList, empFields, setEmpFields } } = this.props;
    let list = [...userSelectedList];
    let fields = [...empFields];
    if (item.canDelete === false) {
      message.warning("该项不可删除");
      return;
    }

    fields = fields.filter(i => item.fieldId != i.fieldId);
    fields.map((item, index) => {
      item.sortedIndex = index;
    });
    setEmpFields(fields);
    setUserSelectedList(list.filter(i => item.fieldId != i.fieldId));
  }

  render() {
    const { ledgerStore: { empBrowserList, userSelectedList, setUserSelectedList } } = this.props;
    const list = _.map(toJS(userSelectedList), it => ({ ...it }));
    return (
      <div className="userInfoSelected">
        <WeaSortable
          datas={list}
          draggableType="icon"
          onChange={(list) => setUserSelectedList(list)}
          renderNodeItem={(item) => {
            return <CanDeleteItem title={item.showname} item={item} onDelete={(item) => {
              this.handleItemDelete(item);
            }}/>;
          }}
          className="wea-sortable-grid-item"
        />
        <Icon type="plus" style={{ marginLeft: "10px", marginRight: "10px", cursor: "pointer" }} title="新增"
              onClick={() => {
                this.setState({ showSelect: true });
              }}/>
        {
          this.state.showSelect && empBrowserList.length > 0 &&
          <WeaSelect showSearch options={empBrowserList}
                     style={{ width: 200 }} onChange={(value) => {
            this.handleSelectChange(value);
          }}/>
        }
      </div>
    );
  }
}
