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

const { TreeNode } = TreeSelect
const { TextArea } = Input

const themeStyles = [
  { name: '个人版' },
  { name: '企业版' },
]

const backgrounds = ['#daebfe', '#FCEAD1', '#f1feed', '#e3ecfe', '#e4fffa']

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

const urlArray = []

const Right = () => {

  const { shema, setShema } = useContext(GlobalStore)
  const { active, themeStyle, carousel } = shema
  const [form] = Form.useForm()
  const [showList, setShowList] = useState([])
  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 currentGroup = useMemo(() => {
    let current = { hideBackground: false }
    shema?.work.forEach(v => {
      if (v.active) {
        current = { ...v }
      }
    })
    return current
  }, [shema])

  const Actives = useMemo(() => {
    let Active = shema?.work.some(v => v.active)
    return {
      cardActive: !Active,
      groupActive: Active,
      carouselActive: shema?.carousel?.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 changeThemeStyles = (v) => {
    setShema({ ...shema, themeStyle: v.name, background: shema.background || '#daebfe' })
  }

  const groupChange = ({ attr, value }) => {
    let array = []
    shema?.work.forEach(v => {
      array.push({ ...v, [attr]: v.active ? value : v[attr] })
    })
    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 (!haveChildren && ['flutter'].includes(org?.product)) {
      return null
    }
    if (!haveChildren) {
      urlArray.push(org)
    }
    if (org.key) {
      if (haveChildren) {
        return (
          <TreeNode
            value={org.menuID}
            title={org.text}
            icon={org.key ? <MobileOutlined /> : <FolderFilled />}
            disabled
          >
            {org.children.map(item => mapTreeMoblie(item))}
          </TreeNode>
        );
      }
      return <TreeNode value={org.menuID} title={org.text} icon={<MobileOutlined />} disabled />;
    }
    return haveChildren ? (
      <TreeNode
        value={org.menuID}
        title={org.text}
        icon={org.key ? <MobileOutlined /> : <FolderFilled />}
        disabled
      >
        {org.children.map(item => mapTreeMoblie(item))}
      </TreeNode>
    ) : (
      <TreeNode
        value={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)
  }

  const content = (
    <TreeSelect
      showSearch
      treeNodeFilterProp="title"
      style={{ width: '280px' }}
      dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
      placeholder="请选择功能路径"
      allowClear
      treeDefaultExpandAll
      treeIcon
      onChange={(value) => {
        let item = urlArray.find(v => v.menuID === value)
        cardSettingOther(item.product + item.pageUrl, 'url')
      }}
    >
      {moblieList.map(i => mapTreeMoblie(i))}
    </TreeSelect>
  )

  const optionsUpload = {
    onChange: ({ file, fileList }) => {
      if (file.status === 'done' && file.response.code === 0) {
        file.url = `${window.origin}/PandaOMS/OMS/FileCenter/DownLoadFiles?module=图库&filePath=${file.response.data}`
        file.sourcePath = file.response.data;
      }
      if (Array.isArray(fileList)) {
        setShowList(fileList)
        setShema({ ...shema, carousel: { ...carousel, imgUrls: fileList.map(v => v.sourcePath) } })
      } else {
        setShowList([])
      }
    },
  }

  const getComSetting = () => {
    const { cardActive, groupActive, carouselActive } = Actives
    if (carouselActive) {
      return (
        <div className={styles.carouselSetting}>
          <div className={styles['g-title']}>轮播图</div>
          <div className={styles['g-content']}>
            <Upload
              multiple
              name="singleFile"
              listType="picture-card"
              className="avatar-uploader"
              fileList={showList}
              action={`${window.location.origin}${PUBLISH_SERVICE}/UploadSingleFile`}
              {...optionsUpload}
            >
              +
            </Upload>
          </div>
        </div>
      )
    }
    if (groupActive) {
      return (
        <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={currentGroup?.name}
                  onChange={(e) => {
                    e.persist()
                    groupChange({ attr: 'name', value: e.target.value })
                  }}
                />
              </div>
            </div>
            <div className={styles['c-item']}>
              <div>
                隐藏背景色：
              </div>
              <div>
                <Switch
                  checkedChildren="隐藏"
                  unCheckedChildren="显示"
                  checked={currentGroup.hideBackground}
                  onChange={(checked) => {
                    groupChange({ attr: 'hideBackground', value: checked })
                  }}
                />
              </div>
            </div>
          </div>
        </div>
      )
    }
    return (
      <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">
            <Popover
              content={content}
              trigger="click"
            >
              <TextArea value={card.url} onChange={e => cardSettingOther(e.target.value, 'url')} rows={4} />
            </Popover>
          </Form.Item>
          <Form.Item label="卡片参数" name="param">
            <Input value={card.param} onClick={paramShowChange} />
          </Form.Item>
        </Form>
      </div>
    )
  }

  useEffect(() => {
    getData()
    //初始增加一个供水主题
    if (!shema.theme) {
      setShema({ ...shema, theme: '供水主题背景' })
    }
    if (!shema.themeStyle) {
      setShema({ ...shema, themeStyle: '个人版' })
    }
    if (Array.isArray(carousel?.imgUrls)) {
      let array = []
      carousel?.imgUrls.forEach((v, i) => {
        let uid = i + '_' + Math.random()
        array.push({
          uid: uid,
          name: v.split('\\').reverse()[0],
          type: 'image/jpeg',
          status: 'done',
          url: `${window.origin}/PandaOMS/OMS/FileCenter/DownLoadFiles?module=图库&filePath=${v}`,
          sourcePath: v,
          thumbUrl: `${window.origin}/PandaOMS/OMS/FileCenter/DownLoadFiles?module=图库&filePath=${v}`,
          originFileObj: { "uid": uid },
          "response": { "code": 0, "msg": "Ok", "data": v, "stackTrace": null },
          "xhr": {},
        })
      })
      setShowList(array)
    }
  }, [])

  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']}>
            <div className={styles.themeStyles}>
              {
                themeStyles.map(v => {
                  return (
                    <div
                      ative={`${v.name === themeStyle}`}
                      className={styles.themeStyle}
                      name={v.name}
                      onClick={() => changeThemeStyles(v)}
                    >
                      {v.name === themeStyle && <div className={styles['s-icon']} name={v.name}></div>}
                      <div className={styles['s-text']}>{v.name}</div>
                    </div>
                  )
                })
              }
            </div>
          </div>
        </div>
        <div className={styles.group}>
          <div className={styles['g-title']}>主题色设置</div>
          <div style={{ width: '100%', display: themeStyle === '企业版' ? 'block' : 'none' }}>
            <div className={styles.mimGroup}>使用背景色</div>
            <div className={styles['g-content']}>
              <div className={styles['c-background']}>
                {
                  backgrounds.map(v => {
                    return (
                      <div
                        className={styles['d-item']}
                        style={{ background: v }}
                        onClick={() => setShema({ ...shema, background: v })}
                      >
                        {shema.background === v && <CheckOutlined style={{ fontSize: '14px', fontWeight: 'bold', color: '#3594FF' }} />}
                      </div>
                    )
                  })
                }
                <Popconfirm
                  placement="topLeft"
                  icon={false}
                  title={
                    <SketchPicker
                      width="217px"
                      color={shema.background}
                      onChange={(e) => setShema({ ...shema, background: e.hex })}
                    />
                  }
                >
                  <div className={styles['d-item']} style={{ background: backgrounds.includes(shema.background) ? '#FFFFFF' : shema.background }}>
                    {!backgrounds.includes(shema.background) && <CheckOutlined style={{ fontSize: '14px', fontWeight: 'bold', color: '#3594FF' }} />}
                  </div>
                </Popconfirm>
              </div>
            </div>
          </div>
          <div style={{ width: '100%', display: themeStyle === '个人版' ? 'block' : 'none' }}>
            <div className={styles.mimGroup}>使用背景图</div>
            <div className={styles['g-content']}>
              <div className={styles['c-backImg']}>
                {
                  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>
      </div>
      <div className={styles.comSetting} style={{ display: !active ? 'block' : 'none' }}>
        {
          getComSetting()
        }
      </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