/*
 * 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 { inject, observer } from "mobx-react";
import { WeaBrowser, WeaFormItem, WeaInput, WeaLocaleProvider, WeaSearchGroup, WeaTab } from "ecCom";
import { calcPageNo } from "../../../../util";
import { getQueryString } from "../../../../util/url";
import ProgressModal from "../../../../components/progressModal";
import StandingBookCalcImportDialog from "./standingBookCalcImportDialog";
import AdjustmentSlide from "./adjustmentSlide";
import { getCalculateProgress } from "../../../../apis/calculate";
import RegEditDetial from "./regEditDetial";
import SupplementarySlide from "./supplementarySlide";
import _ from "lodash";
import "./index.less";

const getLabel = WeaLocaleProvider.getLabel;
@inject("standingBookStore")
@observer
export default class NormalIndex extends Component {
  constructor(props) {
    super(props);
    this.state = {
      date: "",
      current: 1,
      pageSize: 10,
      selectedRowKeys: [],
      addProps: {
        title: "",
        visible: false
      },
      adjustSlide: {
        title: "调差",
        visible: false
      },
      tableData: {
        list: [],
        columns: [],
        total: 0
      },
      searchValue: "",
      workcode: "",
      departmentIds: "",
      subCompanyIds: "",
      progressVisible: false,
      progress: 0,
      fieldData: {}, //选中的表单头信息
      importParams: { //导入信息的弹框表示
        visible: false, fieldUrl: "getWelfareList", tmpUrl: "exportSiaccountWelfareImporttemplate",
        cacheUrl: "cacheWelfareListField", importUrl: "importInsuranceAcctDetail", importparams: {}
      },
      returnEditPersonSlide: {
        title: "",
        editId: "",
        visible: false
      },
      showSum: false,
      siaccountSum: {},
      showSearchAd: false
    };
    this.timer = null;
    this.timerDelete = null;
  }

  componentDidMount() {
    const { selectedKey, location } = this.props;
    const { current } = this.state;
    const billMonth = location.query.billMonth;
    const paymentOrganization = location.query.paymentOrganization;
    selectedKey === "1"
      ? this.getNormalList({ billMonth, current, paymentOrganization })
      : this.getSupplementaryList({ billMonth, current, paymentOrganization });
    window.addEventListener("message", this.handleReceive, false);
  }

  handleReceive = async ({ data }) => {
    const { type, payload: { id, params } = {} } = data;
    if (type === "init") {
      this.postMessageToChild();
    } else if (type === "turn") {
      if (id === "PAGEINFO") {
        const { pageNum: current, size: pageSize } = params;
        this.setState({ current, pageSize }, () => {
          const { billMonth, paymentOrganization, selectedKey } = this.props;
          const { current, pageSize } = this.state;
          selectedKey === "1" ?
            this.getNormalList({
              billMonth, current, pageSize, paymentOrganization
            }) :
            this.getSupplementaryList({
              billMonth, current, pageSize, paymentOrganization
            });
        });
      } 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) {
      const { billMonth, paymentOrganization } = nextProps;
      this.setState({
        current: 1, selectedRowKeys: []
      }, () => {
        const { current } = this.state;
        nextProps.selectedKey === "1"
          ? this.getNormalList({ billMonth, current, paymentOrganization })
          : this.getSupplementaryList({ billMonth, current, paymentOrganization });
      });
    }
  }

  postMessageToChild = () => {
    const billMonth = getQueryString("billMonth");
    const paymentOrganization = getQueryString("paymentOrganization");
    const childFrameObj = document.getElementById("atdTable");
    const { current, pageSize, tableData, selectedRowKeys, showSum, siaccountSum, searchValue: userName } = this.state;
    const { list: dataSource, total, columns } = tableData;
    const pageInfo = { current, pageSize, total };
    childFrameObj.contentWindow.postMessage(JSON.stringify({
      dataSource, columns, pageInfo,
      selectedRowKeys, selectedKey: this.props.selectedKey,
      sumpayload: { billMonth, paymentOrganization, userName },
      showOperates: !getQueryString("type")
    }), "*");
  };

  handleSearch = () => {
    const { billMonth, selectedKey, paymentOrganization } = this.props;
    selectedKey === "1"
      ? this.getNormalList({
        billMonth,
        current: 1,
        paymentOrganization,
        userName: this.state.searchValue,
        workcode: this.state.workcode,
        departmentIds: this.state.departmentIds ? this.state.departmentIds.split(",") : [],
        subCompanyIds: this.state.subCompanyIds ? this.state.subCompanyIds.split(",") : []
      })
      : this.getSupplementaryList({
        billMonth,
        current: 1,
        paymentOrganization,
        userName: this.state.searchValue,
        workcode: this.state.workcode,
        departmentIds: this.state.departmentIds ? this.state.departmentIds.split(",") : [],
        subCompanyIds: this.state.subCompanyIds ? this.state.subCompanyIds.split(",") : []
      });
  };

  handleSave = () => {
    const {
      siaccountCommonSave,
      siaccountSupplementarySave,
      form
    } = this.props.standingBookStore;
    const { billMonth, selectedKey, paymentOrganization } = this.props;
    if (selectedKey === "1") {
      const { includes, excludes } = form.getFormParams();
      const payload = {
        billMonth,
        includes: includes.split(","),
        excludes: _.isEmpty(excludes) ? excludes.split(",") : []
      };
      siaccountCommonSave(payload).then(() => {
        message.success("添加成功");
        this.getNormalList({
          billMonth,
          paymentOrganization,
          current: this.state.current
        });
        this.setState({
          addProps: {
            ...this.state.addProps,
            title: "",
            visible: false
          }
        });
      });
    } else {
      const paymentOrganization = getQueryString("paymentOrganization");
      form.validateForm().then(f => {
        if (f.isValid) {
          const {
            includes,
            billMonth: billMonthList,
            excludes,
            projects
          } = form.getFormParams();
          const payload = {
            billMonth,
            billMonthList: billMonthList.split(","),
            includes: includes.split(","),
            // excludes: excludes.split(","),
            projects: projects.split(","),
            paymentOrganization
          };
          siaccountSupplementarySave(payload).then(() => {
            message.success("添加成功");
            this.getSupplementaryList({
              billMonth,
              current: this.state.current,
              paymentOrganization
            });
            this.setState(
              {
                addProps: {
                  ...this.state.addProps,
                  title: "",
                  visible: false
                }
              },
              () => {
                form.resetForm();
              }
            );
          });
        } else {
          f.showErrors();
          this.setState({ date: new Date() }); // 改变一个state的变量,强制页面刷新
        }
      });
    }
  };
  getNormalList = async (payload = {}) => {
    const { getNormalList } = this.props.standingBookStore;
    getNormalList({ ...payload, pageSize: this.state.pageSize }).then(({ list, columns = [], total }) => {
      this.setState({
        tableData: { list, total, columns }
      }, () => this.postMessageToChild());
    });
  };
  getSupplementaryList = async (payload = {}) => {
    const { getSupplementaryList } = this.props.standingBookStore;
    getSupplementaryList({
      ...payload, pageSize: this.state.pageSize
    }).then(({ list, columns = [], total }) => {
      this.setState({
        tableData: { list, columns, total }
      }, () => this.postMessageToChild());
    });
  };
  onSelectChange = selectedRowKeys => {
    this.setState({ selectedRowKeys });
  };
  handleBatchDelete = () => {
    const { siaccountCommonDelete } = this.props.standingBookStore;
    const { list } = this.state.tableData;
    const { selectedRowKeys } = this.state;
    const { billMonth, selectedKey, paymentOrganization } = this.props;
    if (_.isEmpty(selectedRowKeys)) {
      message.warning("未勾选数据！");
    } else {
      const includes = _.map(
        _.filter(list, it => selectedRowKeys.includes(it.id)),
        item => item.employeeId
      );
      const ids = _.map(
        _.filter(list, it => selectedRowKeys.includes(it.id)),
        item => item.id
      );
      Modal.confirm({
        title: "确认信息",
        content: "确认删除勾选的数据吗？",
        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
                }, () => {
                  message.success("删除成功");
                  selectedKey === "1"
                    ? this.getNormalList({
                      billMonth,
                      paymentOrganization,
                      current: calcPageNo(this.state.tableData.total, this.state.current, 10, includes.length)
                    })
                    : this.getSupplementaryList({
                      billMonth,
                      current: calcPageNo(this.state.tableData.total, this.state.current, 10, includes.length),
                      paymentOrganization
                    });
                });
              }
            }, 800);
          });

          siaccountCommonDelete({
            billMonth,
            includes,
            ids,
            paymentOrganization
          }).then(() => {
            clearInterval(this.timerDelete);
            message.success("删除成功");
            this.setState({ selectedRowKeys: [], progressVisible: false, progress: 0 });
            selectedKey === "1"
              ? this.getNormalList({
                billMonth,
                paymentOrganization,
                current: calcPageNo(this.state.tableData.total, this.state.current, 10, includes.length)
              })
              : this.getSupplementaryList({
                billMonth,
                current: calcPageNo(this.state.tableData.total, this.state.current, 10, includes.length),
                paymentOrganization
              });
          });

        },
        onCancel: () => {
        }
      });
    }
  };
  handleAdd = () => {
    this.setState({
      addProps: {
        ...this.state.addProps,
        title: "添加缴纳人员",
        visible: true
      }
    });
  };

  handleCommonAccountClick = () => {
    const { billMonth, selectedKey, paymentOrganization } = this.props;
    const { commonAccount } = this.props.standingBookStore;
    commonAccount({ 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("核算成功");
                selectedKey === "1"
                  ? this.getNormalList({
                    billMonth,
                    paymentOrganization,
                    current: this.state.current
                  })
                  : this.getSupplementaryList({
                    billMonth,
                    paymentOrganization,
                    current: this.state.current
                  });
              });
            }
          } else {
            clearInterval(this.timer);
            this.setState({
              progressVisible: false,
              progress: 0
            });
          }
        }).catch(() => {
          clearInterval(this.timer);
          this.setState({
            progressVisible: false,
            progress: 0
          });
        });
      }, 600);
    });
  };

  handleExport = () => {
    const { billMonth, selectedKey, paymentOrganization } = 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]}?billMonth=${billMonth}&paymentOrganization=${paymentOrganization}`;
    window.open(url, "_self");
  };
  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) {
        const { current } = this.state;
        const { billMonth, selectedKey, paymentOrganization } = this.props;
        selectedKey === "1"
          ? this.getNormalList({
            billMonth,
            paymentOrganization,
            current
          })
          : this.getSupplementaryList({
            billMonth,
            paymentOrganization,
            current
          });
      }
    });
  };
  getSearchs = () => {
    return <WeaSearchGroup needTigger showGroup title="其他条件">
      <Row>
        <Col span={12}><WeaFormItem label="工号" labelCol={{ span: 4 }} wrapperCol={{ span: 18 }}>
          <WeaInput
            value={this.state.workcode}
            onChange={v => this.setState({ workcode: v })}
          />
        </WeaFormItem></Col>
        <Col span={12}><WeaFormItem label={getLabel(27511, "部门")} labelCol={{ span: 4 }} wrapperCol={{ span: 18 }}>
          <WeaBrowser
            isSingle={false} value={this.state.departmentIds} type={57}
            onChange={v => this.setState({ departmentIds: v })}/>
        </WeaFormItem></Col>
        <Col span={12}><WeaFormItem label={getLabel(33553, "分部")} labelCol={{ span: 4 }} wrapperCol={{ span: 18 }}>
          <WeaBrowser
            isSingle={false} value={this.state.subCompanyIds} type={164}
            onChange={v => this.setState({ subCompanyIds: v })}/>
        </WeaFormItem></Col>
      </Row>
    </WeaSearchGroup>;
  };

  render() {
    const { remarks, billMonth, selectedKey, paymentOrganization, standingBookStore } = this.props;
    const { addProps, adjustSlide, importParams, returnEditPersonSlide, showSearchAd } = this.state;
    const { loading } = standingBookStore;
    const btn1 = [
      <Button type="primary" onClick={this.handleBatchDelete}>批量删除</Button>,
      <Button type="primary" onClick={this.handleAdd}>添加缴纳人员</Button>
    ];
    const btn2 = [
      <Button type="primary" onClick={this.handleCommonAccountClick}>核算</Button>,
      <Button type="primary"
              onClick={() => this.setState({ adjustSlide: { ...adjustSlide, visible: true } })}>调差</Button>
    ];
    const btn3 = [
      <Button type="primary" onClick={() => {
        window.open(`/spa/hrmSalary/static/index.html#/main/hrmSalary/socialSecurityBenefits/sbofflineComparison?billMonth=${billMonth}&paymentOrganization=${paymentOrganization}`);
      }}>线下对比</Button>
    ];
    const btn4 = [
      <Button type="primary"
              onClick={() => this.setState({
                importParams: {
                  ...importParams, visible: true,
                  tmpUrl: selectedKey === "1" ? "exportSiaccountWelfareImporttemplate" : "exportSiaccountWelfaresupplyimporttemplatetemplate"
                }
              })}>导入数据</Button>
    ];
    const btn5 = [
      <Button type="primary" onClick={this.handleExport}>导出全部</Button>
    ];
    let btn = [];
    (this.props.type !== "detail" && this.props.selectedKey == "3") && (btn = [...btn, ...btn1]);
    (selectedKey === "1" && this.props.type !== "detail") && (btn = [...btn, ...btn2]);
    selectedKey === "1" && (btn = [...btn, ...btn3]);
    this.props.type !== "detail" && (btn = [...btn, ...btn4]);
    btn = [...btn, ...btn5];
    return (
      <div className="normalWapper">
        {
          selectedKey === "1" &&
          <div className="topContent">
            <div className="month">
              <span>
                账单月份
                <Tooltip placement="topLeft" title="提示：正常缴纳，账单月份即社保福利缴纳月份">
                  <Icon type="question-circle"/>
                </Tooltip>
              </span>
              <span>
                {billMonth}
              </span>
            </div>
            <div>
              <span>备注：</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={searchValue => this.setState({ searchValue })}
          buttons={btn} onSearch={this.handleSearch} onAdSearch={this.handleSearch}
          onAdReset={() => this.setState({ workcode: "" })} searchsBasePlaceHolder="请输入员工姓名"
        />
        <SupplementarySlide
          {...addProps}
          billMonth={billMonth} paymentOrganization={paymentOrganization}
          onCancel={(isRefresh) => {
            this.setState({
              addProps: {
                ...addProps,
                visible: false
              }
            }, () => {
              isRefresh && this.getSupplementaryList({
                billMonth,
                current: this.state.current,
                paymentOrganization
              });
            });
          }}
        />
        {/*核算进度条*/}
        <ProgressModal
          title={selectedKey === "3" ? "正在删除请稍后" : "正在核算请稍后"}
          visible={this.state.progressVisible}
          onCancel={() => {
            this.setState({ progressVisible: false, progress: 0 });
          }}
          progress={this.state.progress}
        />
        {/*导入弹框*/}
        <StandingBookCalcImportDialog {...importParams}
                                      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}
            onCancel={() => {
              this.setState({
                adjustSlide: {
                  ...adjustSlide,
                  visible: false
                }
              });
            }}
          />
        </div>
      </div>
    );
  }
}
