import React from "react";
import { Button, Col, message, Row } from "antd";
import { WeaDatePicker, WeaDialog, WeaInput, WeaSelect, WeaTable } from "ecCom";
import { inject, observer } from "mobx-react";
import moment from "moment";
import "./index.less";

@inject("salaryFileStore")
@observer
export default class ChangeSalaryModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      inited: false,
      canOperator: false,
      selectedRowKeys: [],
      salaryArchiveItems: [
        {
          key: "1",
          salaryItem: "",
          salaryBefore: "",
          adjustAfter: ""
        }
      ],
      request: {
        effectiveTime: moment(new Date()).format("YYYY-MM-DD"),
        salaryArchiveId: this.props.currentId,
        adjustReason: "",
        description: ""
      }
    };
  }

  // 改变回调
  handleChange(params) {
    let request = { ...this.state.request, ...params };
    this.setState({
      request
    });
  }

  // 表格中薪资项目选择项下拉，改变事件
  handleSalaryItemChange(item, value) {
    const { salaryFileStore: { getSalaryItemAdjustBeforeValue } } = this.props;
    const { salaryArchiveItems } = this.state;
    getSalaryItemAdjustBeforeValue({ salaryArchiveId: this.props.currentId, salaryItemId: value }).then((data) => {
      let dataSource = [...salaryArchiveItems];
      dataSource.map(i => {
        if (i.key == item.key) {
          i.salaryItem = value;
          i.salaryBefore = data;
        }
      });
      this.setState({
        salaryArchiveItems: dataSource
      });
    });
  }

  // 调整后表格字段变化回调
  handleSalaryAfterItemChange(item, value) {
    const { salaryArchiveItems } = this.state;
    let dataSource = [...salaryArchiveItems];
    dataSource.map(i => {
      if (i.key == item.key) {
        i.adjustAfter = value;
      }
    });
    this.setState({
      salaryArchiveItems: dataSource
    });
  }

  // 解析Columns
  getColumns() {
    const { canOperator } = this.state;
    const { salaryFileStore: { salaryItemChangeForm }, recordId } = this.props;
    const { salaryItemList } = salaryItemChangeForm;
    let { columns } = salaryItemChangeForm;
    return columns.map(item => {
      item = { ...item };
      if (item.dataIndex == "salaryItem") {
        item.title = <span>{item.title}</span>;
        item.render = (text, record) => {
          return (
            <WeaSelect
              value={text}
              style={{ width: 150 }}
              viewAttr={!recordId ? 3 : 1}
              options={
                !_.isEmpty(salaryItemList) ? [{ key: "", showname: "" }, ...salaryItemList] : [{
                  key: "",
                  showname: ""
                }]
              }
              onChange={(value) => this.handleSalaryItemChange(record, value)}/>
          );
        };
      } else if (item.dataIndex == "adjustAfter") {
        item.title = <span>{item.title}</span>;
        item.render = (text, record) => {
          return (
            <WeaInput
              style={{ width: "150px" }}
              viewAttr={((recordId && canOperator) || !recordId) ? 3 : 1}
              value={text}
              onChange={(value) => {
                this.handleSalaryAfterItemChange(record, value);
              }}
            />
          );
        };
      }
      return item;
    });
  }

  // 添加按钮点击回调
  handleAddItemClick() {
    const { salaryArchiveItems } = this.state;
    let result = [...salaryArchiveItems];
    let lastKey = "1";
    if (result.length > 0) {
      lastKey = parseInt(result[result.length - 1].key) + 1;
    }
    result.push({
      key: lastKey + "",
      salaryItem: "",
      adjustBefore: "",
      adjustAfter: ""
    });

    this.setState({
      salaryArchiveItems: result
    });
  }

  componentWillMount() {
    const {
      salaryFileStore: { salaryItemChangeForm, getSalaryItemForm, getSalaryItemFormByItemId },
      currentId,
      recordId
    } = this.props;
    if (recordId) {
      getSalaryItemFormByItemId(recordId).then(data => {
        let request = { ...this.state.request };
        request.effectiveTime = data.effectiveTime;
        request.adjustReason = data.adjustReason;
        request.description = data.description;
        this.setState({
          canOperator: data.canOperator,
          salaryArchiveItems: data.dataSource,
          inited: true,
          request
        });
      });
    } else {
      getSalaryItemForm(currentId).then(() => {
        this.setState({
          inited: true
        });
      });
    }
  }

  // 保存
  handleSave() {
    const { salaryFileStore: { saveSalaryItem, editSingleSalaryItem, fetchSingleSalaryItemList, getArchiveForm }, recordId } = this.props;
    let saveRequest = { ...this.state.request };
    const { salaryArchiveItems, canOperator } = this.state;
    if (salaryArchiveItems.length === 0) {
      message.warning("请添加调薪明细");
      return;
    }
    saveRequest.salaryArchiveItems = salaryArchiveItems.map(item => {
      let result = {};
      result.salaryItemId = item.salaryItem;
      result.adjustValue = item.adjustAfter;
      return result;
    });
    if (!recordId) {
      saveSalaryItem(saveRequest).then(() => {
        getArchiveForm(this.props.currentId);
        fetchSingleSalaryItemList({ salaryArchiveId: this.props.currentId });
        this.props.onCancel();
      });
    } else {
      editSingleSalaryItem({ ...saveRequest, salaryArchiveItemId: recordId, canOperator }).then(() => {
        getArchiveForm(this.props.currentId);
        fetchSingleSalaryItemList({ salaryArchiveId: this.props.currentId });
        this.props.onCancel();
      });
    }
  }

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

  // 批量删除回调
  handleRemoveClick = () => {
    const { selectedRowKeys, salaryArchiveItems } = this.state;
    let result = [...salaryArchiveItems];
    if (selectedRowKeys.length === 0) {
      message.warning("未选择条目");
    }

    this.setState({
      salaryArchiveItems: result.filter(item => selectedRowKeys.indexOf(item.key) < 0)
    });
  };

  render() {
    const { salaryFileStore: { salaryItemChangeForm }, recordId } = this.props;
    const { request, salaryArchiveItems, selectedRowKeys, canOperator } = this.state;
    const { effectiveTime, adjustReason, description } = request;

    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange
    };
    return (
      <WeaDialog
        title="调薪"
        style={{ width: 800 }}
        initLoadCss
        visible={this.props.visible}
        onCancel={() => {
          this.props.onCancel();
        }}
        buttons={[<Button type="primary" onClick={() => {
          this.handleSave();
        }}>保存</Button>]}
      >
        <div className="changeSalaryWrapper">
          <div className="changeSalaryModal">
            <Row className="itemWrapper" style={{ lineHeight: "47px" }}>
              <Col span={6}>生效日期</Col>
              <Col span={18}>
                <WeaDatePicker
                  viewAttr={((recordId && canOperator) || !recordId) ? 3 : 1}
                  format="yyyy-MM-dd"
                  style={{ width: "200px" }}
                  value={effectiveTime}
                  onChange={(value) => {
                    this.handleChange({ effectiveTime: value });
                  }}
                />
              </Col>
            </Row>
            <Row className="itemWrapper" style={{ lineHeight: "47px" }}>
              <Col span={6}>调整原因</Col>
              <Col span={18}>
                <WeaSelect
                  value={adjustReason}
                  style={{ width: 200 }}
                  viewAttr={((recordId && canOperator) || !recordId) ? 3 : 1}
                  onChange={(value) => this.handleChange({ adjustReason: value })}
                  options={
                    !_.isEmpty(salaryItemChangeForm.adjustReasonList) ?
                      [{ key: "", showname: "" }, ...salaryItemChangeForm.adjustReasonList] : [{
                        key: "",
                        showname: ""
                      }]
                  }
                />
              </Col>
            </Row>
            <Row className="itemWrapper" style={{ lineHeight: "47px" }}>
              <Col span={6}>
                说明
              </Col>
              <Col span={18}>
                <WeaInput
                  style={{ width: "200px" }}
                  value={description}
                  viewAttr={((recordId && canOperator) || !recordId) ? 2 : 1}
                  onChange={value => {
                    this.handleChange({ description: value });
                  }}
                />
              </Col>
            </Row>
          </div>
          <div className="contentWrapper">
            <div className="contentTitleWrapper" style={{ height: "40px", lineHeight: "40px" }}>
              <span className="contentTitle" style={{ fontSize: "14px", color: "#666" }}>调薪明细</span>
              {
                !recordId &&
                <div className="rightIconWrapper" style={{ display: "inline-block", float: "right" }}>
                  <Button
                    type="primary"
                    size="small"
                    disabled={salaryArchiveItems.length === 1}
                    onClick={() => {
                      this.handleRemoveClick();
                    }}
                  ><span className="icon-coms-form-delete-hot" title="删除"></span></Button>
                  <Button
                    type="primary"
                    size="small"
                    onClick={() => {
                      this.handleAddItemClick();
                    }}
                  ><span className="icon-coms-Add-to-hot" title="添加"></span></Button>
                </div>
              }
            </div>

            <div className="tableWrapper">
              {
                this.state.inited &&
                <WeaTable
                  rowSelection={!recordId ? rowSelection : null}
                  dataSource={salaryArchiveItems}
                  columns={this.getColumns()}
                  pagination={false}
                />
              }
            </div>
          </div>
        </div>
      </WeaDialog>
    );
  }
}
