<style lang="less" scoped>
.require-class {
    ::v-deep .ant-form-item-label {
        label::before {
            display: inline-block;
            margin-right: 4px;
            color: #f5222d;
            font-size: 14px;
            font-family: SimSun, sans-serif;
            line-height: 1;
            content: '*';
        }
    }
}
</style>
<template>
    <div>
        <a-modal
            title="添加应用"
            :visible="application"
            @ok="handleSubmit"
            :confirmLoading="confirmLoading"
            @cancel="handleCancel"
            width="800px"
        >
            <a-card :body-style="{ padding: '24px 32px' }" :bordered="false">
                <a-form :form="form">
                    <a-form-item
                        label="应用类型"
                        :labelCol="{ xs: { span: 24 }, sm: { span: 5 } }"
                        :wrapperCol="{ xs: { span: 24 }, sm: { span: 16 } }"
                        class="require-class"
                    >
                        <a-radio-group
                            button-style="solid"
                            @change="clearData"
                            v-decorator="[
                                'appCreateType',
                                {
                                    rules: [{ required: true, message: '应用类型必选' }],
                                    initialValue: 1
                                }
                            ]"
                        >
                            <a-radio-button :value="1">新建应用</a-radio-button>
                            <a-radio-button :value="2" :disabled="createTypeData && !!!createTypeData.accountId"
                                >选择应用</a-radio-button
                            >
                        </a-radio-group>
                    </a-form-item>
                    <a-form-item
                        label="选择应用"
                        :labelCol="{ xs: { span: 24 }, sm: { span: 5 } }"
                        :wrapperCol="{ xs: { span: 24 }, sm: { span: 16 } }"
                        v-if="getFormData('appCreateType') == 2"
                        class="require-class"
                    >
                        <a-select
                            v-decorator="['appId', { rules: [{ required: true, message: '请选择目标应用' }] }]"
                            showSearch
                            allowClear
                            placeholder="选择应用目标"
                            optionFilterProp="children"
                            :filterOption="filterOption"
                            @change="appIdChange"
                        >
                            <!-- <a-select-option value="0">请选择目标应用</a-select-option> -->
                            <a-select-option v-for="appModel in appList" :key="appModel.appId" :value="appModel.appId">
                                {{ appModel.appName }}&#12288;&nbsp;&#12288;
                                {{ appModel.appVersion }}&#12288;&#12288;&#12288;{{ appModel.platform | platform }}
                            </a-select-option>
                        </a-select>
                        <a-button type="primary" @click="addApplication" :loading="tongbuLoading">刷新应用</a-button>
                    </a-form-item>
                    <a-form-item
                        label="下载链接"
                        :labelCol="{ xs: { span: 24 }, sm: { span: 5 } }"
                        :wrapperCol="{ xs: { span: 24 }, sm: { span: 16 } }"
                    >
                        <a-input
                            placeholder="请填写应用下载链接"
                            v-decorator="[
                                'url',
                                {
                                    rules: [{ required: true, validator: handleConfirmValue }]
                                }
                            ]"
                            id="url"
                            :disabled="getFormData('appCreateType') == 2"
                        />
                        <a-tag
                            color="#2db7f5"
                            @click="getChangeAll('渠道号', 'form', 'url')"
                            v-if="getFormData('appCreateType') != 2"
                            >+渠道号</a-tag
                        >
                    </a-form-item>

                    <a-form-item
                        label="应用包名"
                        v-if="uploadType == '2' && appType == 'android'"
                        :labelCol="{ xs: { span: 24 }, sm: { span: 5 } }"
                        :wrapperCol="{ xs: { span: 24 }, sm: { span: 16 } }"
                    >
                        <a-input
                            v-decorator="[
                                'packageName',
                                {
                                    rules: [{ required: true, message: '请填写正确的应用包名称' }]
                                }
                            ]"
                            :disabled="getFormData('appCreateType') == 2"
                            placeholder="请填写包名称，如com.smile.gifmaker"
                        />
                    </a-form-item>

                    <a-form-item
                        label="应用名称"
                        :labelCol="{ xs: { span: 24 }, sm: { span: 5 } }"
                        :wrapperCol="{ xs: { span: 24 }, sm: { span: 16 } }"
                    >
                        <a-input
                            v-decorator="[
                                'appName',
                                {
                                    rules: [{ required: true, message: '请填写应用名称' }]
                                }
                            ]"
                            :disabled="getFormData('appCreateType') == 2"
                            placeholder="请填写应用名称"
                        />
                    </a-form-item>

                    <a-form-item
                        label="上传图标"
                        :labelCol="{ xs: { span: 24 }, sm: { span: 5 } }"
                        :wrapperCol="{ xs: { span: 24 }, sm: { span: 19 } }"
                        v-if="application"
                        class="require-class"
                    >
                        <uploadFile
                            v-if="application"
                            :value.sync="fileUrl"
                            :multiple="false"
                            :fileCount="1"
                            uploadType="image"
                            @overUpload="overUpload"
                            :size="100"
                            :disabled="getFormData('appCreateType') == 2"
                        ></uploadFile>
                        <p class="upload-txt-rules">文件格式：支持上传png/jpg/jpeg图片,尺寸450*450,小于100KB</p>
                    </a-form-item>
                    <a-form-item
                        label="应用标记"
                        :labelCol="{ xs: { span: 24 }, sm: { span: 5 } }"
                        :wrapperCol="{ xs: { span: 24 }, sm: { span: 16 } }"
                    >
                        <a-input
                            :disabled="getFormData('appCreateType') == 2"
                            v-decorator="[
                                'appVersion',
                                {
                                    rules: [{ required: true, message: '应用标记必填' }]
                                }
                            ]"
                            placeholder="请填写应用标记，必填且不可重复，如快手-5.6.1.66"
                            id="appVersion"
                        />
                        <a-tag
                            color="#2db7f5"
                            @click="getChangeAll('渠道号', 'form', 'appVersion')"
                            v-if="getFormData('appCreateType') != 2"
                            >+渠道号</a-tag
                        >
                    </a-form-item>
                    <a-form-item
                        label="隐私政策链接"
                        :labelCol="{ xs: { span: 24 }, sm: { span: 5 } }"
                        :wrapperCol="{ xs: { span: 24 }, sm: { span: 16 } }"
                    >
                        <a-input
                            :disabled="getFormData('appCreateType') == 2"
                            v-decorator="[
                                'appPrivacyUrl',
                                {
                                    rules: [
                                        { required: true, message: '请填写隐私政策链接' },
                                        { validator: handleConfirmValue }
                                    ]
                                }
                            ]"
                            placeholder="请填写隐私政策链接"
                        />
                    </a-form-item>
                </a-form>
            </a-card>
        </a-modal>
    </div>
</template>

<script>
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { deleteAction, postAction, getAction, downFilePost, downFile } from '@/api/manage'
import uploadFile from './uploadFile.vue'
import { mapActions, mapGetters } from 'vuex'
import BMF from 'browser-md5-file'
import selectTable from '@/views/modules/Statistics/components/selectPagination.vue'
import $ from 'jquery'
const fileSuffix = ['xlsx', 'xls', 'zip']
export default {
    name: 'BaseForm',
    components: {
        uploadFile,
        selectTable
    },
    data() {
        return {
            appList: [],
            useSdk: [],
            loadDisabled: false,
            projectId: '',
            accountId: '',
            fileList: [],
            fileUrl: '',
            accountList: {},
            appType: 'android', //设备类型
            platform: '1', //应用类型   ： 1 Android 应用下载，2： Android 网页游戏，3： iOS 应用下载， 4：iOS 网页游戏
            uploadType: '2', //上传类型 1 本地上传 2 填写链接
            appVersion: '', //应用标记
            appName: '', // 应用名称
            packageName: '', //应用包名
            file: '', // 上传文件
            imageUrl: '', // 上传图标链接链接
            downloadUrl: '', //下载链接
            showUploadFile: true,
            showDownLoad: false,
            showUpload: true,
            showAndroid: true,
            showIOS: false,
            customDomain: '',
            acceptVideo: '/*.apk,/*.png,/*.jpg,/*.jpeg,/*.mp4',
            accessKeyId: 'LTAIbNbqWzSOklQV',
            accessKeySecret: '1rkPz7JNoXk8sJevPaeYHWqfkQXBGh',
            region: 'oss-cn-beijing',
            bucket: 'ctop-media',
            form: this.$form.createForm(this),
            url: {
                insertTemplateUrl: '/kuaishouAppPackage/fillInLink',
                userAllocationList: '/ctop/userAllocation/list'
            },
            application: false,
            confirmLoading: false,
            imageToken: '',
            // uploadAction: '/kuaishouAppPackage/importAppExcel',
            tokenHeader: { 'X-Access-Token': Vue.ls.get(ACCESS_TOKEN) },
            okCreated: false,
            dataFile: null,
            createTypeData: null,
            tongbuLoading: false
        }
    },
    methods: {
        //获取表单的某一个属性值
        getFormData(className) {
            return this.form.getFieldValue(className)
        },
        filterOption(input, option) {
            return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        },
        clearData() {
            this.form.resetFields()
            this.fileUrl = ''
            this.$nextTick(() => {
                this.getAppList()
            })
        },
        addApplication() {
            if (this.createTypeData.accountId) {
                this.tongbuLoading = true
                // this.$refs.application.showApplication()
                getAction('/kuaishou/batch/syncAppList', {
                    accountId: this.createTypeData.accountId
                }).then(res => {
                    if (res.success) {
                        this.tongbuLoading = false
                        this.$message.success(res.message)
                        this.getAppList()
                    } else {
                        this.tongbuLoading = false
                        this.$message.error(res.message)
                    }
                })
            } else {
                this.$message.error('请先选择账户')
            }
        },
        appIdChange(val) {
            if (val) {
                getAction('/kuaishou/kuaiShouAppList/queryByAppId', { appId: val }).then(res => {
                    if (res.success) {
                        console.log(res)
                        let resultData = res.result
                        this.fileUrl = ''
                        this.$nextTick(() => {
                            this.form.setFieldsValue({
                                appName: resultData.appName,
                                appVersion: resultData.appVersion,
                                packageName: resultData.packageName,
                                url: resultData.url,
                                appPrivacyUrl: resultData.appPrivacyUrl
                            })
                            this.fileUrl = resultData.appIconUrl
                        })
                    }
                })
            } else {
                this.form.resetFields()
                this.fileUrl = ''
            }
        },
        // 获取applist
        getAppList() {
            let params = {}
            params.accountId = this.createTypeData.accountId
            getAction('/kuaishou/batch/getAppList', params).then(res => {
                if (res.success) {
                    this.appList = res.result.map((item, index) => {
                        return {
                            ...item,
                            key: index
                        }
                    })
                }
            })
        },
        getChangeAll(type, form, field) {
            var node = document.getElementById(field)
            var v = ''
            if (field == 'url') {
                v = '-{{' + type + '}}-'
            } else {
                v = '-{{' + type + '}}-'
            }
            if (document.selection) {
                //IE
                node.focus()
                var sel = document.selection.createRange()
                sel.text = v
                sel.select()
                if (field == 'channelName') {
                    this[form].setFieldsValue({ channelName: sel.text })
                } else if (field == 'channelCode') {
                    this[form].setFieldsValue({ channelCode: sel.text })
                } else if (field == 'url') {
                    this[form].setFieldsValue({ url: sel.text })
                } else if (field == 'clickTrackUrl') {
                    this[form].setFieldsValue({ clickTrackUrl: sel.text })
                } else if (field == 'actionbarClickUrl') {
                    this[form].setFieldsValue({ actionbarClickUrl: sel.text })
                } else if (field == 'appVersion') {
                    this[form].setFieldsValue({ appVersion: sel.text })
                }
            } else if (node.selectionStart || node.selectionStart == '0') {
                //MOZILLA/GOOGLE
                var startPos = node.selectionStart
                var endPos = node.selectionEnd
                var restoreTop = node.scrollTop
                node.value = node.value.substring(0, startPos) + v + node.value.substring(endPos, node.value.length)
                if (restoreTop > 0) {
                    node.scrollTop = restoreTop
                }
                if (field == 'channelName') {
                    this[form].setFieldsValue({ channelName: node.value })
                } else if (field == 'channelCode') {
                    this[form].setFieldsValue({ channelCode: node.value })
                } else if (field == 'url') {
                    this[form].setFieldsValue({ url: node.value })
                } else if (field == 'clickTrackUrl') {
                    this[form].setFieldsValue({ clickTrackUrl: node.value })
                } else if (field == 'actionbarClickUrl') {
                    this[form].setFieldsValue({ actionbarClickUrl: node.value })
                } else if (field == 'appVersion') {
                    this[form].setFieldsValue({ appVersion: node.value })
                }
                node.focus()
                node.selectionStart = startPos + v.length
                node.selectionEnd = startPos + v.length
                // this.channelName = node.value
            } else {
                //OTHER
                node.value += v
                // console.log(node.value)
                if (field == 'channelName') {
                    this[form].setFieldsValue({ channelName: node.value })
                } else if (field == 'channelCode') {
                    this[form].setFieldsValue({ channelCode: node.value })
                } else if (field == 'url') {
                    this[form].setFieldsValue({ url: node.value })
                } else if (field == 'clickTrackUrl') {
                    this[form].setFieldsValue({ clickTrackUrl: node.value })
                } else if (field == 'actionbarClickUrl') {
                    this[form].setFieldsValue({ actionbarClickUrl: node.value })
                } else if (field == 'appVersion') {
                    this[form].setFieldsValue({ appVersion: node.value })
                }

                node.focus()
                // this.channelName = node.value
            }
        },
        overUpload(file) {},
        downLoadFile() {
            downFile('/kuaishouAppPackage/exportAppTemplate').then(res => {
                let blob = new Blob([res], {
                    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                })
                let downloadElement = document.createElement('a')
                let href = window.URL.createObjectURL(blob) //创建下载的链接
                downloadElement.href = href
                downloadElement.download = '应用模板' //下载后文件名
                document.body.appendChild(downloadElement)
                downloadElement.click() //点击下载
                document.body.removeChild(downloadElement) //下载完成移除元素
                window.URL.revokeObjectURL(href) //释放掉blob对象
            })
        },
        handleChange(info) {
            this.loadDisabled = false
            this.$message.success('文件导入成功')
        },
        beforeUpload(file) {
            this.dataFile = $('.fileUpload')
                .eq(0)
                .find('input')[0].files[0]
            this.loadDisabled = true
            const size = (Number(file.size) / (1024 * 1024)).toFixed(2)
            const fileName = file.name
            const fileStrArr = fileName.split('.')
            const suffix = fileStrArr[fileStrArr.length - 1]

            let result = fileSuffix.some(item => {
                return item === suffix
            })

            if (!result) {
                this.$message.error('不支持该文件类型')
                this.loadDisabled = false
                return false
            }
        },
        cosUpload(file) {
            let that = this
            let date = new Date()
            let y = date.getFullYear()
            let MM = date.getMonth() + 1
            MM = MM < 10 ? '0' + MM : MM
            let d = date.getDate()
            d = d < 10 ? '0' + d : d
            let timeElse = new Date().getTime()
            let arr = file.name.split('.')
            let str = ''
            for (let i = 0; i < arr.length; i++) {
                if (i === arr.length - 1) {
                } else {
                    if (i === arr.length - 2) {
                        str += arr[i]
                    } else {
                        str += arr[i] + '.'
                    }
                }
            }
            cos.putObject(
                {
                    Bucket: 'media-1301855440',
                    Region: 'ap-chongqing',
                    // 存储桶所在地域，必须字段
                    Key:
                        that.appType +
                        '/' +
                        y +
                        '-' +
                        MM +
                        '-' +
                        d +
                        '/' +
                        str +
                        '-' +
                        timeElse +
                        '.' +
                        arr[arr.length - 1],
                    StorageClass: 'STANDARD',
                    Body: file // 上传文件对象
                },
                function(err, data) {
                    if (err) {
                        that.$message.error('上传失败!!!' + err)
                        return
                    }
                    that.loadingElse = false
                    that.fileList.push({
                        uid: file.name,
                        name: file.name,
                        status: 'done',
                        url: '//' + data.Location
                    })
                    if (that.fileList.length > 1) {
                        that.fileList = that.fileList.slice(-1)
                    }
                    const isZip = file.type.includes('zip') || file.type.includes('text')
                    const fileOvesize = file.size > 1024 * 1024 * 1024
                    if (!isZip) {
                        that.$message.error('只能上传zip格式的文件或者txt文件')
                        return
                    }
                    if (fileOvesize) {
                        that.$message.error('文件大小不能超过1G')
                        return
                    }
                    that.handleMd5(file)
                }
            )
        },
        handleMd5(file) {
            let bmf = new BMF()
            let that = this
            return new Promise(function(resolve, reject) {
                bmf.md5(file, (err, md5) => {
                    // getAction('kuaishouPopulationPackage/checkPopulationPackage', { signature: md5 })
                    //   .then((result) => {
                    //     if (result.code === 200) {
                    that.personNameDisabled = false
                    that.personResourceDisabled = false
                    resolve()
                })
            })
        },
        handleOk() {
            this.handleSubmit()
        },
        handleCancel() {
            this.dataFile = null
            this.appType = 'android'
            this.okCreated = false
            this.form.resetFields()
            this.fileUrl = ''
            this.file = ''
            this.platform = '1'
            this.application = false
        },
        showApplication() {
            this.application = true
        },
        handleConfirmValue(rule, value, callback) {
            if (/(http|https):\/\/([\w.]+\/?)\S*/.test(value) && value != '') {
                callback()
            } else {
                callback('链接不能为空且开头为http://或https://')
            }
        },
        ...mapGetters(['nickname', 'avatar', 'userInfo']),
        changePlatform() {
            this.form.resetFields()
            if (this.appType == 'android') {
                this.showAndroid = true
                this.showIOS = false
                this.platform = '1'
            } else {
                this.showAndroid = false
                this.showIOS = true
                this.showDownLoad = true
                this.platform = '1'
            }
        },
        changeShowUpload() {
            this.form.resetFields()
            this.fileUrl = ''
        },
        changeShowUploadType() {
            this.form.resetFields()
            if (this.platform == '2') {
                this.showUpload = false
                this.showUploadFile = false
                this.showDownLoad = true
                this.uploadType = '1'
            } else {
                this.showUpload = true
                this.showUploadFile = true
                this.showDownLoad = false
            }
        },

        handleSubmit() {
            //   console.log('设备类型：' + this.appType)
            //   console.log('应用类型：' + this.platform)
            //   console.log('上传类型：' + this.uploadType)
            //   console.log('应用标记：' + this.appVersion)
            //   console.log('应用名称：' + this.appName)
            //   console.log('包名称：' + this.packageName)
            //   console.log('文件地址：' + this.file)
            //   console.log('图片地址：' + this.imageUrl)
            //   e.preventDefault()

            this.form.validateFields((err, values) => {
                if (!err) {
                    if (this.fileUrl) {
                        this.confirmLoading = true
                        let params = {}
                        var reg = RegExp(/{{渠道号}}/)
                        if (reg.test(values.url) && reg.test(values.appVersion)) {
                            this.url.insertTemplateUrl = '/kuaishouAppPackage/fillInLink'
                            params = { ...values }
                            params.appIconUrl = this.fileUrl
                            this.confirmLoading = false
                            this.$emit('getDataList', params)
                            this.handleCancel()
                        } else if (!reg.test(values.url) && !reg.test(values.appVersion)) {
                            this.url.insertTemplateUrl = '/kuaishouAppPackage/fillInLink'
                            params = { ...values }
                            params.appIconUrl = this.fileUrl
                            this.confirmLoading = false
                            this.$emit('getDataList', params)
                            this.handleCancel()
                        } else {
                            this.confirmLoading = false
                            this.$message.error('下载链接必须和应用标记的通配符保持一致')
                        }

                        // postAction(this.url.insertTemplateUrl, params).then(res => {
                        //     this.confirmLoading = false
                        //     if (res.success) {
                        //         this.$message.success('创建成功')
                        //         this.handleCancel()
                        //         this.$emit('getDataList')
                        //     } else {
                        //         this.$message.error(res.message)
                        //     }
                        // })
                    } else {
                        this.confirmLoading = false
                        this.$message.error('请填写必填项')
                    }
                }
            })
        },

        onChange(value) {}
    },
    created: function() {
        this.createTypeData = JSON.parse(localStorage.getItem('channelInfo'))
        let params = {}
        params.pageSize = '1000'
        params.mediaId = '2'
        params.userId = this.userInfo().id
        this.$nextTick(() => {
            this.getAppList()
        })

        getAction(this.url.userAllocationList, params).then(res => {
            if (res.success) {
                this.accountList = res.result.records
            }
        })
    }
}
</script>
