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 WorkDesign from './menuconfig/WorkDesign';
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';

import styles from './index.less';
const { TabPane } = Tabs;
const MobileConfigPage = props => {
  const { userMode } = props;
  const [activeKey, setActiveKey] = useState('1'); // 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] || '';
        let data = singleList.find(i => i.id === key);
        Modal.confirm({
          title: '确认删除应用?',
          icon: <ExclamationCircleOutlined />,
          content: (
            <span>
              删除应用 <span style={{ fontWeight: 800, color: '#1890ff' }}>{data.text}</span>{' '}
              后，将一并删除所属角色与菜单，确认删除?
            </span>
          ),
          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('1');
    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) => {
    console.log(clientName);
    console.log(val);
    setLoading(true);
    closeModal();
    console.log(val);
    deleteWebsite({
      client: val,
      _version: 9999,
      _dc: Date.now(),
    })
      .then(res => {
        setLoading(false);
        if (res.code === 0) {
          if (clientName === val) {
            setMiniTitle(singleList[0].text);
          }
          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 = () => (
    <Card style={{ height: '100%' }}>
      {/* <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>
        )} */}
        {showConfig && subType !== 'add' && (
          <TabPane tab={tabArr[4].title} key={tabArr[4].key}>
            {activeKey === tabArr[4].key && tabArr[4].component}
          </TabPane>
        )}
      </Tabs>
      {/* </Spin> */}
    </Card>
  );
  const cts = (tabPaneItem, id) => (
    <TabPane key={tabPaneItem.id} tab={tabPaneItem.text}>
      <>{parentKey === tabPaneItem.id && ContentTab()}</>
    </TabPane>
  );
  const tabArr = [
    {
      title: '菜单管理',
      key: '1',
      component: <MiniMenu clientName={clientName} userMode={userMode} parentKey={parentKey} />,
    },
    {
      title: '应用配置',
      key: '0',
      component: (
        <SiteConfig
          miniTitle={miniTitle}
          submitCallback={submitCallback}
          subType={subType}
          addCallback={addCallback}
          clientName={clientName}
          parentKey={parentKey}
          singleList={singleList}
        />
      ),
    },
    {
      title: '七参数配置',
      key: '2',
      component: <SevenParams />,
    },
    {
      title: '版本包配置',
      key: '3',
      component: <VersionPublish clientName={clientName} />,
    },
    {
      title: '工作台搭建',
      key: '4',
      component: <WorkDesign />,
    },
  ];
  return (
    <PageContainer>
      <div className={styles.mobileContainer}>
        <Spin spinning={loading} tip="loading...">
          <Tabs
            activeKey={parentKey}
            onChange={handleParChange}
            type="editable-card"
            onEdit={handleEdit}
          >
            {singleList.map(item => cts(item, parentKey))}
          </Tabs>
        </Spin>
      </div>
      <Drawer
        title="新增应用"
        destroyOnClose
        width={450}
        onClose={() => {
          setAddVisible(false);
        }}
        visible={addVisible}
      >
        <AddConfig
          visible={addVisible}
          addCallback={addCallback}
          submitCallback={submitCallback}
          singleList={singleList}
        />
      </Drawer>
    </PageContainer>
  );
};

export default appConnector(MobileConfigPage);
