/*
 * Author: 黎永顺
 * name: 新增/编辑个税扣缴义务人
 * Description:
 * Date: 2022/11/29
 */
import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import { Button, message, Modal } from "antd";
import { WeaLocaleProvider, WeaSlideModal, WeaSteps } from "ecCom";
import { decentralizationConditions, editConditions } from "../../taxAgent/editConditions";
import BaseSettings, { convertConditon } from "./baseSettings";
import PersonalScope from "./personalScope";
import TaxDeclarationInfo from "./taxDeclarationInfo";
import TaxFilingInfoDialofg from "./taxFillingInfoDialog";
import WeaTopTitle from "../../../components/custom-title/weaTopTitle";
import WeaReqTitle from "../../../components/custom-title/weaReqTitle";
import * as API from "../../../apis/taxAgent";
import { registrationCheck } from "../../../apis/taxAgent";
import "./index.less";

const { getLabel } = WeaLocaleProvider;
const Step = WeaSteps.Step;

@inject("taxAgentStore")
@observer
class TaxAgentSlide extends Component {
  constructor(props) {
    super(props);
    this.state = {
      current: 0, loading: false, verifyLoading: false, taxAgentId: "",
      taxFilingInfoDialofg: {
        visible: false, title: "", checkPayload: {},
        isEdit: false, jumpAll: false, loading: false,
        taxAgentTaxReturnCheckFormDTO: null
      }
    };
    this.taxInfoRef = null;
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.visible !== this.props.visible || nextProps.decentralization !== this.props.decentralization) {
      const { taxAgentStore: { salarytaxAgentForm }, decentralization, isChief } = nextProps;
      decentralization === "0" ?
        salarytaxAgentForm.setCondition(convertConditon(decentralizationConditions, !isChief), true) :
        salarytaxAgentForm.setCondition(convertConditon(editConditions, !isChief), true);
      this.setState({ current: nextProps.current, taxAgentId: nextProps.taxAgentId }, () => {
        if (this.state.taxAgentId) this.getTaxAgentForm();
      });
    }
    if (nextProps.visible !== this.props.visible && !nextProps.visible) this.props.taxAgentStore.setSalarytaxAgentForm();
  }

  getTaxAgentForm = () => {
    const { taxAgentId } = this.state;
    const { taxAgentStore: { salarytaxAgentForm } } = this.props;
    API.getTaxAgentForm({ id: taxAgentId }).then(({ status, data }) => {
      if (status) {
        const { name, description, adminUserIds, sortedIndex } = data;
        salarytaxAgentForm.updateFields({
          name: { value: name },
          adminUserIds: {
            value: _.map(adminUserIds, it => it.id.toString()).join(","),
            valueSpan: _.map(adminUserIds, it => it.content).join(",")
          },
          sortedIndex: { value: sortedIndex },
          description: { value: description }
        });
      }
    });
  };
  /*
   * Author: 黎永顺
   * Description: 保存个税扣缴义务人
   * Params:
   * Date: 2022/12/1
   */
  saveTaxAgent = (payload) => {
    const { onOk, salaryOn } = this.props;
    const { current } = this.state;
    this.setState({ loading: true });
    API.saveTaxAgent(payload).then(({ status, data, errormsg }) => {
      this.setState({ loading: false });
      if (status) {
        message.success(getLabel(22619, "保存成功"));
        this.setState({
          current: !salaryOn ? current + 2 : current + 1,
          taxAgentId: data
        }, () => onOk());
      } else {
        message.error(errormsg || getLabel(22620, "保存失败"));
      }
    }).catch(() => this.setState({ loading: false }));
  };
  /*
   * Author: 黎永顺
   * Description: 编辑个税扣缴义务人
   * Params:
   * Date: 2022/12/1
   */
  updateTaxAgent = (payload) => {
    const { onCancel } = this.props;
    this.setState({ loading: true });
    API.updateTaxAgent(payload).then(({ status, data, errormsg }) => {
      this.setState({ loading: false });
      if (status) {
        message.success(getLabel(31439, "更新成功"));
        onCancel(true);
      } else {
        message.error(errormsg || getLabel(31825, "更新失败"));
      }
    }).catch(() => this.setState({ loading: false }));
  };
  handleSave = () => {
    const { taxAgentStore: { salarytaxAgentForm } } = this.props;
    const { taxAgentId } = this.state;
    salarytaxAgentForm.validateForm().then((f) => {
      if (f.isValid) {
        const formData = salarytaxAgentForm.getFormParams();
        const payload = {
          ...formData,
          adminUserIds: formData.adminUserIds ? formData.adminUserIds.split(",") : []
        };
        taxAgentId ? this.updateTaxAgent({ ...payload, id: taxAgentId }) : this.saveTaxAgent(payload);
      } else {
        f.showErrors();
      }
    });
  };
  handleSaveAndVerify = (jumpAll = false) => {
    const { isEdit } = this.props, { taxAgentId, taxFilingInfoDialofg } = this.state;
    const { fieldForm, fieldItem } = this.taxInfoRef.state;
    const { city: cityStr, cityVal = [], netPassword, realNamePassword, ...extra } = fieldForm;
    const boolean = _.every(_.filter(fieldItem, item => item.viewAttr === 3), it => fieldForm[it.key]);
    if (!boolean) {
      Modal.warning({
        title: getLabel(131329, "信息确认"),
        content: getLabel(518702, "必要信息不完整，红色*为必填项！")
      });
      return;
    }
    const [nation, province, city] = cityStr ? cityStr.split("-") : [];
    const proBool = _.every(cityStr ? cityStr.split("-") : [], it => it !== "undefined");
    if (!proBool) {
      Modal.warning({
        title: getLabel(131329, "信息确认"),
        content: getLabel(111, "请展开选择报税所属区域！")
      });
      return;
    }
    // requestType: 1:保存并验证 2：保存
    const payload = {
      ...extra, nation, province, city,
      taxAgentId, requestType: 1, password: netPassword || realNamePassword,
      cityname: !_.isEmpty(cityVal) ? _.head(cityVal).name : ""
    };
    this.setState({ verifyLoading: true });
    API.saveAndCheck(_.omitBy(payload, val => _.isNil(val))).then(({ status, data, errormsg }) => {
      this.setState({ verifyLoading: false });
      if (status) {
        message.success(getLabel(22619, "保存成功！"));
        this.setState({
          taxFilingInfoDialofg: {
            ...taxFilingInfoDialofg, visible: true,
            isEdit, jumpAll, title: fieldForm.name, checkPayload: payload,
            taxAgentTaxReturnCheckFormDTO: data.TaxAgentTaxReturnCheckFormDTO || data.table.list
          }
        });
      } else {
        message.error(errormsg || getLabel(22620, "保存失败！"));
      }
    }).catch(() => this.setState({ verifyLoading: false }));
  };
  handleSubmit = (selectKey) => {
    const { taxFilingInfoDialofg, taxAgentId } = this.state;
    const { fieldForm } = this.taxInfoRef.state;
    const { city: cityStr, cityVal = [], netPassword, realNamePassword, ...extra } = fieldForm;
    const [nation, province, city] = cityStr ? cityStr.split("-") : [];
    const { taxAgentTaxReturnCheckFormDTO } = taxFilingInfoDialofg;
    this.setState({
      taxFilingInfoDialofg: { ...taxFilingInfoDialofg, loading: true }
    });
    registrationCheck({
      ...extra, nation, province, city,
      taxAgentId, password: netPassword || realNamePassword,
      cityname: !_.isEmpty(cityVal) ? _.head(cityVal).name : "",
      ..._.find(taxAgentTaxReturnCheckFormDTO, it => it.index === selectKey)
    }).then(({ status, data, errormsg }) => {
      this.setState({
        taxFilingInfoDialofg: { ...taxFilingInfoDialofg, loading: false }
      });
      if (status) {
        message.success(getLabel(22619, "保存成功！"));
        this.setState({
          taxFilingInfoDialofg: {
            ...taxFilingInfoDialofg,
            taxAgentTaxReturnCheckFormDTO: data.TaxAgentTaxReturnCheckFormDTO
          }
        });
      } else {
        message.error(errormsg || getLabel(22620, "保存失败！"));
      }
    }).catch(() => {
      this.setState({
        taxFilingInfoDialofg: { ...taxFilingInfoDialofg, loading: false }
      });
    });
  };

  render() {
    const {
      isEdit, title, visible, onCancel, salaryOn, decentralization, isChief, taxAgentStore: { PageAndOptAuth }
    } = this.props;
    const { current, taxAgentId, taxFilingInfoDialofg, loading, verifyLoading } = this.state;
    let tabs = [
      {
        key: 0, title: getLabel(82751, "基础设置"),
        createBtns: [
          <Button type="primary" onClick={this.handleSave}
                  loading={loading}>{getLabel(33199, "保存并进入下一步")}</Button>
        ],
        editBtns: [
          <Button type="primary" onClick={this.handleSave}
                  loading={loading}>{getLabel(537558, "保存")}</Button>
        ],
        children: <BaseSettings decentralization={decentralization} isChief={isChief}/>
      },
      {
        key: 1, title: getLabel(544342, "报税信息"),
        createBtns: [
          <Button type="ghost" loading={verifyLoading}
                  onClick={() => this.handleSaveAndVerify(true)}>{getLabel(543470, "完成，跳过所有步骤")}</Button>,
          <Button type="ghost"
                  onClick={() => this.setState({ current: current + 1 })}>{getLabel(1402, "下一步")}</Button>
        ],
        editBtns: [
          <Button type="primary" loading={verifyLoading}
                  onClick={() => this.handleSaveAndVerify(false)}>{getLabel(544343, "保存并验证")}</Button>
        ],
        children: <TaxDeclarationInfo ref={dom => this.taxInfoRef = dom} taxAgentId={taxAgentId} isChief={isChief}/>
      },
      {
        key: 2, title: getLabel(124810, "人员范围"),
        createBtns: [
          <Button type="ghost"
                  onClick={() => this.setState({ current: !salaryOn ? current - 2 : current - 1 })}>{getLabel(1876, "上一步")}</Button>
        ],
        editBtns: [],
        children: <PersonalScope taxAgentId={taxAgentId}/>
      }
    ];
    tabs = !salaryOn ? _.filter(tabs, it => it.key !== 1) : tabs;
    const showOperateBtn = PageAndOptAuth.opts.includes("admin");
    return (
      <WeaSlideModal
        className="taxAgentSlide" visible={visible} top={0} width={65} height={100} measure="%" direction="right"
        title={
          !this.props.taxAgentId ?
            <WeaTopTitle title={title} buttons={_.find(tabs, o => current === o.key).createBtns}/> :
            <WeaReqTitle buttons={showOperateBtn ? _.find(tabs, o => current === o.key).editBtns : []}
                         tabDatas={tabs} selectedKey={String(current)} title={title}
                         onChange={cur => this.setState({ current: parseInt(cur) })}/>
        }
        content={
          <div className="taxAgentSlideContent">
            {
              !isEdit &&
              <WeaSteps current={current} style={{ margin: "20px 0" }}>
                {
                  _.map(tabs, item => {
                    const { key, title } = item;
                    return <Step description={title} key={key}/>;
                  })
                }
              </WeaSteps>
            }
            {_.find(tabs, o => current === o.key).children}
            <TaxFilingInfoDialofg
              {...taxFilingInfoDialofg}
              onSubmit={this.handleSubmit}
              onCancel={(isRefresh) => {
                const { jumpAll } = taxFilingInfoDialofg;
                this.setState({
                  current: jumpAll ? this.state.current + 1 : this.state.current,
                  taxFilingInfoDialofg: {
                    ...taxFilingInfoDialofg, visible: false,
                    taxAgentTaxReturnCheckFormDTO: null
                  }
                }, () => {
                  isRefresh && this.taxInfoRef.taxReturnGetForm();
                  jumpAll && this.props.onCancel(true);
                });
              }}
            />
          </div>
        }
        onClose={() => onCancel()}
      />
    );
  }
}

export default TaxAgentSlide;
