import React from "react";
import { inject, observer } from "mobx-react";
import { Button, Dropdown, Menu, message, Modal } from "antd";
import { WeaInputSearch, WeaLoadingGlobal, WeaLocaleProvider, WeaTop } from "ecCom";
import * as API from "../../apis/item";
import SalaryItemsTable from "./salaryItemsTable";
import { toDecimal_n } from "../../util";
import SystemSalaryItemModal from "./systemSalaryItemModal";
import CustomSalaryItemSlide from "./customSalaryItemSlide";
import SyncToSalaryAccountSetDialog from "./syncToSalaryAccountSetDialog";
import LogDialog from "../../components/logViewModal";
import SalaryItemImportDialog from "./salaryItemImport";
import "./index.less";

const { getLabel } = WeaLocaleProvider;
@inject("salaryItemStore", "taxAgentStore", "salaryFileStore")
@observer
export default class SalaryItem extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "", isQuery: false, loading: false, sysVisible: false,
      customItemDialog: { visible: false, title: "", buttons: [] },// 自定义薪资项弹窗
      syncSalarySetDialog: { visible: false, id: "" }, // 同步到薪资账套弹窗
      logDialogVisible: false, filterConditions: "[]", selectedRowKeys: [],
      salaryItemImpDialog: { visible: false, title: getLabel(24023, "数据导入") }
    };
  }

  handleDeleteItem = (recordId) => {
    const { selectedRowKeys, isQuery } = this.state;
    const params = recordId ? [recordId] : selectedRowKeys;
    if (_.isEmpty(params)) {
      message.warning(getLabel(111, "请勾选数据！"));
      return;
    }
    Modal.confirm({
      title: getLabel(131329, "信息确认"),
      content: getLabel(111, "确认删除吗？"),
      onOk: () => {
        API.deleteItem(params).then(({ status, errormsg }) => {
          if (status) {
            message.success(getLabel(111, "操作成功！"));
            this.setState({ isQuery: !isQuery });
          } else {
            message.error(errormsg);
          }
        });
      }
    });
  };
  handleValidateForm = () => {
    return new Promise((resolve) => {
      const { salaryItemStore: { itemsForm: form } } = this.props;
      const { formulaId, valueType, sharedType, taxAgentIds } = form.getFormParams();
      let taxAgentValidate = true, formulaValidate = true;
      if (sharedType === "1" && !taxAgentIds) taxAgentValidate = false;
      if (valueType !== "1" && !formulaId) formulaValidate = false;
      resolve({ taxAgentValidate, formulaValidate });
    });
  };
  handleSalaryItem = (type) => {
    const { customItemDialog: { id }, isQuery } = this.state;
    const { salaryItemStore: { itemsForm: form } } = this.props;
    Promise.all([form.validateForm(), this.handleValidateForm()])
      .then(([f1, f2]) => {
        if (f1.isValid && f2.taxAgentValidate && f2.formulaValidate) {
          const { formulaContent, valueType, dataType, defaultValue, pattern, ...formData } = form.getFormParams();
          const key = valueType === "2" ? "originFormulaContent" : valueType === "3" ? "originSqlContent" : "formulaContent";
          this.setState({ loading: true });
          API.saveItem({
            ...formData, valueType, dataType, pattern, [key]: formulaContent, id,
            defaultValue: dataType === "number" ? toDecimal_n(defaultValue, parseInt(pattern)) : defaultValue
          }).then(({ status, errormsg }) => {
            this.setState({ loading: false });
            if (status) {
              this.setState({ isQuery: !isQuery }, () => {
                message.success(getLabel(111, "操作成功"));
                type === "SAVECREATE" && form.updateFields({
                  name: { value: "" }, formulaContent: { value: "" }, formulaId: { value: "" }
                });
                type !== "SAVECREATE" && this.setState({
                  customItemDialog: { ...this.state.customItemDialog, visible: false, id: "" }
                });
              });

            } else {
              message.error(errormsg);
            }
          });
        } else {
          !f1.isValid && f1.showErrors();
          !f2.taxAgentValidate && f1.showError("taxAgentIds", getLabel(111, "\"可见性范围\"未填写"));
          !f2.formulaValidate && f1.showError("formulaContent", getLabel(111, `\"${form.getFormDatas().valueType.valueSpan}\"未填写`));
          this.forceUpdate();
        }
      });
  };
  onDropMenuClick = (key, targetid = "") => {
    switch (key) {
      case "log":
        this.setState({
          logDialogVisible: true,
          filterConditions: targetid ? `[{\"connectCondition\":\"AND\",\"columIndex\":\"targetid\",\"type\":\"=\",\"value\":\"${targetid}\"}]` : "[]"
        });
        break;
      case "export":
        WeaLoadingGlobal.start();
        const { selectedRowKeys } = this.state;
        const promise = API.exportSalaryitem({ ids: selectedRowKeys });
        WeaLoadingGlobal.destroy();
        break;
      case "import":
        this.setState({
          salaryItemImpDialog: {
            ...this.state.salaryItemImpDialog, visible: true
          }
        });
        break;
      case "customAdd":
      case "edit":
        const { taxAgentStore: { showOperateBtn } } = this.props;
        const { loading } = this.state;
        const editTitle = !showOperateBtn ? getLabel(111, "查看自定义薪资项目") : getLabel(111, "修改自定义薪资项目");
        const title = key === "edit" ? editTitle : getLabel(111, "新建自定义薪资项目");
        const buttons = key === "edit" ? [
          <Button type="ghost" onClick={() => this.setState({
            syncSalarySetDialog: { visible: true, id: targetid }
          })}>{getLabel(111, "同步到薪资账套")}</Button>,
          <Button type="primary" loading={loading}
                  onClick={() => this.handleSalaryItem("SAVE")}>{getLabel(111, "保存")}</Button>
        ] : [
          <Button type="primary" loading={loading}
                  onClick={() => this.handleSalaryItem("SAVE")}>{getLabel(111, "保存")}</Button>,
          <Button type="ghost" loading={loading}
                  onClick={() => this.handleSalaryItem("SAVECREATE")}>{getLabel(111, "保存并继续创建")}</Button>
        ];
        this.setState({
          customItemDialog: {
            visible: true, title, buttons: showOperateBtn ? buttons : [], id: targetid
          }
        });
        break;
      case "delete":
        this.handleDeleteItem(targetid);
        break;
      case "sysAdd":
        this.setState({ sysVisible: true });
        break;
      default:
        break;
    }
  };

  render() {
    const { taxAgentStore: { showOperateBtn } } = this.props;
    const {
      selectedRowKeys, logDialogVisible, filterConditions, name, isQuery, customItemDialog, sysVisible,
      salaryItemImpDialog
    } = this.state;
    const menu = (
      <Menu onClick={({ key }) => this.onDropMenuClick(key)}>
        <Menu.Item key="sysAdd">{getLabel(111, "新增系统薪资项")}</Menu.Item>
      </Menu>
    );
    let buttons = [
      <Dropdown.Button overlay={menu} type="primary"
                       onClick={() => this.onDropMenuClick("customAdd")}>{getLabel(111, "新增自定义薪资项")}</Dropdown.Button>,
      <Button type="ghost" onClick={() => this.handleDeleteItem()}>{getLabel(32136, "批量删除")}</Button>,
      <WeaInputSearch value={name} onChange={val => this.setState({ name: val })}
                      placeholder={getLabel(111, "请输入名称")} onSearch={() => this.setState({ isQuery: !isQuery })}/>
    ];
    let dropMenuDatas = [
      { key: "import", icon: <i className="icon-coms02-Template-import1"/>, content: getLabel(111, "导入") },
      { key: "export", icon: <i className="iconfont icon-daochu"/>, content: getLabel(111, "导出") },
      { key: "log", icon: <i className="iconfont icon-caozuorizhi32"/>, content: getLabel(545781, "操作日志") }
    ];
    !showOperateBtn && (buttons = buttons.slice(-1));
    !showOperateBtn && (dropMenuDatas = dropMenuDatas.slice(-1));
    return (
      <React.Fragment>
        <WeaTop title={getLabel(111, "薪资项目管理")} icon={<i className="icon-coms-fa"/>} iconBgcolor="#F14A2D"
                buttons={buttons} showDropIcon onDropMenuClick={this.onDropMenuClick} dropMenuDatas={dropMenuDatas}
                className="salaryProjectManagement">
          <div className="salaryItems_content">
            <SalaryItemsTable {...this.props} name={name} isQuery={isQuery} showOperateBtn={showOperateBtn}
                              selectedRowKeys={selectedRowKeys} onDropMenuClick={this.onDropMenuClick}
                              onChange={val => this.setState({ selectedRowKeys: val })}/>
          </div>
        </WeaTop>
        {/*添加系统薪资项目*/}
        <SystemSalaryItemModal visible={sysVisible} onSearch={() => this.setState({ isQuery: !isQuery })}
                               onCancel={(callback) => this.setState({ sysVisible: false }, () => callback && callback())}/>
        {/*同步薪资账套*/}
        <SyncToSalaryAccountSetDialog
          {...this.state.syncSalarySetDialog}
          onCancel={() => this.setState({ syncSalarySetDialog: { visible: false, id: "" } })}/>
        {/*操作日志*/}
        <LogDialog visible={logDialogVisible} logFunction="salaryitem" filterConditions={filterConditions}
                   onCancel={() => this.setState({ logDialogVisible: false })}/>
        {/* 导入*/}
        <SalaryItemImportDialog {...salaryItemImpDialog}
                                onCancel={callback => {
                                  this.setState({
                                    salaryItemImpDialog: { ...salaryItemImpDialog, visible: false }
                                  }, () => callback && this.setState({ isQuery: !isQuery }));
                                }}/>
        {/*新增编辑自定义薪资项目*/}
        <CustomSalaryItemSlide {...customItemDialog} onSearch={() => this.setState({ isQuery: !isQuery })}
                               showOperateBtn={showOperateBtn}
                               onClose={callback => this.setState({
                                 customItemDialog: { ...customItemDialog, visible: false, id: "" }
                               }, () => callback && callback())}/>
      </React.Fragment>
    );
  }
}
