<template>
    <div>
 
       <div class="dialog-h-content scroll-h">
         
          <el-form ref="ref_form" :inline="true" :model="formData" :rules="dataRule" 
             class="form">
             <el-row>
            <el-col :span="12">
                <el-form-item label-width="150px" label="所属栏目" prop="columnId">
                        <el-select v-model="formData.columnId" placeholder="请选择" clearable>
                            <el-option v-for="item in optionstype" :key="item.value" :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
          </el-col>
          <el-col :span="12">
                 <el-form-item label="文章标题" prop="title" label-width="150px">
                <el-input v-model.trim="formData.title" size="small" clearable placeholder="请输入活动名称"
                   class="u-item-width-normal"></el-input>
             </el-form-item>
                 </el-col>
            <el-col :span="24">
             <el-form-item label="封面图片" label-width="150px" prop="fileList">
                         <template>
                             <upload-image :defaultFileList="fileList" :limit="1" @change="onChangeFileList"
                                 @file-removed="removedImg"></upload-image>
                         </template>
             </el-form-item>
          </el-col>
            <el-col :span="24">
            <el-form-item label="活动详情" prop="content" style="display: block"  label-width="150px"> 
              <div class="item_width_1">
                <Tinymce class="tinymce_view " v-model.trim="formData.content" :height="150" placeholder="请输入活动内容" />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
          <el-form-item  label="置顶
          " style="display: block" prop="peopleCount" label-width="150px">
              <el-switch v-model="formData.online" :active-value=1 :inactive-value=0
                @change="handleSwitchChange"></el-switch>
            </el-form-item>
        </el-col>
          </el-row></el-form>
       </div>
       <div class="div_btn">
          <el-button size="small" @click="handleCancle">取 消</el-button>
          <el-button size="small" v-if="formType != 'detail'" type="primary" :disabled="btnDisable"
             @click="handleComfirm">确 定</el-button>
 
       </div>
    </div>
 </template>
 
 <script>
 import { mapGetters } from 'vuex'
 import { Loading } from 'element-ui' // 引入Loading服务
 import { requestPost } from '@/js/dai/request'
 import Tinymce from '@c/tinymce2/index.vue'
 import daiMap from "@/utils/dai-map";
 import util from '@js/util.js';
 // import UploadImage from './upload-image.vue'
 import UploadImage from '@/views/modules/plugins/rent/upload-image.vue'
 
 var map
 var search
 var markers
 var infoWindowList
 var geocoder // 新建一个正逆地址解析类
 
 let loading // 加载动画
 export default {
    data() {
 
        return {
 
            activityImgs: [],//活动照片
            fileList:[],
            searchValue:"",
            optionstype: [
                    { value: 0, label: "消息发布" },
                    { value: 1, label: "志愿风采" },
            ],
            ServicetypeList:[
                { label: "敬老爱老", value: 1 },
                { label: "助残帮困", value: 2 },
                { label: "扶贫帮困", value: 3 },
                { label: "环保绿化", value: 4 },
                { label: "文化教育", value: 5 },
                { label: "扶贫帮困", value: 6 },
                { label: "其他", value: 7 },
            ],
            Organizationaltype:[
                { label: "社区", value: 1 },
                { label: "企业", value: 2 },
                { label: "学校", value: 3 },
            ],
            formData:    
                { 
                columnId:'',//栏目id
                coverImg:"",//封面图片
                title:"",//标题
                top:0,//置顶
                online:'',//是否上线
                releaseTime:"",//发布时间
                content:"",//内容

                },
 
            corganizerList: [],
            uploadUrl: window.SITE_CONFIG['apiURL'] + '/oss/file/uploadqrcodeV2',
            customerId: localStorage.getItem('customerId'),
 
        }
        
    },
 
    components: { Tinymce, UploadImage },
    mounted() {
        console.log(this.$store.state.user,"this.$store.state.user");
        
        this.formData.agencyName=this.$store.state.user.agencyName
        if (this.$store.state.user.level=="district") {
            this.formData.Servicelevel="区级"
            
        }
        this.activityType()
        this.listServerOrg()
    },
 
    methods: {
        //控制活动时间
        actcontrolTime() {
            console.log("dislfj");
            if (this.formData.startTime > this.formData.endTime) {
                this.$message.error('活动结束时间不能在活动开始时间之前');
                this.formData.endTime = ''
                return
            }
        },
        validateContent() {
      // 使用正则表达式去除HTML标签后检查内容
      const textContent = this.stripHtml(this.formData.sumUp);
      if (textContent.trim() === '') {
        this.formData.sumUp = null;
      }
    },
    stripHtml(html) {
      const div = document.createElement('div');
      div.innerHTML = html;
      return div.textContent || div.innerText || '';
    },
 
        // 上传成功
        handleImgSuccess(res, file, fileList) {
            if (res.code === 0 && res.msg === 'success') {
                let format = file.name.split('.').pop();
                let srcType = file.raw.type;
                let type = 'file';
                if (srcType.indexOf('image') != -1) {
                    type = 'image';
                } else if (srcType.indexOf('video') != -1) {
                    type = 'video';
                }
                // this.formData.activityImgs.push({
                //     format,
                //     name: file.name,
                //     size: file.size,
                //     type,
                //     url: res.data.url
                // });
                // console.log('this.formData.activityImgs',res.data.url)
                this.formData.activityImgs.push(res.data.url);
 
            } else {
                this.$message.error(res.msg);
            }
        },
        // 删除图片
        handleImgRemove(file) {
            console.log('handleImgRemove', file);
            if (file.response) {
                let index = this.formData.activityImgs.findIndex(item => item.url == file.response.data.url);
                this.formData.activityImgs.splice(index, 1);
            } else if (file.url) {
                let index = this.formData.activityImgs.findIndex(item => item.url == file.url);
                this.formData.activityImgs.splice(index, 1);
            }
        },
        // 图片预览
        handleImgPreview(file) {
            console.log(file);
            window.open(file.url || file.response.data.url);
        },
        // 文件数量超过限制
        handleImgExceed() {
            this.$message({
                type: 'warning',
                message: '文件数量最多不超过三个'
            });
        },
        // 上传前的验证
        beforeImgUpload(file) {
            const isLt1M = file.size / 1024 / 1024 < 10;
            const srcType = file.type;
            const format = file.name.split('.').pop();
            if (!isLt1M) {
                this.$message.error('上传文件大小不能超过 10MB!');
                return false;
            }
            if (srcType.indexOf('image') == -1) {
                this.$message.error('仅限图片格式');
                return false;
            }
            return true;
        },
 
        async activityType() {
            const url = "/actual/base/activityType/page"
            let params = {
                // agencyId: this.agencyId
                pageSize: 20,
                pageNo: 1,
                typeName: "",
                enabled: 1
            }
            const { data, code, msg } = await requestPost(url, params)
            if (code === 0) {
                this.typeList = data.list
            } else {
                this.$message.error(msg)
            }
            this.$nextTick(() => {
                if (!map) {
                    this.initMap(this.formData.latitude, this.formData.longitude);
                    console.log("map", map,this.formData.latitude, this.formData.longitude)
                } else {
                    map.setCenter(this.formData.latitude, this.formData.longitude);
                    map.setMarker(this.formData.latitude, this.formData.longitude);
                    console.log("mapmapmap", map)
                }
            })
        },
 
        handleOnlineRegistration(value) {
            // 
            if (value) {
                this.online = true;
                this.formData.online = 1;
            } else {
                this.online = false;
                this.formData.cutOffTime = ''
                this.formData.online = 0;
            }
        },
 
        // onChangeFileList(e) {
        //     if (e.length > 0) {
        //         let item = e[0];
        //         let ob = {
        //             fileType: '0',
        //             fileUrl: item.response.data.url
        //         };
        //         this.fileList = [ob];
        //         this.formData.coverPic = ob.fileUrl;
        //     }
        // },
        removedImg() {
            this.formData.coverPic = ''
        },
        onChangeFileList(e) {
            console.log(e, 'sssssb');
            this.fileList = e.length > 0 ? e.map(item => ({
                fileType: '0',
                fileUrl: item.response.data.url
            })) : []; // 当e为空时清空fileList
            if (e.length > 0) {
                this.formData.coverImg = e[0].response.data.url;
            } else {
                this.formData.coverImg = '';
            }
        },
 
        onChangeImgs(e, rowIndex = 0) {
            console.log('onChangeFileList', e)
            if (e.length > 0) {
                this.activityImgs = []
                e.forEach(item => {
                    let ob = {
                        fileType: '0',
                        fileUrl: item.response.data.url
                    }
                    this.activityImgs.push(ob)
                })
            }
        },
 
        // onChangeImgs(e) {
        //     this.activityImgs = [];
        //     if (e.length > 0) {
        //         e.forEach(item => {
        //             let ob = {
        //                 fileType: '0',
        //                 fileUrl: item.response.data.url
        //             };
        //             this.activityImgs.push(ob);
        //         });
        //         console.log('this.activityImgs',this.activityImgs)
        //     }
        // },
 
        handleChange(value) {},
        handleTimeChange(time) {
            if (time) {
                const startTimeArray = util.dateFormatter(time[0], 'time').split('-')
                console.log(startTimeArray);
                const endTimeArray = util.dateFormatter(time[1], 'time').split('-')
                console.log(endTimeArray);
                this.formData.startTime = startTimeArray[0] + '-' + startTimeArray[1] + '-' + startTimeArray[2] 
                this.formData.endTime = endTimeArray[0] + '-' + endTimeArray[1] + '-' + endTimeArray[2] 
                // this.startTimeShow = startTimeArray[0] + '年' + startTimeArray[1] + '月' + startTimeArray[2] + '日'
                // this.endTimeShow = endTimeArray[0] + '年' + endTimeArray[1] + '月' + endTimeArray[2] + '日'
            } else {
                this.formData.startTime = ''
                this.formData.endTime = ''
            }
 
        },
        async initForm(type, activityId) {
            this.startLoading()
            this.formType = type
            if (type === 'edit') {
                if (activityId.activityImgs || activityId.sumUp) {
                    this.records = true
                } else {
                    this.records = false
                }
                this.formData = activityId
                this.timeRange = [this.formData.startTime, this.formData.endTime]
                console.log(activityId,"activityId");
                
                if (activityId.coverPic) {
                    let ob = {
                        fileType: '0',
                        fileUrl: activityId.coverPic
                    };
                    this.fileList = [ob];
                    this.formData.coverPic = ob.fileUrl;
                    if (this.formData.online == 1) {
                        this.online = true
                    }
                }
            } else if (type === 'records') {
                this.records = true
            } else if (type === 'summary') {
                this.formData = activityId
                this.formData.activityImgs = []
                console.log("this.formData", this.formData)
                this.records = true
                this.summary = false
            } else {
                this.records = false
            }
            this.endLoading()
 
        },
 
        async getDemandOptions() {
            this.$http
                .post("/actual/base/serviceitem/listAllCategory")
                .then(({ data: res }) => {
                    if (res.code !== 0) {
                        return this.$message.error(res.msg);
                    } else {
                        console.log(res.data);
                        this.demandOptions = this.getFlagData(
                            this.getTreeData(res.data),
                            "usableFlag"
                        );
                    }
                })
                .catch(() => {
                    return this.$message.error("网络错误");
                });
        },
        getFlagData(data, flag) {
            if (!Array.isArray(data)) return [];
            let arr1 = data.filter((item) => item[flag]);
            let arr2 = arr1.map((item) => {
                if (item.childCateList)
                    return { ...item, childCateList: this.getFlagData(item.childCateList, flag) };
                else return item;
            });
            return arr2;
        },
        getTreeData(data) {
            if (!Array.isArray(data)) return [];
            let arr = data.map((item) => {
                let _item = {};
                if (item.childCateList) {
                    if (item.childCateList.length === 0)
                        _item = { ...item, childCateList: undefined };
                    else _item = { ...item, childCateList: this.getTreeData(item.childCateList) };
                } else {
                    _item = { ...item };
                }
                return _item;
            });
            return arr;
        },
        async loadGrid() {
            const url = "/gov/org/customergrid/gridoption"
 
            let params = {
                agencyId: this.agencyId
            }
 
            const { data, code, msg } = await requestPost(url, params)
 
            if (code === 0) {
                this.gridList = data
 
            } else {
                this.$message.error(msg)
            }
 
        },
 
 
        //加载组织
        async loadFormData() {
            const url = '/actual/base/icpartyactivity/detail'
            // const url = 'http://yapi.elinkservice.cn/mock/245/heart/icpartyactivity/detail'
            let params = {
                id: this.activityId
            }
 
            const { data, code, msg } = await requestPost(url, params)
 
            if (code === 0) {
                this.formData = data
                let style_img = "style='width:50px;height:40px;' "
 
                if (this.formData.content) {
                    // this.formData.content = this.formData.content.replace(/<img/g, "<img style='width:200px;height:240px;'")
                    // let array=this.formData.content.split('<img')
                }
 
            } else {
                this.$message.error(msg)
            }
        },
 
        async handleComfirm() {

            if (this.formData.columnId!=='0'||this.formData.columnId!=='1') {
              this.$message.error('请输入所属项目');
              return;
           }
           if (!this.formData.content) {
              this.$message.error('请输入活动详情');
              return;
           }
 
           if (!this.formData.coverImg) {
              this.$message.error('请上传封面图片');
              return;
           }
 
           if (!this.formData.title) {
              this.$message.error('请输入文章标题');
              return;
           }
 
           console.log(this.formData,"this.formData");
           this.addActivity()
        },
        async addActivity() {
                let url = '/voluntary/newsTrends/saveOrUpdate'
                const { data, code, msg } = await requestPost(url, this.formData)
                if (code === 0) {
                    this.$message({
                        type: 'success',
                        message: '操作成功'
                    })
                    this.resetData()
                    this.$emit('dialogOk')
                    this.btnDisable = false
                } else {
                    this.btnDisable = false
                    this.$message.error(msg)
                }
                console.log("sdlkfjklsdf ");
                this.$emit('showAddClose')
            },
            
 
 
        handleCancle() {
             console.log("sdlkfjklsdf ");
            this.$emit('showAddClose')
 
        },
 

        // 开启加载动画
        startLoading() {
            loading = Loading.service({
                lock: true, // 是否锁定
                text: '正在加载……', // 加载中需要显示的文字
                background: 'rgba(0,0,0,.7)' // 背景颜色
            })
        },
        // 结束加载动画
        endLoading() {
            // clearTimeout(timer);
            if (loading) {
                loading.close()
            }
        }
    },
    computed: {
        dataRule() {
            return {
                columnId: [
                    { required: true, message: '请选择所属栏目', trigger: 'blur' }
                ],
                content: [
                    { required: true, message: '活动详情不能为空', trigger: 'blur' }
                ],
                title: [
                    { required: true, message: '文章标题不能为空', trigger: 'blur' }
                ],
                fileList: [
                    { required: true, message: '请选择活动照片', trigger: 'blur' }
                ]
            }
        },
 
    },
    props: {
 
 
 
    },
    destroyed () {
     map = null
   }
 }
 </script>
 
 
 <style lang="scss" scoped>
 @import "@/assets/scss/modules/visual/communityManageForm.scss";
 </style>
 <style lang="scss" scoped>
 .item_width_1 {
    width: 634px;
 
    /deep/.tox .tox-dialog {
        z-index: 20000;
    }
 }
 .u-item-width-normal{
    width: 222px;
 }
 
 .tinymce_view {
    ::v-deep .tox .tox-dialog {
        z-index: 2000000000;
    }
 }
 
 .div_map {
    position: relative;
 }
 
 .div_searchmap {
    z-index: 5000;
    position: absolute;
    top: 5px;
    left: 5px;
 }
 
 .tinymce_view {
    height: 400px;
    overflow: auto;
 }
 
 .text_p {
    margin: 0;
    padding: 0 10px;
    border: 1px solid #d9d9d9;
    border-radius: 5px;
 
    >p {
        margin: 0;
    }
 }
 </style>