<template>
    <div class="edit-form-main">
        <div class="form-title">
            <img class="icon" src="@/assets/img/sa_7.png" />
            <span>活动编辑</span>
        </div>
        <div class="form-content">
            <div class="module-panel">
                <p class="module-title">
                    <img src="@/assets/img/sa_13.png" />
                    基本信息
                </p>
                <div class="module-item">
                    <label class="item-title">海报</label>
                    <div class="poster-photo-panel">
                        <el-input v-model="poster_photo_file_name" :readonly="true" class="input"></el-input>
                        <el-upload 
                        action="https://upload.qiniup.com" 
                        :data="{ token: qntoken, key: poster_photo_file_key }"
                        :show-file-list="false"
                        :on-error="posterPhotoUploadFail"
                        :on-success="posterPhotoUploadSuccess"
                        :before-upload="beforePosterPhotoUpload"
                        >
                            <el-button type="primary" style="margin-left: 10px;" :loading="uploading_poster_photo">上传图片</el-button>
                        </el-upload>
                    </div>
                </div>
                <div class="poster-photo-hint">图片建议尺寸828*430,大小不超过3M</div>
                <div class="module-item">
                    <label class="item-title">标题</label>
                    <el-input v-model="activity.title" class="item-input"></el-input>
                </div>
                <div class="module-item">
                    <label class="item-title">名称</label>
                    <el-input v-model="activity.subtitle" class="item-input"></el-input>
                </div>
                <div class="module-item">
                    <label class="item-title">商户简称</label>
                    <el-input v-model="$store.getters.xt_user.org.org_name" class="item-input" readonly></el-input>
                </div>
                <div class="module-item">
                    <label class="item-title">报名时间</label>
                    <el-date-picker v-model="sign_up_deadline" :picker-options="pickerOptions" value-format="timestamp" type="datetime" format="yyyy-MM-dd HH:mm" class="item-input"></el-date-picker>
                </div>
                <div class="module-item">
                    <label class="item-title">活动时间</label>
                    <el-date-picker v-model="activity_time" :picker-options="pickerOptions" value-format="timestamp" type="datetime" format="yyyy-MM-dd HH:mm" class="item-input"></el-date-picker>
                </div>
                <div class="module-item">
                    <label class="item-title">活动地址</label>
                    <el-input v-model="activity.address" class="item-input"></el-input>
                </div>
                <div class="module-item">
                    <label class="item-title">限定人数</label>
                    <el-input v-model="limit_num" class="item-input" :maxlength="9" @keyup.native="limit_num=limit_num.replace(/\D/g,'')" @afterpaste.native="limit_num=limit_num.replace(/\D/g,'')"></el-input>
                    <span class="limit-text">不填写默认为无限制</span>
                </div>
                <div class="module-item">
                    <label class="item-title">联系方式</label>
                    <el-input v-model="activity.phone_number" class="item-input"></el-input>
                </div>
            </div>

            <div class="module-panel" style="margin-top: 30px;">
                <p class="module-title">
                    <img src="@/assets/img/sa_13.png" />
                    报名须知
                </p>
                <div class="module-item">
                    <label class="item-title">报名须知</label>
                    <el-input v-model="activity.sign_up_notice" class="item-input" type="textarea" :rows="4" resize="none"></el-input>
                </div>
            </div>

            <div class="module-panel" style="margin-top: 30px;">
                <p class="module-title">
                    <img src="@/assets/img/sa_13.png" />
                    详细说明
                </p>
                <div class="module-item">
                    <label class="item-title">标题</label>
                    <el-input v-model="paragraph.title" class="item-input"></el-input>
                </div>
                <div class="module-item">
                    <label class="item-title">详情</label>
                    <div class="item-input">
                        <keep-alive>
                            <neditor ref="neditor" id="editor" :r_content="paragraph_init_content" @content_changed="paragraphContentChanged"></neditor>
                        </keep-alive>
                    </div>
                </div>
            </div>

            <div class="submit-button-panel">
                <el-button style="padding: 10px 30px;" type="primary" @click="publishAction" :loading="publishing_activity" :disabled="saving_activity || saving_before_preview_activity">发 布</el-button>
                <el-button style="color: #409eff; border-color: #409eff; padding: 10px 30px;" @click="saveAction" :loading="saving_activity" :disabled="publishing_activity || saving_before_preview_activity">保存草稿</el-button>
                <el-button style="color: #409eff; border-color: #409eff; padding: 10px 30px;" @click="previewAction" :loading="saving_before_preview_activity" :disabled="publishing_activity || saving_activity">预 览</el-button>
            </div>
        </div>
    </div>
</template>

<script>
import Neditor from '@/components/Neditor'
import { getToken } from "@/api/qiniu"
import { getFileExtension } from "@/utils/tools"
import { parseTime } from "@/utils"
import { submitActivity } from "@/api/activity/activity"

export default {
    name: "EditActivityEditForm",
    components: {
        Neditor,
    },
    props: {
        activity: {
            type: Object,
            required: true,
        },
        paragraph: {
            type: Object,
            required: true,
        },
    },
    data() {
        return {
            saving_activity: false,
            publishing_activity: false,
            saving_before_preview_activity: false,

            uploading_poster_photo: false,
            qntoken: "",
            poster_photo_file_key: "",
            poster_photo_file_name: "",

            limit_num: "",
            activity_time: 0,
            sign_up_deadline: 0,
            paragraph_init_content: "",

            pickerOptions: {
                disabledDate: (time) => {
                    return time.getTime() < Date.now() - 8.64e7
                }
            }
        }
    },
    created() {
        this.activity_time = (new Date()).getTime()
        this.sign_up_deadline = (new Date()).getTime()
    },
    watch: {
        limit_num: function(new_val) {
            if (/^[1-9]+[0-9]*]*$/.test(new_val)) {
                this.activity.limit_num = parseInt(new_val)
            } else {
                this.activity.limit_num = 0
            }
        },
        activity_time: function(new_val) {
            this.activity.start_time = parseInt(new_val / 1000)
        },
        sign_up_deadline: function(new_val) {
            this.activity.sign_up_deadline = parseInt(new_val / 1000)
        },
    },
    methods: {
        initForms: function() {
            this.poster_photo_file_name = this.activity.poster_photo
            this.limit_num = this.activity.limit_num > 0 ? this.activity.limit_num : ""
            this.activity_time = this.activity.start_time
            this.sign_up_deadline = this.activity.sign_up_deadline

            this.paragraph_init_content = this.paragraph.content
        },
        paragraphContentChanged: function(content) {
            this.paragraph.content = content
        },

        posterPhotoUploadFail: function(err, file, fileList) {
            this.uploading_poster_photo = false
            this.$message.error(err)
        },
        posterPhotoUploadSuccess: function(res, file) {
            this.poster_photo_file_name = file.name
            this.uploading_poster_photo = false
            this.activity.poster_photo = "https://images.shengws.com/" + res.url
        },
        beforePosterPhotoUpload: function(file) {
            var is_image = file.type.indexOf("image") > -1
            var mb = file.size / 1024 / 1024

            if (!is_image) {
                this.$message.error("请上传图片")
                return false
            }
            if (mb > 3) {
                this.$message.error("上传主图大小不能超过3MB")
                return false
            }

            var rand = Math.floor(Math.random() * 1000000000)
            var date = new Date()
            var ext = getFileExtension(file.name)
            var key = "" + date.getFullYear() + (date.getMonth() + 1) + date.getDate() + "_activity_" + rand + "." + ext

            this.uploading_poster_photo = true

            return new Promise((resolve, reject) => {
                getToken().then(rs => {
                    var token = rs.data.data.uptoken
                    this.qntoken = token
                    this.poster_photo_file_key = key
                    resolve(true)
                }).catch(err => {
                    this.uploading_poster_photo = false
                    reject(false)
                })
            })
        },

        saveAction: function() {
            this.saving_activity = true
            this.submitActivity(false, function() {
                // 弹框 => 再发一条/前往列表
            })
        },
        publishAction: function() {
            this.publishing_activity = true
            this.submitActivity(true, function() {
                this.$router.push({ path: "/activity", query: { id: this.activity.id } })
            })
        },
        previewAction: function() {
            this.saving_before_preview_activity = true
            var t = this
            this.submitActivity(false, function() {
                var new_page = t.$router.resolve({ 
                    path: '/activity/preview',
                    query: {
                        id: t.activity.id,
                    }   
                })
                window.open(new_page.href, '_blank');
            })
        },
        submitActivity: function(is_publish, successCallBack) {
            this.validActivityInfo().then(() => {
                var activity = {
                    id: this.activity.id,
                    poster_photo: this.activity.poster_photo,
                    title: this.activity.title,
                    subtitle: this.activity.subtitle,
                    address: this.activity.address,
                    limit_num: this.activity.limit_num,
                    sign_up_deadline: parseTime(this.activity.sign_up_deadline, "{y}-{m}-{d} {h}:{i}"),
                    start_time: parseTime(this.activity.start_time, "{y}-{m}-{d} {h}:{i}"),
                    phone_number: this.activity.phone_number,
                    sign_up_notice: this.activity.sign_up_notice,

                    paragraph: {
                        title: this.paragraph.title,
                        content: this.paragraph.content,
                    }
                }
                submitActivity(is_publish, activity).then(rs => {
                    var resp = rs.data
                    if (resp.state == 1) {
                        this.activity.id = resp.data.activity_id
                    } else {
                        this.$message.error(resp.msg)
                    }

                    if (successCallBack != null || successCallBack != undefined) {
                        successCallBack()
                    }

                    this.saving_activity = false
                    this.publishing_activity = false
                    this.saving_before_preview_activity = false

                }).catch(err => {
                    console.log('------  ' + err)
                    this.$message.error(err)
                    this.saving_activity = false
                    this.publishing_activity = false
                    this.saving_before_preview_activity = false
                })

            }).catch(err => {
                console.log('asdada  ' + err)
                this.$message.error(err)
                this.saving_activity = false
                this.publishing_activity = false
                this.saving_before_preview_activity = false
            })
        },
        validActivityInfo: function() {
            return new Promise((resolve, reject) => {
                if (this.activity.poster_photo.length == 0) {
                    reject("海报不能为空")
                    return
                } else if (this.activity.title.length == 0) {
                    reject("标题不能为空")
                    return
                } else if (this.activity.subtitle.length == 0) {
                    reject("副标题不能为空")
                    return
                } else if (this.activity.address.length == 0) {
                    reject("活动地址不能为空")
                    return
                } else if (this.activity.sign_up_deadline == 0) {
                    reject("活动报名时间不能为空")
                    return
                } else if (this.activity.start == 0) {
                    reject("活动时间不能为空")
                    return
                } else {
                    if (this.activity.phone_number.length > 0) {
                        if (/^1\d{10}$/.test(this.activity.phone_number) == false && /^(0\d{2,3}-?\d{7,8}$)/.test(this.activity.phone_number) == false) {
                            reject("联系方式格式错误")
                            return
                        }
                    }
                }
                resolve()
            })
        },
    },
}
</script>

<style lang="scss" scoped>
.edit-form-main {
    .form-title {
        width: 100%;
        height: 60px;
        padding: 20px 0 20px 30px;
        border-bottom: 1px #dee2e5 solid;

        .icon {
            margin-top: -4px;
            vertical-align: middle;
        }

        span {
            font-size: 18px;
            font-weight: 500;
            color: #485b6d;
            margin-left: 10px;
        }
    }

    .form-content {
        width: 100%;
        padding: 14px 30px 14px 30px;

        .module-panel {
            // padding: 0 30px;

            .module-title {
                font-size: 18px;
                color: #a8b3ba;

                img {
                    float: left;
                    display: block;
                    padding: 2px 19px 0 0;
                }
            }

            .module-item {
                margin-top: 20px;
                display: flex;
                // padding: 0 30px;

                .item-title {
                    width: 115px;
                    height: 40px;
                    line-height: 40px;
                    color: #485b6d;
                    font-size: 13px;
                    // font-weight: 100;
                    text-align: right;
                    padding-right: 22px;
                    float: left;
                }

                .item-input {
                    flex: 1;
                    color: #485b6d;
                }

                .limit-text {
                    line-height: 40px;
                    color: #a8b3ba;
                    font-size: 13px;
                    // font-weight: 100;
                    text-align: left;
                    padding-left: 10px;
                }

                .poster-photo-panel {
                    display: flex;
                    flex: 1;
                    align-items: center;

                    .input {
                        flex: 1;
                        color: #485b6d;
                        cursor: pointer;
                    }
                }
            }

            .poster-photo-hint {
                font-size: 12px;
                line-height: 16px;
                color: #a8b3ba;
                margin-left: 115px;
            }
        }

        .submit-button-panel {
            padding: 0 0 0 115px;
            margin-top: 30px;
        }
    }
}
</style>

