<template>
    <div class="eta-base-config">
        <el-form  :model="formData" :rules="rules" label-position="top" class="base-config-form"
            label-width="120px" ref="baseConfigForm">
            <div class="part-base part">
                <div class="side">
                    <el-form-item label="公司名称" prop="CompanyName">
                        <el-input type="text" v-model="formData.CompanyName" placeholder="请输入公司名称" />
                        <ConfigAnnotation picHintText="" picName="CompanyName" @showImage="previewImage"/>
                    </el-form-item>
                    <el-form-item label="公司水印" prop="CompanyWatermark" class="watermark">
                        <ImgUpload 
                            :imgUrl="formData.CompanyWatermark"
                            @showImage="showImage"
                            @upload="(file)=>handleUploadImage(file,'CompanyWatermark')"
                            @remove="deleteFormImg('CompanyWatermark')"
                            />
                        <!-- 后面可能会有新的选项 -->
                        <el-checkbox-group v-model="checkList" style="position: absolute;top: -40px;left: 100px;">
                            <el-checkbox label="研报图表"></el-checkbox>
                        </el-checkbox-group>
                        <ConfigAnnotation picName="CompanyWatermark" @showImage="previewImage"/>
                    </el-form-item>
                </div>
                <div class="side">
                    <el-form-item label="免责声明" prop="Disclaimer" class="disclaimer">
                        <div class="rich-editor-wrap">
                            <froala :id="`disclaimer-editor`"
                                :ref="`disclaimerEditor`" 
                                :tag="'textarea'" 
                                :config="disclaimerConfig" v-model="formData.Disclaimer">
                            </froala>
                        </div>
                        <ConfigAnnotation picHintText="" picName="Disclaimer" @showImage="previewImage"/>
                    </el-form-item>
                </div>
            </div>
            <div class="part-ppt part">
                <el-radio-group v-model="pptLang" style="margin-bottom: 22px;">
                    <el-radio-button label="cn">中文PPT</el-radio-button>
                    <el-radio-button label="en">英文PPT</el-radio-button>
                </el-radio-group>
                <div v-show="pptLang === 'cn'" class="ppt-form-item-wrap">
                    <el-form-item label="PPT封面图" prop="CnPptCoverImgs">
                        <div class="input-line" style="display:flex;">
                            <ImgUpload 
                                :imgUrl="formData.CnPptCoverImgs.length===3?formData.CnPptCoverImgs[2]:''"
                                @showImage="(arr)=>{showImageOrder({list:formData.CnPptCoverImgs,item:arr[0]})}"
                                @upload="(file)=>handleUploadImage(file,'CnPptCoverImgs')"
                                @remove="deleteFormImg('CnPptCoverImgs',formData.CnPptCoverImgs.length-1)"
                                />
                            <ImgThumbnail 
                                :imgList="formData.CnPptCoverImgs.length===3?formData.CnPptCoverImgs.slice(0,2):formData.CnPptCoverImgs"
                                @showImage="({item})=>{showImageOrder({list:formData.CnPptCoverImgs,item})}"
                                @deleteImg="(index)=>{deleteFormImg('CnPptCoverImgs',index)}"/>
                        </div>
                        <ConfigAnnotation picName="pptCoverList" @showImage="previewImage"
                            picHintText="上传格式：png、jpg，最多上传三张，建议图片比例：10:7 16:9 4:3"/>
                    </el-form-item>
                    <el-form-item label="PPT背景图" prop="CnPptBackgroundImg">
                        <ImgUpload 
                            :imgUrl="formData.CnPptBackgroundImg"
                            @showImage="showImage"
                            @upload="(file)=>handleUploadImage(file,'CnPptBackgroundImg')"
                            @remove="deleteFormImg('CnPptBackgroundImg')"
                            />
                        <ConfigAnnotation picName="pptBgPic" @showImage="previewImage"
                            picHintText="上传格式：png、jpg，建议图片比例：10:7 16:9 4:3"/>
                    </el-form-item>
                    <el-form-item label="PPT封底图" prop="CnPptBottomImg">
                        <ImgUpload 
                            :imgUrl="formData.CnPptBottomImg"
                            @showImage="showImage"
                            @upload="(file)=>handleUploadImage(file,'CnPptBottomImg')"
                            @remove="deleteFormImg('CnPptBottomImg')"
                            />
                        <ConfigAnnotation picName="pptBackPic" @showImage="previewImage"
                            picHintText="上传格式：png、jpg，建议图片比例：10:7 16:9 4:3"/>
                    </el-form-item>
                </div>
                <div v-show="pptLang === 'en'" class="ppt-form-item-wrap">
                    <el-form-item label="PPT封面图" prop="EnPptCoverImgs">
                        <div class="input-line" style="display:flex;">
                            <ImgUpload 
                                :imgUrl="formData.EnPptCoverImgs.length===3?formData.EnPptCoverImgs[2]:''"
                                @showImage="(arr)=>{showImageOrder({list:formData.EnPptCoverImgs,item:arr[0]})}"
                                @upload="(file)=>handleUploadImage(file,'EnPptCoverImgs')"
                                @remove="deleteFormImg('EnPptCoverImgs',formData.EnPptCoverImgs.length-1)"
                                />
                            <ImgThumbnail 
                                :imgList="formData.EnPptCoverImgs.length===3?formData.EnPptCoverImgs.slice(0,2):formData.EnPptCoverImgs"
                                @showImage="({item})=>{showImageOrder({list:formData.EnPptCoverImgs,item})}"
                                @deleteImg="(index)=>{deleteFormImg('EnPptCoverImgs',index)}"/>
                        </div>
                        <ConfigAnnotation picName="pptCoverList" @showImage="previewImage"
                            picHintText="上传格式：png、jpg，最多上传三张，建议图片比例：10:7 16:9 4:3"/>
                    </el-form-item>
                    <el-form-item label="PPT背景图" prop="EnPptBackgroundImg">
                        <ImgUpload 
                            :imgUrl="formData.EnPptBackgroundImg"
                            @showImage="showImage"
                            @upload="(file)=>handleUploadImage(file,'EnPptBackgroundImg')"
                            @remove="deleteFormImg('EnPptBackgroundImg')"
                            />
                        <ConfigAnnotation picName="pptBgPic" @showImage="previewImage"
                            picHintText="上传格式：png、jpg，建议图片比例：10:7 16:9 4:3"/>
                    </el-form-item>
                    <el-form-item label="PPT封底图" prop="EnPptBottomImg">
                        <ImgUpload 
                            :imgUrl="formData.EnPptBottomImg"
                            @showImage="showImage"
                            @upload="(file)=>handleUploadImage(file,'EnPptBottomImg')"
                            @remove="deleteFormImg('EnPptBottomImg')"
                            />
                        <ConfigAnnotation picName="pptBackPic" @showImage="previewImage"
                            picHintText="上传格式：png、jpg，建议图片比例：10:7 16:9 4:3"/>
                    </el-form-item>
                </div>
            </div>
            <div class="part-Iflytek part">
                <!-- 科大讯飞 -->
                <div style="width:100%;">
                    <span style="color:#606266;">科大讯飞服务</span> 
                    <el-switch v-model="Iflytek"></el-switch>
                </div>
                <template v-if="Iflytek">
                    <div class="side">
                        <el-form-item label="APPID" prop="XfAppid">
                            <el-input type="text" v-model="formData.XfAppid" placeholder="请输入APPID" />
                        </el-form-item>
                        <el-form-item label="APIKey" prop="XfApiKey">
                            <el-input type="text" v-model="formData.XfApiKey" placeholder="请输入APIKey" />
                        </el-form-item>
                    </div>
                    <div class="side">
                        <el-form-item label="APISecret" prop="XfApiSecret">
                            <el-input type="text" v-model="formData.XfApiSecret" placeholder="请输入APISecret" />
                        </el-form-item>
                        <el-form-item label="vcn(voice_name)" prop="XfVcn">
                            <el-input type="text" v-model="formData.XfVcn" placeholder="请输入voice_name" />
                        </el-form-item>
                    </div>
                </template>
            </div>
        </el-form>
        <div class="btn-wrap" style="text-align: center;">
            <el-button type="primary" plain style="width:200px;" @click="cancel">取消</el-button>
            <el-button type="primary"  style="margin-left:50px;width:200px;" @click="saveBaseConfig">保存</el-button>
        </div>
        <el-image-viewer 
            v-if="showViewer" 
            :on-close="()=>{this.picShowList=[];this.showViewer = false}" 
            :url-list="picShowList" />
    </div>
</template>

<script>
import ImgThumbnail from './components/imgThumbnail.vue';
import ImgUpload from './components/imgUpload.vue';
import ConfigAnnotation from './components/configAnnotation.vue';
import ElImageViewer from 'element-ui/packages/image/src/image-viewer';

import {bannerupload} from '@/api/api.js';
import {etaBaseConfigInterence} from '@/api/modules/etaBaseConfigApi.js';
export default {
    components: { ConfigAnnotation , ElImageViewer , ImgThumbnail , ImgUpload},
    data() {
        let ListValidator = (rule,value,callback)=>{
            if(!value.length){
                return callback(new Error('请至少选择一张封面图'))
            }else{
                return callback()
            }
        }
        return {
            /* base config */
            checkList:[],//水印应用
            Iflytek:false,//是否启用科大讯飞服务
            formData: {
                Disclaimer: '',//免责声明
                CompanyName:'',//公司名称
                CompanyWatermark:'',//公司水印
                WatermarkChart:0,//是否在研报图表中使用水印 0否 1是

                UseXf:0,//是否启用科大讯飞服务 0否 1是
                XfAppid:'',
                XfApiKey:'',
                XfApiSecret:'',
                XfVcn:'',

                CnPptCoverImgs:[],//ppt封面列表
                CnPptBackgroundImg:'',//ppt背景图
                CnPptBottomImg:'',//ppt封底图
                EnPptCoverImgs:[],//英文ppt封面列表
                EnPptBackgroundImg:'',//英文ppt背景图
                EnPptBottomImg:'',//英文ppt封底图

            },//表单预设值
            rules: {
                Disclaimer:[{ required: true, message: '请输入免责声明', trigger: 'blur' }],
                CompanyName:[{ required: true, message: '请输入公司名称', trigger: 'blur' }],
                //CompanyWatermark:[{ required: true, message: '请选择水印图片', trigger: 'blur' }],
                CnPptBackgroundImg:[{ required: true, message: '请选择中文PPT背景图', trigger: 'blur' }],
                EnPptBackgroundImg:[{ required: true, message: '请选择英文PPT背景图', trigger: 'blur' }],
                XfAppid:[{ required: true, message: '请输入APPID', trigger: 'blur' }],
                XfApiKey:[{ required: true, message: '请输入APIKey', trigger: 'blur' }],
                XfApiSecret:[{ required: true, message: '请输入APISecret', trigger: 'blur' }],
                XfVcn:[{ required: true, message: '请输入voice_name', trigger: 'blur' }],
                CnPptCoverImgs:[{ required: true, validator:ListValidator}],
                EnPptCoverImgs:[{ required: true, validator:ListValidator}],
            },//表单校验
            disclaimerConfig:{
                toolbarButtons:[
                    'textColor',
                    'bold',
                    'italic',
                    'underline',
                    'fontFamily',
                    'fontSize',
                    'align',
                    'outdent',
                    'indent',
                    'specialCharacters',
                    'insertHR',
                    'selectAll',
                    'clearFormatting',
                    'undo',
                    'redo',
                ],
                height:300,
                fontSizeDefaultSelection: "16",
                quickInsertEnabled: false,
                pasteAllowedStyleProps: ['font-family', 'font-size', 'color'],
                language: "zh_cn",
                placeholderText:'请输入免责声明',
                wordPasteKeepFormatting:false,
                pastePlain:true,
                wordPasteModal:false,
                pluginsEnabled:['colors'],//定义可用插件
            },//富文本编辑器配置项

            /* ppt config */
            pptLang:'cn',//切换中英文表单 
            CnPptCoverImgs:[],//中文封面列表
            EnPptCoverImgs:[],//英文封面列表

            /* image preview */
            showViewer:false,//控制图片预览组件展示
            picShowList:[],//ElImageViewer组件展示图片的列表
            picShowMap:{ //查看示意图需要展示的图片 支持多张
                'Disclaimer':[
                    require('@/assets/img/eta_base_config/disclaimer_1.jpg'),
                    require('@/assets/img/eta_base_config/disclaimer_2.jpg'),
                ],
                'CompanyName':[require('@/assets/img/eta_base_config/company_1.jpg')],
                'CompanyWatermark':[require('@/assets/img/eta_base_config/mark_1.jpg')],
                'pptCoverList':[require('@/assets/img/eta_base_config/ppt_cover.jpg')],
                'pptBgPic':[require('@/assets/img/eta_base_config/ppt_bgpic.jpg')],
                'pptBackPic':[require('@/assets/img/eta_base_config/ppt_back.jpg')]
            },
            /* loading */
            configLoading:null,

        };
    },
    methods: {
        handleUploadImage(file,key){
            /* console.log('type',key)
            console.log('file',file) */
            //如果是封面图
            if(['CnPptCoverImgs','EnPptCoverImgs'].includes(key)&&this.formData[key].length===3){
                this.$message.warning('封面图最多只能上传三张')
                return
            }
            //图片大小和格式限制
            const {size,type} = file.file
            const sizeLimit = key==='CompanyWatermark'?50*1024:500*1024
            if(!['image/png','image/jpeg'].includes(type)){
                this.$message.warning('仅支持png、jpg格式的图片')
                return
            }
            if(size>sizeLimit){
                this.$message.warning(`${key==='CompanyWatermark'?'水印图大小不能超过50kb':'ppt配图大小不能超过500kb'}`)
                return
            }
            
            let form = new FormData();
            form.append('file',file.file);
            bannerupload(form).then(res=>{
                if(res.Ret!==200) return 
                if(['CnPptCoverImgs','EnPptCoverImgs'].includes(key)){
                    this.formData[key].push(res.Data.ResourceUrl)
                }else{
                    this.formData[key] = res.Data.ResourceUrl
                }
            })
        },
        previewImage(picName){
            this.picShowList = this.picShowMap[picName]||[]
            this.picShowList.length&&(this.showViewer = true)
        },
        deleteFormImg(key,index){
            if(['CnPptCoverImgs','EnPptCoverImgs'].includes(key)){
                this.formData[key].splice(index,1)
            }else{
                this.formData[key] = ''
            }
        },
        showImage(imgList){
            this.picShowList = imgList||[]
            this.picShowList.length&&(this.showViewer = true)
        },
        showImageOrder({list,item}){
            //改变list的顺序,当前点击的为第一个
            const index = list.findIndex(img=>img===item)
            this.picShowList = [...list.slice(index),...list.slice(0,index)]
            this.picShowList.length&&(this.showViewer = true)
        },
        getBaseConfig(){
            this.configLoading = this.$loading({
                lock: true,
                target: '.eta-base-config',
                text: '正在获取基本配置...',
                spinner: 'el-icon-loading',
                background: 'rgba(255, 255, 255, 0.8)',
            });
            //获取WatermarkChart的值，赋值checkList
            //获取UseXf的值，赋值Iflytek
            etaBaseConfigInterence.getBaseConfig().then(res=>{
                if(res.Ret!==200) return 
                const {WatermarkChart,UseXf,CnPptCoverImgs,EnPptCoverImgs} = res.Data
                this.checkList = WatermarkChart==='true'?['研报图表']:[]
                this.Iflytek = UseXf==='true'?true:false
                if(res.Data){
                    this.formData = res.Data
                    this.formData.CnPptCoverImgs = CnPptCoverImgs.length?CnPptCoverImgs.split(','):[]
                    this.formData.EnPptCoverImgs = EnPptCoverImgs.length?EnPptCoverImgs.split(','):[]
                }
                this.configLoading&&this.configLoading.close()
            })
        },
        saveBaseConfig(){
            //froala 在非本地环境会有版权标识，在表单验证前去掉
            this.formData.Disclaimer = this.formData.Disclaimer.replace(/<p data-f-id=\"pbf\".*?<\/p>/g, "");
            //rules验证
            this.$refs.baseConfigForm.validate((valid,obj)=>{
                console.log('valid',valid)
                console.log('obj',obj)
                //如果是中英文ppt没填写，切换标签栏
                const keys = Object.keys(obj)
                const cnProps = ['CnPptCoverImgs','CnPptBackgroundImg','CnPptBottomImg']
                const enProps = ['EnPptCoverImgs','EnPptBackgroundImg','EnPptBottomImg']
                for(let i = 0;i < keys.length;i++){
                    if(cnProps.includes(keys[i])){
                        this.pptLang = 'cn'
                        break
                    }
                    if(enProps.includes(keys[i])){
                        this.pptLang = 'en'
                        break
                    }
                }
                if(valid){
                    this.formData.WatermarkChart = ''+(this.checkList.includes('研报图表')?true:false)
                    this.formData.UseXf = ''+(this.Iflytek?true:false)
                    const CnPptCoverImgs = this.formData.CnPptCoverImgs.join(',')
                    const EnPptCoverImgs = this.formData.EnPptCoverImgs.join(',')
                    etaBaseConfigInterence.saveBaseConfig({...this.formData,...{CnPptCoverImgs,EnPptCoverImgs}}).then(res=>{
                        if(res.Ret!==200) return 
                        this.$message.success('保存成功，请稍后到对应页面/项目查看')
                    })
                }
            })
        },
        cancel(){
            //取消就恢复原样
            this.getBaseConfig()
        }
    },
    mounted(){
        this.getBaseConfig()
    }
};
</script>

<style lang="scss">
.eta-base-config{
    .el-form-item{
        .el-form-item__content{line-height: normal;}
    }
}
</style>
<style scoped lang="scss">
.eta-base-config{
    box-sizing: border-box;
    padding:30px;
    border-radius: 4px;
    background-color: #fff;
    .base-config-form{
        .el-form-item{
            width:100%;
        }
        .part{
            display: flex;
            justify-content: space-between;
            flex-wrap: wrap;
            &:not(:last-child){
                border-bottom: 1px solid #DCDFE6;
            }
            &:not(:first-child){
                margin-top: 30px;
            }
            .side{
                width:45%;
            }
            .ppt-form-item-wrap{
                width:100%;
                display: flex;
                justify-content: space-between;
            }
        }
    }
}
</style>
