<template>
    <div class="create-opensource-wrapper">
        <div class="create-opensource-title">新建开源项目</div>
        <div class="form-wrapper">
            <!-- 标题 -->
            <div class="title-field">
                <div class="field-name"><span class="required">*</span> 项目标题</div>
                <el-input
                    class="title-input"
                    v-model="title"
                    maxlength="50"
                    show-word-limit
                    placeholder="请输入项目标题"></el-input>
            </div>
            <!-- 描述 -->
            <div class="content-field">
                <div class="content-field-name">
                    <div><span class="required">*</span> 项目介绍</div>
                    <!-- <a class="example" :href="`/c/${exampleUid}?from=example`" target="_blank">查看示例</a> -->
                </div>
                <el-input
                    class="content-input"
                    type="textarea"
                    :rows="8"
                    :autosize="{ minRows: 8 }"
                    placeholder="请输入项目介绍"
                    v-model="content"></el-input>
            </div>
            <!-- 分类 -->
            <div class="price-field">
                <div class="cate-wrapper">
                    <div class="field-name"><span class="required">*</span> 项目分类</div>
                    <div class="cate-content">
                        <el-cascader
                            class="cate-cascader"
                            v-model="selectedOpensourceCate"
                            :options="opensourceCate"
                            :props="{ expandTrigger: 'hover' }"
                            placeholder="请选择类别"></el-cascader>
                    </div>
                </div>
            </div>
            <!-- 项目源码链接 -->
            <div class="sourcelink-field">
                <div class="field-name">项目源码链接</div>
                <el-input
                    class="sourcelink-input"
                    v-model="sourcelink"
                    placeholder="请添加github或gitee项目链接"></el-input>
            </div>
            <!-- 图片 -->
            <div class="image-field">
                <div class="field-name">项目logo</div>
                <multi-uploader
                    class="opensource-image-uploader"
                    :showTips="false"
                    :limit="1"
                    v-model="imageList"></multi-uploader>
                <div class="upload-tips"><strong style="color: #19222e;">请优先上传项目logo</strong>
                    请优先注重手机浏览体验，分辨率至少800*400，最多5M
                    电脑浏览可在上述基础上增加宽度 1500*400
                </div>
            </div>
            <!-- 按钮 -->
            <div class="actions-wrapper">
                <el-button
                    class="create-btn"
                    :loading="publishIsLoading"
                    @click="handleCreate">保存并提交审核</el-button>
            </div>
        </div>
    </div>
</template>

<script>
import { mapState } from "vuex";
import editor from "@/components/editor";
import multiUploader from '@/components/multi-uploader';

// 查看示例 uid
const exampleUid = process.env.NODE_ENV == "development" ? '680581' : '583073'

export default {
    head: {
        title: '新建开源项目'
    },
    components: {
        editor,
        multiUploader
    },
    data () {
        return {
            sale_id: '', // 编辑时的 id
            title: '', // 标题
            selectedOpensourceCate: [], // 选中的开源充电分类
            opensourceCate: [], // 开源充电分类数据源
            content: '', // 话题描述
            contentText: '', // 话题描述文字
            imageList: [], // 用户上传的图片
            sourcelink: '', // 源码链接
            publishIsLoading: false,
            exampleUid,
        }
    },
    computed: {

    },
    mounted () {
        this.needLogin()
        this._getOpensourceCate()
        this.sale_id = this.$route.query.sale_id || ''
        if (this.sale_id) {
            this._getOpensourceDetail()
        }
    },
    methods: {
        /** 获取开源充电分类 */
        _getOpensourceCate () {
            this.$axios.$post('/api/sale/cateListYes', { type: 5, point: 1 }).then(res => {
                if (res.status === 1) {
                    let opensourceCate = res.data || []
                    this.opensourceCate = opensourceCate.map(item => {
                        let children = item.child_list.map(child => {
                            return {
                                value: child.category_id,
                                label: child.name
                            }
                        })
                        return {
                            value: item.category_id,
                            label: item.name,
                            children: children
                        }
                    })
                }
            }).catch(err => {
                console.log('get opensource cate error: ', err)
            })
        },
        /** 获取开源充电服务详情 */
        _getOpensourceDetail () {
            const self = this

            this.$axios.$post('/api/sale/saleInfo', { sale_id: this.sale_id }).then(res => {
                if (res.status === 1) {
                    console.log('获取开源充电详情成功', res.data)
                    self.title = res.data.title || ""
                    self.content = res.data.content || ""
                    if (res.data.cate_id_one && res.data.cate_id_two) {
                        self.selectedOpensourceCate = [res.data.cate_id_one, res.data.cate_id_two]
                    }
                    self.sourcelink = res.data.source_link || ""
                    if (res.data.image) {
                        self._setOpensourceImages(res.data)
                    }
                }
            })
        },
        /** 编辑时初始化图片列表 */
        _setOpensourceImages (data) {
            let images = data.image.split(',')
            if (images && images.length > 0) {
                images.forEach((image, index) => {
                    let imageName = this._getImageName(image);
                    console.log("imageName", imageName);
                    this.imageList.push({ name: imageName + index, url: image });
                })
            }
        },
        /** 通过 image url 获取名字 */
        _getImageName (url)  {
            if (url) {
                try {
                    const lastquotaIndex = url.lastIndexOf("/");
                    const lastDotIndex = url.lastIndexOf('.');
                    return url.substring(lastquotaIndex + 1, lastDotIndex);
                } catch (e) {
                    console.log(e);
                }
            }
            return ""
        },
        /** 创建、编辑开源充电服务 */
        _publishOpensourceData (actType) {
            const self = this

            const data = {
                title: this.title,
                content: this.content,
                img: this.imageList.map((it) => it.url).join(","),
                type: 5,
                cate_id_one: this.selectedOpensourceCate[0],
                cate_id_two: this.selectedOpensourceCate[1],
                act: actType,
                source_link: this.sourcelink,
                sale_id: this.sale_id || '',
            }

            this.publishIsLoading = true

            this.$axios.$post('/api/sale/create', data).then(res => {
                if (res.status === 1) {
                    self.$message.success('您已成功提交开源充电服务审核，平台将在1-3个工作日内完成审核，并通过短信、邮件通知您')
                    setTimeout(() => {
                        window.location.href = '/workbench/opensource/index'
                    }, 1200)
                } else {
                    console.error('保存失败')
                }
            }).then(() => {
                setTimeout(() => {
                    self.publishIsLoading = false
                }, 800)
            })
        },
        /** 验证提交的数据 */
        _validateOpensourceData () {
            if (this.title === '') {
                this.$message.error('请输入项目标题')
                return false
            }
            if (this.title.length < 5) {
                this.$message.error('项目标题不可少于5字符')
                return false
            }
            if (this.title.length > 50) {
                this.$message.error('项目标题不可超过50字符，请删减')
                return false
            }
            if (this.content.length < 50) {
                this.$message.error('项目描述不可少于50字符')
                return false
            }
            if (this.content.length > 5000) {
                this.$message.error('项目描述不可超过5000字符，请删减')
                return false
            }
            if (this.selectedOpensourceCate.length !== 2 ||
                (!this.selectedOpensourceCate[0] || !this.selectedOpensourceCate[1])) {
                this.$message.error('请选择项目类别')
                return false
            }

            return true
        },
        /** 点击提交审核时 */
        handleCreate () {
            if (this._validateOpensourceData()) {
                this._publishOpensourceData(this.sale_id ? 'update' : 'create')
            }
        },
    }
}
</script>

<style scope lang="scss">
@import "@/assets/css/opensource/create.scss";
</style>
<style>
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}
input[type="number"]{
  -moz-appearance: textfield !important;
}
</style>
<style lang="scss">
// 图片上传器样式
.opensource-image-uploader {
    .el-upload-list__item {
        width: 300px !important;
        height: 168.75px !important;
        line-height: 168.75px !important;
    }
    .el-upload {
        .el-upload-dragger {
            width: 300px !important;
            height: 168.75px !important;
            display: flex !important;
            align-items: center;
            justify-content: center;
        }
    }
    .el-upload--picture-card {
        width: 300px !important;
        height: 168.75px !important;
        line-height: 168.75px !important;
        .el-upload-list__item-thumbnail {
            object-fit: scale-down !important;
        }
    }
    .el-upload-list--picture-card {
        .el-upload-list__item-thumbnail {
            object-fit: scale-down !important;
        }
    }
}
</style>
