import React from "react";
import { inject, observer } from "mobx-react";
import { toJS } from "mobx";
import { getQueryString } from "../../util/url";
import { WeaLocaleProvider } from "ecCom";
import { message, Modal } from "antd";
import Authority from "../mySalary/authority";
import "../payroll/templatePreview/index.less";
import * as API from "../../apis/mySalaryBenefits";
import { salaryBillGetToken } from "../../apis/mySalaryBenefits";
import { confirmSalaryBill, feedBackSalaryBill, payrollCheckType } from "../../apis/payroll";
import CaptchaModal from "../../components/captchaModal";
import { ConfirmBtns } from "../mySalary/mySalaryView";
import Content from "../../components/pcTemplate/content";
import MobileTemplate from "../../components/mobileTemplate";
import SecondaryVerify from "./secondaryVerify";
import LoginVerify from "./loginVerify";
import SecondarypwdVerify from "./secondarypwdVerify";
import "../mySalary/index.less";

const getLabel = WeaLocaleProvider.getLabel;

@inject("mySalaryStore") @observer
export default class MobilePayroll extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false, captchaVisible: false, loginVisible: false, pwdSetVisible: false,
      mySalaryBillData: { employeeInformation: {}, salaryTemplate: [] },
      salaryBillToken: {}
    };
    this.id = "";
  }

  async componentWillMount() {
    const type = getQueryString("type");
    this.id = getQueryString("id");
    const { mySalaryStore: { init, setMySalaryBill } } = this.props;
    setMySalaryBill({});
    if (type !== "phone") {
      const { data, status } = await payrollCheckType();
      if (status && data === "PWD") {
        init(false, () => this.getMySalaryBill(this.id));
      } else {
        this.setState({ captchaVisible: true });
      }
    }
    type === "phone" && await this.initMobile();
  }

  initMobile = async () => {
    const { mySalaryStore: { setInitEmVerify } } = this.props;
    if (window.em) {
      API.isNeedSecondPwdVerify({ mouldCode: "HRM", itemCode: "SALARY" }, this.state.salaryBillToken)
        .then(({ status, isNeedSecondAuth }) => {
          if (status && isNeedSecondAuth) {
            this.setState({ visible: true });
          } else {
            this.getMySalaryBill(getQueryString("id"));
            setInitEmVerify();
          }
        });
    } else {
      const params = this.getUrlkey();
      const { data } = await salaryBillGetToken({
        id: _.pick(params, ["id"]).id,
        recipient: _.pick(params, ["recipient"]).recipient,
        salaryCode: _.pick(params, ["salaryCode"]).salaryCode
      });
      this.setState({ salaryBillToken: data }, () => {
        API.isNeedSecondPwdVerify({ mouldCode: "HRM", itemCode: "SALARY" }, this.state.salaryBillToken)
          .then(({ status, isNeedSecondAuth }) => {
            if (status && isNeedSecondAuth) {
              this.setState({ visible: true });
            } else {
              this.getMySalaryBill(getQueryString("id"));
              setInitEmVerify();
            }
          });
      });
    }
  };
  getMySalaryBill = (salaryInfoId) => {
    const { salaryBillToken } = this.state;
    const { mySalaryStore: { getMySalaryBill } } = this.props;
    const params = this.getUrlkey();
    const payload = {
      salaryInfoId, header: salaryBillToken, ..._.pick(params, ["recipient"])
    };
    getMySalaryBill(payload).then(result => {
      this.setState({
        mySalaryBillData: result
      });
    });
  };
  getUrlkey = () => {
    let url = window.location.href;
    let params = {}, arr = url.split("?");
    if (arr.length <= 1) return params;
    arr = arr[1].split("&");
    for (var i = 0, l = arr.length; i < l; i++) {
      var a = arr[i].split("=");
      params[a[0]] = a[1];
    }
    return params;
  };
  confirmSalaryBill = () => {
    const { salaryBillToken } = this.state;
    confirmSalaryBill({ salaryInfoId: getQueryString("id"), header: salaryBillToken })
      .then(({ status, errormsg }) => {
        if (status) {
          message.success(getLabel(30700, "操作成功"));
          this.getMySalaryBill(getQueryString("id"));
        } else {
          message.error(errormsg || getLabel(30651, "操作失败"));
        }
      });
  };
  handleGoFeedback = () => {
    Modal.confirm({
      title: getLabel(131329, "信息确认"),
      content: getLabel(111, "确认是否发起反馈流程？"),
      onOk: () => {
        const { salaryBillToken } = this.state;
        feedBackSalaryBill({ salaryInfoId: getQueryString("id"), header: salaryBillToken })
          .then(({ status, errorMsg }) => {
            if (status) {
              const { mySalaryBillData } = this.state;
              const { salaryTemplate } = mySalaryBillData;
              const { feedbackUrl, mobileFeedbackUrl } = salaryTemplate;
              this.getMySalaryBill(getQueryString("id"));
              window.location.href = `${window.ecologyContentPath || ""}${getQueryString("type") === "phone" ? mobileFeedbackUrl : feedbackUrl}`;
              // window.open(`${window.ecologyContentPath || ""}${feedbackUrl}`);
            } else {
              message.error(errorMsg);
            }
          });
      }
    });
  };

  render() {
    const { mySalaryStore: { setInitEmVerify } } = this.props, {
      captchaVisible, visible, loginVisible, pwdSetVisible
    } = this.state;
    const type = getQueryString("type");
    if (_.isEmpty(toJS(this.props.mySalaryStore.mySalaryBill))) return <React.Fragment>
      {visible && <SecondaryVerify {...this.props} salaryBillToken={this.state.salaryBillToken}
                                   onSetLogin={() => this.setState({ visible: false, loginVisible: true })}
                                   onSuccess={() => {
                                     setInitEmVerify();
                                     this.getMySalaryBill(getQueryString("id"));
                                   }}/>}
      {loginVisible && <LoginVerify {...this.props} salaryBillToken={this.state.salaryBillToken}
                                    onSetPwdSet={() => this.setState({ loginVisible: false, pwdSetVisible: true })}/>}
      {pwdSetVisible && <SecondarypwdVerify {...this.props} salaryBillToken={this.state.salaryBillToken}
                                            onSuccess={() => this.setState({ pwdSetVisible: false }, () => this.initMobile())}/>}
      {/*发送验证码*/}
      <CaptchaModal
        visible={captchaVisible} id={getQueryString("id")}
        onCancel={() => this.setState({ captchaVisible: false })}
        onConfirm={() => this.props.mySalaryStore.setInitEmVerify()}
      />
    </React.Fragment>;
    const {
      salaryTemplate, salaryGroups, employeeInformation, sendTime, confirmStatus, showAck, showFeedback
    } = toJS(this.props.mySalaryStore.mySalaryBill);
    const salaryProps = {
      theme: salaryTemplate.theme,
      tip: salaryTemplate.textContent,
      sendTime,
      background: salaryTemplate.background,
      tipPosi: salaryTemplate.textContentPosition || "",
      itemTypeList: [employeeInformation, ...salaryGroups]
    };
    return (<React.Fragment>
      {type === "phone" ? <Authority ecId={`${this && this.props && this.props.ecId || ""}_Authority@lulowc`}
                                     store={this.props.mySalaryStore}>
        <MobileTemplate {...salaryProps} title={getLabel(111, "工资单查看")}>
          <ConfirmBtns
            showAck={showAck} showFeedback={showFeedback}
            confirmSalaryBill={this.confirmSalaryBill}
            goFeedback={this.handleGoFeedback}
          />
        </MobileTemplate>
      </Authority> : <Authority ecId={`${this && this.props && this.props.ecId || ""}_Authority@lulowc`}
                                store={this.props.mySalaryStore}>
        <div className="weapp-salary-my-salary-view-payroll">
          <Content {...salaryProps}>
            <ConfirmBtns
              showAck={showAck} showFeedback={showFeedback}
              confirmSalaryBill={this.confirmSalaryBill}
              goFeedback={this.handleGoFeedback}
            />
          </Content>
        </div>
      </Authority>}
    </React.Fragment>);
  }
}
