import Modal,{Confirm} from '../modal';
import Message from '../message';
import FileUpload from '../fileUpload/index'
import SourceManage from '../sourceManage/index'
const btnInTpl = `
    <div class="cd-image-panel J_imagePanel {{if imageUrl}}cd-hasimg cd-show-mask{{/if}} {{if hasMakeImage}}cd-has-make-image{{/if}}" data-url="{{imageUrl}}" style="background-image: url('{{imageUrl}}')">
        <div class="cd-image-panel-mask">
        </div>
        <span class="cd-img-size J_imgSize"></span>
        {{if delImg}}<span class="cd-icons cd-icons-link-del-white J_delImg" title="删除图片"></span>{{/if}}
        <img src="{{imageUrl}}" class="cd-hide"/>
        {{if hasMakeImage}}
            <a href="javascript:void(0);" class="J_makeImg">{{ if hasLinglongMaked }}在线编辑{{else}}在线制作{{/if}}</a>
        {{/if}}
        <a href="javascript:void(0)" class="J_selectImageBtn">{{if imageUrl}}从图库替换{{else}}从图库选择{{/if}}</a>
    </div>
`
const sdkBtnLingLongTpl = `
    <div class="cd-image-panel J_imagePanel {{if imageUrl}}cd-hasimg cd-show-mask{{/if}} {{if hasMakeImage}}cd-has-make-image{{/if}}" data-url="{{imageUrl}}" style="background-image: url('{{imageUrl}}')">
        <div class="cd-image-panel-mask">
        </div>
        <span class="cd-img-size J_imgSize"></span>
        {{if delImg}}<span class="cd-icons cd-icons-link-del-white J_delImg" title="删除图片"></span>{{/if}}
        <img src="{{imageUrl}}" class="cd-hide"/>
        {{if sdkUseOnlineMake}}
            <a href="javascript:void(0);" class="J_makeImg">{{ if sdkUseOnlineMakeEditState }}在线编辑{{else}}在线制作{{/if}}</a>
        {{else if hasMakeImage}}
            <a href="javascript:void(0);" class="J_makeImg">{{ if imageUrl }}在线编辑{{else}}在线制作{{/if}}</a>
        {{else}}
            <a href="javascript:void(0)" class="cd-file-upload-btn">{{if imageUrl}}从本地替换{{else}}从本地上传{{/if}}<input type="file" class="J_uploadImageBtn cd-file" enctype="multipart/form-data" multiple="" accept=".jpg,.jpeg,.gif,.png"></a>
        {{/if}}
        <a href="javascript:void(0)" class="J_selectImageBtn">{{if imageUrl}}从图库替换{{else}}从图库选择{{/if}}</a>
    </div>
`
const btnOutTpl = `
    <div class="cd-image-wap J_imagePanel {{if imageUrl}}cd-hasimg{{/if}}">
        <div class="cd-preview">
            <span class="cd-img-size J_imgSize"></span>
            <img src="{{imageUrl}}" data-url="{{imageUrl}}"/>
            <div class="cd-imgholder"></div>
        </div>
        <div class="cd-operate">
            <a href="javascript:void(0)" class="cd-file-upload-btn">{{if imageUrl}}从本地替换{{else}}从本地上传{{/if}}<input type="file" class="J_uploadImageBtn cd-file" enctype="multipart/form-data" multiple="" accept=".jpg,.jpeg,.gif,.png"></a>
            <a href="javascript:void(0)" class="J_selectImageBtn">{{if imageUrl}}从图库替换{{else}}从图库选择{{/if}}</a>
        </div>
    </div>
`
const CLS_NEW = 'cd--new'
const CLS_DISABLED = 'cd--disabled'
const CLS_ACTIVE = 'cd--active'
class ImageDom {
    constructor(config) {
        this.node = ''
        this.format = ''
        this.useSquare = false
        this.moduleConfg = null 
        this.linglongTemplateState = false
        this.moduleItemData = null 
        this.hasConfig = false 
        this.btnOutBox = false
        this.chooseSizeLimit = 500 
        this.typeLimit = ''
        this.delImg = false 
        this.delImgCallback = null 
        this.templateEditor = null 
        this.sdkUseOnlineMake = false 
        this.hasMakeImage = false 
        this.componentDidMount = () => {}
        this.fileUploadSuccess = () => {}
        this.chooseSuccess = () => {}
        this.composeSuccess = () => {}
        $.extend(this, { ...config })
        if (
            this.moduleConfg &&
            this.moduleConfg.isSDK &&
            window.page_data.template &&
            window.page_data.template.templateGrade
        ) {
            this.linglongTemplateState =
                window.page_data.template.templateGrade == 4
        } else {
            this.linglongTemplateState =
                this.moduleConfg &&
                this.moduleConfg.curTemplate &&
                this.moduleConfg.curTemplate.middleConfig &&
                this.moduleConfg.curTemplate.middleConfig.couponConfig &&
                this.moduleConfg.curTemplate.middleConfig.couponConfig
                    .moduleCreate == 2
        }
        this.isCoupon =
            (this.moduleConfg &&
                (this.moduleConfg.domData.datasource == 'J_COUPON' ||
                    this.moduleConfg.module.moduleFlag === 'mCoupon')) ||
            false
        this.isCustom =
            (this.moduleConfg &&
                this.moduleConfg.module.moduleFlag === 'newAndOld') ||
            false
        if (!this.node) {
            throw new Error('请设置node节点')
        }
        if (!this.format) {
            throw new Error('请设置 format 参数')
        }
        this.$element = $(this.node)
        this.renderImageDom()
        this.bindEvent()
    }
    formatParse() {
        let limitFormatData = {
            type: 0, 
            minWidth: 0, 
            maxWidth: 9999, 
            minHeight: 0, 
            maxHeight: 9999, 
        }
        if (/-/.test(this.format)) {
            limitFormatData.type = 1
        } else if (/\|/.test(this.format)) {
            limitFormatData.type = 2
        } else {
            limitFormatData.type = 0
        }
        this.format.split(',').forEach((item, index) => {
            const rangeNum = item.split('-')
            let someNum = item.split('|')
            switch (limitFormatData.type) {
                case 0:
                    if (index === 0) {
                        limitFormatData.minWidth = item
                        limitFormatData.maxWidth = item
                    } else {
                        limitFormatData.minHeight = item
                        limitFormatData.maxHeight = item
                    }
                    break
                case 1:
                    if (index === 0) {
                        if (rangeNum.length <= 1) {
                            limitFormatData.minWidth = rangeNum[0]
                            limitFormatData.maxWidth = rangeNum[0]
                        } else {
                            limitFormatData.minWidth = rangeNum[0]
                            limitFormatData.maxWidth = rangeNum[1]
                        }
                    } else {
                        if (rangeNum.length <= 1) {
                            limitFormatData.minHeight = rangeNum[0]
                            limitFormatData.maxHeight = rangeNum[0]
                        } else {
                            limitFormatData.minHeight = rangeNum[0]
                            limitFormatData.maxHeight = rangeNum[1]
                        }
                    }
                    break
                case 2:
                    if (index === 0) {
                        limitFormatData.list = []
                        someNum.forEach((value) => {
                            limitFormatData.list.push({
                                width: value,
                                height: value,
                            })
                        })
                    } else {
                        someNum.forEach((value, index) => {
                            limitFormatData.list[index].height = value
                        })
                    }
                    break
                default:
                    break
            }
        })
        return limitFormatData
    }
    renderImageSize(imgNode) {
        const img = imgNode.find('img')[0]
        img.onload = () => {
            let $imgSize = imgNode.find('.J_imgSize')
            $imgSize.html(img.naturalWidth + '*' + img.naturalHeight)
            $imgSize.attr('picWidth', img.naturalWidth)
            $imgSize.attr('picHeight', img.naturalHeight)
            this.componentDidMount()
        }
    }
    renderImageDom() {
        let currentNode = this.$element
        let imageTpl = this.btnOutBox ? btnOutTpl : btnInTpl
        const renderData = {
            imageUrl: currentNode.attr('originData'),
            delImg: this.delImg,
            useCompose: !!(
                this.templateEditor && typeof this.templateEditor === 'function'
            ),
            hasMakeImage: this.hasMakeImage, 
        }
        if (this.isCoupon || this.isCustom) {
            renderData['hasLinglongMaked'] =
                (this.moduleItemData &&
                    this.moduleItemData['linglongBannerId'] &&
                    this.moduleItemData['linglongTemplateId']) ||
                false
        }
        if (
            this.linglongTemplateState &&
            this.moduleConfg &&
            (this.moduleConfg.domData.datasource == 'J_COUPON' ||
                this.moduleConfg.module.moduleFlag === 'mCoupon')
        ) {
            imageTpl = sdkBtnLingLongTpl
            renderData.sdkUseOnlineMake = true
            renderData.sdkUseOnlineMakeEditState =
                this.moduleItemData &&
                (this.moduleItemData['linglongBannerId'] ||
                    this.moduleItemData['linglongTemplateId'])
        }
        currentNode.html(template.render(imageTpl, renderData))
        this.renderImageSize(currentNode)
    }
    bindEvent() {
        const that = this
        const currentNode = $(that.node)
        currentNode.on('click', '.J_uploadImageBtn', () => {
            let imageSizeObj = that.formatParse(that.format)
            new FileUpload({
                fileChooseNode: currentNode.find('.J_uploadImageBtn'),
                minWidth: imageSizeObj.minWidth, 
                maxWidth: imageSizeObj.maxWidth, 
                minHeight: imageSizeObj.minHeight, 
                maxHeight: imageSizeObj.maxHeight, 
                typeLimit: that.typeLimit,
                onFileCheckFail() {},
                onSelectBefore() {},
                onSelect() {},
                onProgress() {},
                onSuccess(file, data) {
                    if (that.useSquare) {
                        let _imgdata = data.data
                        if (_imgdata.width != _imgdata.height) {
                            Message.error(
                                '请上传形状为正方形，宽高范围为68-800px的图片。',
                            )
                        } else {
                            that.updateImage(data.data.url)
                            that.fileUploadSuccess(data)
                        }
                    } else {
                        that.updateImage(data.data.url)
                        that.fileUploadSuccess(data)
                    }
                },
                onFailure() {},
            })
        })
        currentNode.on('click', '.J_templateEdit', function () {
            if (
                that.templateEditor &&
                typeof that.templateEditor === 'function'
            ) {
                that.templateEditor.call()
            }
        })
        currentNode.on('click', '.J_selectImageBtn', function () {
            SourceManage.open({
                format: that.format,
                useSquare: that.useSquare,
                chooseSizeLimit: that.chooseSizeLimit,
                typeLimit: that.typeLimit,
                afterEnsureClose: false,
                onEnsureBack(imgInfo) {
                    that.updateImage(imgInfo.url)
                    that.chooseSuccess(imgInfo)
                    this.dialogClose()
                },
            })
        })
        currentNode.on('click', '.J_delImg', function () {
            new Confirm({
                title: '删除图片',
                content: '确认删除该图片吗？',
                onClose: (flag) => {
                    if (flag == Modal.CloseType.TYPE_OK) {
                        that.onDelImg()
                    }
                },
            })
        })
        currentNode.on('click', '.J_makeImg', (evt) => {
            const $target = $(evt.currentTarget)
            let currentItem = this.isCoupon
                ? $target.parents('.J_couponItem')
                : this.isCustom
                ? $target.closest('.J_image')
                : $target
            if (currentItem.find('.J_makeImg').hasClass(CLS_DISABLED)) {
                return false
            }
            this._focusImgEidt(currentItem)
        })
    }
    
    onDelImg() {
        this.imageUrl = ''
        this.$element.attr('originData', '')
        this.$element.html('')
        this.renderImageDom()
        if (typeof this.delImgCallback == 'function') {
            this.delImgCallback()
        }
    }
    
    updateImage(imgUrl) {
        const currentNode = $(this.node)
        let imgNode = currentNode
            .attr('origindata', imgUrl)
            .find('.J_imagePanel')
        imgNode.find('img').attr('src', imgUrl)
        imgNode.attr('data-url', imgUrl)
        if (imgUrl) {
            if (imgNode.hasClass('cd-hasimg') == false) {
                imgNode.addClass('cd-hasimg')
            }
            if (!this.btnOutBox) {
                if (imgNode.hasClass('cd-show-mask') == false) {
                    imgNode.addClass('cd-show-mask')
                }
                imgNode.css('background-image', "url('" + imgUrl + "')")
            }
            this.hasConfig = true
        } else {
            if (imgNode.hasClass('cd-hasimg')) {
                imgNode.removeClass('cd-hasimg')
            }
            if (!this.btnOutBox) {
                if (imgNode.hasClass('cd-show-mask')) {
                    imgNode.removeClass('cd-show-mask')
                }
                imgNode.css('background-image', "url('" + imgUrl + "')")
            }
            this.hasConfig = false
        }
        this.renderImageSize(imgNode)
    }
    
    setConfigState(hasConfig) {
        if (typeof hasConfig !== 'boolean') {
            return false
        }
        this.hasConfig = hasConfig
    }
    
    refreshFormat(format) {
        this.format = format
    }
    _focusImgEidt(currentItem) {
        this.$element.find('.J_imgEdit').removeClass(CLS_ACTIVE)
        currentItem.addClass(CLS_ACTIVE)
    }
    
    _changeImg(data, imgEditEl) {
        let _getBeforeOriginalData = imgEditEl.data('original'),
            _mergeData = $.extend({}, _getBeforeOriginalData, data)
        this.moduleConfg.isSDK
            ? imgEditEl
                  .removeClass(CLS_NEW)
                  .attr('data-original', JSON.stringify(_mergeData))
            : imgEditEl.removeClass(CLS_NEW).data('original', _mergeData)
        this.updateImage(data.url)
    }
    getConfigState() {
        return this.hasConfig
    }
}
export default ImageDom