/*
  *  数据推送
  *  新增编辑
  * @Author:    黎永顺
  * @Date:      2024/11/19
  * @Wechat:
  * @Email:     971387674@qq.com
  * @description:
*/
import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import { WeaButtonIcon, WeaLocaleProvider, WeaSearchGroup, WeaSlideModal, WeaTable, WeaTools } from "ecCom";
import PDetailDialog from "../PDDialog";
import { postFetch } from "../../../../util/request";
import * as API from "../../../../apis/datapush";
import { conditions } from "../../conditions";
import { Button, message, Modal } from "antd";
import { formRender } from "../../formRender";

const getLabel = WeaLocaleProvider.getLabel;
const getKey = WeaTools.getKey;

@inject("baseFormStore") @observer
class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      conditions: [], loading: false, columns: [], dataSource: [],
      PDDialog: { visible: false, title: "", settingId: "", detail: {} } //推送明细弹框
    };
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.visible !== this.props.visible && nextProps.visible) {
      document.querySelector(".datapush_wrapper").classList.add("zIndex0-weaslide-title");
      this.initForm(nextProps);
    }
    if (nextProps.visible !== this.props.visible && !nextProps.visible) {
      document.querySelector(".datapush_wrapper").classList.remove("zIndex0-weaslide-title");
      this.props.baseFormStore.initForm();
    }
  }

  initForm = async (props) => {
    const { detail } = props;
    const { data: salarySobList } = await postFetch("/api/bs/hrmsalary/salarysob/listAuth", { filterType: "ADMIN_DATA" });
    this.setState({
      conditions: _.map(conditions, item => ({
        ...item, title: getLabel(item.lanId, item.title), items: _.map(item.items, o => {
          o = { ...o, label: getLabel(o.lanId, o.label), value: detail[getKey(o)] || "" };
          if (getKey(o) === "salarySobIds") {
            return {
              ...o, value: detail[getKey(o)] ? detail[getKey(o)] : "",
              options: _.map(salarySobList, o => ({ key: String(o.id), showname: o.name }))
            };
          } else if (getKey(o) === "able") {
            return { ...o, value: !_.isEmpty(detail) ? String(detail[getKey(o)]) : o.value };
          }
          return { ...o };
        })
      }))
    }, () => {
      props.baseFormStore.form.initFormFields(this.state.conditions);
      !_.isEmpty(detail) && this.getPushItemList(props);
    });
  };
  getPushItemList = (props) => {
    const { detail } = props || this.props;
    const { id: settingId } = detail;
    API.getPushItemList({ settingId }).then(({ status, data }) => {
      if (status) {
        const { columns, list: dataSource } = data;
        this.setState({
          dataSource, columns: [...columns, {
            title: getLabel(111, "操作"), width: 120, render: (__, record) => (<React.Fragment>
              <a href="javascript: void(0);" style={{ marginRight: 10 }}
                 onClick={() => this.handleOpts("edit", record)}>{getLabel(111, "编辑")}</a>
              <a href="javascript: void(0);" style={{ marginRight: 10 }}
                 onClick={() => this.handleOpts("del", record.id)}>{getLabel(111, "删除")}</a>
            </React.Fragment>)
          }],
          PDDialog: { ...this.state.PDDialog, settingId }
        });
      }
    });
  };
  handleOpts = (type, detail = {}) => {
    switch (type) {
      case "edit":
        const { PDDialog } = this.state;
        this.setState({ PDDialog: { ...PDDialog, visible: true, title: getLabel(111, "编辑"), detail } });
        break;
      case "del":
        Modal.confirm({
          title: getLabel(111, "信息确认"),
          content: getLabel(111, "确认要删除吗?"),
          onOk: () => {
            API.deletePushItemList({ id: detail }).then(({ status, errormsg }) => {
              if (status) {
                message.success(getLabel(111, "删除成功"));
                this.getPushItemList();
              } else {
                message.error(errormsg);
              }
            });
          }
        });
        break;
      default:
        break;
    }
  };
  save = () => {
    const { baseFormStore: { form }, detail } = this.props;
    form.validateForm().then(f => {
      if (f.isValid) {
        const { salarySobIds, ...payload } = form.getFormParams();
        this.setState({ loading: true });
        API.savePushSetting({ ...payload, salarySobIds: salarySobIds.split(","), id: detail.id })
          .then(({ status, errormsg }) => {
            this.setState({ loading: false });
            if (status) {
              message.success(getLabel(30700, "操作成功"));
              this.props.onClose(this.props.onSearch());
            } else {
              message.error(errormsg);
            }
          }).catch(() => this.setState({ loading: false }));
      } else {
        f.showErrors();
      }
    });
  };
  renderTitle = () => {
    const { loading } = this.state, { title } = this.props;
    return <div className="titleDialog">
      <div className="titleCol titleLeftBox">
        <div className="titleIcon"><i className="icon-coms-fa"/></div>
        <div className="title">{title}</div>
      </div>
      <div className="titleCol titleRightBox">
        <Button type="primary" loading={loading} onClick={this.save}>{getLabel(537558, "保存")}</Button>
      </div>
    </div>;
  };

  render() {
    const { baseFormStore: { form }, detail } = this.props, { conditions, columns, dataSource, PDDialog } = this.state;
    return (<WeaSlideModal
      className="pushdata_create_dialog" {...this.props} direction="right"
      top={0} width={800} height={100} measureT="%" measureX="px" measureY="%" title={this.renderTitle()}
      content={<div className="form-dialog-layout">
        {formRender(form, conditions)}
        {!_.isEmpty(detail) &&
          <WeaSearchGroup title={getLabel(111, "推送明细")} showGroup needTigger className="pushdata_detail">
            <div className="opts">
              <WeaButtonIcon buttonType="add" type="primary" title={getLabel(111, "添加")}
                             onClick={() => this.setState({
                               PDDialog: { ...PDDialog, visible: true, title: getLabel(111, "新建") }
                             })}/>
            </div>
            <WeaTable pagination={false} columns={columns} dataSource={dataSource} bordered/>
            <PDetailDialog {...PDDialog} onSearch={this.getPushItemList}
                           onCancel={() => this.setState({ PDDialog: { ...PDDialog, visible: false, detail: {} } })}/>
          </WeaSearchGroup>}
      </div>}
    />);
  }
}

export default Index;
