import React, { useEffect, useMemo, useState } from 'react'
import styles from './index.less'
import { Form, Modal, Input, message, Button, TreeSelect, Select } from 'antd'
import { RightOutlined, ExclamationCircleOutlined, PlusOutlined } from '@ant-design/icons'
import { getSchemeList, saveScheme, deleteScheme, roleGroupList } from '@/services/mobileConfig/api'
import Designer from './components/Designer'

const cardType = [
  { label: '管理工作台', value: '管理' },
  { label: '运营工作台', value: '运营' },
  { label: '执行工作台', value: '执行' },
]

const WorkDesign = (props) => {

  const userName = sessionStorage.getItem('userName')
  const [isCardList, setIsCardList] = useState(true)
  const [tabIndex, setTabIndex] = useState(0)
  const [cardList, setCardList] = useState([])
  const [roleList, setRoleList] = useState([])
  const [visible, setVisible] = useState(false)
  const [isDesign, setIsDesign] = useState(false)
  const [currentCard, setCurrentCard] = useState({})
  const [form] = Form.useForm()

  const tabs = useMemo(() => {
    const getCount = (type) => {
      return cardList.filter(v => v['类型'] === type).length
    }
    return [
      { label: '全部', value: '全部', count: cardList.length },
      { label: '运营', value: '运营', count: getCount('运营') },
      { label: '执行', value: '执行', count: getCount('执行') },
      { label: '管理', value: '管理', count: getCount('管理') },
    ]
  }, [cardList])

  const addCard = () => {
    form.setFieldsValue({ '名称': '', '关联角色ID': [], '描述': '', '类型': '' })
    setCurrentCard({})
    setVisible(true)
  }

  const editCard = (item) => {
    setCurrentCard(item)
    form.setFieldsValue({ '名称': item['名称'], '描述': item['描述'], '关联角色ID': item.roleInfo.map(v => `${v['角色ID']}`), '类型': item['类型'] })
    setVisible(true)
  }

  const getCardList = async () => {
    const { code, data } = await getSchemeList()
    if (code === 0) {
      setCardList(data)
      if (data.length) {
        setIsCardList(false)
      } else {
        setIsCardList(true)
      }
    }
  }

  const getRoleList = async () => {
    const { code, data } = await roleGroupList({ userID: 1 })
    if (code === 0) {
      let array = []
      data?.roleList?.forEach(v => {
        if (v.visibleValue === 'miniapp') {
          array = [...v.child, ...v.roleList]
        }
      })
      array.forEach(v => {
        if (v.roleList) {
          v.roleID = v.visibleTitle
          v.roleName = v.visibleTitle
          v.disabled = true
        }
        v.roleList = v.roleList || []
      })
      setRoleList(array)
    }
  }

  const getData = () => {
    getCardList()
    getRoleList()
  }

  const onOk = async () => {
    const validate = await form.validateFields()
    if (validate) {
      const values = form.getFieldsValue()
      let parmas = {
        ID: currentCard.ID || 0,
        ...values,
        '关联角色ID': values['关联角色ID'].join(','),
        '创建人': userName,
        '卡片结构': currentCard['卡片结构'],
        '路径': currentCard['路径'],
      }
      const { code, data, msg } = await saveScheme(parmas)
      if (code === 0) {
        getCardList()
        message.info({ type: 'success', content: '添加成功!' })
        setVisible(false)
      } else {
        message.info({ type: 'fail', content: msg })
      }
    }
  }

  const toDesign = (item) => {
    setIsDesign(true)
    setCurrentCard(item)
  }

  const deleteDesgin = async (item) => {
    Modal.confirm({
      title: '是否确定删除该工作方案?',
      icon: <ExclamationCircleOutlined />,
      centered: true,
      onOk() {
        return new Promise(async (resolve, reject) => {
          const { code, data, msg } = await deleteScheme({ ID: item.ID })
          if (code === 0) {
            resolve()
            getCardList()
            message.success({ content: '删除成功!' })
          } else {
            reject()
            message.error({ content: msg })
          }
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    })
  }

  const saveDesgin = async (card) => {
    const { code, data, msg } = await saveScheme(card)
    if (code === 0) {
      message.info({ type: 'success', content: '保存成功!' })
    } else {
      message.info({ type: 'fail', content: msg })
    }
  }

  const goBack = () => {
    setIsDesign(false)
    getCardList()
  }

  useEffect(() => {
    getData()
  }, [])

  return (
    <div className={styles.workDesign}>
      {
        isCardList ? (
          <div className={styles.workBg}>
            <div className={styles['b-text']}>
              <span onClick={() => addCard()}>开始搭建工作台</span>
              <RightOutlined style={{ position: 'relative', top: '1px', marginLeft: '5px' }} />
            </div>
          </div>
        ) :
          !isDesign ? (
            <div className={styles.content}>
              <div className={styles.listHeader}>
                <div className={styles['h-left']}>
                  {
                    tabs.map((v, i) => {
                      return (
                        <div
                          key={v.value}
                          icon={<PlusOutlined />}
                          className={styles.tab}
                          active={`${tabIndex === i}`}
                          onClick={() => setTabIndex(i)}
                        >
                          <span>{v.label}</span>
                          <span>({v.count + '个'})</span>
                          <div className={styles.line} style={{ width: tabIndex === i ? '80px' : '0px' }}></div>
                        </div>
                      )
                    })
                  }
                </div>
                <div className={styles['h-right']}>
                  <Button type='primary' icon={<PlusOutlined />} onClick={() => addCard()}>新建</Button>
                </div>
              </div>
              <div className={styles.cardList}>
                {
                  cardList.map(v => {
                    const type = tabs[tabIndex].value
                    const isShow = (type === '全部') || (type === v['类型'])
                    return (
                      <div className={styles.card} key={v.ID} style={{ display: isShow ? 'block' : 'none' }}>
                        <div className={styles['card-type']} type={v['类型']}>{v['类型']}</div>
                        <div className={styles.title}>
                          <div className={styles['title-click']} onClick={() => editCard(v)}>
                            <span className={styles['title-text']}>{v['名称']}</span>
                            <span className={styles['title-icon']}></span>
                          </div>
                        </div>
                        <div className={styles.img}>
                          {v['路径'] ? <img style={{ width: '100%' }} src={`${origin}/PandaOMS/OMS/FileCenter/DownloadFiles?module=图库&filePath=${v['路径']}`}></img> : null}
                          <div className={styles.imgCenter}>
                            <div>
                              <Button type="primary" onClick={() => toDesign(v)}>设计</Button>
                            </div>
                            <div style={{ marginTop: '10px' }}>
                              <Button type="primary" danger onClick={() => deleteDesgin(v)}>删除</Button>
                            </div>
                          </div>
                        </div>
                        <div className={styles.footer}>
                          <div style={{ marginTop: '5px' }}>
                            <span className={styles.label}>角色名称:</span>
                            <span>{v['角色名称']}</span>
                          </div>
                          <div style={{ marginTop: '5px' }}>
                            <span className={styles.label}>更新时间:</span>
                            <span>{v['更新时间']}</span>
                          </div>
                        </div>
                      </div>
                    )
                  })
                }
              </div>
            </div>
          ) : (
            <Designer
              currentCard={currentCard}
              goBack={goBack}
              saveDesgin={saveDesgin}
            />
          )
      }
      <Modal
        title={currentCard.ID ? '编辑工作台' : '创建工作台'}
        visible={visible}
        onCancel={() => setVisible(false)}
        onOk={onOk}
        centered
      >
        <Form
          layout="vertical"
          form={form}
          initialValues={{ '名称': '', '关联角色ID': '', '描述': '' }}
        >
          <Form.Item
            label={'工作台名称'}
            name={'名称'}
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label={'关联角色'}
            name={'关联角色ID'}
            rules={[{ required: true }]}
          >
            <TreeSelect
              multiple
              style={{ width: '100%' }}
              placeholder='请选择角色'
              allowClear
              fieldNames={{ label: 'roleName', value: 'roleID', children: 'roleList' }}
              treeData={roleList}
            >
            </TreeSelect>
          </Form.Item>
          <Form.Item
            label={'工作台类型'}
            name={'类型'}
            rules={[{ required: true }]}
          >
            <Select options={cardType}></Select>
          </Form.Item>
          <Form.Item
            label={'工作台描述'}
            name={'描述'}
          >
            <Input.TextArea allowClear showCount />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )

}

export default WorkDesign