<template>
    <div class="admin-HangYeZiXunConfig">
        <!--    按钮组合    -->
        <div class="my-Config-top">
            <el-button size="mini" type="primary" @click="back">返回</el-button>
        </div>
        <div class="my-Config-content">
            <el-form :model="configData" :rules="configRules" ref="HangYeZiXun" label-width="110px"
                     class="my-Config-content-form">
                <el-form-item label="标题:" prop="title">
                    <el-input :maxlength="9" v-model="configData.title" placeholder="请输入标题"></el-input>
                </el-form-item>
                <el-form-item prop="startTime" label="开始时间:" porp="startTime">
                    <div>
                        <el-date-picker
                                class="my-form-width"
                                type="date"
                                format="yyyy-MM-dd"
                                value-format="yyyy-MM-dd"
                                placeholder="选择日期"
                                v-model="configData.startTime"
                                style="width: 100%;"></el-date-picker>
                    </div>
                </el-form-item>
                <el-form-item label="访问次数:" prop="visits">
                    <el-input :maxlength="9" placeholder="请输入访问次数" v-model="configData.visits"></el-input>
                </el-form-item>
                <el-form-item label="新闻分类:" prop="newsClassifyId">
                    <mySelect label="name"
                              id="newsClassifyId"
                              @select-change="handleSelectDoChange"
                              placeholder="请选择新闻分类"></mySelect>
                </el-form-item>
                <el-form-item label="图片:" prop="pic">
                    <upload-file :imageUrl="configData.pic"
                                 :showBtnFlag="false"
                                 @getFileUrl="getImageUrl"></upload-file>
                    <h5 class="picture-size-h5">（最佳尺寸为400*400像素）</h5>
                </el-form-item>
                <el-form-item label="描述:" prop="intro">
                    <el-input type="textarea" placeholder="请输入描述" :rows="6"
                              v-model="configData.intro"></el-input>
                </el-form-item>
            </el-form>
            <div class="my-Config-editor">
                <mta-st-quill-editor
                        class="admin-quill-editor"
                        ref="editorQuill"
                        :value="configData.content"
                        quillEditorRef="quillEditorRef1"
                        flg="1"
                        @syncValue="syncValue" />
            </div>
        </div>
        <div class="my-Config-bottom">
            <el-button
                    v-if="queryData && queryData.code === 'add'"
                    type="primary"
                    @click="handleAdd('HangYeZiXun')"
            >新增
            </el-button>
            <div v-else>
                <el-button type="primary" @click="handleSave('HangYeZiXun')">保存</el-button>
                <el-button type="primary" @click="back">关闭</el-button>
            </div>

        </div>
    </div>
</template>

<script>
    import uploadFile           from './components/uploadFile';
    import MtaStQuillEditor     from '@/components/management/QuillEditor.vue';
    import mySelect             from '../components/Select';
    import * as commonTools     from '@/utils/admin/tools';
    import * as HYZXService     from '@/api/news';
    import * as NewsClassifyApi from '@/api/newsClassify';
    import Vue                  from 'vue';

    const selectData = {
        options:        [],
        newsClassifyId: null,
        placeholder:    '请选择新闻资讯分类',
    };
    let selectServiceData = Vue.observable(selectData);

    export default {
        name:       'HangYeZiXunConfig',
        components: {
            uploadFile,
            MtaStQuillEditor,
            mySelect,
        },
        provide:    {
            selectServiceData: selectServiceData,
        },
        computed:   {
            newsClassifyId() {
                return selectServiceData.newsClassifyId;
            },
        },
        data() {
            return {
                defaultValue: new Date(),
                configData:   {
                    content:        '',
                    intro:          '',
                    pic:            '',
                    startTime:      '',
                    newsClassifyId: '',
                    title:          '',
                    visits:         '',
                },
                configRules:  {
                    title:          [
                        { required: true, message: '标题不能为空', trigger: 'blur' },
                    ],
                    startTime:      [
                        { required: true, message: '开始时间不能为空', trigger: 'blur' },
                    ],
                    intro:          [
                        { required: true, message: '描述不能为空', trigger: 'blur' },
                    ],
                    pic:            [
                        { required: true, message: '图片不能为空', trigger: 'blur' },
                    ],
                    visits:         [
                        { required: true, message: '访问次数不能为空', trigger: 'blur' },
                    ],
                    content:        [
                        { required: true, message: '行业详情不能为空', trigger: 'blur' },
                    ],
                    newsClassifyId: [
                        { required: true, message: '请选择新闻分类', trigger: 'blur' },
                    ],
                },
                queryData:    null,
                userId:       null,
            };
        },
        methods:    {
            handleSelectDoChange(data) {
                console.log('change', data);
                this.configData.newsClassifyId = data;
            },
            back() {
                window.history.go(-1);
            },
            getImageUrl(data) {
                this.configData.pic = data;
            },
            syncValue(flg, content) {
                if (flg === '1') {
                    this.configData.content = content;
                }
            },
            handleSave(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.saveAddHangYeZiXun();
                    } else {
                        return false;
                    }
                });
            },
            handleAdd(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.addAddHangYeZiXun();
                    } else {
                        return false;
                    }
                });
            },
            initPageData(data) {
                selectServiceData.newsClassifyId = data.newsClassifyId;
                this.configData.newsClassifyId = data.newsClassifyId;
                this.$refs.editorQuill.setContent(data.content);
                this.configData.intro = data.intro;
                this.configData.pic = data.pic;
                this.configData.startTime = data.startTime;
                this.configData.title = data.title;
                this.configData.visits = data.visits;
            },
            async recoverPage() {

                const opt = {
                    iiId: this.queryData.iiId,
                };

                const loading = this.$loading({ background: 'rgba(0, 0, 0, 0.7)' });
                try {

                    // 新闻资讯分类
                    const { data: newsClassifyArr } = await NewsClassifyApi.getNewsClassifySearch();

                    selectServiceData.options = newsClassifyArr;

                    const res = await HYZXService.getNewsInfo(opt);
                    if (res.code === 0) {
                        this.initPageData(res.data);
                    }
                    loading.close();

                } catch (err) {
                    loading.close();
                }
            },
            async addAddHangYeZiXun() {
                const loading = this.$loading({ background: 'rgba(0, 0, 0, 0.7)' });
                try {
                    const res = await this.handleAddHangYeZiXun();
                    loading.close();
                    if (res.code === 0 && res.data) {
                        this.$message.success('新增成功');
                        this.back();
                    }
                } catch (e) {
                    loading.close();
                }
            },
            async saveAddHangYeZiXun() {
                const loading = this.$loading({ background: 'rgba(0, 0, 0, 0.7)' });
                try {
                    const res = await this.handleSaveHangYeZiXun();
                    loading.close();
                    if (res.code === 0 && res.data) {
                        this.$message.success('保存成功');
                        this.back();
                    }
                } catch (e) {
                    loading.close();
                }
            },
            getOptions() {
                return Object.assign({}, this.configData, { userId: this.userId });
            },
            handleAddHangYeZiXun() {
                const opt = this.getOptions();
                return HYZXService.getNewsAdd(opt);
            },
            handleSaveHangYeZiXun() {
                const opt = this.getOptions();
                const newOpt = Object.assign(opt, { iiId: this.queryData.iiId });
                return HYZXService.getNewsUpdate(newOpt);
            },
            async initPage() {
                // 新闻资讯分类
                const loading = this.$loading({ background: 'rgba(0, 0, 0, 0.7)' });
                try {
                    const { data: newsClassifyArr } = await NewsClassifyApi.getNewsClassifySearch();
                    selectServiceData.options = newsClassifyArr;
                    loading.close();
                } catch (e) {
                    loading.close();
                }

            },
            clearPageData() {
                selectServiceData.options = [];
                selectServiceData.newsClassifyId = null;
                this.$refs.HangYeZiXun.resetFields();
                this.$refs.editorQuill.setContent('');
            },
        },
        created() {
            this.queryData = this.$route.query;
            const userAuth = commonTools.getUserAuth();
            this.userId = userAuth && userAuth.userId;
        },
        mounted() {
            if (this.queryData.code === 'editor' && this.queryData.iiId) {
                this.recoverPage();
            } else {
                this.initPage();
            }
        },
        beforeDestroy() {
            this.clearPageData();
        },
    };
</script>

<style lang="scss" scoped>
    .admin-HangYeZiXunConfig {
        padding: 20px;

        .my-Config-top {
            display: flex;
            justify-content: flex-end;
            margin-bottom: 20px;
        }

        .my-Config-content {
            display: flex;
            justify-content: space-between;

            &-form {
                .form-timer {
                    .timer-wrap {
                        display: flex;
                        flex-direction: row;
                    }

                    .line {
                        margin: 0 5px;
                        width: 20px;
                        text-align: center;
                        box-sizing: border-box;
                    }
                }

                .el-form-item:nth-last-child(1) {
                    margin-bottom: 0;
                }
            }

            .my-Config-editor {
                flex: 1;
                margin-left: 30px;

                .admin-quill-editor {
                    height: 100%;

                    ::v-deep .quill-editor {
                        height: 100%;
                        display: flex;
                        flex-direction: column;
                        background: #FFF;
                    }
                }
            }
        }

        .my-Config-bottom {
            margin-top: 20px;
            text-align: center;
        }
    }
</style>