/*
 * Author: 黎永顺
 * name: 薪资核算-重构页面
 * Description:
 * Date: 2023/10/9
 */
import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import { WeaLocaleProvider, WeaTools, WeaTop } from "ecCom";
import { WeaForm } from "comsMobx";
import { Button, Dropdown, Icon, Menu, message, Modal } from "antd";
import moment from "moment";
import CalculateQuery from "./components/calculateQuery";
import CalculateTablelist from "./components/calculateTablelist";
import CalculateDialog from "./components/calculateDialog";
import ProgressModal from "../../components/progressModal";
import LogDialog from "../../components/logViewModal";
import {
  backCalculate,
  batFile,
  batReAccounting,
  deleteSalaryacct,
  fileSalaryAcct,
  reAccounting
} from "../../apis/calculate";
import FormInfo from "../../components/FormInfo";
import { queryConditions } from "./config";
import { getTaxAgentSelectList } from "../../apis/taxAgent";
import cs from "classnames";
import "./index.less";

const getKey = WeaTools.getKey;
const getLabel = WeaLocaleProvider.getLabel;
const form = new WeaForm();

@inject("calculateStore", "taxAgentStore")
@observer
class Calculate extends Component {
  constructor(props) {
    super(props);
    this.state = {
      queryParams: {
        name: "",
        dateRange: [
          moment(new Date()).subtract(1, "year").startOf("year").format("YYYY-MM"),
          moment(new Date()).endOf("year").format("YYYY-MM")
        ]
      }, isRefresh: false, logDialogVisible: false, conditions: [], selectedRowKeys: [],
      progressModule: { visible: false, progress: 0, title: getLabel(111, "正在归档中请稍后") },
      calcDaialog: { visible: false, title: "" }, showAdvance: false
    };
    this.timer = null;
    this.handleDebounce = null;
  }

  async componentDidMount() {
    const { data } = await getTaxAgentSelectList();
    this.setState({
      conditions: _.map(queryConditions, item => ({
        ...item, items: _.map(item.items, o => {
          o = { ...o, label: getLabel(o.lanId, o.label) };
          if (getKey(o) === "taxAgentIds") {
            return { ...o, options: _.map(data, k => ({ key: k.id, showname: k.content })) };
          }
          return { ...o };
        })
      }))
    }, () => form.initFormFields(this.state.conditions));
  }

  renderCalculateOpts = () => {
    const { taxAgentStore: { showOperateBtn } } = this.props;
    const { queryParams, isRefresh, showAdvance, selectedRowKeys } = this.state;
    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>
    );
    let calculateOpts = [
      // <Button type="primary" onClick={() => this.setState({
      //   calcDaialog: {
      //     visible: true, type: "acct",
      //     title: getLabel(538780, "核算")
      //   }
      // })}>{getLabel(538780, "核算")}</Button>,
      <Button type="primary" onClick={() => this.setState({
        calcDaialog: {
          visible: true, title: getLabel(538780, "批量新建并核算"), type: "batSaveAndAcct"
        }
      })}>{getLabel(111, "批量新建并核算")}</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>,
      <CalculateQuery queryParams={queryParams} onAdvance={() => this.setState({ showAdvance: !showAdvance })}
                      onChange={v => this.setState({
                        isRefresh: _.keys(v)[0] === "name" ? isRefresh : !isRefresh,
                        queryParams: { ...queryParams, ...v }
                      })} onSearch={() => this.setState({ isRefresh: !isRefresh })}/>
    ];
    return !showOperateBtn ? calculateOpts.slice(2) : calculateOpts;
  };
  handleCalcOpts = ({ key }, record) => {
    const { isRefresh, progressModule } = this.state, { id } = record;
    switch (key) {
      case "0":
        //核算
        window.open(`/spa/hrmSalary/static/index.html#/main/hrmSalary/calculate/${id}`);
        break;
      case "1":
        //删除
        Modal.confirm({
          title: getLabel(131329, "信息确认"),
          content: getLabel(543231, "确认删除本条数据吗?"),
          onOk: () => {
            deleteSalaryacct([id]).then(({ status, errormsg }) => {
              if (status) {
                message.success(getLabel(502230, "删除成功！"));
                this.setState({ isRefresh: !isRefresh });
              } else {
                message.error(errormsg);
              }
            });
          }
        });
        break;
      case "2":
        //归档
        if (!this.handleDebounce) {
          this.handleDebounce = _.debounce(() => {
            if (this.timer) clearInterval(this.timer);
            this.setState({ progressModule: { ...progressModule, visible: true } });
            this.timer = setInterval(() => {
              if (progressModule.progress === 100 && this.timer) {
                clearInterval(this.timer);
                this.timer = null;
                this.setState({
                  progressModule: { ...progressModule, visible: false, progress: 0 },
                  isRefresh: !isRefresh
                });
              }
              this.setState({
                progressModule: { ...progressModule, progress: progressModule.progress + 1 }
              });
            }, 800);
            fileSalaryAcct({ id }).then(({ status, errormsg }) => {
              if (status) {
                clearInterval(this.timer);
                this.timer = null;
                this.setState({
                  progressModule: { ...progressModule, visible: false, progress: 0 },
                  isRefresh: !isRefresh
                });
                message.success(getLabel(503690, "归档成功"));
              } else {
                clearInterval(this.timer);
                this.timer = null;
                this.setState({
                  progressModule: { ...progressModule, visible: false, progress: 0 }
                });
                message.error(errormsg);
              }
            });
            this.handleDebounce = null;
          }, 500);
        }
        this.handleDebounce();
        break;
      case "3":
        //查看详情
        window.open(`/spa/hrmSalary/static/index.html#/main/hrmSalary/calcView/${id}`);
        break;
      case "4":
        //重新核算
        if (!this.handleDebounce) {
          this.handleDebounce = _.debounce(() => {
            reAccounting({ salaryAcctRecordId: id }).then(({ status, errormsg }) => {
              if (status) {
                message.success(getLabel(30700, "操作成功！"));
                this.setState({ isRefresh: !isRefresh });
              } else {
                message.error(errormsg);
              }
            });
            this.handleDebounce = null;
          }, 500);
        }
        this.handleDebounce();
        break;
      case "5":
        //回算
        Modal.confirm({
          title: getLabel(131329, "信息确认"),
          content: getLabel(543538, "确定回算吗？回算后，正常核算的数据会被覆盖，正常核算的工资单不能继续发放或撤回！"),
          onOk: () => {
            if (!this.handleDebounce) {
              this.handleDebounce = _.debounce(() => {
                backCalculate({ salaryAcctRecordId: id }).then(({ status, errormsg }) => {
                  if (status) {
                    message.success(getLabel(544367, "回算成功！"));
                    this.setState({ isRefresh: !isRefresh });
                  } else {
                    message.error(errormsg);
                  }
                });
                this.handleDebounce = null;
              }, 500);
            }
            this.handleDebounce();
          }
        });
        break;
      case "log":
        //操作日志
        this.onDropMenuClick(key, record.id);
        break;
      default:
        break;
    }
  };
  onDropMenuClick = (key, targetid = "") => {
    switch (key) {
      case "batArchiving":
        batFile({ salaryAcctRecordIds: this.state.selectedRowKeys }).then(({ status, errormsg }) => {
          if (status) {
            message.success(getLabel(111, "操作成功！"));
            this.setState({ isRefresh: !this.state.isRefresh });
          } else {
            message.error(errormsg);
          }
        });
        break;
      case "batReAcct":
        Modal.confirm({
          title: getLabel(111, "确认信息"),
          content: getLabel(111, "重新核算后，选中的台账数据将可以删除且可以进行此月份的核算，是否确认取消归档？"),
          onOk: () => {
            batReAccounting({ salaryAcctRecordIds: this.state.selectedRowKeys })
              .then(({ status, errormsg }) => {
                if (status) {
                  message.success(getLabel(30700, "操作成功！"));
                  this.setState({ isRefresh: !this.state.isRefresh });
                } else {
                  message.error(errormsg);
                }
              });
          }
        });
        break;
      case "batDel":
        Modal.confirm({
          title: getLabel(111, "确认信息"), content: getLabel(388758, "确认要删除吗?"),
          onOk: () => {
            deleteSalaryacct(this.state.selectedRowKeys).then(({ status, errormsg }) => {
              if (status) {
                message.success(getLabel(502230, "删除成功！"));
                this.setState({ selectedRowKeys: [], isRefresh: !this.state.isRefresh });
              } 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 {
      queryParams, isRefresh, calcDaialog, progressModule, logDialogVisible, filterConditions, conditions, showAdvance,
      selectedRowKeys
    } = this.state;
    return (
      <WeaTop title={getLabel(538011, "薪资核算")} icon={<i className="icon-coms-fa"/>} iconBgcolor="#F14A2D"
              buttons={this.renderCalculateOpts()} className="calculate-main-layout" showDropIcon
              onDropMenuClick={this.onDropMenuClick}
              dropMenuDatas={[
                {
                  key: "log", icon: <i className="iconfont icon-caozuorizhi32"/>,
                  content: getLabel(545781, "操作日志")
                }
              ]}
      >
        <div className="calculate-body">
          <div className={cs("advance-calc", { "show-advance-calc": showAdvance })}>
            <FormInfo center={false} itemRender={{}} form={form} formFields={conditions} colCount={2}/>
            <div className="advance-calc-btns">
              <Button type="primary"
                      onClick={() => this.setState({ isRefresh: !isRefresh })}>{getLabel(111, "搜索")}</Button>
              <Button type="ghost" onClick={() => form.resetForm()}>{getLabel(111, "重置")}</Button>
              <Button type="ghost"
                      onClick={() => this.setState({ showAdvance: !showAdvance })}>{getLabel(111, "取消")}</Button>
            </div>
          </div>
          <CalculateTablelist form={form} queryParams={queryParams} isRefresh={isRefresh}
                              selectedRowKeys={selectedRowKeys} onCalcOpts={this.handleCalcOpts}
                              onChangeSelectedRowKeys={v => this.setState({ selectedRowKeys: v })}/>
          <CalculateDialog {...calcDaialog}
                           onCancel={(bool, id) => this.setState({
                             calcDaialog: { ...calcDaialog, visible: false },
                             isRefresh: bool === "refresh" ? !isRefresh : isRefresh
                           })}/>
          {/*操作日志*/}
          <LogDialog visible={logDialogVisible} logFunction="acctrecord" filterConditions={filterConditions}
                     onCancel={() => this.setState({ logDialogVisible: false })}/>
          {/*  归档进度条*/}
          {
            progressModule.visible &&
            <ProgressModal
              {...progressModule}
              onCancel={() => {
                this.setState({
                  progressModule: {
                    ...progressModule,
                    visible: false,
                    progress: 0
                  }
                }, () => clearInterval(this.timer));
              }}
            />
          }
        </div>
      </WeaTop>
    );
  }
}

export default Calculate;
