import './form.scss'
import { formTpl } from './formTpl'
import FormModules from './formModules'
import { FloorChannelType } from '../../../../editor/src/const'
const DataSourceUserConfigType = {
  TEXTAREA: {
    type: 'textarea',
    name: '文本区域',
  },
  RADIO: {
    type: 'radio',
    name: '单选框',
  },
  IMAGE: {
    type: 'image',
    name: '图片',
  },
  LINK_IMAGE: {
    type: 'linkImage',
    name: '图片+链接',
  },
  GOODS_GROUP: {
    type: 'goodsGroup',
    name: '商品组',
  },
  ADV_GROUP: {
    type: 'advGroup',
    name: '广告素材组(不推荐)',
  },
  NEW_ADV_GROUP: {
    type: 'swiper',
    name: '新广告素材组',
  },
  HOTSPOT: {
    type: 'hotspot',
    name: '图片热区',
  },
  SERIES_GOODS: {
    type: 'seriesGoods',
    name: '系列商品',
  },
  INPUT: {
    type: 'input',
    name: '单行文本',
  },
  LINK_TEXT: {
    type: 'linkText',
    name: '文本+链接',
  },
  COLOR: {
    type: 'color',
    name: '颜色选择器',
  },
  CHECKBOX: {
    type: 'checkbox',
    name: '多选框',
  },
  VIDEO: {
    type: 'video',
    name: '视频选择器',
  },
  TOP_RANK: {
    type: 'topRank',
    name: '排行榜',
  },
  PRE_SELL: {
    type: 'preSell',
    name: '预售',
  },
}
const DataSourceTypeToLocalKey = {
  [DataSourceUserConfigType.TEXTAREA.type]: DataSourceUserConfigType.TEXTAREA.type,
  [DataSourceUserConfigType.RADIO.type]: DataSourceUserConfigType.RADIO.type,
  [DataSourceUserConfigType.IMAGE.type]: 'imageWH',
  [DataSourceUserConfigType.LINK_IMAGE.type]: 'J_LINK_IMAGE',
  [DataSourceUserConfigType.GOODS_GROUP.type]: 'J_COMMON_SKU_MATERIAL',
  [DataSourceUserConfigType.ADV_GROUP.type]: 'J_ADV_MATERIAL',
  [DataSourceUserConfigType.NEW_ADV_GROUP.type]: 'J_ADV_MATERIAL_NEW',
  [DataSourceUserConfigType.HOTSPOT.type]: 'J_PICTURE_HOTSPOT',
  [DataSourceUserConfigType.SERIES_GOODS.type]: 'J_SERIES_PRODUCTS',
  [DataSourceUserConfigType.INPUT.type]: 'J_NORMAL_TEXT',
  [DataSourceUserConfigType.LINK_TEXT.type]: 'J_LINK_TEXT',
  [DataSourceUserConfigType.COLOR.type]: 'J_NORMAL_COLOR',
  [DataSourceUserConfigType.CHECKBOX.type]: 'J_NORMAL_ARRAY',
  [DataSourceUserConfigType.VIDEO.type]: 'J_VIDEO',
  [DataSourceUserConfigType.TOP_RANK.type]: 'J_BIG_PROMO_TOP_RANK',
  [DataSourceUserConfigType.PRE_SELL.type]: 'J_PRESELL_SKU_MATERIAL',
}
const Form = (($) => {
    const DefaultConfig = {
        node: '',
        module: null,
        skin: 'cd-form',
        moduleInfo: {},
        domData: [],
        moduleData: {},
    }
    class Form {
        constructor(config) {
            this.config = this.getConfig(config)
            this.element = $(this.config.node) 
            this.formContent = $(formTpl)
            this.element.append(this.formContent)
            
            this.instanceList = []
            this.getPlatFrom()
            this.setSkin()
            this.getModuleByFormTypeOrDatasource()
        }
        
        getPlatFrom() {
            this.platForm = page_data.clientType || 'M'
        }
        
        renderProperties(properties) {
            const { module: configModule } = this.config
            $.each(properties, (i, item) => {
                let moduleKey = ''
                
                if (item.formType) {
                  moduleKey = item.formType.type || item.datasource
                } else {
                  moduleKey = item.datasource || item.dataType
                }
                console.log('moduleKey', moduleKey)
                let module = FormModules[moduleKey.toLocaleUpperCase()]
                
                this.getPlatFrom()
                if (typeof module === 'function') {
                    this.initModule(module, item)
                }else{
                  console.log('没有定义' + moduleKey.toLocaleUpperCase() + '的数据源的实现函数')
                }
            })
        }
        
        getModuleByFormTypeOrDatasource() {
            let { domData, moduleInfo, moduleData } = this.config
            let properties = []
            properties = domData.properties
            this.renderProperties(properties)
        }
        
        initModule(Module, item) {
            let _moduleData = this.config.moduleData[item.name] || item.default
            if (
				item.formType &&
				item.formType.type === 'radio' &&
				_moduleData === undefined
			) {
				const _radioOptions = item.formType.option
				const _checkedOptionItem = _radioOptions.filter(
					(option) => option.checked === true
				)
				_moduleData = _checkedOptionItem[0].value
			}
            let moduleConfig = {
                node: this.element,
                type: item.type,
                domData: item,
                moduleInfo: this.config.moduleInfo, 
                value: _moduleData,
                defaultChecked: _moduleData,
                moduleData: _moduleData,
                defaultImage: _moduleData,
                defaultSelected: _moduleData,
                defaultDate: _moduleData,
                defaultValue: _moduleData,
                centerModules: this.config.centerModules, 
                module: this.config.module,
                platForm: this.platForm,
                formContent: this.formContent,
                isSDK: this.config.isSDK,
                asyncHandler: this.config.asyncHandler,
                curTemplate: this.config.curTemplate,
                moduleId: this.config.moduleId, 
                formInstance: this,
            }
            let instance = new Module(moduleConfig)
            this.instanceList.push(instance)
        }
        
        setSkin() {
            this.element &&
                this.element
                    .find('.cd-form-container')
                    .addClass(this.config.skin)
        }
        
        getConfig(config) {
          const { domData, module, ...otherConfig } = config
            if(module && domData){
              if(module.moduleType && Number(module.moduleType) === FloorChannelType.JOINT){
                if(domData.properties && Array.isArray(domData.properties)){
                  domData.properties.forEach(item => {
                    if(item.datasource && DataSourceTypeToLocalKey[item.datasource]){
                      item.originDataSource = item.datasource
                      item.moduleType = module.moduleType
                      item.datasource = DataSourceTypeToLocalKey[item.datasource]
                    }
                  })
                }
              }
            }
            return $.extend(true, {}, DefaultConfig, {
              ...otherConfig,
              module,
              domData
            })
        }
        getData() {
            return new Promise((resolve) => {
                let promiseArr = []
                $.each(this.instanceList, function (index, item) {
                    let formData = item.getData()
                    if (formData && formData.hasError) return false
                    const dataSource = item.config.domData.datasource
                    if (
                        dataSource === 'J_COMMON_SKU_MATERIAL' ||
                        dataSource === 'J_SECKILL_SKU_MATERIAL' ||
                        dataSource === 'J_PINGOU_SKU_MATERIAL' ||
                        dataSource === 'J_PRESELL_SKU_MATERIAL' ||
                        dataSource === 'J_ADV_MATERIAL' ||
                        dataSource === 'J_AUCTION_SKU_MATERIAL'
                    ) {
                        promiseArr.push(formData)
                    } else {
                        if (
                            this.config.isSDK &&
                            this.config.platForm == 'M' &&
                            dataSource == 'J_PICTURE_HOTSPOT'
                        ) {
                            formData['pictureHotspot'] &&
                                formData['pictureHotspot'][
                                    'pictureList'
                                ].forEach((picHotItem) => {
                                    if (
                                        picHotItem['lingBannerId'] &&
                                        picHotItem['lingTemplateId']
                                    ) {
                                        delete picHotItem['lingBannerId']
                                    }
                                })
                        }
                        promiseArr.push(Promise.resolve(formData))
                    }
                })
                Promise.all(promiseArr).then((data) => {
                    let result = data.reduce((acc, val) => {
                        return $.extend(acc, val)
                    }, {})
                    resolve(result)
                })
            })
        }
        
        dispose() {
            this.element.off('click')
            this.element.html('')
            delete this
        }
    }
    return Form
})($)
export default Form