/*
 * Author: 黎永顺
 * name: 新增人员范围弹框
 * Description:
 * Date: 2022/11/30
 */
import React, { Component } from "react";
import {
  WeaBrowser,
  WeaDialog,
  WeaFormItem,
  WeaHelpfulTip,
  WeaLocaleProvider,
  WeaSearchGroup,
  WeaSelect,
  WeaTextarea
} from "ecCom";
import { Button, message, Modal } from "antd";
import { getTaxAgentRangeForm } from "../../apis/taxAgent";
import { commonEnumList } from "../../apis/ruleconfig";
import { SelectWithAll } from "../../pages/socialSecurityBenefits/standingBookDetail/components/regAddEmployee";
import "./index.less";

const getLabel = WeaLocaleProvider.getLabel;

class PersonalScopeModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      employeeStatus: [],
      targetTypeList: [],
      targetType: "EMPLOYEE",
      targetTypeIds: "",
      targetTypeIdsNames: "",
      status: "",
      statusAll: ""
    };
  }

  componentDidMount() {

  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.visible !== this.props.visible && nextProps.visible) {
      const { isTaxgent = true } = nextProps;
      if (isTaxgent) {
        this.getTaxAgentRangeForm();
      } else {
        this.commonEnumList(nextProps);
      }
      if (!_.isEmpty(nextProps.record)) {
        this.setState({
          targetType: nextProps.record.targetType,
          targetTypeIds: nextProps.record.targetType !== "SQL" ? String(nextProps.record.targetId) : nextProps.record.target,
          targetTypeIdsNames: nextProps.record.targetName,
          status: nextProps.record.status,
          statusAll: ""
        });
      } else {
        this.handleReset();
      }
    }
  }

  commonEnumList = (props) => {
    const { record } = props;
    commonEnumList({ enumClass: "com.engine.salary.enums.UserStatusEnum" }).then(({ status, data }) => {
      if (status) {
        const targetTypeList = [
          {
            key: "EMPLOYEE",
            showname: "人员",
            selected: false
          },
          {
            key: "SUBCOMPANY",
            showname: "分部",
            selected: false
          },
          {
            key: "DEPT",
            showname: "部门",
            selected: false
          },
          {
            key: "POSITION",
            showname: "岗位",
            selected: false
          },
          {
            key: "SQL",
            showname: "SQL",
            selected: false
          }
        ];
        this.setState({
          targetTypeList,
          employeeStatus: _.map(_.filter(data, o => o.value !== 7), it => ({ key: it.enum, showname: it.defaultLabel }))
        }, () => {
          if (!_.isEmpty(record)) {
            const bool = _.every(_.map(this.state.employeeStatus, it => it.key), item => record.status.split(",").includes(item));
            this.setState({ statusAll: bool ? "0" : "" });
          }
        });
      }
    });
  };
  getTaxAgentRangeForm = () => {
    getTaxAgentRangeForm().then(({ status, data }) => {
      if (status) {
        const { employeeStatus, targetTypeList } = data;
        this.setState({
          targetTypeList: _.map(targetTypeList, it => ({ key: it.id, showname: it.name })),
          employeeStatus: _.map(employeeStatus, it => ({ key: it.id, showname: it.name }))
        });
      }
    });
  };
  handleSubmit = () => {
    const { status, targetTypeIds, targetType } = this.state;
    const { includeType, saveKeyVal, onSuccess, onCancel, APISaveFox, record } = this.props;
    if (_.isEmpty(status) || _.isEmpty(targetTypeIds)) {
      Modal.warning({
        title: "信息确认",
        content: "必要信息不完整，红色*为必填项！"
      });
      return;
    }
    const payload = {
      employeeStatus: status.split(","),
      includeType, id: record.id,
      targetParams: targetType !== "SQL" ?
        _.map(targetTypeIds.split(","), it => ({ targetType, targetId: it, target: "" })) :
        [{ targetType, targetId: "0", target: targetTypeIds }],
      [saveKeyVal["key"]]: saveKeyVal["value"]
    };
    this.setState({ loading: true });
    APISaveFox[_.isEmpty(record) ? "save" : "edit"](payload).then(({ status, errormsg }) => {
      this.setState({ loading: false });
      if (status) {
        message.success("保存成功");
        this.handleReset();
        onSuccess();
        onCancel();
      } else {
        message.error(errormsg || "保存失败");
      }
    }).catch(() => this.setState({ loading: true }));
  };
  renderBrowser = () => {
    const { record } = this.props;
    const { targetType, targetTypeIds, targetTypeIdsNames } = this.state;
    let browserType = {};
    switch (targetType) {
      case "EMPLOYEE":
        browserType = { ...browserType, type: 17, title: "人员选择" };
        break;
      case "DEPT":
        browserType = { ...browserType, type: 57, title: "部门选择" };
        break;
      case "SUBCOMPANY":
        browserType = { ...browserType, type: 164, title: "分部选择" };
        break;
      case "POSITION":
        browserType = { ...browserType, type: 278, title: "岗位选择" };
        break;
      case "SQL":
        return <div style={{ display: "flex", alignItems: "center" }}>
          <WeaTextarea minRows={2} viewAttr={3} style={{ width: 270 }} value={targetTypeIdsNames}
                       onChange={val => this.setState({ targetTypeIds: val, targetTypeIdsNames: val })}/>
          <WeaHelpfulTip style={{ marginLeft: 10 }} width={200} placement="topLeft" title={<SQLHelpTip/>}/>
        </div>;
      default:
        break;
    }
    return <WeaBrowser
      {...browserType}
      viewAttr={3}
      isSingle={!_.isEmpty(record)}
      value={targetTypeIds}
      replaceDatas={[{ id: targetTypeIds, name: targetTypeIdsNames }]}
      inputStyle={{ width: 200 }}
      onChange={(targetTypeIds, targetTypeIdsNames) => {
        this.setState({ targetTypeIds, targetTypeIdsNames });
      }}
    />;
  };
  handleReset = () => {
    this.setState({
      targetType: !_.isEmpty(this.props.record) ? this.props.record.targetType : "EMPLOYEE",
      targetTypeIds: "",
      status: "",
      statusAll: ""
    });
  };

  render() {
    const { onCancel, title, visible, record } = this.props;
    const { employeeStatus, targetTypeList, targetType, status, statusAll, loading } = this.state;
    const buttons = [
      <Button type="primary" onClick={this.handleSubmit} loading={loading}>确定</Button>,
      <Button type="ghost" onClick={this.handleReset}>重置</Button>
    ];
    return (
      <WeaDialog
        initLoadCss
        className="personalScopeModalWrapper"
        title={title}
        visible={visible}
        style={{ width: 600 }}
        buttons={buttons}
        onCancel={() => {
          this.handleReset();
          onCancel();
        }}
      >
        <WeaSearchGroup col={1} needTigger title="" showGroup center>
          <WeaFormItem
            label="对象类型"
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 18 }}
          >
            <div style={{ display: "flex", alignItems: "center" }}>
              <WeaSelect
                style={{ width: 60, marginRight: 12 }}
                disabled={!_.isEmpty(record)}
                value={targetType}
                options={targetTypeList}
                onChange={(targetType) => this.setState({ targetType })}
              />
              {this.renderBrowser()}
            </div>
          </WeaFormItem>
          {
            SelectWithAll({
              label: "选择员工状态",
              options: employeeStatus,
              detailtype: 2,
              valueAll: statusAll,
              value: status,
              onChangeAll: ({ selected }) => {
                if (selected) {
                  this.setState({
                    status: _.map(employeeStatus, it => it.key).join(","),
                    statusAll: selected
                  });
                } else {
                  this.setState({
                    status: "",
                    statusAll: selected
                  });
                }
              },
              onChange: ({ selected }) => {
                const bool = _.every(_.map(employeeStatus, it => it.key), item => selected.split(",").includes(item));
                if (bool) {
                  this.setState({
                    status: selected,
                    statusAll: "0"
                  });
                } else {
                  this.setState({
                    status: selected,
                    statusAll: ""
                  });
                }
              }
            })
          }
        </WeaSearchGroup>
      </WeaDialog>
    );
  }
}

export default PersonalScopeModal;

export const SQLHelpTip = () => {
  return <div>
    <p>{getLabel(111, "注意事项：")}</p>
    <p>{getLabel(111, "1、sql需返回人员id")}</p>
    <p>{getLabel(111, "2、sql结尾不需要 ; go /等符号")}</p>
    <p>{getLabel(111, "使用例子：定义获取岗位是开发的人员")}</p>
    <p>{getLabel(111, "select id from hrmresource where JOBTITLE = 17")}</p>
  </div>;
};
