import React, { useEffect, useState } from 'react';
import PageContainer from '@/components/BasePageContainer';
import { notification, Spin, Tabs, Button, Tooltip, Card } from 'antd';
import {
  getWebModuleTree,
  getWebconfig,
  postEditWebConfig,
  postAddWebSite,
  deleteWebsite,
  getAllConfigName,
  getProductList,
  getWebSite,
  addWebsite,
  editWebsite,
  omsDeleteWebsite,
  SyncMapComponent,
  BatchDragSingleWebsite,
} from '@/services/webConfig/api';
import { EditTwoTone, ExclamationCircleOutlined, OrderedListOutlined } 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';
import SortModal from './sortModal';

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(''); // 当前展示的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 [productList, setProductList] = useState([]); // 产品列表
  const [sortVisible, setSortVisible] = useState(false);
  const [allProductList, setAllProductList] = 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.data);
    });
    getProduct();
    return () => {
      canceled.cancel = true;
    };
  }, []);

  useEffect(() => {
    console.log(curWeb, 'curWeb');
    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 getProduct = () => {
    getProductList({ isDel: 0 }).then(res => {
      const { code } = res;
      if (code === 0) {
        const {
          data: { UserProducts },
        } = res;
        setAllProductList(res.data.AllProducts);
        if (UserProducts && UserProducts.length > 0) {
          setProductList(UserProducts);
        }
      }
    });
  };

  const updateModuleTree = (userModePrama, canceled = { cancel: false }) => {
    setLoading(true);
    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) {
          console.log(websArr, 'websArr');
          setWebs(websArr);
          if (!curWeb) setCurWeb(websArr[0]);
          setLoading(false);
        }
      })
      .catch(err => {
        // eslint-disable-next-line no-console
        setLoading(false);
      });
  };

  const updateWebconfig = (webTitle, canceled = { cancel: false }) => {
    setLoading(true);
    return getWebconfig(webTitle)
      .then(res => {
        setLoading(false);
        if (!canceled.cancel) {
          setConfigObj(res.data);
          // setConfigObj(res.data);
          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.code === 0 || res.success) {
            notification.success({
              message: `删除网站${webToOperate.text}成功！`,
              duration: 3,
            });
            // updateModuleTree(userMode || 'super');
            if (webToOperate.id === curWeb.id) {
              setCurWeb(webs[0]);
            }
            // setTimeout(() => {
            updateModuleTree(userMode || 'super');
            // }, 500);
          } 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 handleGeturl = val => {
    let url;
    const isSite = val.includes('CityTemp');
    if (isSite) {
      url = val;
    } else {
      url =
        localStorage.getItem('pd2-baseUrl') &&
        localStorage.getItem('pd2-baseUrl') != 'null' &&
        localStorage.getItem('pd2-baseUrl') != 'undefined'
          ? localStorage.getItem('pd2-baseUrl') + val
          : val;
    }
    return url;
  };
  const handleSubmit = val => {
    let { bannerLogo, logo, shortcutIcon, baseBannerUrl, baseIconUrl, baseLogoUrl } = val;
    baseBannerUrl = handleGeturl(bannerLogo);
    baseIconUrl = handleGeturl(shortcutIcon);
    baseLogoUrl = handleGeturl(logo);
    let values = {
      ...val,
      baseBannerUrl,
      baseIconUrl,
      baseLogoUrl,
    };
    setSubmitting(true);
    const requestMap = {
      postEditWebConfig,
      postAddWebSite,
    };
    // const requestMap = {
    //   addWebsite,
    //   editWebsite,
    // };

    const successMsg = isEdit ? '保存成功！' : '新增网站成功！';
    const failMsg = isEdit ? '编辑失败!' : '新增网站失败!';
    requestMap[isEdit ? 'postEditWebConfig' : 'postAddWebSite'](values)
      .then(res => {
        setSubmitting(false);
        if (res.code === 0 || res.success) {
          // setTimeout(() => {
          if (isEdit) {
            setCurWeb({ ...curWeb, text: values.title });
          } else {
            setCurWeb({ ...curWeb, text: values.title, id: res.data });
          }
          // }, 200);

          notification.success({
            message: successMsg,
            duration: 3,
          });
          setConfigVisible(false);
          // setTimeout(() => {
          updateModuleTree(userMode || 'super');
          // }, 500);
        } else {
          notification.warning({
            message: res.msg || 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 SyncMap = e => {
    console.log(e);
    SyncMapComponent({ visible: e.subSystemValue }).then(res => {
      if (res.code == 0) {
        notification.success({
          message: '提示',
          duration: 3,
          description: '同步成功',
        });
        updateModuleTree(userMode || 'super');
      } else {
        notification.error({
          message: '提示',
          duration: 3,
          description: res.msg,
        });
      }
    });
  };

  const sort = () => {
    console.log(webs);
    setSortVisible(true);
  };

  const renderTabPane = tabPaneItem => (
    <TabPane key={tabPaneItem.id} tab={tabPaneItem.text}>
      <>
        <Card className={styles.webConfigTabcontent}>
          <span
            className={styles.link}
            onClick={() => {
              setToEdit({ ...configObj });
              setConfigVisible(true);
              setIsEdit(true);
            }}
          >
            <EditTwoTone /> 查看/编辑网站配置
          </span>

          <div style={{ display: 'inline-block', float: 'right', marginTop: '-15px' }}>
            <strong style={{ marginRight: '15px' }}>
              地图组件数量
              {tabPaneItem.existMapComponent < tabPaneItem.mapComponent ? (
                <Tooltip title="点击一键修复" placement="topRight">
                  <span style={{ color: 'red' }} onClick={() => SyncMap(tabPaneItem)}>
                    {tabPaneItem.existMapComponent}
                  </span>
                  /
                  <span style={{ color: '#1890ff' }} onClick={() => SyncMap(tabPaneItem)}>
                    {tabPaneItem.mapComponent}
                  </span>
                </Tooltip>
              ) : (
                <Tooltip title="点击同步地图组件" placement="topRight">
                  <span style={{ color: '#1890ff' }} onClick={() => SyncMap(tabPaneItem)}>
                    {tabPaneItem.existMapComponent}
                  </span>
                  <span>/</span>
                  {tabPaneItem.existMapComponent !== tabPaneItem.mapComponent ? (
                    <span style={{ color: '#1890ff' }} onClick={() => SyncMap(tabPaneItem)}>
                      {tabPaneItem.existMapComponent}
                    </span>
                  ) : (
                    <span style={{ color: '#1890ff' }} onClick={() => SyncMap(tabPaneItem)}>
                      {tabPaneItem.mapComponent}
                    </span>
                  )}
                </Tooltip>
              )}
            </strong>
            {/* {tabPaneItem.existMapComponent < 9 && (
              <Button
                type="primary"
                style={{ marginRight: '20px' }}
                onClick={() => SyncMap(tabPaneItem)}
              >
                一键修复
              </Button>
            )} */}
          </div>
          <MenuConfig
            menu={
              tabPaneItem.children && tabPaneItem.children.find(w => w.menuType === 'Web4MenuRoot')
            }
            onUpdate={handleUpdateOnMenuChange}
            configFiles={configFiles}
            updateMenuTree={updateMenuTree}
            userMode={userMode}
            webid={tabPaneItem?.id}
            subSystemValue={tabPaneItem?.subSystemValue}
            productList={productList}
            allProductList={allProductList}
          />
        </Card>
      </>
    </TabPane>
  );

  const onOK = e => {
    setSortVisible(false);
    console.log(e.str);
    BatchDragSingleWebsite(e.str).then(res => {
      if (res.code === 0) {
        updateModuleTree(userMode || 'super');
        notification.success({
          message: '提示',
          duration: 3,
          description: '调序成功',
        });
      } else {
        notification.error({
          message: '提示',
          duration: 3,
          description: res.msg,
        });
      }
    });
  };

  return (
    <PageContainer>
      <div className={styles.webConfigContainer}>
        <Spin spinning={loading || submitting}>
          <div
            style={{
              display: 'flex',
              alignContent: 'center',
              justifyContent: 'flex-start',
            }}
          >
            <Tabs
              type="editable-card"
              onEdit={onEdit}
              onChange={handleTabChange}
              activeKey={curWeb && curWeb.id}
              style={{
                display: 'flex',
                alignContent: 'center',
                justifyContent: 'flex-start',
                width: '97% ',
              }}
            >
              {/* <TabPane key={99} tab="产品配置" closable={false}>
              <ProductConfig />
            </TabPane> */}
              {/* {webs.map(renderTabPane)} */}
              {webs.map(item => renderTabPane(item))}
            </Tabs>
            <Tooltip title="调序" placement="topRight">
              <span
                style={{
                  display: 'inline-block',
                  width: '40px',
                  height: '40px',
                  backgroundColor: '#FAFAFA',
                  marginLeft: '5px',
                  padding: '0 8px',
                  border: '1px solid #f0f0f0',
                  borderRadius: '2px 2px 0 0',
                  outline: 'none',
                  cursor: 'pointer',
                }}
                onClick={sort}
              >
                <OrderedListOutlined style={{ marginTop: '12px', marginLeft: '2px' }} />
              </span>
            </Tooltip>
          </div>
          <SiteConfig
            webs={webs}
            curWeb={curWeb}
            productList={productList}
            allProductList={allProductList}
            isEdit={isEdit}
            userMode={userMode}
            visible={configVisible}
            onClose={onDrawerClose}
            config={toEdit}
            onOk={handleSubmit}
            submitting={submitting}
            hasIntegerate={hasIntegerate()}
          />
          <SortModal
            visible={sortVisible}
            onCancel={() => setSortVisible(false)}
            webs={webs}
            callBackSubmit={onOK}
          />
        </Spin>
      </div>
    </PageContainer>
  );
};

export default appConnector(WebConfigPage);
