import React, { useEffect, useState } from 'react';
import PageContainer from '@/components/BasePageContainer';
import { notification, Spin, Tabs } from 'antd';
import {
  getWebModuleTree,
  getWebconfig,
  postEditWebConfig,
  postAddWebSite,
  deleteWebsite,
  getAllConfigName,
} from '@/services/webConfig/api';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import Modal from 'antd/lib/modal/Modal';
import ProCard from '@ant-design/pro-card';
import styles from './index.less';
import SiteConfig from './components/siteConfigDrawer';
import { appConnector } from '@/containers/App/store';
import { defaultWebConfigObj, webMode } from './utils';
import MenuConfig from './menuconfig/MenuConfig';
const { TabPane } = Tabs;

const WebConfigPage = props => {
  const { userMode } = props;
  const [configVisible, setConfigVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [webs, setWebs] = useState([]);
  const [curWeb, setCurWeb] = useState(null); // 当前展示的web
  const [configObj, setConfigObj] = useState({}); // 获取当前的web的配置
  const [toEdit, setToEdit] = useState(null); // 编辑展示用的配置
  const [isEdit, setIsEdit] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [configFiles, setConfigFiles] = useState([]);

  const hasIntegerate = () =>
    webs.some(w => w.id.startsWith(webMode.integration));

  useEffect(() => {
    let canceled = { cancel: false };
    setLoading(true);
    updateModuleTree(userMode || 'super', canceled);
    getAllConfigName().then(res => {
      if (!canceled.cancel) setConfigFiles(res);
    });
    return () => {
      canceled.cancel = true;
    };
  }, []);

  useEffect(() => {
    let canceled = { cancel: false };
    if (!curWeb) return;
    const title = curWeb.text;
    updateWebconfig(title, canceled);

    // eslint-disable-next-line consistent-return
    return () => {
      canceled.cancel = true;
    };
  }, [curWeb]);

  const updateModuleTree = (userModePrama, canceled = { cancel: false }) => {
    getWebModuleTree(userModePrama).then(res => {
      const websArr = [
        // 暂时不要集成网站
        // res.data
        //   .filter(d => d.id === 'Web4IntegrateStation')
        //   .map(r =>
        //     r.children.map(c => ({
        //       ...c,
        //       subSystemValue: c.id.split(webMode.integration)[1],
        //     })),
        //   ),
        res.data
          .filter(d => d.id === 'Web4SingleStation')
          .map(r =>
            r.children.map(c => ({
              ...c,
              subSystemValue: c.id.split(webMode.single)[1],
            })),
          ),
      ].flat(2);
      if (!canceled.cancel) {
        setWebs(websArr);
        if (!curWeb) setCurWeb(websArr[0]);
        setLoading(false);
      }
    });
  };

  const updateWebconfig = (webTitle, canceled = { cancel: false }) => {
    setLoading(true);
    return getWebconfig(webTitle)
      .then(res => {
        setLoading(false);
        if (!canceled.cancel) {
          setConfigObj(res);
          if (webTitle === curWeb.text) {
            setToEdit(res);
          }
        }
      })
      .catch(err => {
        setLoading(false);
        // eslint-disable-next-line no-console
        console.error(err);
      });
  };

  const handleDeleteWeb = (webToOperate, closeModal) => {
    // eslint-disable-next-line prefer-destructuring
    const client = webToOperate?.id?.split(
      webToOperate.id.startsWith(webMode.single)
        ? webMode.single
        : webMode.integration,
    )[1];
    if (client) {
      deleteWebsite(client)
        .then(res => {
          if (res.success) {
            notification.success({
              message: `删除网站${webToOperate.text}成功!`,
              duration: 3,
            });
            updateModuleTree(userMode || 'super');
          } else {
            notification.error({
              message: res.message || `删除网站 ${webToOperate.text} 失败`,
            });
          }
          // eslint-disable-next-line no-unused-expressions
          closeModal && closeModal();
        })
        .catch(err => {
          // eslint-disable-next-line no-console
          console.error(err);
          notification.error({ message: '删除网站失败!', duration: 5 });
          // eslint-disable-next-line no-unused-expressions
          closeModal && closeModal();
        });
    }
  };

  const onEdit = (targetKey, action) => {
    const webToOperate = webs.find(w => w.id === targetKey);
    switch (action) {
      case 'add':
        setIsEdit(false);
        setToEdit(defaultWebConfigObj);
        setConfigVisible(true);
        break;
      case 'remove':
        Modal.confirm({
          title: '删除网站',
          icon: <ExclamationCircleOutlined />,
          content: (
            <span>
              删除网站{' '}
              <span style={{ fontWeight: 800, color: '#1890ff' }}>
                {webToOperate.text}
              </span>{' '}
              后将无法恢复, 确认删除?
            </span>
          ),
          okText: '确认',
          cancelText: '取消',
          onOk: closeModal => {
            handleDeleteWeb(webToOperate, closeModal);
          },
        });
        break;
      default:
    }
  };

  const onDrawerClose = form => {
    setConfigVisible(false);
  };

  const handleTabChange = v => {
    setCurWeb(webs.find(w => w.id === v));
  };

  const handleSubmit = values => {
    setSubmitting(true);
    const requestMap = {
      postEditWebConfig,
      postAddWebSite,
    };
    const successMsg = isEdit ? '保存成功!' : '新增网站成功!';
    const failMsg = isEdit ? '编辑失败!' : '新增网站失败!';
    requestMap[isEdit ? 'postEditWebConfig' : 'postAddWebSite'](values)
      .then(res => {
        setSubmitting(false);
        if (res.success) {
          setCurWeb({ ...curWeb, text: values.title });
          notification.success({
            message: successMsg,
            duration: 3,
          });
          updateModuleTree(userMode || 'super');
        } else {
          notification.warning({
            message: res.message || failMsg,
            duration: 5,
          });
        }
      })
      .catch(err => {
        notification.error({
          message: failMsg,
          duration: 5,
        });
        // eslint-disable-next-line no-console
        console.error(err);
        setSubmitting(false);
      });
  };

  const handleUpdateOnMenuChange = () => {
    updateModuleTree(userMode || 'super');
  };

  const updateMenuTree = (type, menuNode) => {
    updateModuleTree(userMode || 'super');
  };

  const renderTabPane = tabPaneItem => (
    <TabPane key={tabPaneItem.id} tab={tabPaneItem.text}>
      <>
        <ProCard className={styles.webConfigTabcontent}>
          <span
            className={styles.link}
            onClick={() => {
              setToEdit({ ...configObj });
              setConfigVisible(true);
              setIsEdit(true);
            }}
          >
            查看/编辑网站配置
          </span>
          <MenuConfig
            menu={tabPaneItem?.children.find(
              w => w.menuType === 'Web4MenuRoot',
            )}
            onUpdate={handleUpdateOnMenuChange}
            configFiles={configFiles}
            updateMenuTree={updateMenuTree}
            subSystemValue={tabPaneItem?.subSystemValue}
          />
        </ProCard>
      </>
    </TabPane>
  );

  return (
    <PageContainer>
      <div className={styles.webConfigContainer}>
        <Spin spinning={loading || submitting}>
          <Tabs type="editable-card" onEdit={onEdit} onChange={handleTabChange}>
            {webs.map(renderTabPane)}
          </Tabs>
          <SiteConfig
            isEdit={isEdit}
            visible={configVisible}
            onClose={onDrawerClose}
            config={toEdit}
            onOk={handleSubmit}
            submitting={submitting}
            hasIntegerate={hasIntegerate()}
          />
        </Spin>
      </div>
    </PageContainer>
  );
};

export default appConnector(WebConfigPage);