import DatePicker from '@core/component/datePicker';
import Message from '@core/component/message';
import Tooltips from '@core/component/toast/tooltips';
import { Confirm } from '@core/lib/MyMobal'
import { send, getByteLen } from '@core/lib/util'
import Domain from '@core/util/domain'
import { getShopType, getChannelId, IsYaoB2B } from '@core/util/channelUtil'
import { status1, status4 } from '@core/lib/const'
import '../sourceManage/sourceManage'
import SourceManage from '../sourceManage'
import FileUpload from '@core/component/fileUpload'
import linkTool from '../linkTool'
import JDCategorySelect from '@core/component/form/formType/categorySelect'
import '../sku/sku'
import sku from '../sku'
import './style.scss'
import MAIN_RENDER from './template/main.tpl'
import AD_RENDER from './template/ad.tpl'
import PRODUCT_1_RENDER from './template/product_1.tpl'
import PRODUCT_2_RENDER from './template/product_2.tpl'
import PRODUCT_3_RENDER from './template/product_3.tpl'
import PRODUCT_4_RENDER from './template/product_4.tpl'
import PRODUCT_7_RENDER from './template/product_7.tpl'
import PRODUCT_8_RENDER from './template/product_8.tpl'
import diffDOM from 'diff-dom'
import set from 'lodash/set'
import get from 'lodash/get'
import sortedIndexBy from 'lodash/sortedIndexBy'
import findIndex from 'lodash/findIndex'
import cloneDeep from 'lodash/cloneDeep'
import isEqual from 'lodash/isEqual'
import isObject from 'lodash/isObject'
import throttle from 'lodash/throttle'
let defaultConfig = {
    node: $('body'),
    mainData: {},
    limit: 100,
    versionType: 1,
    dataType: 1,
    renderType: 0,
    pop: false,
    height: 'calc(100vh - 73px)',
    channel: 1,
}
const DATA_TYPE = [
    ['图片+链接'],
    ['普通商品', '单品促销（秒杀）', '拼购', '预售'],
]
const RENDER = [
    [AD_RENDER],
    [
        PRODUCT_1_RENDER,
        PRODUCT_2_RENDER,
        PRODUCT_3_RENDER,
        PRODUCT_4_RENDER,
        PRODUCT_1_RENDER,
        PRODUCT_1_RENDER,
        PRODUCT_7_RENDER,
        PRODUCT_8_RENDER,
    ],
]
const API = [
    {
        load: Domain.opJshop + '/operations/shopAdvert/queryAllSchedules',
        save: Domain.opJshop + '/operations/shopAdvert/putAllSchedules',
    },
    {
        load: Domain.opJshop + '/operations/goodsGroup/getMaterialDetailInfo',
        save: Domain.opJshop + '/operations/goodsGroup/saveMaterialDetailInfo',
    },
]
const HELP_LINK = [
    {
        link: '//conecli.com/onSaleWare/onSaleWare_newDoSearch.action?first',
        text: '商品管理',
    },
    {
        link: '//conecli.com/promotion/info/dp2_addActivityInit.action',
        text: '促销系统',
    },
    {
        link: '//conecli.com/pingou/pingou_pop_manage/index.html',
        text: '拼购系统',
    },
    {
        link: '//conecli.com/promotion/info/pre_queryPresaleList.action',
        text: '预售系统',
    },
]
const VERSION_LABEL = ['广告', '商品']
const isYaoB2B = (window.page_data && window.page_data.yaoB2B) || false
let dd = new diffDOM({
    valueDiffing: true,
})
let dom = document.createElement('div')
let versionIndex = 0
let oldMainData
let uploadTypeLimit = '.jpg,.png'
let sourceTypeLimit = 'jpg,png'
import moment from 'moment'
import ImageMatting from '../imageMatting'
new Tooltips({})
class VersionManage {
    
    constructor(config) {
        this.config = {
            ...defaultConfig,
            ...config,
        }
        if (this.config.dataType == 7) {
            this.config.limit = 10 
        }
        if (config && config.node && typeof config.node === 'string') {
            this.config.node = $(config.node)
        }
        this.chooseSizeLimit = window.page_config.chooseSizeLimit
        this.root = this.config.node[0]
        this.API = API[this.config.versionType]
        this.render = throttle(this.render, 200)
        this._init()
    }
    static open(config) {
        let manage
        let HELP = HELP_LINK[config.dataType - 1] || {
            link: '/marketing/list/product',
            text: '运营中心',
        }
        let versionLabel = VERSION_LABEL[config.versionType]
        if (!config.select && config.crmActivityType !== 2) {
            config.title += `<span style="font-size:12px;color:#999;font-weight: normal;margin-left: 10px;">(更改${versionLabel}组数据后，所有引用该${versionLabel}组的页面均会自动更新为最新版数据）</span>`
        }
        Confirm({
            title: config.title || '新建分组',
            close: function () {
                manage.dp && manage.dp.close()
            },
            width: 1100,
            ok: '保存',
            style: 'padding:0 0 20px 0;',
            bottomStyle: 'padding: 0 20px;',
            bottomCon:
                !config.select &&
                config.versionType == 1 &&
                config.crmActivityType !== 2
                    ? `<a target="_blank" style="font-size: 12px;color: #29f;" href="${HELP.link}">点击前往${HELP.text}>></a>`
                    : '',
            content: `<div style="height: 535px;border-bottom:1px solid #EFEFEF;margin-bottom: 20px;"><div class="J_version-manage"><p style="text-align:center;">加载中...</p></div></div>`,
            onDomReady: ($dialog) => {
                if (config.crmActivityType === 2) {
                    $dialog.find('.J_my-confirm-ok').addClass('cd-hide')
                }
            },
            onOk: async function (modal) {
                let res = await manage._saveData()
                if (!res) {
                    return
                }
                let check = true
                if (!manage.config.uuid) {
                    check = false
                } else {
                    if (
                        !isEqual(oldMainData, {
                            materialPlanList: manage.mainData.materialPlanList,
                            name: manage.mainData.name,
                        })
                    ) {
                        check = false
                    }
                }
                if (check) {
                    config.onOk(manage.config.uuid, manage.mainData)
                    modal.close()
                } else {
                    Message.warn('分期还没有保存')
                }
            },
        })
        manage = new VersionManage({
            node: $('.J_version-manage'),
            ...config,
            pop: true,
        })
        return manage
    }
    async _loadData() {
        let { uuid, backShowType, renderType } = this.config
        try {
            let res = await send({
                url: this.API.load,
                query: {
                    uuid,
                    backShowType,
                    renderType,
                },
            })
            return res.data
        } catch (e) {
            console.log(e)
        }
    }
    
    async _saveData(noCheckCount = false, showTip = true) {
        let {
                uuid,
                name,
                materialPlanList,
                dataType,
                sourceType,
                terminalType,
                backShowType,
                renderType,
                channel,
                imageWidth,
                imageHeight,
            } = this.mainData,
            update = undefined
        if (name !== this.groupName) {
            update = true
        }
        if (!this.checkListData(noCheckCount)) {
            return
        }
        materialPlanList.sort(
            (a, b) =>
                new Date(a.startTime).getTime() -
                new Date(b.startTime).getTime(),
        )
        try {
            let res = await send({
                url: this.API.save,
                query: {
                    update,
                    uuid,
                    name,
                    dataType,
                    sourceType,
                    terminalType,
                    backShowType,
                    materialPlanList,
                    renderType,
                    channel,
                    imageWidth,
                    imageHeight,
                },
                showTip,
            })
            if (!this.config.uuid) {
                this.mainData.uuid = res.data.uuid
                this.config.uuid = res.data.uuid
                this.groupName = res.data.name
            }
            oldMainData = {
                materialPlanList: cloneDeep(this.mainData.materialPlanList),
                name: this.mainData.name,
            }
            if (showTip) {
                Message.success('保存成功')
            }
            return true
        } catch (e) {
            return false
        }
    }
    checkListData(noCheckCount) {
        let check = true
        let msg = ''
        let data = this.mainData.materialPlanList
        for (let [index, item] of data.entries()) {
            if (!item.startTime) {
                check = false
                msg = `第${index + 1}个分期没有选择开始时间!`
                break
            }
            if (!item.materialList.length) {
                check = false
                msg = `第${index + 1}个分期不能为空!`
                break
            }
            if (this.config.versionType === 0) {
                for (let [subIndex, subItem] of item.materialList.entries()) {
                    msg = `第${index + 1}个分期，第${subIndex + 1}条广告，`
                    if (!subItem.picUrl) {
                        check = false
                        msg += `广告图不能为空`
                        break
                    }
                    if (!subItem.link.link) {
                        check = false
                        msg += `广告连接不能为空`
                        break
                    }
                }
            }
            if (
                this.config.versionType === 1 &&
                this.config.moduleFlag == 'mBlindBoxPreBlock' &&
                !noCheckCount
            ) {
                for (let [subIndex, subItem] of item.materialList.entries()) {
                    msg = `第${index + 1}个分期，第${subIndex + 1}个商品，`
                    if (subItem.count === null) {
                        check = false
                        msg += `库存数量不能为空`
                        break
                    }
                    if (subItem.count && parseInt(subItem.count) < 1) {
                        check = false
                        msg += `库存数量不能小于3`
                        break
                    }
                }
            }
            if (!check) {
                break
            }
        }
        if (!check) {
            Message.warn(msg)
        }
        return check
    }
    setImageLimit({
        versionType,
        dataType,
        terminalType,
        imageWidth,
        imageHeight,
    }) {
        if (versionType === 0) {
            if (dataType === 1) {
                if (terminalType === 1) {
                    this.format = `${imageWidth ? imageWidth : 990},${
                        imageHeight ? imageHeight : 495
                    }`
                    this.chooseSizeLimit = window.page_config.pcChooseSizeLimit
                } else if (terminalType === 2) {
                    this.format = `${imageWidth ? imageWidth : 1125},${
                        imageHeight ? imageHeight : 450
                    }`
                    this.chooseSizeLimit = window.page_config.mChooseSizeLimit
                }
                let formatArr = this.format.split(',')
                if (!this.mainData.imageWidth) {
                    this.mainData.imageWidth = formatArr[0]
                }
                if (!this.mainData.imageHeight) {
                    this.mainData.imageHeight = formatArr[1]
                }
            }
        }
    }
    async _init() {
        let data
        let {
            dataType,
            sourceType,
            terminalType,
            backShowType,
            channel,
            renderType,
            pop,
            versionType,
            height,
            select,
            imageWidth,
            imageHeight,
            isBi,
        } = this.config
        try {
            data = this.config.uuid
                ? await this._loadData()
                : {
                      name:
                          this.config.versionType === 0
                              ? '广告组名称'
                              : '商品组名称',
                      materialPlanList: [
                          {
                              startTime: moment().format('YYYY-MM-DD HH:mm:ss'),
                              materialList: [],
                          },
                      ],
                      dataType,
                      sourceType,
                      terminalType,
                      backShowType,
                      renderType,
                      channel,
                      imageWidth,
                      imageHeight,
                  }
            this.groupName = data.name || ''
        } catch (e) {
            console.log(e)
        }
        this.mainData = {
            versionIndex,
            versionType,
            pop,
            height,
            DATA_TYPE,
            status4,
            status1,
            isYaoB2B,
            materialPlanList: [],
            ...data,
            renderType,
            select,
            isBi,
            moduleFlag: this.config.moduleFlag,
            crmActivityType: this.config.crmActivityType, 
        }
        this.setImageLimit(this.mainData)
        oldMainData = cloneDeep({
            materialPlanList: this.mainData.materialPlanList,
            name: this.mainData.name,
        })
        this.render()
        this._bindEvent()
    }
    checkImage(width, height) {
        let limit = this.format.split(',')
        let isCheck = true
        if (width != parseInt(limit[0]) || height != parseInt(limit[1])) {
            Message.warn(
                `上传成功,图片使用失败,请上传${limit[0]}*${limit[1]}尺寸的图片!`,
            )
            isCheck = false
        }
        return isCheck
    }
    render() {
        let table = ''
        if (
            this.mainData.versionType == 1 &&
            this.mainData &&
            this.mainData.materialPlanList[this.mainData.versionIndex] &&
            !this.mainData.materialPlanList[this.mainData.versionIndex]
                .materialList.length
        ) {
            table = `
                <div class="empty-product-con">
                    <p>你还未添加任何商品!</p>
                    <span class="cd-middle-red-border-btn J_edit-item">添加商品</span>
                </div>
            `
        } else {
            table = RENDER[this.mainData.versionType][
                this.mainData.dataType - 1
            ](this.mainData)
        }
        dom.innerHTML = MAIN_RENDER({
            ...this.mainData,
            table,
        })
        dd.apply(this.root, dd.diff(this.root, dom))
        $('.J_EldTooltips').remove()
    }
    hideCategorySelect(node) {
        let $con = this.config.node
        let $CatItemNodes = $con.find('.J_add')
        $CatItemNodes.each((i, el) => {
            let $Node = $(el)
            if (node && node.size()) {
                if ($Node[0] === node[0]) {
                    return
                }
            }
            let catInstance = $Node.data('categorySelectInstance')
            if (catInstance) {
                catInstance._hide()
                catInstance._dispose()
            }
        })
    }
    
    _bindEvent() {
        let $con = this.config.node
        let mainData = this.mainData
        let { dataType } = this.mainData.dataType ? this.mainData : this.config
        let self = this
        let $parent = $con.parent().css('position', 'relative')
        
        $con.on('click', '.J_add', function (evt) {
            if ($(this).hasClass('disabled')) {
                return false
            }
            let $Node = $(evt.target).closest('.J_add')
                ? $(evt.target).closest('.J_add')
                : $(evt.target)
            let index = parseInt($(this).parents('tr').attr('data-index'))
            let index2 = parseInt(
                $(this).parents('.J_add').attr('data-index')
                    ? $(this).parents('.J_add').attr('data-index')
                    : $(this).attr('data-index'),
            )
            if (
                !(
                    $Node.data('categorySelectInstance') instanceof
                    JDCategorySelect
                )
            ) {
                $Node.data(
                    'categorySelectInstance',
                    new JDCategorySelect({
                        node: $Node,
                        displayMode: 'arrow',
                        value: [],
                        scrollNode:
                            '.J_editorInstanceArea,.J_mainContent,.J_content-middle,body',
                        callback: function (_cat) {
                            let _catName = [],
                                _catId = []
                            _cat.forEach((item) => {
                                _catName.push(item.catName)
                                _catId.push(item.catId)
                            })
                            let cid1 =
                                    mainData.materialPlanList[
                                        mainData.versionIndex
                                    ].materialList[index].cid1,
                                cid2 =
                                    mainData.materialPlanList[
                                        mainData.versionIndex
                                    ].materialList[index].cid2,
                                cid3 =
                                    mainData.materialPlanList[
                                        mainData.versionIndex
                                    ].materialList[index].cid3
                            if (cid1) {
                                cid1[index2] = _catId[0] + '#' + _catName[0]
                                cid2[index2] = _catId[1] + '#' + _catName[1]
                                cid3[index2] = _catId[2] + '#' + _catName[2]
                            } else {
                                cid1 = [_catId[0] + '#' + _catName[0]]
                                cid2 = [_catId[1] + '#' + _catName[1]]
                                cid3 = [_catId[2] + '#' + _catName[2]]
                            }
                            mainData.materialPlanList[
                                mainData.versionIndex
                            ].materialList[index].cid1 = cid1
                            mainData.materialPlanList[
                                mainData.versionIndex
                            ].materialList[index].cid2 = cid2
                            mainData.materialPlanList[
                                mainData.versionIndex
                            ].materialList[index].cid3 = cid3
                            self.render()
                        },
                    }),
                )
            }
            $Node.data('categorySelectInstance').show()
            self.hideCategorySelect($Node)
            return false
        })
        $con.on('click', (ev) => {
            let target = $(ev.target)
            const isCategorySelectShow =
                $('.cd-cascade-select-layer.cd-cascade-select-layer').length > 0
            if (
                isCategorySelectShow &&
                !target.hasClass('cd-cascade-select-layer') &&
                !target.parents('.cd-cascade-select-layer').length &&
                !target.is(this.target)
            ) {
                self.hideCategorySelect()
                self.render()
            }
        })
        $con.on('click', '.J_levelClose', function (e) {
            if ($(this).hasClass('disabled')) {
                return false
            }
            e.stopPropagation()
            let index = parseInt($(this).parents('tr').attr('data-index'))
            let index2 = parseInt($(this).parents('.J_add').attr('data-index'))
            Confirm({
                title: '提示',
                content: '确定删除吗？',
                onOk: function (modal) {
                    $(e.currentTarget).closest('.J_add').remove()
                    setTimeout(() => {
                        mainData.materialPlanList[
                            mainData.versionIndex
                        ].materialList[index].cid1.splice(index2, 1)
                        mainData.materialPlanList[
                            mainData.versionIndex
                        ].materialList[index].cid2.splice(index2, 1)
                        mainData.materialPlanList[
                            mainData.versionIndex
                        ].materialList[index].cid3.splice(index2, 1)
                        self.render()
                    }, 500)
                    modal.close()
                },
            })
        })
        $con.on('click', '.J_version-item', function () {
            if ($(this).hasClass('disabled')) {
                return false
            }
            mainData.versionIndex = $(this).index()
            self.render()
            setTimeout(() => {
                self.render()
            }, 200)
        })
        $con.on('click', '.J_edit-version', function () {
            if ($(this).hasClass('disabled')) {
                return false
            }
            let index = parseInt($(this).attr('data-index'))
            let type = $(this).attr('data-type')
            let isNew = type === 'new'
            
            let isCopy = type === 'copy'
            let data = {
                name: '',
                startTime: '',
            }
            
            if (!isNew) {
                data.name = mainData.materialPlanList[index].name
                data.startTime = mainData.materialPlanList[index].startTime
            }
            let version = null
            if (isNew) {
                version = {
                    materialList: [],
                    ...data,
                }
            }
            if (isCopy) {
                version = cloneDeep({
                    ...mainData.materialPlanList[index],
                    startTime: '',
                })
            }
            if (
                mainData.versionType === 0 &&
                version.materialList.length === 0
            ) {
                version.materialList = [
                    {
                        name: '',
                        link: {
                            originalData: '',
                        },
                        picUrl: '',
                    },
                ]
            }
            
            
            
            mainData.materialPlanList = mainData.materialPlanList
                ? mainData.materialPlanList
                : []
            if (mainData.materialPlanList.length >= 10) {
                Message.warn('每个分组最多创建10个分期!')
                return
            }
            mainData.versionIndex = mainData.materialPlanList.push(version) - 1
            self.render()
            $con.find('.J_version-item')
                .eq(mainData.versionIndex)
                .addClass('slide-in-top')
            setTimeout(() => {
                $con.find('.J_version-item')
                    .eq(mainData.versionIndex)
                    .removeClass('slide-in-top')
                    .parents('.version-tab')
                    .scrollLeft(100000)
                $con.find('.J_edit-time').eq(mainData.versionIndex).click()
            }, 500)
            
        })
        $con.on('click', '.J_edit-time', function () {
            if ($(this).hasClass('disabled')) {
                return false
            }
            self.dp = new DatePicker({
                elem: this,
                positionElem: $(this).closest('.J_version-item')[0],
                isBackfill: false,
                isClosePicker: false,
                min: new Date().getTime(),
                type: 'datetime',
                value: mainData.materialPlanList[mainData.versionIndex]
                    .startTime,
                show: true,
                btns: ['confirm'],
                confirm: (value) => {
                    let eqIndex = value
                        ? findIndex(mainData.materialPlanList, function (o) {
                              return o.startTime === value
                          })
                        : -1
                    if (eqIndex >= 0) {
                        Message.warn('请检查分期时间,分期时间不能重叠！')
                        return false
                    } else {
                        mainData.materialPlanList[
                            mainData.versionIndex
                        ].startTime = value
                        let newIndex = sortedIndexBy(
                            mainData.materialPlanList,
                            mainData.materialPlanList[mainData.versionIndex],
                            function (o) {
                                return new Date(o.startTime).getTime()
                            },
                        )
                        let currentVersion = mainData.materialPlanList.splice(
                            mainData.versionIndex,
                            1,
                        )[0]
                        if (newIndex > mainData.versionIndex) {
                            mainData.versionIndex = newIndex - 1
                        } else {
                            mainData.versionIndex = newIndex
                        }
                        mainData.materialPlanList.splice(
                            mainData.versionIndex,
                            0,
                            currentVersion,
                        )
                        self.dp && self.dp.close()
                        self.render()
                    }
                },
            })
        })
        $con.on('click', '.J_tool-con i', function (e) {
            if ($(this).hasClass('disabled')) {
                return false
            }
            let $target = $(e.target)
            if (!$target.closest('.J_edit-time').length) {
                self.dp && self.dp.close()
            }
            e.stopPropagation()
        })
        $con.on('click', '.J_delete-version', function () {
            if ($(this).hasClass('disabled')) {
                return false
            }
            let index = parseInt(
                $(this).parents('.J_version-item').attr('data-index'),
            )
            $parent.append(`
                <div class="version-delete-pop J_version-delete-pop">
                    <h2>你确认要删除此分期吗?</h2>
                    <p>删除分期会同时删除掉此分期下录入的全部商品，请谨慎操作。</p>
                    <div style="margin-top: 10px;">
                        <span style="margin-right:10px;" class="cd-middle-black-border-btn J_version-delete-pop-colse">取消</span>
                        <span data-index="${index}" class="cd-middle-red-btn J_version-delete-pop-ok">确定</span>
                    </div>
                </div>
            `)
        })
        $con.on('click', '.J_save-version', async function () {
            if ($(this).hasClass('disabled')) {
                return false
            }
            
            await self._saveData()
        })
        $con.on('click', '.J_batch-delete', function () {})
        $con.on('click', '.J_edit-item', function () {
            if ($(this).hasClass('disabled')) {
                return false
            }
            if (mainData.versionType !== 0) {
                sku.open({
                    onSelect: async function (data) {
                        let oldSkus =
                            mainData.materialPlanList[mainData.versionIndex]
                                .materialList
                        data = data.map(function (item) {
                            for (let oldItem of oldSkus) {
                                if (item.id == oldItem.id) {
                                    item = { ...item, ...oldItem }
                                }
                            }
                            return item
                        })
                        mainData.materialPlanList[
                            mainData.versionIndex
                        ].materialList = data 
                        self.mainData = mainData
                        if (
                            mainData.materialPlanList &&
                            mainData.materialPlanList[0].materialList
                        ) {
                            let showTip = true
                            if (mainData.dataType == 7) {
                                showTip = false
                            }
                            await self._saveData(true, showTip)
                        }
                        self.render()
                        setTimeout(() => {
                            self.render()
                        }, 200)
                    },
                    skus: mainData.materialPlanList[mainData.versionIndex]
                        .materialList,
                    limit: self.config.limit,
                    oldDelete: false,
                    dataType,
                })
            } else {
                let planItem = mainData.materialPlanList[mainData.versionIndex]
                let itemData = {
                    name: '',
                    link: {
                        originalData: '',
                    },
                    picUrl: '',
                }
                let scrollCon = self.config.node.find('.table-con')[0]
                planItem.materialList.push(itemData)
                self.render()
                if (scrollCon.scrollHeight > scrollCon.clientHeight) {
                    self.config.node
                        .find('tbody tr:last-child')[0]
                        .scrollIntoView()
                }
            }
        })
        $con.on('click', '.J_link', function () {
            if ($(this).hasClass('disabled')) {
                return false
            }
            let index = parseInt($(this).parents('tr').attr('data-index'))
            let path = $(this).attr('data-path')
            let tab = [
                'custom',
                'frequent',
                'product',
                'userdefine',
                'activity',
                'shopCategory',
            ]
            if (self.mainData.terminalType === 2) {
                tab = tab.filter((v) => v != 'userdefine')
            }
            if (getChannelId() === 3) {
                tab = tab.concat(['miniApps', 'widgetPlug'])
            }
            if (IsYaoB2B()) {
                tab = tab.concat(['index', 'search'])
            }
            if (self.mainData.terminalType === 2) {
                if (!window.page_data.isSDKM) {
                    tab = tab.concat('financeCouponLink')
                }
            }
            new linkTool({
                linkObj:
                    self.mainData.materialPlanList[mainData.versionIndex]
                        .materialList[index].link,
                onConfirm: function (url, linkObj) {
                    set(self.mainData, path, linkObj)
                    self.render()
                },
                tab,
                env: {
                    platformId: self.mainData.terminalType - 1, 
                    shopType: getShopType(), 
                },
            })
        })
        $con.on('click', '.J_make-online', function () {
        })
        $con.on('click', '.J_select-image', function () {
            if ($(this).hasClass('disabled')) {
                return false
            }
            let $input = $(this).closest('.J_image')
            SourceManage.open({
                format: self.format || '800,800',
                typeLimit: sourceTypeLimit,
                chooseSizeLimit: self.chooseSizeLimit,
                onEnsureBack: function (imgInfo) {
                    set(self.mainData, $input.attr('data-path'), imgInfo.url)
                    self.render()
                },
                onCancelBack: function () {},
            })
        })
        $con.on('click', '.J_matting-image', function () {
            if ($(this).hasClass('disabled')) {
                return false
            }
            let $input = $(this).closest('.J_image')
            let imgNode = $input.find('img')
            let imgPath = get(imgNode, '[0].src', '')
            if (imgPath) {
                ImageMatting.open({
                    url: imgPath,
                    ensureCallback: function (imageData) {
                        const { width, height, url } = imageData
                        if (self.format) {
                            if (!self.checkImage(width, height)) {
                                return
                            }
                        }
                        let oldItem = get(
                            self.mainData,
                            $input.attr('data-path'),
                        )
                        let newData
                        if (isObject(oldItem)) {
                            newData = {
                                ...oldItem,
                                width,
                                height,
                                picUrl: url,
                            }
                        } else {
                            newData = url
                        }
                        set(self.mainData, $input.attr('data-path'), newData)
                        Message.success('抠图使用成功')
                        self.render()
                    },
                })
            } else {
                Message.error('图片地址不合法')
            }
        })
        $con.on('click', '.J_upload-image', function () {
            if ($(this).hasClass('disabled')) {
                return false
            }
            let $input = $(this).closest('.J_image')
            let formatArr = []
            if (self.format) {
                formatArr = self.format.split(',')
            } else {
                if (self.config.versionType == 1) {
                    formatArr = [800, 800]
                }
            }
            FileUpload.upload({
                minWidth: formatArr.length ? formatArr[0] : 0,
                maxWidth: formatArr.length ? formatArr[0] : 9999,
                minHeight: formatArr.length > 1 ? formatArr[1] : 0,
                maxHeight: formatArr.length > 1 ? formatArr[1] : 9999,
                typeLimit: uploadTypeLimit,
                fileSizeLimit: self.chooseSizeLimit * 1024,
                onSuccess: function (file, result, width, height) {
                    width = width || result.data.width
                    height = height || result.data.height
                    if (self.format) {
                        if (!self.checkImage(width, height)) {
                            return
                        }
                    }
                    let oldItem = get(self.mainData, $input.attr('data-path'))
                    let newData
                    if (isObject(oldItem)) {
                        newData = {
                            ...oldItem,
                            width,
                            height,
                            picUrl: result.data.url,
                        }
                    } else {
                        newData = result.data.url
                    }
                    set(self.mainData, $input.attr('data-path'), newData)
                    Message.success('上传成功！')
                    self.render()
                },
            })
        })
        $con.on('change', '.J_input-edit,.J_inputCount', function () {
            if ($(this).hasClass('disabled')) {
                return false
            }
            let value = $(this).val().trim()
            if ($(this).hasClass('J_inputCount')) {
                value = parseInt(value)
            }
            const dataPath = $(this).attr('data-path')
            set(self.mainData, dataPath, value || null) 
        })
        $con.on('keyup', '.J_inputCount', function () {
            if ($(this).hasClass('disabled')) {
                return false
            }
            let value = $(this).val().trim()
            if (value) {
                value = value.replace(/[^\d]/g, '')
                $(this).val(value)
            }
        })
        $con.on('click', '.J_to-top', function () {
            if ($(this).hasClass('disabled')) {
                return false
            }
            let index = parseInt($(this).parents('tr').attr('data-index'))
            let materialList =
                mainData.materialPlanList[mainData.versionIndex].materialList
            if (index === 0) {
                return
            }
            materialList.unshift(materialList.splice(index, 1)[0])
            self.render()
            setTimeout(() => {
                self.render()
            }, 200)
        })
        $con.on('click', '.J_top', function () {
            if ($(this).hasClass('disabled')) {
                return false
            }
            let index = parseInt($(this).parents('tr').attr('data-index'))
            let materialList =
                mainData.materialPlanList[mainData.versionIndex].materialList
            if (index === 0) {
                return
            }
            materialList.splice(index - 1, 0, materialList.splice(index, 1)[0])
            self.render()
            setTimeout(() => {
                self.render()
            }, 200)
        })
        $con.on('click', '.J_to-bottom', function () {
            if ($(this).hasClass('disabled')) {
                return false
            }
            let index = parseInt($(this).parents('tr').attr('data-index'))
            let materialList =
                mainData.materialPlanList[mainData.versionIndex].materialList
            if (index === materialList.length) {
                return
            }
            materialList.push(materialList.splice(index, 1)[0])
            self.render()
            setTimeout(() => {
                self.render()
            }, 200)
        })
        $con.on('click', '.J_bottom', function () {
            if ($(this).hasClass('disabled')) {
                return false
            }
            let index = parseInt($(this).parents('tr').attr('data-index'))
            let materialList =
                mainData.materialPlanList[mainData.versionIndex].materialList
            if (index === materialList.length) {
                return
            }
            materialList.splice(index + 1, 0, materialList.splice(index, 1)[0])
            self.render()
            setTimeout(() => {
                self.render()
            }, 200)
        })
        $con.on('click', '.J_delete-item', function () {
            if ($(this).hasClass('disabled')) {
                return false
            }
            let index = parseInt($(this).parents('tr').attr('data-index'))
            Confirm({
                title: '提示',
                content: '确定删除吗？',
                onOk: function (modal) {
                    $(this).parents('tr').addClass('slide-out-right')
                    setTimeout(() => {
                        mainData.materialPlanList[
                            mainData.versionIndex
                        ].materialList.splice(index, 1)
                        self.render()
                    }, 500)
                    modal.close()
                },
            })
        })
        $con.on('click', '.J_cancel-edit', function () {
            if ($(this).hasClass('disabled')) {
                return false
            }
            self.render()
        })
        $con.on('click', '.J_enable-edit', function (e) {
            if ($(this).hasClass('disabled')) {
                return false
            }
            let $input = $(this)
                .parents('.J_edite-toggle')
                .addClass('editing')
                .find('input,textarea')
            $input.prop('disabled', false).focus()
            e.stopPropagation()
            return false
        })
        $con.on('click', '.J-enable-save', function () {
            if ($(this).hasClass('disabled')) {
                return false
            }
            let $input = $(this)
                .parents('.J_edite-toggle')
                .find('input,textarea')
            let value = $input.val().trim()
            let path = $input.attr('data-path')
            let length = getByteLen(value)
            let limit = $input
                .attr('data-limit')
                .split('-')
                .map((v) => parseInt(v))
            if (limit[0] > length || limit[1] < length) {
                Message.warn(
                    $input.attr('data-msg') ||
                        `可输入范围是${limit[0]}到${limit[1]}个字符!`,
                )
                return false
            }
            set(self.mainData, path, value)
            if (path.indexOf('jshopName') > 0) {
                set(
                    self.mainData,
                    path.split('jshopName')[0] + 'nameLength',
                    length,
                )
            }
            self.render()
        })
        $con.on('click', '.J_reset-name', function () {
            if ($(this).hasClass('disabled')) {
                return false
            }
            let $input = $(this)
                .parents('.J_edite-toggle')
                .find('input,textarea')
            set(self.mainData, $input.attr('data-path'), '')
            self.render()
        })
        $con.on('click', '.J_product-group select', function (e) {
            if ($(this).hasClass('disabled')) {
                return false
            }
            e.stopPropagation()
        })
        $con.on('change', '.J_product-group select', function () {
            if ($(this).hasClass('disabled')) {
                return false
            }
            let value = parseInt($(this).val())
            let index = parseInt($(this).parents('tr').attr('data-index'))
            let old = self.mainData.materialPlanList[
                self.mainData.versionIndex
            ].materialList.splice(index, 1)
            self.mainData.materialPlanList[
                self.mainData.versionIndex
            ].materialList.splice(--value, 0, old[0])
            self.render()
            setTimeout(() => {
                self.render()
            }, 200)
        })
        $con.on('click', '.J_check-all', function () {
            if ($(this).hasClass('disabled')) {
                return false
            }
            if (
                !self.mainData.materialPlanList.length ||
                !self.mainData.materialPlanList[self.mainData.versionIndex]
            ) {
                return
            }
            let version =
                self.mainData.materialPlanList[self.mainData.versionIndex]
            let list = version.materialList
            let check = false
            if (!$(this).hasClass('checked')) {
                check = true
            }
            list.forEach((item) => {
                item.check = check
            })
            self.render()
        })
        $con.on('click', '.J_product-group .J_ui-checkbox', function () {
            if ($(this).hasClass('disabled')) {
                return false
            }
            let index = $(this).parents('tr').attr('data-index')
            let check = false
            let version =
                self.mainData.materialPlanList[self.mainData.versionIndex]
            if (!$(this).hasClass('checked')) {
                check = true
            }
            version.materialList[index].check = check
            setTimeout(() => {
                self.render()
            }, 200)
        })
        $con.on('click', '.J_addBiSort', function () {
            if ($(this).hasClass('disabled')) {
                return false
            }
            let index = $(this).parents('tr').attr('data-index')
            let check = false
            let version =
                self.mainData.materialPlanList[self.mainData.versionIndex]
            if (!$(this).hasClass('checked')) {
                check = true
            }
            version.materialList[index].keepBiOrder = check
            setTimeout(() => {
                self.render()
            }, 200)
        })
        $con.on('click', '.J_batch-delete', function () {
            if ($(this).hasClass('disabled')) {
                return false
            }
            let list =
                self.mainData.materialPlanList[self.mainData.versionIndex]
                    .materialList
            Confirm({
                title: '提示',
                content: '确定删除吗？',
                onOk: function (modal) {
                    self.mainData.materialPlanList[
                        self.mainData.versionIndex
                    ].materialList = list.filter((item) => !item.check)
                    self.render()
                    modal.close()
                },
            })
        })
        $con.on('click', function (e) {
            let $target = $(e.target)
            if (!$target.closest('.cd-date-picker').length) {
                self.dp && self.dp.close()
            }
        })
        $con.closest('.J_modalOverlay').on('click', function (e) {
            let $target = $(e.target)
            if (!$target.closest('.cd-date-picker').length) {
                self.dp && self.dp.close()
            }
        })
        $parent.on('click', '.J_version-delete-pop-colse', function () {
            $parent.find('.J_version-delete-pop').fadeOut(500, function () {
                $(this).remove()
            })
        })
        $parent.on('click', '.J_version-delete-pop-ok', function () {
            let index = parseInt($(this).attr('data-index'))
            $con.find('.J_version-item').eq(index).addClass('slide-out-top')
            setTimeout(() => {
                mainData.materialPlanList.splice(index, 1)
                if (index === mainData.versionIndex) {
                    if (index > 0) {
                        mainData.versionIndex = --index
                    } else {
                        mainData.versionIndex = 0
                    }
                } else if (index < mainData.versionIndex) {
                    mainData.versionIndex = mainData.versionIndex - 1
                }
                self.render()
            }, 500)
            $parent.find('.J_version-delete-pop').fadeOut(500, function () {
                $(this).remove()
            })
        })
        $('body').on(
            'keydown',
            '.J_edite-toggle input,.J_edite-toggle textarea',
            function (e) {
                let limit = $(this)
                    .attr('data-limit')
                    .split('-')
                    .map((v) => parseInt(v))
                let $Jnum = $(this)
                    .parents('.J_edite-toggle')
                    .find('.J_limit-num')
                if (e.which == 13) {
                    $(this)
                        .parents('.J_edite-toggle')
                        .find('.J-enable-save')
                        .trigger('click')
                    e.preventDefault()
                } else {
                    $Jnum.text(limit[1] - $(this).val().length)
                }
            },
        )
    }
    
    dispose() {
        this.config.node.off()
    }
}
export default VersionManage