import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import { Button, message, Modal } from "antd";
import { WeaCheckbox, WeaFormItem, WeaInputSearch, WeaLocaleProvider, WeaSearchGroup, WeaTop } from "ecCom";
import { apiflowBillingConfigStatus } from "../../apis/intelligentCalculateSalarySettings";
import ComHint from "./components/comHint";
import TaxAgentTable from "./components/taxAgentTable";
import TaxAgentSlide from "./components/taxAgentSlide";
import * as API from "../../apis/taxAgent";
import LogDialog from "../../components/logViewModal";
import "./index.less";

const { getLabel } = WeaLocaleProvider;

@inject("taxAgentStore")
@observer
class TaxAgent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      syncLoading: false, //同步人员范围loading
      searchValue: "",
      decentralization: "0", //启用分权
      permission: {},
      taxAgentSlideProps: {
        isEdit: false, visible: false, title: getLabel(543629, "新增个税扣缴义务人"),
        taxAgentId: "", current: 0, salaryOn: true
      },
      logDialogVisible: false,
      filterConditions: "[]"
    };
    this.taxAgentTableRef = null;
  }

  componentDidMount() {
    this.getTaxAgentBaseForm();
    this.getPermission();
    this.apiflowBillingConfigStatus();
  }

  getTaxAgentBaseForm = () => {
    API.getTaxAgentBaseForm().then(({ status, data }) => {
      if (status) {
        const { devolutionStatus } = data;
        this.setState({ decentralization: String(devolutionStatus || 0) });
      }
    });
  };
  getPermission = () => {
    const { taxAgentStore: { getPermission } } = this.props;
    getPermission().then(({ status, data }) => {
      if (status) {
        this.setState({ permission: data });
      }
    });
  };
  apiflowBillingConfigStatus = () => {
    const { taxAgentSlideProps } = this.state;
    apiflowBillingConfigStatus().then(({ status, data }) => {
      if (status) this.setState({ taxAgentSlideProps: { ...taxAgentSlideProps, salaryOn: data } });
    });
  };
  /*
   * Author: 黎永顺
   * Description:开启关闭个税扣缴义务人开关
   * Params:
   * Date: 2022/11/29
   */
  taxAgentBaseSave = devolutionStatus => {
    this.setState({ decentralization: this.state.decentralization }, () => {
      Modal.confirm({
        title: getLabel(131329, "信息确认"),
        content: `${getLabel(33703, "确认")}${devolutionStatus === "0" ? getLabel(26471, "停用") : getLabel(26472, "启用")}${getLabel(524044, "分权")}?`,
        onOk: () => {
          const paylaod = { devolutionStatus };
          const { taxAgentStore } = this.props;
          const { taxAgentBaseSave, setSalarytaxAgentForm } = taxAgentStore;
          taxAgentBaseSave(paylaod).then(({ status, errormsg }) => {
            if (status) {
              message.success(`${devolutionStatus === "0" ? "停用" : "启用"}分权成功`);
              this.getTaxAgentBaseForm();
              this.getPermission();
              this.taxAgentTableRef.getTaxAgentList();
              setSalarytaxAgentForm();
            } else {
              message.error(errormsg || `${devolutionStatus === "0" ? "停用" : "启用"}分权失败`);
            }
          });
        }
      });
    });
  };
  /*
   * Author: 黎永顺
   * Description:
   * Params:添加个税扣缴义务人
   * Date: 2022/11/29
   */
  handleAddTaxAgent = () => {
    this.setState({
      taxAgentSlideProps: {
        ...this.state.taxAgentSlideProps,
        visible: true, current: 0
      }
    });
  };
  /*
   * Author: 黎永顺
   * Description:启用分权
   * Params:
   * Date: 2022/12/1
   */
  taxAgentRangeSync = () => {
    const { taxAgentStore } = this.props;
    const { taxAgentRangeSync } = taxAgentStore;
    this.setState({ syncLoading: true });
    taxAgentRangeSync({}).then(({ status, data, errormsg }) => {
      this.setState({ syncLoading: false });
      if (status) {
        message.success(data || getLabel(30700, "操作成功"));
        this.taxAgentTableRef.getTaxAgentList();
      } else {
        message.error(data || errormsg || getLabel(30651, "操作失败"));
      }
    });
  };
  handelResetSlide = (isUpdate = false) => {
    const { taxAgentStore } = this.props;
    const { salarytaxAgentForm } = taxAgentStore;
    this.setState({
      taxAgentSlideProps: {
        ...this.state.taxAgentSlideProps,
        isEdit: false,
        visible: false,
        title: getLabel(543629, "新增个税扣缴义务人"),
        taxAgentId: "",
        current: 0
      }
    }, () => {
      isUpdate && this.taxAgentTableRef.getTaxAgentList();
      salarytaxAgentForm.resetForm();
    });
  };
  handleOperate = (type, itemId, current = 0) => {
    switch (type) {
      case "edit":
        this.setState({
          taxAgentSlideProps: {
            ...this.state.taxAgentSlideProps,
            visible: true, title: getLabel(543632, "编辑个税扣缴义务人"),
            taxAgentId: itemId, current, isEdit: true
          }
        });
        break;
      case "delete":
        Modal.confirm({
          title: getLabel(131329, "信息确认"),
          content: getLabel(388758, "确认要删除吗?"),
          onOk: () => {
            API.deleteTaxAgent([itemId]).then(({ status, errormsg }) => {
              if (status) {
                message.success(getLabel(502230, "删除成功"));
                this.taxAgentTableRef.getTaxAgentList();
              } else {
                message.error(errormsg || getLabel(20462, "删除失败"));
              }
            });
          }
        });
        break;
      case "log":
        this.setState({
          logDialogVisible: true,
          filterConditions: itemId ? `[{\"connectCondition\":\"AND\",\"columIndex\":\"targetid\",\"type\":\"=\",\"value\":\"${itemId}\"}]` : "[]"
        });
        break;
      default:
        break;
    }
  };

  render() {
    const {
      searchValue, decentralization, taxAgentSlideProps,
      permission, syncLoading, logDialogVisible, filterConditions
    } = this.state;
    const btns = [
      <Button type="primary" onClick={this.taxAgentRangeSync}
              loading={syncLoading}>{getLabel(543633, "同步人员范围")}</Button>,
      <WeaInputSearch
        style={{ width: 220 }}
        value={searchValue}
        onChange={searchValue => this.setState({ searchValue })}
        placeholder={getLabel(543634, "请输入个税扣缴义务人名称")}
        onSearch={() => this.taxAgentTableRef.getTaxAgentList()}
      />
    ];
    const customTitle = <div className="customTitleWrapper">
      <span>{getLabel(537996, "个税扣缴义务人")}</span>
      {
        permission.isChief &&
        <Button type="primary" size="small" onClick={this.handleAddTaxAgent}>
          <span className="icon-coms-Add-to-hot" title={getLabel(384113, "添加")}></span>
        </Button>
      }
    </div>;
    return (
      <div className="salaryAgentWrapper">
        <WeaTop
          title={getLabel(537996, "个税扣缴义务人")}
          icon={<i className="icon-coms-fa"/>}
          iconBgcolor="#F14A2D"
          buttons={btns}
          showDropIcon onDropMenuClick={key => this.handleOperate(key)}
          dropMenuDatas={[
            {
              key: "log", icon: <i className="iconfont icon-caozuorizhi32"/>,
              content: getLabel(545781, "操作日志")
            }
          ]}
        >
          <div className="comContent">
            {
              permission.isChief &&
              <WeaSearchGroup title={getLabel(82743, "基础信息")} showGroup>
                <WeaFormItem label={getLabel(543639, "启用分权")} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
                  <WeaCheckbox value={decentralization} display="switch" onChange={this.taxAgentBaseSave}/>
                </WeaFormItem>
              </WeaSearchGroup>
            }
            <WeaSearchGroup title={customTitle} showGroup>
              <TaxAgentTable searchValue={searchValue} onOperate={this.handleOperate}
                             isChief={permission.isChief} //isChief- 是否是总管理员
                             ref={dom => this.taxAgentTableRef = dom}/>
            </WeaSearchGroup>
          </div>
          <ComHint/>
          <TaxAgentSlide
            {...taxAgentSlideProps}
            isChief={permission.isChief} //isChief- 是否是总管理员
            decentralization={decentralization} //是否开启分权 0：否 1：是 ;开启分权才有管理员的添加
            onOk={() => this.taxAgentTableRef.getTaxAgentList()}
            onCancel={(isUpdate = false) => this.handelResetSlide(isUpdate)}
          />
          {/*操作日志*/}
          <LogDialog visible={logDialogVisible} logFunction="taxagent" filterConditions={filterConditions}
                     onCancel={() => this.setState({ logDialogVisible: false })}/>
        </WeaTop>
      </div>
    );
  }
}

export default TaxAgent;
