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

const { TreeNode } = TreeSelect

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

const Right = () => {

  const { shema, setShema } = useContext(GlobalStore)
  const { active } = shema
  const [form] = Form.useForm()
  const [paramForm] = Form.useForm()
  const [moblieList, setMoblieList] = useState([])
  const [iconShow, setIconShow] = useState()
  const [iconList, setIconList] = useState([])
  const [currentIcon, setCurrentIcon] = useState('')
  const [paramShow, setParamShow] = useState(false)

  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 = [];
      console.log('array', array)
      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 />;
    }
    if (!haveChildren && org?.product === 'flutter') {
      return null
    }
    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()
    getIconList()
  }

  const getIconList = async () => {
    const { code, data } = await getImageBases('appWorkSpace')
    if (code === 0) {
      let array = []
      data.forEach(v => {
        if (v.moduleName === 'appWorkSpace') {
          array = v.fileUrls
        }
      })
      setIconList(array)
    }
  }

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

  const paramShowChange = () => {
    let field = []
    let array = card?.param?.split('&') || []
    array.forEach(v => {
      field.push({ key: v.split('=')[0], value: v.split('=')[1] })
    })
    paramForm.setFieldsValue({ field })
    setParamShow(true)
  }

  const paramOk = () => {
    const { field } = paramForm.getFieldsValue()
    let value = ''
    field.forEach(v => {
      value = value ? (value + `&${v.key}=${v.value}`) : `${v.key}=${v.value}`
    })
    cardSettingOther(value, 'param')
    setParamShow(false)
  }

  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 className={styles.cardSetting}>
              <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">
                  {
                    card.icon ? (
                      <div className={styles['card-img']}>
                        <img
                          onClick={() => {
                            setCurrentIcon(card.icon)
                            setIconShow(true)
                          }}
                          style={{ width: '100%', height: '100%' }}
                          src={`${origin}/civweb4/${card.icon}`}
                        />
                      </div>
                    ) : (
                      <div className={styles['card-icon']} onClick={() => setIconShow(true)}>
                        <PlusOutlined />
                      </div>
                    )
                  }
                </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} onClick={paramShowChange} />
                </Form.Item>
              </Form>
            </div>
          )
        }
      </div>
      <Modal
        title={'卡片图标'}
        visible={iconShow}
        onCancel={() => setIconShow(false)}
        onOk={() => {
          cardSettingOther(currentIcon, 'icon')
          setIconShow(false)
        }}
      >
        <div className={styles.iconBox}>
          {
            iconList.map(v => {
              return (
                <div
                  className={styles.iconItem}
                  active={`${currentIcon === v}`}
                  onClick={() => setCurrentIcon(v)}
                >
                  <img style={{ width: '100%', height: '100%' }} src={`${origin}/civweb4/${v}`}></img>
                </div>
              )
            })
          }
        </div>
      </Modal>
      <Modal
        title={'参数配置'}
        visible={paramShow}
        onCancel={() => setParamShow(false)}
        onOk={paramOk}
      >
        <Form name="dynamic_form_nest_item" form={paramForm} autoComplete="off">
          <Form.List name="field" label='字段映射'>
            {(value, { add, remove }) => (
              <>
                {value.map(({ key, name, ...restField }, index) => (
                  <Space
                    key={key}
                    style={{
                      display: 'flex',
                      marginBottom: '5px',
                      justifyContent: 'center',
                      position: 'relative',
                      left: '-11px',
                    }}
                    align="baseline"
                  >
                    <Form.Item
                      {...restField}
                      name={[name, 'key']}
                      rules={[
                        {
                          required: true,
                          message: '参数名必填',
                        },
                        {
                          validator: (rules, value, callback) => {
                            const { field } = paramForm.getFieldsValue()
                            let keys = Array.from(new Set([...field.map(v => v.key)]))
                            if (keys.length !== field.length) {
                              return Promise.reject('参数名不能重复！')
                            }
                            return Promise.resolve()
                          }
                        }
                      ]}
                    >
                      <Input placeholder='请输入参数名' />
                    </Form.Item>
                    <div className={styles.centerImg}></div>
                    <Form.Item
                      {...restField}
                      name={[name, 'value']}
                      rules={[
                        {
                          required: true,
                          message: '参数值必填',
                        },
                      ]}
                    >
                      <Input placeholder='请输入参数值' />
                    </Form.Item>
                    <MinusCircleOutlined onClick={() => remove(name)} />
                  </Space>
                ))}
                <Form.Item style={{ padding: '0 10px' }}>
                  <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                    添加参数
                  </Button>
                </Form.Item>
              </>
            )}
          </Form.List>
        </Form>
      </Modal>
    </div>
  )

}

export default Right