/*
 * Author: 黎永顺
 * name:社保方案页面重构-社保方案编辑与查看
 * Description:
 * Date: 2024/2/5
 */
import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import { WeaLocaleProvider, WeaSearchGroup, WeaSlideModal, WeaTab, WeaTools } from "ecCom";
import PlanSetTable from "./planSetTable";
import { Button, message, Modal } from "antd";
import * as API from "../../../../../apis/welfareScheme";
import { getTaxAgentSelectListAsAdmin } from "../../../../../apis/taxAgent";
import { getConditionDomkeys, getSearchs } from "../../../../../util";
import BaseValidateDialog from "./baseValidateDialog";
import { planConditons } from "../../config";
import cs from "classnames";

const getKey = WeaTools.getKey;
const getLabel = WeaLocaleProvider.getLabel;

@inject("programmeStore")
@observer
class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false, conditions: [], selectedKey: "2", planDatas: [],
      baseValidateDialog: {
        visible: false, baseChangeInfo: [], validatePayload: { validate: true, changeData: false }
      }
    };
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.visible !== this.props.visible && nextProps.visible) {
      document.querySelector(".salary-welfare-plan-wrapper").classList.add("zIndex0-welfare-plan");
      const promise = this.getForm(nextProps);
    } else if (nextProps.visible !== this.props.visible && !nextProps.visible) {
      document.querySelector(".salary-welfare-plan-wrapper").classList.remove("zIndex0-welfare-plan");
      nextProps.programmeStore.initPlanForm();
      this.setState({ loading: false, conditions: [], selectedKey: "2", planDatas: [] });
    }
  }

  getForm = async (props) => {
    const { data: result } = await getTaxAgentSelectListAsAdmin();
    const { id, welfareTypeEnum, programmeStore: { planForm }, showOperateBtn } = props;
    API.getForm(id ? _.assign({ welfareTypeEnum }, { id }) : { welfareTypeEnum }).then(({ status, data }) => {
      if (status) {
        const { form: { schemeBatch, schemeDetailList } } = data;
        this.setState({
          planDatas: schemeDetailList,
          conditions: _.map(planConditons, item => ({
            ...item, title: getLabel(item.lanId, item.title),
            items: _.map(item.items, o => {
              if (getKey(o) === "taxAgentIds") {
                return {
                  ...o, hide: schemeBatch["sharedType"] === "0" || _.isNil(schemeBatch["sharedType"]),
                  viewAttr: (schemeBatch["sharedType"] === "1" && showOperateBtn) ? 3 : showOperateBtn ? o.viewAttr : 1,
                  options: _.map(result, k => ({ key: k.id, showname: k.content })),
                  label: getLabel(o.lanId, o.label)
                };
              } else if (getKey(o) === "paymentType" || getKey(o) === "sharedType") {
                return {
                  ...o, label: getLabel(o.lanId, o.label),
                  options: _.map(o.options, k => ({ ...k, showname: getLabel(k.lanId, k.showname) }))
                };
              }
              return { ...o, viewAttr: showOperateBtn ? o.viewAttr : 1, label: getLabel(o.lanId, o.label) };
            })
          }))
        }, () => {
          planForm.initFormFields(this.state.conditions);
          _.map(getConditionDomkeys(this.state.conditions), k => {
            if (k === "sharedType") {
              planForm.updateFields({ [k]: schemeBatch[k] || "0" });
            } else {
              planForm.updateFields({ [k]: schemeBatch[k] || "" });
            }
          });
        });
      }
    });
  };
  save = async () => {
    const { programmeStore: { planForm, setHasBeenModify }, welfareTypeEnum, id } = this.props;
    planForm.validateForm().then(f => {
      if (f.isValid) {
        if (planForm.getFormParams().sharedType === "1" && _.isEmpty(planForm.getFormParams().taxAgentIds)) {
          planForm.showError("taxAgentIds", getLabel(111, "\"可见范围\"未填写"));
        } else {
          const { planDatas, baseValidateDialog } = this.state;
          const { validatePayload } = baseValidateDialog;
          let payload = {
            insuranceScheme: {
              ...planForm.getFormParams(), welfareType: welfareTypeEnum, id,
              paymentArea: planForm.getFormParams().paymentType
            },
            insuranceSchemeDetailList: planDatas
          };
          id && (payload = { ...payload, ...validatePayload });
          this.setState({ loading: true });
          API[id ? "updateScheme" : "createScheme"](payload).then(({ status, data, errormsg }) => {
            this.setState({ loading: false });
            if (status) {
              if (id && Object.prototype.toString.call(data) === "[object String]" && data.indexOf("\n") !== -1) {
                this.setState({
                  baseValidateDialog: {
                    visible: true, baseChangeInfo: data,
                    validatePayload: { ...baseValidateDialog.validatePayload, validate: false }
                  }
                });
              } else {
                message.success(getLabel(30700, "操作成功！"));
                setHasBeenModify(false);
                this.props.onClose(true);
                this.setState({
                  baseValidateDialog: {
                    ...baseValidateDialog, baseChangeInfo: [], validatePayload: { validate: true, changeData: false }
                  }
                });
              }
            } else {
              message.error(errormsg);
            }
          }).catch(() => this.setState({ loading: false }));
        }
      } else {
        f.showErrors();
      }
    });
  };
  renderTitle = () => {
    const { loading } = this.state, { title, showOperateBtn } = this.props;
    return <div className="titleDialog">
      <div className="titleCol titleLeftBox">
        <div className="titleIcon"><i className="icon-coms-fa"/></div>
        <div className="title">{title}</div>
      </div>
      <div className="titleCol titleRightBox">
        {
          showOperateBtn &&
          <Button type="primary" loading={loading} onClick={this.save}>{getLabel(537558, "保存")}</Button>
        }
      </div>
    </div>;
  };
  handleClose = (visible = false) => {
    const { programmeStore: { hasBeenModify, setHasBeenModify }, onClose } = this.props;
    if (hasBeenModify) {
      Modal.confirm({
        title: getLabel(131329, "信息确认"),
        content: getLabel(545770, "确定放弃填写吗？放弃后数据将不会被保存！"),
        onOk: () => {
          onClose(visible);
          setHasBeenModify(false);
        }
      });
    } else {
      onClose(visible);
      setHasBeenModify(false);
    }
  };
  onChange = (params) => {
    const { programmeStore: { planForm, setHasBeenModify } } = this.props;
    const key = _.keys(params)[0];
    if (key === "sharedType") {
      this.setState({
        conditions: _.map(this.state.conditions, it => ({
          ...it, items: _.map(it.items, o => {
            if (getKey(o) === "taxAgentIds") {
              return {
                ...o, hide: params[key].value === "0",
                rules: params[key].value === "1" ? "required|string" : "",
                viewAttr: params[key].value === "1" ? 3 : 2
              };
            }
            return { ...o };
          })
        }))
      }, () => {
        planForm.updateFields({ taxAgentIds: "" });
      });
    }
    setHasBeenModify(true);
  };
  renderTab = () => {
    const { selectedKey } = this.state;
    return <WeaTab
      keyParam="viewcondition" selectedKey={selectedKey}
      datas={[
        { title: getLabel(500201, "个人"), viewcondition: "2" },
        { title: getLabel(1851, "公司"), viewcondition: "1" }
      ]} onChange={v => this.setState({ selectedKey: v })}
    />;
  };
  handleSetPlanDatas = (datas) => {
    const { programmeStore: { setHasBeenModify } } = this.props;
    const { planDatas } = this.state;
    //先统一上下限值
    let dataSource = _.reduce(planDatas, (pre, cur) => {
      const curData = _.find(datas, o => o.insuranceId === cur.insuranceId);
      if (_.isEmpty(curData)) return [...pre, cur];
      return [...pre, { ...cur, lowerLimit: curData.lowerLimit, upperLimit: curData.upperLimit }];
    }, []);
    //再赋值修改值
    dataSource = _.reduce(dataSource, (pre, cur) => {
      const curData = _.find(datas, o => o.id === cur.id);
      return [...pre, { ...cur, ...curData }];
    }, []);
    this.setState({ planDatas: dataSource }, () => setHasBeenModify(true));
  };


  render() {
    const { conditions, planDatas, selectedKey, baseValidateDialog } = this.state;
    const { programmeStore: { planForm }, showOperateBtn } = this.props;
    return (
      <WeaSlideModal
        className={cs("welfare-plan-edit-layout", { "nopermission-welfare-plan-edit-layout": !showOperateBtn })}
        top={0} width={1000} height={100} measureT="%" measureX="px" measureY="%"{...this.props}
        direction={"right"} title={this.renderTitle()} onClose={() => this.handleClose(false)}
        content={<div className="welfare-plan-edit-area">
          {getSearchs(planForm, conditions, 1, false, this.onChange)}
          <WeaSearchGroup showGroup needTigger title={this.renderTab()}>
            <PlanSetTable dataSource={planDatas} selectedKey={selectedKey} showOperateBtn={showOperateBtn}
                          onPlanSet={this.handleSetPlanDatas}/>
          </WeaSearchGroup>
          {/*  */}
          <BaseValidateDialog {...baseValidateDialog}
                              onCancel={(validatePayload = {}) => this.setState({
                                baseValidateDialog: {
                                  visible: false, baseChangeInfo: [],
                                  validatePayload: { validate: true, changeData: false, ...validatePayload }
                                }
                              }, () => !_.isEmpty(validatePayload) && this.save())}/>
        </div>}
      />
    );
  }
}

export default Index;
