import React, { useState, useContext, useMemo, useEffect } from 'react'
import styles from './index.less'
import { Input, Form, TreeSelect, Switch, Modal } from 'antd'
import { GlobalStore } from '../index'
import { getMenuInfo, getMiniAppModuleTree } from '@/services/mobileConfig/api'
import {
  UsergroupDeleteOutlined,
  IdcardOutlined,
  DesktopOutlined,
  FolderFilled,
  FileOutlined,
  MobileOutlined,
  DeleteOutlined,
  PictureOutlined,
} from '@ant-design/icons'

const { TreeNode } = TreeSelect

const themes = [
  { name: '供水主题背景' },
  { name: '排水主题背景' },
  { name: '农饮水主题背景' },
]

const Right = () => {

  const { shema, setShema } = useContext(GlobalStore)
  const { active } = shema
  const [form] = Form.useForm()
  const [moblieList, setMoblieList] = useState([])
  const [iconShow, setIconShow] = useState()

  const name = useMemo(() => {
    let name = ''
    shema?.work.forEach(v => {
      if (v.active) {
        name = v.name
      }
    })
    return name
  }, [shema])

  const groupActive = useMemo(() => {
    let Active = false
    shema?.work.forEach(v => {
      if (v.active) {
        Active = true
      }
    })
    return Active
  }, [shema])

  const card = useMemo(() => {
    let card = {}
    shema?.work.forEach(v => {
      v.children.forEach(s => {
        if (s.active) {
          card = { ...s }
        }
      })
    })
    return card
  }, [shema])

  useEffect(() => {
    form?.setFieldsValue?.({ ...card })
  }, [card])

  const changeThemes = (v) => {
    setShema({ ...shema, theme: v.name })
  }

  const groupChange = (e) => {
    e.persist()
    let array = []
    shema?.work.forEach(v => {
      array.push({ ...v, name: v.active ? e.target.value : v.name })
    })
    setShema({ ...shema, work: array })
  }

  const cardSetting = (e, attr) => {
    e.persist()
    let array = []
    shema?.work.forEach(v => {
      array.push({ ...v, children: v.children.map(v => ({ ...v, [attr]: v.active ? e.target.value : v[attr] })) })
    })
    setShema({ ...shema, work: array })
  }

  const cardSettingOther = (value, attr) => {
    let array = []
    shema?.work.forEach(v => {
      array.push({ ...v, children: v.children.map(v => ({ ...v, [attr]: v.active ? value : v[[attr]] })) })
    })
    setShema({ ...shema, work: array })
  }

  const getAppList = async () => {
    const { code, data } = await getMiniAppModuleTree({ userMode: 'super', })
    if (code === 0) {
      let array = (data[0].children.length > 0 && [...data[0].children]) || [];
      let list = [];
      array.map((i, j) => {
        let aa = [];
        i.children.map(k => {
          if (k.text === '菜单管理') {
            aa = k.children;
          }
        });
        let a = {};
        a.value = `praent${j}`;
        a.text = i.text;
        a.children = aa;
        a.menuID = `praent${j}`;
        a.key = `praent${j}`;
        list.push(a);
      })
      setMoblieList(list)
    }
  }

  const mapTreeMoblie = (org) => {
    const haveChildren = Array.isArray(org.children) && org.children.length > 0;
    if (org.key) {
      if (haveChildren) {
        return (
          <TreeNode
            value={org.pageUrl || org.menuID}
            title={org.text}
            icon={org.key ? <MobileOutlined /> : <FolderFilled />}
            disabled
          >
            {org.children.map(item => mapTreeMoblie(item))}
          </TreeNode>
        );
      }
      return <TreeNode value={org.pageUrl || org.menuID} title={org.text} icon={<MobileOutlined />} disabled />;
    }
    return haveChildren ? (
      <TreeNode
        value={org.pageUrl || org.menuID}
        title={org.text}
        icon={org.key ? <MobileOutlined /> : <FolderFilled />}
        disabled
      >
        {org.children.map(item => mapTreeMoblie(item))}
      </TreeNode>
    ) : (
      <TreeNode
        value={org.pageUrl || org.menuID}
        title={org.text}
        icon={
          org.menuType == 'MiniAppMenuGroup' || org.menuType == 'MiniAppMenuGroupTwo' ? (
            <FolderFilled />
          ) : (
            <FileOutlined style={{ color: '#1890ff' }} />
          )
        }
        disabled={org.menuType == 'MiniAppMenuGroup' || org.menuType == 'MiniAppMenuGroupTwo'}
      />
    )
  }

  const getData = () => {
    getAppList()
  }

  const iconShowChange = () => {
    setIconShow(true)
  }

  useEffect(() => {
    getData()
    //初始增加一个供水主题
    if (!shema.theme) {
      setShema({ ...shema, theme: '供水主题背景' })
    }
  }, [])

  return (
    <div className={styles.right}>
      <div className={styles.header}>{active ? '页面配置' : '组件配置'}</div>
      <div className={styles.pageSetting} style={{ display: active ? 'block' : 'none' }}>
        <div className={styles.group}>
          <div className={styles['g-title']}>主题色设置</div>
          <div className={styles['g-content']}>
            {
              themes.map(v => {
                return (
                  <div
                    className={styles['c-center']}
                    onClick={() => changeThemes(v)}
                    key={v.name}
                  >
                    <div className={styles['c-img']} ative={`${v.name === shema.theme}`} name={v.name}></div>
                    <div className={styles['c-text']} ative={`${v.name === shema.theme}`}>{v.name}</div>
                  </div>
                )
              })
            }
          </div>
        </div>
      </div>
      <div className={styles.comSetting} style={{ display: !active ? 'block' : 'none' }}>
        {
          groupActive ? (
            <div className={styles.group}>
              <div className={styles['g-title']}>分组设置</div>
              <div className={styles['g-content']}>
                <div className={styles['c-item']}>
                  <div>
                    分组名称：
                  </div>
                  <div>
                    <Input value={name} onChange={groupChange} />
                  </div>
                </div>
              </div>
            </div>
          ) : (
            <div style={{ padding: '10px' }}>
              <Form form={form} layout='vertical'>
                <Form.Item label="卡片名称" name="name">
                  <Input value={card.name} onChange={(e) => cardSetting(e, 'name')} />
                </Form.Item>
                <Form.Item label="卡片名称是否显示" name="nameShow" valuePropName='checked'>
                  <Switch checked={card.nameShow} onChange={check => cardSettingOther(check, 'nameShow')} />
                </Form.Item>
                <Form.Item label="卡片图标" name="icon">
                  <Input value={card.icon} onChange={(e) => cardSetting(e, 'icon')} />
                </Form.Item>
                <Form.Item label="功能跳转" name="url">
                  <TreeSelect
                    showSearch
                    treeNodeFilterProp="title"
                    style={{ width: '97%' }}
                    value={card.url}
                    dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                    placeholder="请选择功能路径"
                    allowClear
                    treeDefaultExpandAll
                    treeIcon
                    onChange={(value) => cardSettingOther(value, 'url')}
                  >
                    {moblieList.map(i => mapTreeMoblie(i))}
                  </TreeSelect>
                </Form.Item>
                <Form.Item label="卡片参数" name="param">
                  <Input value={card.param} onChange={(e) => cardSetting(e, 'param')} />
                </Form.Item>
              </Form>
            </div>
          )
        }
      </div>
      <Modal
        title={'卡片图标'}
        visible={iconShow}
        onCancel={() => setIconShow(false)}
      >

      </Modal>
    </div>
  )

}

export default Right