// 核心库
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'dva'
// 工具库
import { get, isEqual } from 'lodash'
import storage from '../utils/storage'
import {
  initFilterGroup,
  extendFilterGroup,
  extendGroupRule,
  extendInclude,
  initFilter
} from '../utils/common'
import MD5 from 'md5'
// 默认图片
import assetsPic from './assetsPic'

class PictureThumb extends Component {
  constructor (props) {
    super(props)
    // 同一个页面中可能有数十个节点，请求的都是同一个api，所以用这个key来识别相同的api请求，并通过store获取数据
    // 数十个节点，同时请求同一个api没关系，因为在httpPost中做了相同url接口请求的节流
    this.thumbKey = ''
  }

  componentDidMount () {
    this.getThumbs(this.props.thumbCodes)
  }

  UNSAFE_componentWillReceiveProps (nextProps) {
    if (!isEqual(nextProps.thumbCodes, this.props.thumbCodes)) {
      this.getThumbs(nextProps.thumbCodes)
    }
  }

  getThumbs = (thumbCodes = []) => {
    if (!thumbCodes.length) return
    const webOrgId = storage('lacal').getItem('webOrgId').val

    const initParams = initFilter(webOrgId)
    const group = initFilterGroup(false)
    thumbCodes.forEach(code => {
      extendGroupRule(group, 'CODE', 1, code)
    })
    extendFilterGroup(initParams, group)
    extendInclude(initParams, 'Nav_PictureFiles.Nav_ImgFile.Nav_Details.Nav_File')
    this.thumbKey = MD5(JSON.stringify(initParams))

    this.props.dispatch({
      type: 'app/getDataByPost',
      payload: initParams,
      url: 'BD/Picture/OrderEntities',
      onComplete: (ret) => {
        if (ret) {
          this.props.dispatch({
            type: 'treePage/save',
            payload: {
              [this.thumbKey]: {
                pictureThumbs: ret,
                pictureThumbTargetPath: 'Nav_PictureFiles[0].Nav_ImgFile.Nav_Details[0].Nav_File.FILE_DATA'
              }
            }
          })
        }
      }
    })
  }

  checkThumbs = () => {
    const { thumbConfigs = [], nodeData = {} } = this.props
    // 获取全局图片配置
    const globalThumbConfig = thumbConfigs.filter(config => !config.rules || !config.rules.length)
    // 获取节点对应图片资源
    let thumbTarget = globalThumbConfig[0] ? globalThumbConfig[0].target : ''
    for (let i = 0, j = thumbConfigs.length; i < j; i++) {
      const { target, rules = [] } = thumbConfigs[i]
      let matchRules = true
      rules.forEach(rule => {
        const { field, operate, value } = rule
        const fieldValue = get(nodeData, field.toLowerCase())
        switch (operate) {
          case 1:
            fieldValue != value && (matchRules = false)
            break
          default:
            fieldValue != value && (matchRules = false)
            break
        }
      })
      matchRules && (thumbTarget = target)
    }
    return thumbTarget
  }

  getTargetImage = () => {
    const thumbTarget = this.checkThumbs()
    const { pictureThumbs = [], pictureThumbTargetPath = '' } = this.props.treePage[this.thumbKey] || {}
    const picTargetData = pictureThumbs.find(pic => pic.CODE === thumbTarget && pic.Nav_PictureFiles.length)

    let picTaget = ''
    if (picTargetData) {
      picTaget = get(picTargetData, pictureThumbTargetPath, '')
    }
    return picTaget
  }

  render () {
    const { defaultThumb, style = {}, className } = this.props
    const picTaget = this.getTargetImage()
    const picSrc = picTaget ? `data:image/png;base64,${picTaget}` : defaultThumb
    return (
      <div className='opt-pic-thumb'>
        <img src={picSrc} alt='logo' style={style} className={className} />
        <div className='opt-pic-thumb__content'>{this.props.children}</div>
      </div>
    )
  }
}

/**
 * thumbCodes: ['A001']
 * thumbConfigs
 * [
 *  {
 *    target: 'A001'
 *    rules: [{ field: 'Level1', operate: 1, value: 1 }]
 *  }
 * ]
 * 对 thumbConfigs 进行顺序遍历，rules 里面的规则是 and 规则，所有 rules 符合条件，则取 target 作为图片
 * 有一个特殊逻辑，如果遍历到 rules 为空数组，则视为默认符合条件，可直接取 target 作为图片
 */
PictureThumb.propTypes = {
  thumbCodes: PropTypes.array.isRequired,
  thumbConfigs: PropTypes.array.isRequired,
  defaultThumb: PropTypes.any,
  nodeData: PropTypes.object
}

PictureThumb.defaultProps = {
  thumbCodes: [],
  thumbConfigs: [],
  defaultThumb: assetsPic,
  nodeData: {}
}

export default connect(({ treePage }) => ({ treePage }))(PictureThumb)
