import React, { useState, useEffect, useMemo } from 'react';
import {
  Card,
  Tabs,
  Button,
  Popconfirm,
  notification,
  Spin,
  Modal,
  Drawer,
} from 'antd';
import ProCard from '@ant-design/pro-card';
import PageContainer from '@/components/BasePageContainer';
import SevenParams from './menuconfig/SevenParams';
import VersionPublish from './menuconfig/VersionPublish';
import {
  getMiniAppModuleTree,
  deleteWebsite,
  deleteMiniMenu,
} from '@/services/mobileConfig/api';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import SiteConfig from './SiteConfig';
import MiniMenu from './menuconfig/miniMenu';
import AddConfig from './addConfig';
import { appConnector } from '@/containers/App/store';
const { TabPane } = Tabs;
const MobileConfigPage = props => {
  const { userMode } = props;
  const [activeKey, setActiveKey] = useState('0'); // tabs活动页
  const [miniTitle, setMiniTitle] = useState(''); // 应用名称
  const [flag, setFlag] = useState(1); // 刷新标志
  const [showConfig, setShowConfig] = useState(true);
  const [loading, setLoading] = useState(false);
  const [subType, setSubType] = useState('');
  const [parentKey, setParentKey] = useState('');
  const [singleList, setSingleList] = useState([]);
  const [clientName, setClientName] = useState(''); // client
  const [addVisible, setAddVisible] = useState(false);
  useEffect(() => {
    setLoading(true);
    getMiniAppModuleTree({
      userMode: userMode || 'super',
    }).then(res => {
      setLoading(false);
      if (res.code === 0) {
        const { data } = res;
        let array =
          (data[0].children.length > 0 && [...data[0].children]) || [];
        let arr = [];
        array.map(item => {
          arr.push({
            ...item,
            subSystemValue: item.id.split('single')[1],
          });
          console.log(item.id.split('single')[1]);

          return item;
        });
        setSingleList(arr);
        if (miniTitle) {
          let obj = arr.find(item => item.text === miniTitle);
          setParentKey(obj.id);
          setMiniTitle(obj.text);
          setClientName(obj.subSystemValue);
        } else {
          setParentKey(arr[0].id);
          setMiniTitle(arr[0].text);
          setClientName(arr[0].subSystemValue);
        }

        console.log(arr);
      } else {
        setShowConfig(false);
      }
      console.log(res);
    });
  }, [flag]);

  // 修改选中的tab
  const handleChange = key => {
    setActiveKey(key);
  };
  // tab新增编辑的回调
  const handleEdit = (key, action) => {
    console.log(key, 'key', action);

    switch (action) {
      case 'add': {
        setAddVisible(true);
        break;
      }
      case 'remove': {
        let val = key.split('single')[1] || '';
        Modal.confirm({
          title: '确认删除应用?',
          icon: <ExclamationCircleOutlined />,
          okText: '确认',
          cancelText: '取消',
          onOk: closeModal => {
            delMini(val, closeModal);
          },
        });
        break;
      }
      default:
        break;
    }
  };
  const handleParChange = key => {
    console.log(key);
    let obj = singleList.find(item => item.id === key);
    console.log(obj);
    setParentKey(key);
    setActiveKey('0');
    setClientName(obj.subSystemValue);
    setMiniTitle(obj.text);
  };
  const submitCallback = val => {
    setFlag(flag + 1);
    setMiniTitle(val);
    setSubType('');
  };
  const addCallback = val => {
    console.log(val);
    setSubType('');
    setAddVisible(false);
    setMiniTitle(val);

    setFlag(flag + 1);
    // setMiniTitle(val);
  };
  // 删除
  const delMini = (val, closeModal) => {
    setLoading(true);
    closeModal();
    console.log(val);
    deleteWebsite({
      client: val,
      _version: 9999,
      _dc: Date.now(),
    })
      .then(res => {
        setLoading(false);
        if (res.success) {
          setMiniTitle('');
          setTimeout(() => {
            setFlag(flag + 1);
          }, 500);
          setTimeout(() => {
            deleteMiniMenu({ visible: val });
          }, 1500);
          notification.success({
            message: '提示',
            duration: 3,
            description: '删除成功',
          });
        } else {
          notification.success({
            message: '提示',
            duration: 3,
            description: res.message || '删除失败',
          });
        }
      })
      .catch(() => {
        setLoading(false);
      });
  };
  const addMini = () => {
    setShowConfig(true);
    setSubType('add');
  };

  const ContentTab = () => (
    <ProCard>
      {/* <Spin tip="loading..." spinning={loading}> */}
      <Tabs activeKey={activeKey} type="card" onChange={handleChange}>
        {showConfig && (
          <TabPane tab={tabArr[0].title} key={tabArr[0].key}>
            {activeKey === tabArr[0].key && tabArr[0].component}
          </TabPane>
        )}
        {showConfig && subType !== 'add' && (
          <TabPane tab={tabArr[1].title} key={tabArr[1].key}>
            {activeKey === tabArr[1].key && tabArr[1].component}
          </TabPane>
        )}
        {/* {showConfig && subType !== 'add' && (
            <TabPane tab={tabArr[2].title} key={tabArr[2].key}>
              {activeKey === tabArr[2].key && tabArr[2].component}
            </TabPane>
          )} */}
        {showConfig && subType !== 'add' && (
          <TabPane tab={tabArr[3].title} key={tabArr[3].key}>
            {activeKey === tabArr[3].key && tabArr[3].component}
          </TabPane>
        )}
      </Tabs>
      {/* </Spin> */}
    </ProCard>
  );
  const cts = (tabPaneItem, id) => (
    <TabPane key={tabPaneItem.id} tab={tabPaneItem.text}>
      <>{parentKey === tabPaneItem.id && ContentTab()}</>
    </TabPane>
  );
  const tabArr = [
    {
      title: '应用配置',
      key: '0',
      component: (
        <SiteConfig
          miniTitle={miniTitle}
          submitCallback={submitCallback}
          subType={subType}
          addCallback={addCallback}
          clientName={clientName}
          parentKey={parentKey}
        />
      ),
    },
    {
      title: '菜单管理',
      key: '1',
      component: (
        <MiniMenu
          clientName={clientName}
          userMode={userMode}
          parentKey={parentKey}
        />
      ),
    },
    {
      title: '七参数配置',
      key: '2',
      component: <SevenParams />,
    },
    {
      title: '版本包配置',
      key: '3',
      component: <VersionPublish clientName={clientName} />,
    },
  ];
  return (
    <PageContainer>
      <Spin spinning={loading} tip="loading...">
        <Tabs
          activeKey={parentKey}
          onChange={handleParChange}
          type="editable-card"
          onEdit={handleEdit}
        >
          {singleList.map(item => cts(item, parentKey))}
        </Tabs>
      </Spin>
      <Drawer
        title="新增应用"
        destroyOnClose
        width={500}
        onClose={() => {
          setAddVisible(false);
        }}
        visible={addVisible}
      >
        <AddConfig addCallback={addCallback} submitCallback={submitCallback} />
      </Drawer>
    </PageContainer>
  );
};

export default appConnector(MobileConfigPage);