import React from "react";
import { Button, Spin } from "antd";
import { WeaCheckbox, WeaDialog, WeaInputSearch, WeaLocaleProvider, WeaTable } from "ecCom";
import { listSalaryItem } from "../../../apis/ledger";

const getLabel = WeaLocaleProvider.getLabel;
export default class LedgerSalaryItemAddModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: { query: false }, name: "", selectedRowKeys: [], dataSource: [],
      dataSourceCopy: [], columns: [], pageInfo: { current: 1, pageSize: 10, total: 0 }
    };
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.visible !== this.props.visivle && nextProps.visible) {
      this.setState({ selectedRowKeys: [], dataSourceCopy: [] }, () => {
        this.listSalaryItem();
      });
    } else {
      this.setState({ pageInfo: { current: 1, pageSize: 10, total: 0 } });
    }
  }

  listSalaryItem = (extra = {}) => {
    const { itemGroups } = this.props;
    const { name, pageInfo, loading, dataSourceCopy } = this.state;
    let excludeIds = [];
    itemGroups.map(item => {
      item.items && item.items.map(i => {
        excludeIds.push(i.salaryItemId);
      });
    });
    const payload = { excludeIds, name, ...pageInfo, ...extra };
    this.setState({ loading: { ...loading, query: true } });
    listSalaryItem(payload).then(({ status, data }) => {
      this.setState({ loading: { ...loading, query: false } });
      if (status) {
        const { pageNum: current, pageSize, total, columns, list: dataSource } = data;
        const tmpV = !_.isEmpty(dataSource) ? dataSource : [];
        this.setState({
          dataSourceCopy: [...dataSourceCopy, ...tmpV],
          pageInfo: { ...pageInfo, current, pageSize, total }, dataSource: tmpV, columns
        });
      }
    }).catch(() => {
      this.setState({ loading: { ...loading, query: false } });
    });
  };
  getSalaryItemAddColumns = () => {
    const { columns } = this.state;
    let newColumns = [];
    newColumns = columns.map(column => {
      let newColumn = column;
      newColumn.render = (text, record, index) => { //前端元素转义
        let valueSpan = record[newColumn.dataIndex + "span"] !== undefined ? record[newColumn.dataIndex + "span"] : record[newColumn.dataIndex];
        switch (newColumn.dataIndex) {
          case "useDefault":
          case "hideDefault":
          case "useInEmployeeSalary":
            return <WeaCheckbox value={String(text)} disabled display="switch"/>;
          default:
            return <div dangerouslySetInnerHTML={{ __html: valueSpan }}/>;
        }
      };
      return newColumn;
    });
    return newColumns;
  };
  handleAdd = () => {
    const { dataSourceCopy, selectedRowKeys } = this.state;
    const { onAddSalaryItems, id, onCancel, itemGroups, record } = this.props;
    const arrItems = _.find(itemGroups, it => it.uuid === id).items || [];
    let selectItems = [];
    _.uniqWith(dataSourceCopy, _.isEqual).map((item) => {
      item = { ...item };
      selectedRowKeys.map((key, keyIdx) => {
        if (item.id === key) {
          item.salaryItemId = item.id;
          item.key = item.id;
          item.itemHide = item.hideDefault;
          item.sortedIndex = (!_.isEmpty(_.maxBy(arrItems, it => it.sortedIndex)) ? _.maxBy(arrItems, it => it.sortedIndex).sortedIndex : 0) + keyIdx + 1;
          selectItems.push(item);
        }
      });
    });
    onCancel();
    onAddSalaryItems(id, selectItems, record.id || record.key);
  };
  renderTitle = () => {
    const { name, pageInfo } = this.state;
    return <div className="sys-item-title">
      <span>{getLabel(111, "添加薪资项目")}</span>
      <WeaInputSearch value={name} onChange={val => this.setState({ name: val })} style={{ width: 200 }}
                      placeholder={getLabel(111, "请输入薪资项目名称")} onSearch={() => this.setState({
        pageInfo: { ...pageInfo, current: 1 }
      }, () => this.listSalaryItem())}/>
    </div>;
  };

  render() {
    const { selectedRowKeys, pageInfo, dataSource, loading } = this.state;
    const pagination = {
      ...pageInfo,
      showTotal: total => `共 ${total} 条`,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ["10", "20", "50", "100"],
      onShowSizeChange: (current, pageSize) => {
        this.setState({ pageInfo: { ...pageInfo, current: 1, pageSize } }, () => this.listSalaryItem());
      },
      onChange: current => {
        this.setState({ pageInfo: { ...pageInfo, current } }, () => this.listSalaryItem());
      }
    };
    const rowSelection = {
      selectedRowKeys, onChange: (selectedRowKeys) => this.setState({ selectedRowKeys })
    };
    return (
      <WeaDialog {...this.props} initLoadCss className="sys-salary-wrapper" ref={dom => this.sysItemRef = dom}
                 title={this.renderTitle()}
                 buttons={[<Button type="primary" onClick={this.handleAdd}
                                   disabled={_.isEmpty(selectedRowKeys)}>{getLabel(111, "添加")}</Button>]}
                 style={{
                   width: "60vw", height: 600, minHeight: 200, minWidth: 380,
                   maxHeight: "90%", maxWidth: "90%", overflow: "hidden", transform: "translate(0px, 0px)"
                 }}>
        <div className="sys-item-table-box">
          <Spin spinning={loading.query && pageInfo.total === 0}>
            <WeaTable columns={this.getSalaryItemAddColumns()} dataSource={dataSource} pagination={pagination}
                      loading={loading.query} scroll={{ y: this.sysItemRef ? this.sysItemRef.state.height - 112 : 600 }}
                      rowKey={record => record.id || record.key} rowSelection={rowSelection}/>
          </Spin>
        </div>
      </WeaDialog>
    );
  }
}
