import React, { useState, useEffect } from 'react';
import { connect } from 'react-redux';
import { request } from 'utils/fetch';
import { api } from 'constants/config';
import ImageUpload from './ImageUpload';
import style from './index.less';
import message from 'components/message';
import {getAssetsUrl} from 'utils/utils';
import defaultLoginLogo from '../../../images/login_logo.png';
import defaultIcon from '../../../favicon.ico';
import defaultLogo from '../../../images/logo.png';
import defaultLoadPage from '../../../images/loading_background.jpg';
import EasyvModal, { useActionModalRef } from 'components/EasyvModal';

function isString(arg) {
  if (typeof arg === 'string') {
    return true;
  }
  return false;
}

const paramsFormat = (key) => (isString(key) ? null : key);

const PLATFORM = 'PLATFORM';
const LOAD_PAGE = 'LOAD_PAGE';

const GeneralSettingModal = ({ children, userRole }) => {
  const modalRef = useActionModalRef();
  const [btnLoading, setBtnLoading] = useState(false);
  const [loadingPage, setLoadingPage] = useState('');
  const [imgParams, setImgParams] = useState<{
    icon: string | null;
    logo: string | null;
    loginLogo: string | null;
    loadingPage: string | null;
  }>({
    icon: null,
    logo: null,
    loginLogo: null,
    loadingPage: null
  });
  const [isImgChange, setIsImgChange] = useState(false);

  const initUploadCover = () => {
    const { ICON = '', LOGO = '', LOGIN_LOGO = '' } = window.appConfig;
    setImgParams({
      icon: ICON ? getAssetsUrl(ICON) : '',
      logo: LOGO ?getAssetsUrl( LOGO) : '',
      loginLogo: LOGIN_LOGO ? getAssetsUrl(LOGIN_LOGO) : '',
      loadingPage: loadingPage ? getAssetsUrl(loadingPage) : ''
    });
  };

  useEffect(() => {
    initUploadCover();
  }, [loadingPage]);

  const init = async () => {
    const result = await request(api.getLoadingPage);
    const { loadingPage: _loadingPage = '' } = result;
    setLoadingPage(_loadingPage);
  };

  const onCancel = () => {
    modalRef.current?.close();
  };

  const isBlob = (file) => Object.prototype.toString.call(file) === '[object File]';

  const submitSetting = async () => {
    if (!isImgChange) {
      modalRef.current?.close();
      return;
    }
    setBtnLoading(true);
    const PlatformLogoValues = Object.values(imgParams);
    PlatformLogoValues.length = PlatformLogoValues.length - 1;
    let hasPlatformLogoVal = false;
    const hasLoadingPageVal = isBlob(imgParams.loadingPage);
    PlatformLogoValues.forEach((item) => {
      if (isBlob(item)) {
        hasPlatformLogoVal = true;
        return;
      }
    });
    const hide = message.loading('修改中...', 0);
    let result = true;
    if (hasPlatformLogoVal && !hasLoadingPageVal) {
      const formData = getRequestParams(PLATFORM);
      result = await request(api.updateSetting, undefined, undefined, formData);
    }
    if (!hasPlatformLogoVal && hasLoadingPageVal) {
      const formData = getRequestParams(LOAD_PAGE);
      result = await request(api.patchLoadingPage, undefined, undefined, formData);
    }
    if (hasPlatformLogoVal && hasLoadingPageVal) {
      await Promise.all([requestAsync(LOAD_PAGE), requestAsync(PLATFORM)]);
    }
    hide();
    result && location.reload();
  };

  const requestAsync = (type) => {
    const _api = type === LOAD_PAGE ? api.patchLoadingPage : api.updateSetting;
    return new Promise((resolve) => {
      (async () => {
        const formData = getRequestParams(type);
        const res = await request(_api, undefined, undefined, formData);
        if (res) {
          setBtnLoading(false);
          resolve(res);
        }
      })();
    });
  };

  const getRequestParams = (type) => {
    const { icon, logo, loginLogo, loadingPage } = imgParams;
    const formData = new FormData();
    if (type === LOAD_PAGE) {
      formData.append('loadingPage', paramsFormat(loadingPage));
    }
    if (type === PLATFORM) {
      formData.append('icon', paramsFormat(icon));
      formData.append('logo', paramsFormat(logo));
      formData.append('loginLogo', paramsFormat(loginLogo));
    }
    return formData;
  };

  const uploadChange = async (key, value) => {
    setIsImgChange(true);
    setImgParams((prev) => ({ ...prev, [key]: value }));
    if (!value) {
      if (key === 'loadingPage') {
        await request(api.deleteLoadingPage, undefined, undefined, JSON.stringify({ loadingPage: '' }));
        await init();
      } else {
        request(api.putSetting, undefined, undefined, JSON.stringify({ [key]: '' }));
      }
    }
  };

  const Platform = () => (
    <>
      <div className={style.title}>以下修改针对平台</div>
      {window.appConfig.LOCAL && (
        <div style={{ marginBottom: 24 }}>
          <ImageUpload
            title="登录画面："
            size={200}
            format="jpg"
            onChange={(value) => uploadChange('loginLogo', value)}
            defaultImgUrl={defaultLoginLogo}
            imgUrl={imgParams.loginLogo}
          />
        </div>
      )}
      <div style={{ marginBottom: 24 }}>
        <ImageUpload
          title="网站logo："
          dpr="16*16"
          size={50}
          format="ico、png"
          onChange={(value) => uploadChange('icon', value)}
          defaultImgUrl={defaultIcon}
          imgUrl={imgParams.icon}
        />
      </div>
      <div style={{ marginBottom: 24 }}>
        <ImageUpload
          title="平台logo："
          size={50}
          format="常见图片格式"
          onChange={(value) => uploadChange('logo', value)}
          defaultImgUrl={defaultLogo}
          imgUrl={imgParams.logo}
        />
      </div>
    </>
  );

  const Tenant = () => (
    <>
      <div className={style.title}>以下修改针对租户</div>
      <ImageUpload
        title="加载页面："
        dpr="1920*1080"
        size={200}
        format="jpg"
        onChange={(value) => uploadChange('loadingPage', value)}
        defaultImgUrl={defaultLoadPage}
        imgUrl={imgParams.loadingPage}
      />
    </>
  );

  return (
    <div>
      <div
        style={{ display: 'flex', alignItems: 'center' }}
        onClick={() => {
          init();
          modalRef.current?.show();
        }}>
        {children}
      </div>
      <EasyvModal.ActionModal
        okText="完成"
        title="通用设置"
        ref={modalRef}
        confirmLoading={btnLoading}
        onOk={submitSetting}
        onCancel={onCancel}
        content={
          <>
            {userRole === 2 ? <Platform /> : null}
            <Tenant />
          </>
        }
      />
    </div>
  );
};

function mapStateToProps(state) {
  const { user } = state;
  return {
    userRole: user.userInfo.role
  };
}

export default connect(mapStateToProps)(GeneralSettingModal);
