/*
 * Author: 黎永顺
 * Description: 正常缴纳月份
 * Date: 2022-04-20 08:56:08
 * LastEditTime: 2022-06-29 09:53:36
 */
import React, { Component } from "react";
import { Button, Col, Icon, message, Modal, Row, Spin, Tooltip } from "antd";
import { WeaBrowser, WeaButtonIcon, WeaFormItem, WeaInput, WeaLocaleProvider, WeaSearchGroup, WeaTab } from "ecCom";
import * as API from "../../../../apis/standingBook";
import { getCalculateProgress } from "../../../../apis/calculate";
import { sysConfCodeRule } from "../../../../apis/ruleconfig";
import { calcPageNo } from "../../../../util";
import { convertToUrlString } from "../../../../util/url";
import ProgressModal from "../../../../components/progressModal";
import StandingBookCalcImportDialog from "./standingBookCalcImportDialog";
import AdjustmentSlide from "./adjustmentSlide";
import RegEditDetial from "./regEditDetial";
import SupplementarySlide from "./supplementarySlide";
import "./index.less";

const getLabel = WeaLocaleProvider.getLabel;

export default class NormalIndex extends Component {
  constructor(props) {
    super(props);
    this.state = {
      pageInfo: { current: 1, pageSize: 10, total: 0 }, selectedRowKeys: [], showSearchAd: false, loading: false,
      formParams: { userName: "", workcode: "", departmentIds: [], subCompanyIds: [] },
      addProps: { title: "", visible: false }, adjustSlide: { title: "调差", visible: false },
      progressVisible: false, progress: 0, importParams: { //导入信息的弹框表示
        visible: false, fieldUrl: "getWelfareList", tmpUrl: "exportSiaccountWelfareImporttemplate",
        cacheUrl: "cacheWelfareListField", importUrl: "importInsuranceAcctDetail", importparams: {}
      },
      returnEditPersonSlide: { title: "", editId: "", visible: false },
      columns: [], dataSource: [], sumRow: {}, normalPayer: ""
    };
    this.timer = null;
    this.timerDelete = null;
  }

  componentDidMount() {
    window.addEventListener("message", this.handleReceive, false);
  }

  handleReceive = ({ data }) => {
    const { type, payload: { id, params } = {} } = data, { selectedKey } = this.props;
    if (type === "init") {
      selectedKey === "1" ? this.getNormalList() : this.getSupplementaryList();
    } else if (type === "turn") {
      if (id === "PAGEINFO") {
        const { pageNum: current, size: pageSize } = params;
        this.setState({ pageInfo: { ...this.state.pageInfo, current, pageSize } }, () => {
          selectedKey === "1" ? this.getNormalList(true) : this.getSupplementaryList(true);
        });
      } else if (id === "ROWSELECT") {
        const { selectedRowKeys } = params;
        this.setState({ selectedRowKeys });
      } else if (id === "EDIT") {
        this.handleEditNormalStandingBook(params);
      }
    }
  };

  componentWillUnmount() {
    if (this.timer) clearInterval(this.timer);
    if (this.timerDelete) clearInterval(this.timerDelete);
    window.removeEventListener("message", this.handleReceive, false);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.selectedKey !== this.props.selectedKey) {
      this.setState({
        pageInfo: { current: 1, pageSize: 10, total: 0 }, selectedRowKeys: [], dataSource: [], sumRow: {},
        addProps: { title: "", visible: false }, returnEditPersonSlide: { title: "", editId: "", visible: false }
      }, () => {
        nextProps.selectedKey === "1" ? this.getNormalList() : this.getSupplementaryList();
      });
    }
  }

  postMessageToChild = () => {
    const childFrameObj = document.getElementById("atdTable");
    childFrameObj && childFrameObj.contentWindow.postMessage(JSON.stringify({
      ..._.pick(this.state, ["dataSource", "columns", "pageInfo", "selectedRowKeys", "sumRow"]),
      showOperates: !this.props.type
    }), "*");
  };
  handleSearch = () => this.props.selectedKey === "1" ? this.getNormalList() : this.getSupplementaryList();
  getNormalList = (pageTurning = false) => {
    const { pageInfo, formParams } = this.state;
    const payload = { ..._.pick(this.props, ["billMonth", "paymentOrganization"]) };
    this.setState({ loading: true });
    API.getNormalList({ ...payload, ...pageInfo, ...formParams }).then(({ status, data }) => {
      this.setState({ loading: false });
      if (status) {
        const { pageInfo: { columns, list: dataSource, pageNum: current, pageSize, total } } = data;
        this.setState({ pageInfo: { current, pageSize, total }, columns, dataSource }, () => this.postMessageToChild());
      }
    });
    sysConfCodeRule({ code: "OPEN_ACCT_RESULT_SUM" }).then(({ status, data }) => {
      if (status && data === "1" && !pageTurning) {
        API.getNormalListSum({ ...payload, ...pageInfo, ...formParams })
          .then(({ status: sumStatus, data: sumData }) => {
            if (sumStatus) this.setState({ sumRow: sumData.sumRow }, () => this.postMessageToChild());
          });
      }
    });
  };
  getSupplementaryList = (pageTurning = false) => {
    const { pageInfo, formParams } = this.state;
    const payload = { ..._.pick(this.props, ["billMonth", "paymentOrganization"]) };
    this.setState({ loading: true });
    API.getSupplementaryList({ ...payload, ...pageInfo, ...formParams }).then(({ status, data }) => {
      this.setState({ loading: false });
      if (status) {
        const { pageInfo: { columns, list: dataSource, pageNum: current, pageSize, total } } = data;
        this.setState({ pageInfo: { current, pageSize, total }, columns, dataSource }, () => this.postMessageToChild());
      }
    });
    sysConfCodeRule({ code: "OPEN_ACCT_RESULT_SUM" }).then(({ status, data }) => {
      if (status && data === "1" && !pageTurning) {
        API.getSupplementaryListSum({ ...payload, ...pageInfo, ...formParams })
          .then(({ status: sumStatus, data: sumData }) => {
            if (sumStatus) this.setState({ sumRow: sumData.sumRow }, () => this.postMessageToChild());
          });
      }
    });
  };
  handleBatchDelete = () => {
    const { selectedRowKeys, dataSource, pageInfo } = this.state;
    const { billMonth, selectedKey, paymentOrganization } = this.props;
    const includes = _.map(_.filter(dataSource, it => selectedRowKeys.includes(it.id)), item => item.employeeId);
    const ids = _.map(_.filter(dataSource, it => selectedRowKeys.includes(it.id)), item => item.id);
    Modal.confirm({
      title: getLabel(111, "确认信息"),
      content: getLabel(111, "确认删除勾选的数据吗？"),
      onOk: () => {
        this.setState({ progressVisible: true }, () => {
          this.timerDelete = setInterval(() => {
            if (this.state.progress !== 100) {
              this.setState({ progress: this.state.progress + 10 });
            } else {
              clearInterval(this.timerDelete);
              this.setState({
                progressVisible: false, progress: 0, pageInfo: {
                  ...pageInfo, current: calcPageNo(pageInfo.total, pageInfo.current, 10, includes.length)
                }
              }, () => {
                message.success(getLabel(111, "操作成功！"));
                selectedKey === "1" ? this.getNormalList() : this.getSupplementaryList();
              });
            }
          }, 800);
        });
        API.siaccountCommonDelete({ billMonth, includes, ids, paymentOrganization })
          .then(() => {
            clearInterval(this.timerDelete);
            this.setState({
              selectedRowKeys: [], progressVisible: false, progress: 0, pageInfo: {
                ...pageInfo, current: calcPageNo(pageInfo.total, pageInfo.current, 10, includes.length)
              }
            }, () => {
              message.success(getLabel(111, "操作成功！"));
              selectedKey === "1" ? this.getNormalList() : this.getSupplementaryList();
            });
          });

      }
    });
  };
  handleAdd = () => this.setState({
    addProps: { ...this.state.addProps, title: getLabel(111, "添加缴纳人员"), visible: true }
  });
  handleCommonAccountClick = () => {
    const { billMonth, paymentOrganization, selectedKey } = this.props;
    const promise = API.commonAccount({ ..._.pick(this.props, ["billMonth", "paymentOrganization"]), includes: [] });
    this.setState({ progressVisible: true }, () => {
      this.timer = setInterval(() => {
        getCalculateProgress(billMonth, paymentOrganization).then(({ status, data }) => {
          if (status) {
            if (!data.status) {
              clearInterval(this.timer);
              this.setState({ progressVisible: false, progress: 0 });
              message.error(data.message);
            }
            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(111, "操作成功！"));
                this.getNormalList();
              });
            }
          } else {
            clearInterval(this.timer);
            this.setState({ progressVisible: false, progress: 0 });
          }
        }).catch(() => {
          clearInterval(this.timer);
          this.setState({ progressVisible: false, progress: 0 });
        });
      }, 600);
    });
  };
  handleAddSocialAcctEmp = () => {
    const { normalPayer, pageInfo } = this.state, { current, pageSize, total } = pageInfo;
    API.addSocialAcctEmp({
      ..._.pick(this.props, ["billMonth", "paymentOrganization"]), includes: normalPayer.split(",")
    }).then(({ status, errormsg }) => {
      if (status) {
        message.success(getLabel(111, "操作成功"));
        this.setState({
          pageInfo: { ...pageInfo, current: calcPageNo(total, current, pageSize, normalPayer.split(",").length) }
        }, () => this.getNormalList());
      } else {
        message.error(errormsg);
      }
    });
  };
  handleDeleteNormalPayer = () => {
    Modal.confirm({
      title: getLabel(111, "确认信息"),
      content: getLabel(111, "确认删除勾选的数据吗？"),
      onOk: () => {
        const { selectedRowKeys: ids, pageInfo } = this.state, { current, pageSize, total } = pageInfo;
        API.deleteSocialAcctEmp({ ..._.pick(this.props, ["billMonth", "paymentOrganization"]), ids })
          .then(({ status, errormsg }) => {
            if (status) {
              message.success(getLabel(111, "操作成功！"));
              this.setState({
                selectedRowKeys: [],
                pageInfo: { ...pageInfo, current: calcPageNo(total, current, pageSize, ids.length) }
              }, () => this.getNormalList());
            } else {
              message.error(errormsg);
            }
          });
      }
    });
  };
  handleExport = () => {
    const { selectedKey } = this.props;
    const urlObj = {
      "1": "/api/bs/hrmsalary/welfare/common/export",
      "3": "/api/bs/hrmsalary/welfare/supplementary/export"
    };
    const url = `${window.location
      .origin}${urlObj[selectedKey]}?${convertToUrlString(_.pick(this.props, ["billMonth", "paymentOrganization"]))}`;
    window.open(url, "_blank");
  };
  handleEditNormalStandingBook = (record) => {
    const { userName, id: editId } = record;
    const { returnEditPersonSlide } = this.state;
    this.setState({
      returnEditPersonSlide: { ...returnEditPersonSlide, visible: true, title: userName, editId }
    });
  };
  handleCloseNormalStandingBookModal = (refreshList = false) => {
    const { returnEditPersonSlide } = this.state;
    this.setState({
      returnEditPersonSlide: { ...returnEditPersonSlide, visible: false, title: "", editId: "" }
    }, () => {
      if (refreshList) this.props.selectedKey === "1" ? this.getNormalList() : this.getSupplementaryList();
    });
  };
  getSearchs = () => {
    const { formParams } = this.state, { workcode, departmentIds, subCompanyIds } = formParams;
    return <WeaSearchGroup needTigger showGroup title="">
      <Row>
        <Col span={12}><WeaFormItem label={getLabel(111, "工号")} labelCol={{ span: 4 }} wrapperCol={{ span: 18 }}>
          <WeaInput value={workcode} onChange={v => this.setState({ formParams: { ...formParams, workcode: v } })}/>
        </WeaFormItem></Col>
        <Col span={12}><WeaFormItem label={getLabel(27511, "部门")} labelCol={{ span: 4 }} wrapperCol={{ span: 18 }}>
          <WeaBrowser
            isSingle={false} value={departmentIds.join(",")} type={57}
            onChange={v => this.setState({ formParams: { ...formParams, departmentIds: v.split(",") } })}/>
        </WeaFormItem></Col>
        <Col span={12}><WeaFormItem label={getLabel(33553, "分部")} labelCol={{ span: 4 }} wrapperCol={{ span: 18 }}>
          <WeaBrowser
            isSingle={false} value={subCompanyIds.join(",")} type={164}
            onChange={v => this.setState({ formParams: { ...formParams, subCompanyIds: v.split(",") } })}/>
        </WeaFormItem></Col>
      </Row>
    </WeaSearchGroup>;
  };

  render() {
    const { remarks, billMonth, selectedKey, paymentOrganization, type } = this.props;
    const {
      formParams, addProps, adjustSlide, importParams, returnEditPersonSlide,
      showSearchAd, selectedRowKeys, loading
    } = this.state;
    const btn1 = [
      <WeaButtonIcon buttonType="del" type="primary" title={getLabel(111, "删除")} disabled={_.isEmpty(selectedRowKeys)}
                     onClick={this.handleBatchDelete}/>,
      <WeaButtonIcon buttonType="add" type="primary" title={getLabel(111, "添加")}
                     onClick={this.handleAdd}/>
    ];
    const btn2 = [
      <WeaButtonIcon buttonType="del" type="primary" title={getLabel(111, "删除")} disabled={_.isEmpty(selectedRowKeys)}
                     onClick={this.handleDeleteNormalPayer}/>,
      <WeaBrowser type={17} title={getLabel(383694, "添加人员")} isSingle={false} customized
                  onChange={ids => this.setState({ normalPayer: ids }, () => this.handleAddSocialAcctEmp())}>
        <WeaButtonIcon buttonType="add" type="primary" title={getLabel(111, "添加")}/>
      </WeaBrowser>,
      <Button type="primary" onClick={this.handleCommonAccountClick}>{getLabel(111, "核算")}</Button>,
      <Button type="ghost" onClick={() => this.setState({
        adjustSlide: { ...adjustSlide, visible: true }
      })}>{getLabel(111, "调差")}</Button>
    ];
    const btn3 = [
      <i className="iconfont icon-duibi" onClick={() => {
        window.open(`/spa/hrmSalary/static/index.html#/main/hrmSalary/socialSecurityBenefits/sbofflineComparison?billMonth=${billMonth}&paymentOrganization=${paymentOrganization}`);
      }} title={getLabel(111, "线下对比")}/>
    ];
    const btn4 = [
      <i className="iconfont icon-import" onClick={() => this.setState({
        importParams: {
          ...importParams, visible: true,
          tmpUrl: selectedKey === "1" ? "exportSiaccountWelfareImporttemplate" : "exportSiaccountWelfaresupplyimporttemplatetemplate"
        }
      })} title={getLabel(111, "导入")}/>
    ];
    const btn5 = [
      <i className="iconfont icon-export" onClick={this.handleExport} title={getLabel(111, "导出")}/>
    ];
    let btn = [];
    (type !== "detail" && selectedKey === "3") && (btn = [...btn, ...btn1]);
    (selectedKey === "1" && type !== "detail") && (btn = [...btn, ...btn2]);
    btn = [...btn5, ...btn];
    type !== "detail" && (btn = [...btn4, ...btn]);
    selectedKey === "1" && (btn = [...btn3, ...btn]);
    return (
      <div className="normalWapper">
        {
          selectedKey === "1" &&
          <div className="topContent">
            <div className="month">
              <span>
                {getLabel(111, "账单月份")}
                <Tooltip placement="topLeft" title={getLabel(111, "提示：正常缴纳，账单月份即社保福利缴纳月份")}>
                  <Icon type="question-circle"/>
                </Tooltip>
              </span>
              <span>{billMonth}</span>
            </div>
            <div>
              <span>{getLabel(111, "备注：")}</span>
              <span>{remarks}</span>
            </div>
          </div>
        }
        <WeaTab
          datas={[]} selectedKey="" advanceHeight={200} searchsAd={this.getSearchs()}
          searchType={["base", "advanced"]} showSearchAd={showSearchAd}
          setShowSearchAd={bool => this.setState({ showSearchAd: bool })}
          onSearchChange={userName => this.setState({ formParams: { ...formParams, userName } })}
          buttons={btn} onSearch={this.handleSearch} onAdSearch={this.handleSearch}
          onAdReset={() => this.setState({
            formParams: { userName: "", workcode: "", departmentIds: [], subCompanyIds: [] }
          })}/>
        {/*添加补缴弹框*/}
        <SupplementarySlide {...addProps} {..._.pick(this.props, ["billMonth", "paymentOrganization"])}
                            onCancel={(isRefresh) => {
                              this.setState({ addProps: { ...addProps, visible: false } }, () => {
                                isRefresh && this.getSupplementaryList();
                              });
                            }}/>
        {/*核算进度条*/}
        <ProgressModal
          title={selectedKey === "3" ? getLabel(111, "正在删除请稍后") : getLabel(111, "正在核算请稍后")}
          visible={this.state.progressVisible}
          onCancel={() => this.setState({ progressVisible: false, progress: 0 })}
          progress={this.state.progress}/>
        {/*导入弹框*/}
        <StandingBookCalcImportDialog {...importParams} {..._.pick(this.props, ["billMonth", "paymentOrganization"])}
                                      onCancel={(isInit) => this.setState({
                                        importParams: { ...importParams, visible: false }
                                      }, () => isInit && this.handleSearch())}/>
        {/* table */}
        <div className="tableWrapper">
          <Spin spinning={loading}>
            <iframe
              style={{ border: 0, width: "100%", height: "100%" }}
              // src="http://localhost:7607/#/standingbookTable"
              src="/spa/hrmSalary/hrmSalaryCalculateDetail/index.html#/standingbookTable"
              id="atdTable"
            />
          </Spin>
          {/*编辑弹框*/}
          <RegEditDetial {...returnEditPersonSlide} onCancel={this.handleCloseNormalStandingBookModal}/>
          {/*调差*/}
          <AdjustmentSlide {...adjustSlide} {..._.pick(this.props, ["billMonth", "paymentOrganization"])}
                           onCancel={() => this.setState({ adjustSlide: { ...adjustSlide, visible: false } })}/>
        </div>
      </div>
    );
  }
}
