/*
  * 数据推送记录
  * 创建
  * @Author:    黎永顺
  * @Date:      2025/4/15
  * @Wechat:
  * @Email:     971387674@qq.com
  * @description:
*/
import React, { Component } from "react";
import { WeaDialog, WeaFormItem, WeaLocaleProvider, WeaTable, WeaTools } from "ecCom";
import FormInfo from "../../../../components/FormInfo";
import { RQconditions } from "../../conditions";
import { MonthRangePicker } from "../../../reportView/components/statisticalMicroSettingsSlide";
import { getSalaryAcctList } from "../../../../apis/calculate";
import { createPushRecords } from "../../../../apis/datapush";
import { WeaForm, WeaSwitch } from "comsMobx";
import { Button, message } from "antd";
import moment from "moment";

const form = new WeaForm();
const getKey = WeaTools.getKey;
const getLabel = WeaLocaleProvider.getLabel;

class CreatePushRecordDialog extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataSource: [], columns: [], loading: false, pageInfo: { current: 1, pageSize: 10, total: 0 },
      conditions: []
    };
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.visible !== this.props.visible && nextProps.visible) {
      this.setState({
        conditions: _.map(RQconditions, item => ({
          ...item,
          items: _.map(item.items, o => {
            o = { ...o, label: getLabel(o.lanId, o.label) };
            if (getKey(o) === "startMonthStr") {
              return {
                ...o, value: moment(new Date()).subtract(1, "year").startOf("year").format("YYYY-MM")
              };
            } else if (getKey(o) === "endMonthStr") {
              return {
                ...o, value: moment(new Date()).endOf("year").format("YYYY-MM")
              };
            }
            return o;
          })
        }))
      }, () => {
        form.initFormFields(this.state.conditions);
        this.getSalaryAcctList();
      });
    } else {
      form.resetForm();
    }
  }

  getSalaryAcctList = () => {
    const { pageInfo } = this.state, payload = { ...pageInfo, ...form.getFormParams() };
    this.setState({ loading: true });
    getSalaryAcctList(payload).then(({ status, data }) => {
      this.setState({ loading: false });
      if (status) {
        const { columns, list: dataSource, pageNum: current, pageSize, total } = data;
        this.setState({
          dataSource, pageInfo: { current, pageSize, total },
          columns: _.filter(columns, it => (it.dataIndex !== "backCalcStatus" && it.dataIndex !== "acctTimes" && it.dataIndex !== "operate"))
        });
      }
    }).catch(() => this.setState({ loading: false }));
  };
  save = (record) => {
    this.setState({ loading: true });
    createPushRecords({ salaryAcctRecordIds: [record.id] }).then(({ status, errormsg }) => {
      this.setState({ loading: false });
      if (status) {
        message.success(getLabel(111, "操作成功！"));
        this.props.onCancel(this.props.onSuccess);
      } else {
        message.error(errormsg);
      }
    });
  };

  render() {
    const { loading, conditions, dataSource, columns, pageInfo } = this.state;
    const pagination = {
      ...pageInfo,
      showTotal: total => `${getLabel(18609, "共")} ${total} ${getLabel(18256, "条")}`,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ["10", "20", "50", "100"],
      onShowSizeChange: (current, pageSize) => {
        this.setState({ pageInfo: { ...pageInfo, current, pageSize } }, () => this.getSalaryAcctList());
      },
      onChange: current => {
        this.setState({ pageInfo: { ...pageInfo, current } }, () => this.getSalaryAcctList());
      }
    };
    const itemRender = {
      name: (field, textAreaProps, form, formParams) => {
        return (<WeaSwitch fieldConfig={{ ...field, ...textAreaProps }} form={form} formParams={formParams}
                           onChange={_.debounce(() => this.getSalaryAcctList(), 500)}/>);
      },
      startMonthStr: () => null,
      endMonthStr: () => null
    };
    const childrenComponents = {
      startMonthStr: () => {
        const { startMonthStr, endMonthStr } = form.getFormParams();
        const coms = [], { fieldMap } = form;
        const dateRange = [startMonthStr, endMonthStr];
        coms.push(
          <WeaFormItem label={<span>{fieldMap["startMonthStr"].label}</span>} labelCol={{ span: 6 }}
                       wrapperCol={{ span: 14 }}>
            <MonthRangePicker dateRange={dateRange} viewAttr={2} onChange={v => {
              const [v1, v2] = v;
              form.updateFields({ startMonthStr: v1, endMonthStr: v2 });
              this.getSalaryAcctList();
            }}/>
          </WeaFormItem>
        );
        return [{ com: coms, col: 2 }];
      }
    };
    const scrollHeight = this.refs.recordRef ? this.refs.recordRef.state.height - 162 : 606;

    return (<WeaDialog {...this.props} initLoadCss className="record-dialog" title={getLabel(111, "创建推送记录")}
                       ref="recordRef"
                       style={{
                         width: 1000, height: 580, minHeight: 200, minWidth: 380, maxHeight: "70%", maxWidth: "90%",
                         overflow: "hidden", transform: "translate(0px, 0px)"
                       }} buttons={[
      <Button onClick={() => this.props.onCancel()}>{getLabel(111, "取消")}</Button>
    ]}>
      <FormInfo className="record-form" center={false} itemRender={itemRender} colCount={2}
                form={form} formFields={conditions} childrenComponents={childrenComponents}/>
      <WeaTable className="wea-browser-table-cursor" rowKey="id" scroll={{ y: scrollHeight + "px" }}
                dataSource={dataSource} loading={loading} pagination={pagination} columns={columns}
                onRowClick={this.save}/>
    </WeaDialog>);
  }
}

export default CreatePushRecordDialog;
