/* eslint-disable */
import React, { useEffect, useState } from "react";
import { Button, Dropdown, Spin } from "antd-v4";
import { DownOutlined, LoadingOutlined } from "@ant-design/icons";
import * as commonServices from "@/services/services";
import commonConfig from "@/utils/config";
import * as commonFunc from "@/components/Common/commonFunc";
import * as commonUtils from "@/utils/utils";
import styles from "./index.less";

const SwitchCompanyAndLanguageEvent = props => {
  const { app } = props;
  const { token, userinfo } = app;

  const addState = {};
  const [state, setState] = useState({ language: userinfo.sLanguage === "sChinese" ? "中文" : "EN" });

  useEffect(() => {
    const getComponyList = async () => {
      const dataUrl = `${commonConfig.server_host}brand/getBrand/${userinfo.sId}`;

      const dataReturn = (await commonServices.getService(token, dataUrl)).data;
      if (dataReturn?.code === 1) {
        const companyList = dataReturn.dataset.rows[0];
        setState(pre => ({ ...pre, companyList, companyData: companyList.find(item => item.sSubsidiaryId === userinfo.sSubsidiaryId) }));
        setTimeout(() => {
          const resizeEvent = new Event("resize");
          window.dispatchEvent(resizeEvent);
        }, 1000);
      }
    };

    getComponyList();
  }, []);

  addState.onChangeCompany = async item => {
    if (item.sSubsidiaryId === state.companyData.sSubsidiaryId) return;

    setState(pre => ({ ...pre, companyLoading: true }));
    const dataUrl = `${commonConfig.server_host}brand/changeBrand`;
    const conditions = {
      sBrandsId: item.sBrandsId,
      sSubsidiaryId: item.sSubsidiaryId,
    };
    const dataReturn = (await commonServices.postValueService(token, conditions, dataUrl)).data;
    if (dataReturn.code === 1) {
      setState(pre => ({ ...pre, companyData: item }));
      const {
        token,
        systemData,
        rxtx,
        commonConst,
        gdslogininfo: userinfo,
        auxiliaryQty,
        footer,
        logoImageInfo,
        isInitPassword,
      } = {
        ...app,
        ...dataReturn.dataset.rows[0],
      };

      const decimals = {};
      if (commonUtils.isNotEmptyArr(systemData)) {
        const dNetPrice = systemData.filter(item => item.sName === "NetPrice")[0];
        const dNumAlign = systemData.filter(item => item.sName === "CkxNumAlign")[0];
        decimals.dNetPrice = Number(dNetPrice.sValue);
        decimals.dNetMoney = 2;
        decimals.dNumAlign = dNumAlign !== undefined && dNumAlign.sValue !== undefined ? dNumAlign.sValue : 0;
      }

      props.dispatch({
        type: "login/login",
        payload: {
          token,
          rxtx,
          commonConst,
          userinfo,
          auxiliaryQty,
          dispatch: props.dispatch,
          systemData,
          decimals,
          dateFormat: commonFunc.getDateFormat(systemData),
          footer,
          logoImageInfo,
          isInitPassword,
          bChangeLanguage: true,
        },
      });

      setTimeout(() => {
        commonUtils.clearStoreDropDownData();
        commonUtils.clearFormStoreDropDownData();
        window.xlyReload();
      }, 1000);
    } else {
      props.dispatch({ type: "app/throwError", payload: dataReturn });
    }

    setState(pre => ({ ...pre, companyLoading: false }));
  };

  addState.onChangeLanguage = async () => {
    setState(pre => ({ ...pre, btnLoading: true }));
    const dataUrl = `${commonConfig.server_host}brand/changeLanguage`;
    const { language } = state;

    const dataReturn = (await commonServices.postValueService(token, { sLanguage: language === "中文" ? "sEnglish" : "sChinese" }, dataUrl)).data;
    if (dataReturn.code === 1) {
      setState(pre => ({ ...pre, language: language === "中文" ? "EN" : "中文" }));
      const {
        token,
        systemData,
        rxtx,
        commonConst,
        gdslogininfo: userinfo,
        auxiliaryQty,
        footer,
        logoImageInfo,
        isInitPassword,
      } = {
        ...app,
        ...dataReturn.dataset.rows[0],
      };

      const decimals = {};
      if (commonUtils.isNotEmptyArr(systemData)) {
        const dNetPrice = systemData.filter(item => item.sName === "NetPrice")[0];
        const dNumAlign = systemData.filter(item => item.sName === "CkxNumAlign")[0];
        decimals.dNetPrice = Number(dNetPrice.sValue);
        decimals.dNetMoney = 2;
        decimals.dNumAlign = dNumAlign !== undefined && dNumAlign.sValue !== undefined ? dNumAlign.sValue : 0;
      }

      props.dispatch({
        type: "login/login",
        payload: {
          token,
          rxtx,
          commonConst,
          userinfo,
          auxiliaryQty,
          dispatch: props.dispatch,
          systemData,
          decimals,
          dateFormat: commonFunc.getDateFormat(systemData),
          footer,
          logoImageInfo,
          isInitPassword,
          bChangeLanguage: true,
        },
      });

      setTimeout(() => {
        commonUtils.clearStoreDropDownData();
        commonUtils.clearFormStoreDropDownData();
        window.xlyReload();
      }, 1000);
    }

    setState(pre => ({ ...pre, btnLoading: false }));
  };

  return {
    ...props,
    ...addState,
    ...state,
  };
};

const SwitchCompanyAndLanguage = baseProps => {
  const props = SwitchCompanyAndLanguageEvent(baseProps);
  return (
    <div className={styles.switchCompanyAndLanguage}>
      <CompanyComponent {...props} />
      {/* <LanguageComponent {...props} /> */}
    </div>
  );
};

const CompanyComponent = props => {
  const { companyList = [], companyData = {}, companyLoading = false } = props;

  const bMutiLine = companyData.sName?.includes("-");
  const sName0 = bMutiLine ? companyData.sName.split("-")[0] : "";
  const sName1 = bMutiLine ? companyData.sName.split("-")[1] : "";
  return (
    !!companyList.length && (
      <Dropdown
        trigger={["click"]}
        menu={{
          items: companyList.map(item => ({
            ...item,
            key: item.sId,
            label: item.sName,
            onClick: props.onChangeCompany.bind(this, item),
          })),
        }}
      >
        <Spin
          spinning={companyLoading}
          indicator={
            <LoadingOutlined
              style={{
                fontSize: 24,
              }}
              spin
            />
          }
        >
          <div className="company">
            {bMutiLine ? (
              <div className="companyMutiLine">
                <div>{sName0}</div>
                <div>{sName1}</div>
              </div>
            ) : (
              <span>{companyData.sName}</span>
            )}
            <DownOutlined />
          </div>
        </Spin>
      </Dropdown>
    )
  );
};

const LanguageComponent = props => {
  const { language, btnLoading } = props;
  return (
    <div className="language">
      {btnLoading ? (
        <LoadingOutlined style={{ fontSize: 16 }} />
      ) : (
        <Button type="link" onClick={props.onChangeLanguage}>
          {language}
        </Button>
      )}
    </div>
  );
};

export default SwitchCompanyAndLanguage;
