/*
 * Author: 黎永顺
 * name: 数据采集-详情记录页面
 * Description:
 * Date: 2023/2/20
 */
import React, { Component } from "react";
import { WeaLocaleProvider, WeaSearchGroup, WeaTable } from "ecCom";
import { getTableRecordDate } from "../../../apis/cumDeduct";
import { DataCollectionDateRangePick, DataCollectionSelect, Input } from "../cumDeduct";
import "./index.less";

const getLabel = WeaLocaleProvider.getLabel;

class TableRecord extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: {
        query: false
      },
      width: 0,
      dataSource: [],
      columns: [],
      selectedRowKeys: [],
      pageInfo: {
        current: 1, pageSize: 10, total: 0
      },
      recordPayload: {
        accumulatedSpecialAdditionalDeductionId: "",
        otherTaxExemptDeductionId: "",
        accumulatedSituationId: "",
        specialAddDeductionId: "",
        taxAgentId: "",
        declareMonth: null,
        taxYearMonth: null
      }
    };
  }

  componentDidMount() {
    this.setState({ width: window.innerWidth });
    this.convertData(this.props);
    window.addEventListener("resize", this.resizeWidth);
  }

  componentWillUnmount() {
    window.removeEventListener("resize", this.resizeWidth);
  }

  componentWillReceiveProps(nextProps, nextContext) {
    this.convertData(nextProps);
  }

  resizeWidth = (e) => {
    this.setState({ width: e.target.innerWidth });
  };

  convertData = (props) => {
    const { recordPayload } = this.state;
    const { record, screenParams } = props;
    const modules = _.reduce(screenParams, (pre, cur) => (_.assign(pre, {
      [cur]: record[cur],
      [screenParams[0]]: record.id
    })), {});
    this.setState({
      recordPayload: {
        ...recordPayload,
        ...modules
      },
      pageInfo: {
        current: 1, pageSize: 10, total: 0
      }
    }, () => this.getTableRecordData());
  };

  getTableRecordData = () => {
    const { loading, pageInfo, recordPayload } = this.state;
    const { url, screenParams } = this.props;
    const monthkey = screenParams[screenParams.length - 1];
    const module = {
      ...pageInfo, ...recordPayload, url,
      [monthkey]: Object.prototype.toString.call(recordPayload[monthkey]) === "[object Array]" ? _.compact(recordPayload[monthkey]) : recordPayload[monthkey]
    };
    this.setState({ loading: { ...loading, query: true } });
    getTableRecordDate(_.pick(module, [...screenParams, "current", "pageSize", "url"])).then(({ status, data }) => {
      this.setState({ loading: { ...loading, query: false } });
      if (status) {
        const { columns, list: dataSource, pageNum: current, pageSize, total } = data;
        this.setState({
          pageInfo: { ...pageInfo, current, pageSize, total }, dataSource,
          columns: _.map(columns, (o, i) => {
            let col = {
              ...o, width: 110,
              render: text => (<span className="dataAc-ellipsis" title={text}>{text}</span>)
            };
            switch (o.dataIndex) {
              case "taxAgentName":
                col = { ...col, width: 180 };
                break;
              default:
                col = { ...col };
                break;
            }
            return i === 0 ? { ...col, fixed: "left" } : col;
          })
        });
      }
    }).catch(() => this.setState({ loading: { ...loading, query: false } }));
  };

  /*
  * Author: 黎永顺
  * Description: 详情页面-筛选操作
  * Params:
  * Date: 2023/2/20
  */
  handleTablerecordScreen = ({ key, value }) => {
    const { recordPayload } = this.state;
    this.setState({
      recordPayload: {
        ...recordPayload,
        [key]: value
      }
    }, () => this.getTableRecordData());
  };
  handleResetSelectKeys = () => {
    this.setState({
      selectedRowKeys: [],
      recordPayload: {
        accumulatedSpecialAdditionalDeductionId: "",
        otherTaxExemptDeductionId: "",
        accumulatedSituationId: "",
        specialAddDeductionId: "",
        taxAgentId: "",
        declareMonth: null,
        taxYearMonth: null
      }
    });
  };

  render() {
    const { className, screenParams, taxAgentOption, record } = this.props;
    const { columns, dataSource, loading, selectedRowKeys, pageInfo, recordPayload, width } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: (selectedRowKeys) => this.setState({ selectedRowKeys })
    };
    const pagination = {
      ...pageInfo,
      showTotal: (total) => `共 ${total} 条`,
      pageSizeOptions: ["10", "20", "50", "100"],
      showSizeChanger: true,
      showQuickJumper: true,
      onShowSizeChange: (current, pageSize) => {
        this.setState({
          pageInfo: { ...pageInfo, current, pageSize }
        }, () => {
          this.getTableRecordData();
        });
      },
      onChange: (current) => {
        this.setState({
          pageInfo: { ...pageInfo, current }
        }, () => {
          this.getTableRecordData();
        });
      }
    };
    const items = screenParams.length === 1 ? [
      {
        com: Input({ label: getLabel(111, "姓名"), value: record.username })
      }
    ] : [
      {
        com: Input({ label: getLabel(111, "姓名"), value: record.username })
      },
      {
        com: DataCollectionSelect({
          label: "个税扣缴义务人",
          value: !_.isNil(recordPayload.taxAgentId) ? recordPayload.taxAgentId.toString() : "",
          options: [{ key: "", showname: "全部" }, ...taxAgentOption],
          onChange: this.handleTablerecordScreen,
          key: "taxAgentId"
        })
      },
      {
        com: DataCollectionDateRangePick({
          label: "税款所属期",
          range: recordPayload[screenParams[screenParams.length - 1]] || [],
          onChange: this.handleTablerecordScreen,
          key: screenParams[screenParams.length - 1]
        })
      }
    ];
    return (
      <div className="tableRecordWrapper">
        {
          !_.isEmpty(screenParams) &&
          <div className="form-dialog-layout">
            <WeaSearchGroup className={className} showGroup needTigger={false} items={items} col={2}/>
          </div>
        }
        <WeaTable rowKey="id" rowSelection={rowSelection} bordered dataSource={dataSource} pagination={pagination}
                  loading={loading.query} scroll={{ x: 1200, y: `calc(100vh - 310px)` }} columns={columns}/>
      </div>
    );
  }
}

export default TableRecord;
