<template>
    <div  style="width: 100%;background: #fff;min-height: 700px;" class="userCenterAuthenticationPersonal">
        <div v-show="$i18n.locale == 'zh'" style="height: 80px;line-height: 80px;margin-top: 20px;margin: 0 20px; color: #666;font-size: 15px; border-bottom: 1px solid #bcbcbc;">
           添加资讯
            <!-- <span style="float: right;margin-top: 27px;"> <i class="el-icon-edit"></i> 修改</span> -->
        </div>     
        <div v-show="$i18n.locale == 'zh'" style="width: 600px;" >
            <el-form ref="form1" :model="cmsInformationView" label-width="160px" class="demo-ruleForm"  style="margin-top: 20px;width: 1200px;" :rules="chineseFormRules">
                  <el-form-item  label="资讯标题:" prop='title' >
                    <el-input v-model="cmsInformationView.title" placeholder="请输入资讯标题" :disabled="disableDet" style="width: 70%;"  maxlength="100" show-word-limit></el-input>
                  </el-form-item>
                  <el-form-item :required="true" label="资讯类型:" prop='typeDict'>
                    <el-select v-model="cmsInformationView.typeDict" placeholder="请选择资讯类型" :disabled="disableDet"  style="width: 30%;">
                        <el-option
                            v-for="item in typeDicts"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                            :disabled="disableDet">
                        </el-option>
                      </el-select>
                  </el-form-item>
                  <el-form-item  label="作者:" prop='auther' >
                    <el-input v-model="cmsInformationView.auther" :disabled="disableDet" placeholder="请输入作者" style="width: 70%;" maxlength="100" show-word-limit></el-input>
                  </el-form-item>
                  <el-form-item label="资讯来源:">
                    <el-select v-model="cmsInformationView.sourceDict" placeholder="请选择资讯来源" :disabled="disableDet"  style="width: 30%;">
                        <el-option
                            v-for="item in sourceDicts"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                            :disabled="disableDet">
                        </el-option>
                      </el-select>
                  </el-form-item>
                  <el-form-item  label="原文链接:" prop='sourceAddress'>
                    <el-input v-model="cmsInformationView.sourceAddress" placeholder="请输入原文链接" :disabled="disableDet" style="width: 70%;" maxlength="100" show-word-limit></el-input>
                  </el-form-item>
                  <el-form-item label="发布时间:">
                    <el-col :span="11">
                    <el-date-picker type="date" placeholder="选择日期" v-model="cmsInformationView.publishDate" :disabled="disableDet" style="width: 50%;"></el-date-picker>
                    </el-col>
                </el-form-item>
                  <el-form-item label="资讯内容:" prop='content'>
                    <el-input type="textarea" :rows="20" v-model="cmsInformationView.content" placeholder="请输入资讯内容" :disabled="disableDet"  style="width: 70%;min-height: 100px;" maxlength="10000" show-word-limit></el-input>
                  </el-form-item>
                  <!-- <el-form-item label="资讯附件:" style="width: 50%;">
                    <el-upload
                        class="upload-demo"
                        drag
                        action="/api/file/upload/attachment?module=cmsInformationInfo&attachmentBusinessType=cms_information_info"
                        :on-change="handleChange"
                        :on-success="handleAvatarSuccessAnnex"
                        :on-preview="handlePreview"
                        :headers="myHeaders"
                        :on-remove="handleRemove"
                        :before-upload="beforeUpload"
                        :file-list="fileList"
                        multiple>
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                        <div class="el-upload__tip" slot="tip">请上传zip,pdf,word,excel的附件！</div>
                        </el-upload>
                </el-form-item> -->

                 <el-form-item label="资讯图片:">
                    <el-upload
                        class="avatar-uploader"
                        action="/api/file/upload/attachment?module=cmsInformationInfo&attachmentBusinessType=cms_information_info"
                        :before-upload="beforeUploadCatalog"
                        :show-file-list="false"
                        :disabled="disableDet"
                        :on-success="photoSuccess"
                        :headers="myHeaders">
                        <img v-if="cmsInformationView.pictureUrl != ''" :src="'/api/file/pub/'+cmsInformationView.pictureUrl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        <div slot="tip" class="el-upload__tip" >{{$t('common.resourceHint')}}{{$t('common.resourceUploadJPGPNG')}}，{{$t('common.resourceFilesCannotExceed10Mb')}}，{{$t('common.resourceUploadOne')}}</div>
                    </el-upload>
                </el-form-item>
              </el-form>
        </div>
       
        <div v-show="$i18n.locale == 'zh'" style="height: 200px;">
            <div style="margin-top: 100px;">
                <el-button v-if="!disableDet" type="warning" style="margin-left: 300px;" @click="save('form1')">保存</el-button>
                <el-button v-if="!disableDet" type="primary" style="margin-left: 30px;" @click="close">关闭</el-button>       
                <el-button v-if="disableDet" type="primary" style="margin-left: 450px;" @click="close">关闭</el-button>       
            </div>
        </div>
        <div  v-if="dialogVisible && $i18n.locale == 'zh'">
            <userCenterAddTag v-bind:systemLabel="systemLabel" :mergeSelectedLabels="mergeSelectedLabels" @closeMain="closeMain"></userCenterAddTag>
        </div>

        <div v-show="$i18n.locale == 'en'" style="height: 80px;line-height: 80px;margin-top: 20px;margin: 0 20px; color: #666;font-size: 15px; border-bottom: 1px solid #bcbcbc;">
            Add Info Data
        </div>     
        <div v-show="$i18n.locale == 'en'" style="width: 600px;" >
             <el-form ref="form2" :model="cmsInformationView" label-width="160px" class="demo-ruleForm"  style="margin-top: 20px;width: 1200px;" :rules="englishFormRules">
                <el-form-item  label="Information Title:" prop='title'>
                    <el-input v-model="cmsInformationView.title" placeholder="Please enter the information title" :disabled="disableDet" style="width: 70%;" maxlength="100" show-word-limit></el-input>
                  </el-form-item>
                  <el-form-item :required="true" label="Information Type:" prop='typeDict'>
                    <el-select v-model="cmsInformationView.typeDict" placeholder="Please select a information type" :disabled="disableDet"  style="width: 30%;">
                        <el-option
                            v-for="item in typeDicts"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                            :disabled="false">
                        </el-option>
                      </el-select>
                  </el-form-item>
                  <el-form-item  label="Author:" prop='auther' >
                    <el-input v-model="cmsInformationView.auther" placeholder="Please enter the author" :disabled="disableDet" style="width: 70%;" maxlength="100" show-word-limit></el-input>
                  </el-form-item>
                  <el-form-item label="Source Dict:">
                    <el-select v-model="cmsInformationView.sourceDict" placeholder="Please select a source dict" :disabled="disableDet"  style="width: 30%;">
                        <el-option
                            v-for="item in sourceDicts"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                            :disabled="false">
                        </el-option>
                      </el-select>
                  </el-form-item>
                  <el-form-item  label="Original Link:" prop='sourceAddress'>
                    <el-input v-model="cmsInformationView.sourceAddress" placeholder="Please enter the original link" :disabled="disableDet" style="width: 70%;" maxlength="100" show-word-limit></el-input>
                  </el-form-item>
                  <el-form-item label="Release Time:">
                    <el-col :span="11">
                    <el-date-picker type="date" :disabled="disableDet" placeholder="Select a date" v-model="cmsInformationView.publishDate" style="width: 50%;"></el-date-picker>
                    </el-col>
                </el-form-item>
                  <el-form-item label="Information Content:" prop='content'>
                    <el-input type="textarea" :rows="20" v-model="cmsInformationView.content" placeholder="Please enter the information content" :disabled="disableDet" maxlength="10000" show-word-limit  style="width: 70%;min-height: 100px;"></el-input>
                  </el-form-item>
                  <!-- <el-form-item label="Information Attachment:" >
                    <el-upload
                        class="upload-demo"
                        drag
                        action="/api/file/upload/attachment?module=cmsInformationInfo&attachmentBusinessType=cms_information_info"
                        :on-change="handleChange"
                        :on-success="handleAvatarSuccessAnnex"
                        :on-preview="handlePreview"
                        :headers="myHeaders"
                        :on-remove="handleRemove"
                        :before-upload="beforeUpload"
                        :file-list="fileList"
                        multiple>
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">Drag the file here, or <em> click upload </em> </div>
                        <div class="el-upload__tip" slot="tip">Please upload the attachment of zip, PDF, word, excel!</div>
                        </el-upload>
                </el-form-item> -->
                <el-form-item label="Information Map:">
                    <el-upload
                        class="avatar-uploader"
                        action="/api/file/upload/attachment?module=cmsInformationInfo&attachmentBusinessType=cms_information_info"
                        :before-upload="beforeUploadCatalog"
                        :show-file-list="false"
                        :disabled="disableDet"
                        :on-success="photoSuccess"
                        :headers="myHeaders">
                    <img v-if="cmsInformationView.pictureUrl != ''" :src="'/api/file/pub/'+cmsInformationView.pictureUrl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        <div slot="tip" class="el-upload__tip" >{{$t('common.resourceHint')}}{{$t('common.resourceUploadJPGPNG')}}，{{$t('common.resourceFilesCannotExceed10Mb')}}，{{$t('common.resourceUploadOne')}}</div>
                     </el-upload>
                </el-form-item>
              </el-form>
        </div>
       
        <div v-show="$i18n.locale == 'en'" style="height: 200px;">
            <div style="margin-top: 100px;">
                <el-button v-if="!disableDet" type="warning" style="margin-left: 300px;" @click="save('form2')">Save</el-button>
                <el-button v-if="!disableDet" type="primary" style="margin-left: 30px;" @click="close">Close</el-button>
                <el-button v-if="disableDet" type="primary" style="margin-left: 450px;" @click="close">Close</el-button>
            </div>
        </div>
        <div v-if="dialogVisible && $i18n.locale == 'en'">
            <userCenterAddTag v-bind:systemLabel="systemLabel" :mergeSelectedLabels="mergeSelectedLabels" @closeMain="closeMain"></userCenterAddTag>
        </div>
    </div>

</template>
<script>
    import { regionDataPlus } from 'element-china-area-data'
    import ue  from '@/components/ue'
    import userCenterAddTag  from './userCenterAddTag'
    import Base from "@/views/base/Base";
    import { getDicts } from "@/api/dict";
    import { getTreeByLanguagePortal,getAllCountryAndCity } from "@/api/operation/baseCityInformationDict";
    import { saveOrUpdateByUserCenter , getInfoDataByUserCenter } from "@/api/cms/cmsInformationEntity";
    import { getToken ,resetToken} from '@/utils/auth';
    import { searchFiles }  from '@/api/file';

     export default {
        name: 'userCenteraddMaintenanceJournalInformations',
        extends: Base,
        components: {
            ue,userCenterAddTag
        },
        data () {
            return {
                placehoders:'Please select',
                textareaMessaage:
                    "",
                textareaMessaageEn:
                    "",
                fileList:[],
                myHeaders: {Authorization: ('Bearer ' +getToken())}, 
                 isCreateNewUser: [
                    { label: "是", value: "Y"},
                    { label: "否（只对合作组织公开）", value: "N" }
                ],
                isCreateNewUserEn: [
                    { label: "Yes", value: "Y"},
                    { label: "No (Visible only to GEIDCO)", value: "N" }
                ],
                informationsClass:'1',
                dialogVisible: false,
                ifDiaslog:'',
                title:'',
                options: regionDataPlus,
                selectedOptions: [],
                systemLabel:[],
                mergeSelectedLabels:[],
                cmsInformationView:{
                    pictureUrl:''
                },
                continentCountryDicts: [],
                unitCountryDicts: [],
                reserveOnes: [],
                technicalCategoriesDicts: [],
                technicalScopeDicts: [],
                phaseTypeDicts: [],
                languageDicts: [],
                imageUrl: '',
                form: {},
                files: [],
                imgList: [],
                path: "",
                typeDicts:[],
                approveStatusDicts:[],
                sourceDicts:[],
                entityId:this.$route.query.key,
                disableDet: this.$route.query.disableDet ? this.$route.query.disableDet : false,//详情传来参数不能修改页面值
            }
        },
        watch: {
            // "baseProjectView.continentCountry"() {
            //     this.continentCountryDicts.forEach((i) => {
            //         if (this.baseProjectView.continentCountry == i.value) {
            //         this.unitCountryDicts = i.data;
            //         }
            //     });
            // },
            // "baseProjectView.unitCountry"() {
            //     this.unitCountryDicts.forEach((i) => {
            //         if (this.baseProjectView.unitCountry == i.value) {
            //             this.reserveOnes= i.data;
            //         }
            //     })
            // },
            '$i18n.locale'(){
            this.initData();
            // this.getBaseProject();
            }
        },
        mounted() {
            this.initData();
        },
        computed:{
            englishFormRules(){
                  return{
                    title: [
                       { required: true, message: 'Please enter the information title', trigger: 'change' },
                    ],
                    typeDict: [
                        { required: true, message: 'Please select a information type', trigger: 'change' },
                    ],
                    auther: [
                        { required: true, message: 'Please enter the author', trigger: 'change' },
                    ],
                    // sourceDict: [
                    //     { required: true, message: 'Please Select Information Source', trigger: 'change' },
                    // ],
                    // sourceAddress: [
                    //    { required: true, message: 'Please Input Link Of Original Text', trigger: 'change' },
                    // ],
                    content: [
                       { required: true, message: 'Please enter the information content', trigger: 'change' },
                    ]
                }
            },
            chineseFormRules(){
                 return{
                    title: [
                       { required: true, message: '请输入资讯标题', trigger: 'blur' },
                    ],
                    typeDict: [
                        { required: true, message: '请选择资讯类型', trigger: 'blur' },
                    ],
                    auther: [
                        { required: true, message: '请输入作者', trigger: 'change' },
                    ],
                    // sourceDict: [
                    //     { required: true, message: '请选择资讯来源', trigger: 'change' },
                    // ],
                    // sourceAddress: [
                    //    { required: true, message: '请输入原文链接', trigger: 'change' },
                    // ],
                    content: [
                       { required: true, message: '请输入资讯内容', trigger: 'change' },
                    ]
                }
            },
        },
        methods:{
            searchFiles() { 
                var _that = this;
                 var file = {
                        attachmentBusinessId : _that.cmsInformationView.id,
                        attachmentBusinessType : "cms_information_info"
                        
                        }
                    _that.fileList = [];
                    searchFiles(file).then(result => {
                        result.data.attachmentInfos.forEach((i) => {
                            var fileTo = {
                                name : i.attachmentName,
                                url : i.attachmentSavePath,
                                uid : i.id
                                }
                                _that.fileList.push(fileTo);
                                _that.files.push(i.id)
                                console.log(_that.files+"_that.files")
                            
                        })  
                    })       
            },
            initData(){
                 if (this.entityId) {
                     var params = {
                         id : this.entityId
                     }
                    getInfoDataByUserCenter(params).then(result => {
                        this.cmsInformationView = result.data.cmsInformationView
                        this.searchFiles();
                    });  
                 }
                 if (this.$i18n.locale.toUpperCase() == 'ZH') {

                    getDicts(
                        "CMS_INFORMATION_TYPE_DICT,APPROVE_STATUS_DICT,DISPLAY_INFORMATION_SOURCE"
                    ).then(result => {
                        var data = result.data;
                        if (data) {
                        this.typeDicts = result.data[0] || [];
                        this.approveStatusDicts = result.data[1] || [];
                        this.sourceDicts = result.data[2] || [];
                        }
                    });   
                } 
                if (this.$i18n.locale.toUpperCase() == 'EN') {

                    getDicts(
                        "CMS_INFORMATION_TYPE_DICT_EN,APPROVE_STATUS_DICT,DISPLAY_INFORMATION_SOURCE_EN"
                    ).then(result => {
                        var data = result.data;
                        if (data) {
                        this.typeDicts = result.data[0] || [];
                        this.approveStatusDicts = result.data[1] || [];
                        this.sourceDicts = result.data[2] || [];
                        }
                    });   
                } 
            },
            // 下载文件方法file参数为已上传文件的信息，其实就是取得fileList里的值
            handlePreview(file, fileList) {
                document.location.href = 'http://localhost:8080/api/file/pub/'+file.url
            },
            handleRemove(file, fileList) {
                this.files.forEach((i) => {
                    if (i == file.uid) {
                        var index = this.files.indexOf(i);
                        this.files.splice(index, 1);
                    }
                })
            },
            handleAvatarSuccessAnnex(res, file) {
               this.files.push(res.data.attachmentId);
            },  
            beforeUploadCatalog(file) {},
            beforeUpload(file) {
                var FileExt = file.name.replace(/.+\./, "");
                if (['zip', 'pdf', 'doc', 'docx', 'excel', 'xls', 'xlsx'].indexOf(FileExt.toLowerCase()) === -1) {
                    if (this.$i18n.locale.toUpperCase() == 'ZH') {
                        this.$message({
                            type: 'warning',
                            message: '请上传zip,pdf,word,excel的附件！'
                        });
                    } else {
                        this.$message({
                            type: 'warning',
                            message: 'Please upload the attachment of zip, PDF, word and excel!'
                        });
                    }
                    this.fileList.splice(this.fileList.indexOf(file), 1)
                    return false;
                }
                this.isLt2k = file.size / 1024 / 1024 < 2 ? '1' : '0';
                if (this.isLt2k === '0') {
                    if (this.$i18n.locale.toUpperCase() == 'ZH') {
                        this.$message({
                        message: '上传文件大小不能超过2M!',
                        type: 'error'
                    });
                    } else {
                        this.$message({
                        message: 'Upload file size cannot exceed 2m!',
                        type: 'error'
                    });
                    }
                    this.fileList.splice(this.fileList.indexOf(file), 1)
                    return false;
                }
            },
            
            save: function (formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.cmsInformationView.updateDate = new Date();
                        this.cmsInformationView.approveStatusDict = "1";
                        this.cmsInformationView.editStatusDict = "1";
                        this.cmsInformationView.publishChannelDict = "1";//发布渠道
                        this.cmsInformationView.language = this.$i18n.locale.toUpperCase();
                        let token = getToken();
                        this.submitHandler(token => {
                            saveOrUpdateByUserCenter(
                                JSON.stringify(this.cmsInformationView),
                                JSON.stringify(Array.from(this.files)),
                                token
                            ).then(result => {
                                if (this.$i18n.locale.toUpperCase() == 'ZH') {
                                    alert("资讯信息保存成功");
                                } else {
                                    alert("Info Data saved successfully");
                                }
                                
                                this.baseProjectView = {};
                                this.$router.go(-1);//返回上一层
                            }).catch(error => {
                                // 此处你的业务代码
                                this.resetToken();
                            });
                        });
                    }else{
                        if (this.$i18n.locale.toUpperCase() == 'ZH') {
                            this.$notify.error({
                                title: '保存失败',
                                message: '请填写必填项'
                            });
                        } else {
                            this.$notify.error({
                                title: 'Error',
                                message: 'Please fill in the required fields'
                            });
                        }
                        return false;
                    }
                });
            },
            close(){
                this.$router.go(-1);
            },
            closeMain(val){
                this.mergeSelectedLabels = [];
                val.forEach((element,index) => {
                    this.mergeSelectedLabels.push(element.label)
                });
                this.systemLabel=val;
                this.cmsInformationView.projectLabel = JSON.stringify(this.mergeSelectedLabels).replace(/\[|]/g,'').replace(/\"/g, "");;
                this.dialogVisible=false;
            },
            goAithentication(num){
                this.$router.go(-1);//返回上一层
            },
            handleChange (file, fileList) {
                this.fileList = fileList.slice(-3);
            },
            photoSuccess(res, file) {
                this.cmsInformationView.pictureUrl = res.data.path
            }, 
            dialogVisibles(){
                this.dialogVisible=true
            },
        }
    }
</script>
<style scoped>
    .el-button {
        width: 200px;
        height: 45px;
    }
    .authenticationBox1 {
        margin-left: 35px;
        margin-right: 150px;
        height: 100px;
        border: 1px solid rgba(153, 153, 153, 1);
        border-radius: 10px;
        margin-top: 50px;
        position: relative;
    }
    .authenticationBox2 {
        margin: 50px 150px 0 35px;
         height: 100px;
         border: 1px solid rgba(153, 153, 153, 1);
         border-radius: 10px;
         position: relative;
    }
    .authenticationBox1:hover,
    .authenticationBox2:hover {
        border: 1px solid #ff8400;
    }
        .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    .userCenterAuthenticationPersonal>>>.el-upload {
        border: 1px solid rgba(204, 204, 204, 1);
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }
    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
     /deep/.el-textarea__inner {
        display: block;
        resize: vertical;
        padding: 5px 8px;
        line-height: 1.5;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
        width: 100%;
        font-size: inherit;
        color: #606266;
        background-color: #FFF;
        background-image: none;
        border: 1px solid #DCDFE6;
        border-radius: 4px;
        -webkit-transition: border-color .2s cubic-bezier(.645,.045,.355,1);
        transition: border-color .2s cubic-bezier(.645,.045,.355,1);
    }
</style>