/*
 * Author: 黎永顺
 * name: 新增人员范围弹框
 * Description:
 * Date: 2022/11/30
 */
import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import { WeaSwitch } from "comsMobx";
import { WeaCheckbox, WeaDialog, WeaFormItem, WeaHelpfulTip, WeaLocaleProvider, WeaSearchGroup, WeaTools } from "ecCom";
import { Button, message } from "antd";
import { getTaxAgentRangeForm, taxAgentRangeEdit, taxAgentRangeSave } from "../../../apis/taxAgent";
import { personScopeConditions, scopeSelectLinkageDatas } from "./constants";

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

@inject("taxAgentStore")
@observer
class PersonalScopeModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false, conditions: [], employeeStatus: []
    };
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.visible !== this.props.visible && nextProps.visible) this.getTaxAgentRangeForm(nextProps);
    if (nextProps.visible !== this.props.visible && !nextProps.visible) this.props.taxAgentStore.initPersonScopeForm();
  }

  getTaxAgentRangeForm = (props) => {
    const { record } = props;
    getTaxAgentRangeForm().then(({ status, data }) => {
      if (status) {
        const { employeeStatus, targetTypeList } = data;
        this.setState({
          employeeStatus, conditions: _.map(personScopeConditions, item => ({
            ...item, items: _.map(item.items, o => {
              if (getKey(o) === "employeeStatus") {
                return {
                  ...o, label: getLabel(o.lanId, o.label), value: !_.isEmpty(record) ? record.status : "",
                  options: _.map(employeeStatus, it => ({ key: it.id, showname: it.name }))
                };
              }
              return {
                ...o, label: getLabel(o.lanId, o.label), viewAttr: !_.isEmpty(record) ? 1 : 3,
                options: _.map(targetTypeList, it => ({
                  key: it.id, showname: it.name,
                  selected: !_.isEmpty(record) ? it.id === record.targetType : it.id === "EMPLOYEE"
                })),
                selectLinkageDatas: {
                  ..._.reduce(_.keys(scopeSelectLinkageDatas), (pre, cur) => {
                    if (cur !== "SQL") {
                      return {
                        ...pre,
                        [cur]: {
                          ...scopeSelectLinkageDatas[cur],
                          browserConditionParam: {
                            ...scopeSelectLinkageDatas[cur].browserConditionParam,
                            isSingle: true,
                            replaceDatas: !_.isEmpty(record) ? [{
                              id: String(record.targetId),
                              name: record.targetName
                            }] : []
                          }
                        }
                      };
                    }
                    return {
                      ...pre, [cur]: { ...scopeSelectLinkageDatas[cur], value: !_.isEmpty(record) ? record.target : "" }
                    };
                  }, {})
                }
              };
            })
          }))
        }, () => this.props.taxAgentStore.personScopeForm.initFormFields(this.state.conditions));
      }
    });
  };
  taxAgentRangeSave = () => {
    const { taxAgentStore: { personScopeForm }, record = {} } = this.props;
    personScopeForm.validateForm().then(f => {
      if (f.isValid) {
        const { employeeStatus, targetType, target } = personScopeForm.getFormParams();
        const { includeType, taxAgentId } = this.props;
        const payload = {
          includeType, taxAgentId, employeeStatus: employeeStatus.split(","), id: record.id,
          targetParams: _.map(target.split(","), it => ({
            targetType, targetId: targetType === "SQL" ? "0" : it,
            target: targetType === "SQL" ? target : ""
          }))
        };
        this.setState({ loading: true });
        const API = !_.isEmpty(record) ? taxAgentRangeEdit : taxAgentRangeSave;
        API(payload).then(({ status, errormsg }) => {
          this.setState({ loading: false });
          if (status) {
            message.success(getLabel(111, "操作成功！"));
            this.props.onCancel(this.props.onSuccess);
          } else {
            message.error(errormsg);
          }
        }).catch(() => this.setState({ loading: true }));
      } else {
        f.showErrors();
      }
    });
  };
  renderForm = () => {
    const { taxAgentStore: { personScopeForm } } = this.props;
    const { conditions, employeeStatus } = this.state, { isFormInit } = personScopeForm,
      formParams = personScopeForm.getFormParams();
    const checked = formParams.employeeStatus && _.every(_.map(employeeStatus, o => o.id), k => formParams.employeeStatus.indexOf(k) !== -1);
    let group = [];
    isFormInit && conditions.map(c => {
      let items = [];
      c.items.map(fields => {
        items.push({
          com: (
            <WeaFormItem label={`${fields.label}`} labelCol={{ span: `${fields.labelcol}` }}
                         wrapperCol={{ span: `${fields.fieldcol}` }} error={personScopeForm.getError(fields)}
                         tipPosition="bottom">
              {
                getKey(fields) === "employeeStatus" &&
                <WeaCheckbox value={checked ? "1" : "0"} content={getLabel(111, "全选")}
                             onChange={this.handleChangeAll}/>
              }
              <WeaSwitch fieldConfig={fields} form={personScopeForm} formParams={formParams}/>
              {
                personScopeForm.getFormParams().targetType === "SQL" && getKey(fields) === "targetType" &&
                <WeaHelpfulTip placement="topLeft" style={{ position: "absolute", top: "50%", right: "-35px" }}
                               width={200} title={
                  <span
                    dangerouslySetInnerHTML={{ __html: getLabel(111, "注意事项：<br>1、sql需返回人员id<br>2、sql结尾不需要 ; go /等符号<br>使用例子：定义获取岗位是开发的人员<br>select id from hrmresource where JOBTITLE = 17") }}/>
                }/>
              }
            </WeaFormItem>),
          hide: fields.hide
        });
      });
      group.push(<WeaSearchGroup col={1} needTigger showGroup={c.defaultshow} items={items}/>);
    });
    return group;
  };
  handleChangeAll = (val) => {
    const { taxAgentStore: { personScopeForm } } = this.props, { employeeStatus } = this.state;
    val === "1" ? personScopeForm.updateFields({ employeeStatus: { value: _.map(employeeStatus, o => o.id).join(",") } }) :
      personScopeForm.updateFields({ employeeStatus: { value: "" } });
  };

  render() {
    const { title, taxAgentStore: { personScopeForm } } = this.props, { loading } = this.state;
    const buttons = [
      <Button type="primary" onClick={this.taxAgentRangeSave} loading={loading}>{getLabel(111, "确定")}</Button>,
      <Button type="ghost" onClick={() => personScopeForm.resetForm()}>{getLabel(111, "重置")}</Button>
    ];
    return (
      <WeaDialog {...this.props} initLoadCss title={title} style={{ width: 600, height: 159 }} buttons={buttons}
                 className="scopeDialog">
        <div className="form-dialog-layout">{this.renderForm()}</div>
      </WeaDialog>
    );
  }
}

export default PersonalScopeModal;
