/*
 * Author: 黎永顺
 * name: 社保福利台账重构
 * version: 1.0
 * Description:
 * Date: 2024/1/23
 */
import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import { WeaLocaleProvider, WeaTop } from "ecCom";
import { Button, Dropdown, Icon, Menu, message, Modal } from "antd";
import * as API from "../../../apis/standingBook";
import WelfareRecordQuery from "./components/welfareRecordQuery";
import WelfareRecordList from "./components/welfareRecordList";
import Accountdialog from "./components/accountDialog";
import ProgressModal from "../../../components/progressModal";
import LogDialog from "../../../components/logViewModal";
import moment from "moment";
import "./index.less";

const getLabel = WeaLocaleProvider.getLabel;

@inject("standingBookStore", "taxAgentStore")
@observer
class StandingBook extends Component {
  constructor(props) {
    super(props);
    this.state = {
      queryForm: {
        startTime: moment(new Date()).subtract(1, "year").startOf("year").format("YYYY-MM"),
        endTime: moment(new Date()).endOf("year").format("YYYY-MM"),
        taxAgents: ""
      }, progressVisible: false, progress: 0, selectedRowKeys: [],
      accountDialog: { visible: false, title: "", loading: false, options: [] },
      logDialogVisible: false, filterConditions: "[]"
    };
    this.wfListRef = null;
    this.timer = null;
  }

  /*
   * Author: 黎永顺
   * Description: 社保福利台账重构-核算
   * Params:
   * Date: 2024/1/23
   */
  handleAccount = async (formVal) => {
    const { billMonth, paymentOrganization, ...extra } = formVal;
    const payload = {
      billMonth: moment(billMonth).format("YYYY-MM"),
      paymentOrganizations: paymentOrganization.split(","),
      ...extra
    };
    this.setState({ accountDialog: { ...this.state.accountDialog, loading: true } });
    API.batSave(payload).then(({ status, errormsg }) => {
      this.setState({ accountDialog: { ...this.state.accountDialog, loading: false } });
      if (status) {
        message.success(getLabel(543232, "核算成功"));
        this.setState({
          accountDialog: { ...this.state.accountDialog, visible: false }
        }, () => {
          this.wfListRef.wrappedInstance.getWelfareRecordList();
        });
      } else {
        message.error(errormsg);
      }
    });
    // const { data: creator, status, errormsg } = await API.save(payload);
    // if (status) {
    //   this.setState({
    //     accountDialog: { ...this.state.accountDialog, loading: false },
    //     progressVisible: true
    //   }, () => {
    //     this.timer = setInterval(() => {
    //       getCalculateProgress(moment(billMonth).format("YYYY-MM"), payload.paymentOrganization)
    //         .then(({ status, data }) => {
    //           if (status) {
    //             if (!data.status) {
    //               clearInterval(this.timer);
    //               this.setState({ progressVisible: false, progress: 0 });
    //               message.error(data.message);
    //               return;
    //             }
    //             if (this.state.progress !== 100) {
    //               this.setState({
    //                 progress: (Number(data.progress).toFixed(2)) * 100
    //               });
    //             } else {
    //               clearInterval(this.timer);
    //               this.setState({ progressVisible: false, progress: 0 }, () => {
    //                 message.success(getLabel(543232, "核算成功"));
    //                 this.setState({
    //                   accountDialog: { ...this.state.accountDialog, visible: false }
    //                 }, () => {
    //                   this.wfListRef.wrappedInstance.getWelfareRecordList();
    //                   const calcPayload = { ...payload, creator };
    //                   window.open(`/spa/hrmSalary/static/index.html#/main/hrmSalary/socialSecurityBenefits/standingBookDetail?${convertToUrlString(calcPayload)}`);
    //                 });
    //               });
    //             }
    //           } else {
    //             clearInterval(this.timer);
    //             this.setState({ progressVisible: false, progress: 0 });
    //           }
    //         }).catch(() => {
    //         clearInterval(this.timer);
    //         this.setState({ progressVisible: false, progress: 0 });
    //       });
    //     }, 600);
    //   });
    // } else {
    //   message.error(errormsg);
    //   clearInterval(this.timer);
    //   this.setState({
    //     accountDialog: { ...this.state.accountDialog, loading: false },
    //     progressVisible: false, progress: 0
    //   });
    // }
  };
  onDropMenuClick = (key, targetid = "") => {
    switch (key) {
      case "batReAcct":
        Modal.confirm({
          title: getLabel(111, "确认信息"),
          content: getLabel(111, "重新核算后，选中的台账数据将可以删除且可以进行此月份的核算，是否确认取消归档？"),
          onOk: () => {
            API.batSocialSecurityBenefitsRecalculate({ ids: this.state.selectedRowKeys })
              .then(({ status, errormsg }) => {
                if (status) {
                  message.success(getLabel(30700, "操作成功！"));
                  this.wfListRef.wrappedInstance.getWelfareRecordList();
                } else {
                  message.error(errormsg);
                }
              });
          }
        });
        break;
      case "batDel":
        Modal.confirm({
          title: getLabel(111, "确认信息"), content: getLabel(388758, "确认要删除吗?"),
          onOk: () => {
            const delDataLen = this.state.selectedRowKeys.length;
            API.batSiaccountDelete({ ids: this.state.selectedRowKeys }).then(({ status, errormsg }) => {
              if (status) {
                message.success(getLabel(502230, "删除成功"));
                this.setState({ selectedRowKeys: [] }, () => this.wfListRef.wrappedInstance.batDelQueryList(delDataLen));
              } else {
                message.error(errormsg);
              }
            });
          }
        });
        break;
      case "batArchiving":
        Modal.confirm({
          title: getLabel(111, "确认信息"),
          content: getLabel(111, "归档后，此条台账数据无法删除且不可以再进行此月份的核算，是否确认归档？"),
          onOk: () => {
            API.batSiaccountFile({ ids: this.state.selectedRowKeys }).then(({ status, errormsg }) => {
              if (status) {
                message.success(getLabel(30700, "操作成功！"));
                this.wfListRef.wrappedInstance.getWelfareRecordList();
              } else {
                message.error(errormsg);
              }
            });
          }
        });
        break;
      case "log":
        this.setState({
          logDialogVisible: true,
          filterConditions: targetid ? `[{\"connectCondition\":\"AND\",\"columIndex\":\"targetid\",\"type\":\"=\",\"value\":\"${targetid}\"}]` : "[]"
        });
        break;
      default:
        break;
    }
  };

  render() {
    const { accountDialog, queryForm, logDialogVisible, filterConditions, selectedRowKeys } = this.state;
    const { taxAgentStore: { showOperateBtn } } = this.props;
    const menu = (
      <Menu onClick={({ key }) => this.onDropMenuClick(key)}>
        <Menu.Item key="batDel" disabled={_.isEmpty(selectedRowKeys)}>{getLabel(111, "批量删除")}</Menu.Item>
        <Menu.Item key="batReAcct" disabled={_.isEmpty(selectedRowKeys)}>{getLabel(111, "批量重新核算")}</Menu.Item>
      </Menu>
    );
    const rightBtns = [
      <Button type="primary" onClick={() => this.setState({
        accountDialog: { ...accountDialog, visible: true, title: getLabel(538780, "核算") }
      })}>{getLabel(538780, "核算")}</Button>,
      <React.Fragment>
        <Button type="primary" onClick={() => this.onDropMenuClick("batArchiving")} className="cust-dropdown-btn"
                disabled={_.isEmpty(selectedRowKeys)}>{getLabel(111, "批量归档")}</Button>
        <Dropdown overlay={menu}>
          <Button type="primary" disabled={_.isEmpty(selectedRowKeys)} className="cust-dropdown-btnIcon"><Icon
            type="down"/></Button>
        </Dropdown>
      </React.Fragment>
    ];
    return (<WeaTop title={getLabel(538002, "社保福利台账")} icon={<i className="icon-coms-fa"/>}
                    iconBgcolor="#F14A2D" buttons={showOperateBtn ? rightBtns : []} className="salary-welfare-record"
                    showDropIcon onDropMenuClick={this.onDropMenuClick}
                    dropMenuDatas={[
                      {
                        key: "log", icon: <i className="iconfont icon-caozuorizhi32"/>,
                        content: getLabel(545781, "操作日志")
                      }
                    ]}>
      <div className="salary-welfare-record-content">
        <WelfareRecordQuery
          onSearch={(payload) => {
            this.setState({
              queryForm: { ...queryForm, ...payload }
            }, () => this.wfListRef.wrappedInstance.getWelfareRecordList());
          }}
          onPutAccountOptions={options => this.setState({ accountDialog: { ...accountDialog, options } })}
        />
        <WelfareRecordList ref={dom => this.wfListRef = dom} queryForm={queryForm} selectedRowKeys={selectedRowKeys}
                           onFilterLog={(type, targetid) => this.onDropMenuClick(type, targetid)}
                           onChangeSelectedRowKeys={v => this.setState({ selectedRowKeys: v })}/>
      </div>
      <Accountdialog {...accountDialog}
                     onCancel={() => this.setState({
                       accountDialog: { ...accountDialog, visible: false, title: "", loading: false }
                     })} onOk={this.handleAccount}
      />
      {/*操作日志*/}
      <LogDialog visible={logDialogVisible} logFunction="siaccount" filterConditions={filterConditions}
                 onCancel={() => this.setState({ logDialogVisible: false })}/>
      {/*核算进度条*/}
      {
        this.state.progressVisible &&
        <ProgressModal visible={this.state.progressVisible} progress={this.state.progress}
                       onCancel={() => {
                         this.setState({ progressVisible: false, progress: 0 }, () => clearInterval(this.timer));
                       }}
        />
      }
    </WeaTop>);
  }
}

export default StandingBook;
