/*
 * 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, message } from "antd";
import * as API from "../../../apis/standingBook";
import { getCalculateProgress } from "../../../apis/calculate";
import WelfareRecordQuery from "./components/welfareRecordQuery";
import WelfareRecordList from "./components/welfareRecordList";
import Accountdialog from "./components/accountDialog";
import ProgressModal from "../../../components/progressModal";
import { convertToUrlString } from "../../../util/url";
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,
      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, ...extra } = formVal;
    const payload = {
      billMonth: moment(billMonth).format("YYYY-MM"),
      ...extra
    };
    this.setState({ accountDialog: { ...this.state.accountDialog, loading: true } });
    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 "log":
        this.setState({
          logDialogVisible: true,
          filterConditions: targetid ? `[{\"connectCondition\":\"AND\",\"columIndex\":\"targetid\",\"type\":\"=\",\"value\":\"${targetid}\"}]` : "[]"
        });
        break;
      default:
        break;
    }
  };

  render() {
    const { accountDialog, queryForm, logDialogVisible, filterConditions } = this.state;
    const { taxAgentStore: { showOperateBtn } } = this.props;
    const rightBtns = [<Button type="primary" onClick={() => this.setState({
      accountDialog: { ...accountDialog, visible: true, title: getLabel(538780, "核算") }
    })}>{getLabel(538780, "核算")}</Button>];
    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}
                           onFilterLog={(type, targetid) => this.onDropMenuClick(type, targetid)}/>
      </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;
