import React, { useState, useEffect, useMemo } from 'react';
import { Card, Tabs, Button, Popconfirm, notification, Spin } 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,
} from '@/services/mobileConfig/api';
import SiteConfig from './SiteConfig';
import MenuConfig from './menuconfig/MenuConfig';
import { appConnector } from '@/containers/App/store';
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 [position, setPosition] = useState([]);
  const [subType, setSubType] = useState('');
  useEffect(() => {
    setLoading(true);
    getMiniAppModuleTree({
      userMode: userMode || 'super',
    }).then(res => {
      setLoading(false);
      console.log(res, 'res');
      if (res.code === 0) {
        const { data } = res;
        let obj =
          data[0].children.length > 0 &&
          data[0].children.find(item => item.id.includes('miniapp'));
        console.log(obj, 'obj');
        if (data[0].children.length > 0 && obj) {
          const title = obj.text || '';
          setShowConfig(true);
          setMiniTitle(title);
          setPosition(['right']);
        } else {
          setPosition(['left']);
          setShowConfig(false);
        }
      } else {
        setShowConfig(false);
      }
      console.log(res);
    });
  }, [flag]);

  useEffect(() => {
    // getMiniAppModuleTree({
    //   userMode: 'super',
    // }).then(res => {
    //   console.log(res);
    // });
  }, []);
  // 修改选中的tab
  const handleChange = key => {
    setActiveKey(key);
  };
  const submitCallback = () => {
    setFlag(flag + 1);
    setSubType('');
  };
  const addCallback = val => {
    console.log(val);
    setSubType('');
    setMiniTitle(val);
    setPosition(['right']);
  };
  // 删除
  const delMini = () => {
    setLoading(true);
    deleteWebsite({
      client: 'miniapp',
      _version: 9999,
      _dc: Date.now(),
    })
      .then(res => {
        setLoading(false);
        if (res.success) {
          setFlag(flag + 1);
          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 options = {
    left: (
      <Button type="primary" onClick={addMini}>
        新增移动应用
      </Button>
    ),
    right: (
      <Popconfirm
        title="是否删除移动应用,及相关联的角色和菜单"
        okText="确认"
        cancelText="取消"
        placement="left"
        onConfirm={delMini}
      >
        <Button type="primary" danger>
          删除移动应用
        </Button>
      </Popconfirm>
    ),
  };
  const slot = useMemo(() => {
    if (position.length === 0) return null;

    return position.reduce((acc, direction) => {
      console.log(acc, direction);
      return { ...acc, [direction]: options[direction] };
    }, {});
  }, [position]);
  const tabArr = [
    {
      title: '网站配置',
      key: '0',
      component: (
        <SiteConfig
          miniTitle={miniTitle}
          submitCallback={submitCallback}
          subType={subType}
          addCallback={addCallback}
        />
      ),
    },
    {
      title: '菜单管理',
      key: '1',
      component: <MenuConfig />,
    },
  ];
  return (
    <PageContainer>
      <ProCard>
        <Spin tip="loading..." spinning={loading}>
          <Tabs
            activeKey={activeKey}
            type="card"
            onChange={handleChange}
            tabBarExtraContent={slot}
          >
            {/* {showConfig &&
              tabArr?.length > 0 &&
              tabArr.map(item => (
                <TabPane tab={item.title} key={item.key}>
                  {activeKey === item.key && item.component}
                </TabPane>
              ))} */}
            {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="其他配置" key="tab3">
                <SevenParams />
                <VersionPublish />
              </TabPane>
            )}
          </Tabs>
        </Spin>
      </ProCard>
    </PageContainer>
  );
};

export default appConnector(MobileConfigPage);