<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="服务区域" prop="projectScopeOrgName" label-width="150px">
                <el-input v-model.trim="formData.projectScopeOrgName" size="small" clearable placeholder="请输入服务区域" :disabled="true"
                   class="u-item-width-normal"></el-input>
             </el-form-item>
           </el-col>
             <el-col :span="12">
                 <el-form-item label="服务级别" prop="projectLevelName" label-width="150px">
                <el-input v-model.trim="formData.projectLevelName" size="small" clearable placeholder="请输入服务级别" :disabled="true"
                   class="u-item-width-normal">
                </el-input>
             </el-form-item>
                 </el-col>
                 <el-col :span="12">
                 <el-form-item label="发布单位" prop="publishUnitName" label-width="150px">
                <el-input v-model.trim="formData.publishUnitName" size="small" clearable placeholder="请输入活动名称"
                   class="u-item-width-normal"></el-input>
             </el-form-item>
                 </el-col>
                 <el-col :span="12">
                 <el-form-item label="名称" prop="projectTitle" label-width="150px">
                <el-input v-model.trim="formData.projectTitle" size="small" clearable placeholder="请输入活动名称"
                   class="u-item-width-normal"></el-input>
             </el-form-item>
                 </el-col>
                 <el-col :span="24">
                 <el-form-item label="项目介绍" prop="description" label-width="150px" style="display: block">
                         <div class="item_width_1">
                             <el-input type="textarea" autosize placeholder="请填写组织介绍" v-model.trim="formData.description" :autosize="{ minRows:4., maxRows: 10}" >
                         </el-input>
                         </div>
             </el-form-item>
            </el-col>
            <el-col :span="12">
             <el-form-item label="项目展示图" label-width="150px" prop="fileList">
                         <template>
                             <upload-image  :defaultFileList="fileList1" :limit="1" @change="onChangeFileList"
                                 @file-removed="removedImg"></upload-image>
                         </template>
             </el-form-item>
          </el-col>
                 <el-col :span="12">
             <el-form-item label="服务类型" label-width="150px" prop="serviceClasses">
                <el-select  multiple-limit=4 class="u-item-width-normal" v-model.trim="formData.serviceClasses" placeholder="请选择" clearable multiple>
                   <el-option v-for="item in ServicetypeListName" :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="招募截止时间" label-width="150px" prop="recruitDeadline">
            <el-date-picker v-model="formData.recruitDeadline" type="datetime" placeholder="请选择日期"   class="u-item-width-normal"
               format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss">
            </el-date-picker>
         </el-form-item>
            </el-col>
          <el-col :span="24">
                 <el-form-item label="招募要求" prop="recruitRequirement" label-width="150px" style="display: block">
                         <div class="item_width_1">
                             <el-input type="textarea" autosize placeholder="请填写组织介绍" v-model.trim="formData.recruitRequirement" :autosize="{ minRows:4., maxRows: 10}" >
                         </el-input>
                         </div>
             </el-form-item>
            </el-col>
            <el-col :span="24">
            <el-form-item label="服务期限" prop="serviceTimeFrom"   label-width="150px" >
              <el-date-picker v-model.trim="formData.serviceTimeFrom" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss" placeholder="开始时间" style="width:195px">
              </el-date-picker> <span style="margin: 0 10px">至</span>
              <el-date-picker v-model.trim="formData.serviceTimeTo" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss" placeholder="结束时间" style="width:195px" @change="actcontrolTime ">
              </el-date-picker>
            </el-form-item>
            
          </el-col>
          <el-col :span="24">
          <el-form-item  label="上线" style="display: block" prop="onlineStatus" label-width="150px">
              <el-switch v-model="formData.onlineStatus" :active-value=1 :inactive-value=0
              ></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"  type="primary"
             @click="handleComfirm">确 定</el-button>
 
       </div>
    </div>
 </template>
 
 
 <script>
 import { mapGetters } from 'vuex'
 import { Loading } from 'element-ui' // 引入Loading服务
 import { requestPost,requestGet } 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 {
            ServicetypeListName:[
          
          ],
            activityImgs: [],//活动照片
            fileList:[],
            searchValue:"",
            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:    
                {
                    projectScopeOrgId: "",//服务范围ID
                serviceTimeFrom: "",//服务时间
                serviceTimeTo: "",//服务时间
                onlineStatus: "",//上线状态
                serviceClasses: [],//服务类型
                recruitDeadline: "",//招募截止时间,
                recruitRequirement: "",//招募要求
                attachments: [
                    {
                        format: "png",
                        name: "banner.png",
                        type: "image",
                        url: "https://elink-esua-epdc.oss-cn-qingdao.aliyuncs.com/epmet-saas/dev/20240912/36cbe79b43cd45d381e3c8e4f92e1c3d.png"
                    }
                ],//附件
                description:"",//项目简介
                projectTitle:"",//项目标题
                projectLevel:'',//项目级别
                projectScopeOrgId:"",//服务范围ID
                publishUnitName:"",//发布单位名称
                },
                fileList1:[],
 
        
            corganizerList: [],
            uploadUrl: window.SITE_CONFIG['apiURL'] + '/oss/file/uploadqrcodeV2',
            customerId: localStorage.getItem('customerId'),
 
        }
        
    },
 
    components: { Tinymce, UploadImage },
    mounted() {
        console.log(this.VolunteerList,"this.VolunteerList");
        // this.formData = this.VolunteerList
        this.formData.agencyName=this.$store.state.user.agencyName
        if (this.$store.state.user.level=="district") {
            this.formData.Servicelevel="区级"
        }
        this.getDetail()
        this.volunteerservicetype()
    },
    watch: {
    fileList1: {
      handler(newValue, oldValue) {
        console.log('fileList changed:', newValue);
      },
      deep: true // 开启深度监听
    }
  },
 
    methods: {
             // 获取志愿组织服务类型
             volunteerservicetype() {
            console.log("skldfjlsdfjlksjfd");
            const url = "/sys/dict/data/dictlist"
            let params = {
                dictType: 'voluntary_project_service_class'
            }
            requestPost(url, params).then(res=>{
                console.log(res,"res");
                this.ServicetypeListName=res.data
            })
            // console.log(data,"sdlkfjlsdkf");
            
            // if (code === 0) {
            //     this.ServicetypeListName = data;
      
                
            // } else {
            //     this.$message.error(msg)
            // }
            console.log(this.ServicetypeListName,"  this.ServicetypeListName ");
        },
        //控制活动时间
        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;
            }
        },
 

        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,
                name: item.response.data.fileName,
                url: item.response.data.url,
                type: "image",
                format: item.raw.name.split('.').pop(),
            })) : []; // 当e为空时清空fileList
            if (e.length > 0) {
                this.formData.coverPic = e[0].response.data.url;
                console.log(this.fileList, 'sssssb');
                this.formData.attachments= this.fileList
             
                console.log(this.formData.attachments, 'sssssb');
                
            } else {
                this.formData.coverPic = '';
            }
        },
 
        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)
                })
            }
        },

        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 getDetail() {
            console.log("dsjfkcl");
            const url = "/voluntary/project/admin/detail"
            let params = {
                id: this.VolunteerList.id
            }
            const { data, code, msg } = await requestGet(url, params)
            if (code === 0) {
                this.formData = data
                console.log(this.formData,"lkjsdlkdcjkl");
                console.log(this.formData.attachments[0].url,"lkjsdlkdzxczccjk");
                this.fileList1.push({fileUrl:this.formData.attachments[0].url})
                // this.fileList.push(url)
                debugger
                console.log(this.fileList1,"lkjsdlkdzxczccfsdfdsjk");
                debugger
            } 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.agencyName) {
        //       this.$message.error('请选择所属组织');
        //       return;
        //    }
    
 
  
        //    if (!this.formData.Organizational) {
        //       this.$message.error('请填写项目介绍');
        //       return;
        //    }
 
        //    if (this.fileList.length === 0) {
        //       this.$message.error('请上传封面图片');
        //       return;
        //    }
 
        //    if (!this.formData.AdministratorIDCard) {
        //       this.$message.error('请输入身份证信息');
        //       return;
        //    }
 
        //    if (!this.formData.Administratorphone) {
        //       this.$message.error('请输入管理员电话');
        //       return;
        //    }
 
        //    if (!this.formData.AdministratorName) {
        //       this.$message.error('请输入管理员姓名');
        //       return;
        //    }
 
        //    if (!this.formData.Organizationaltype) {
        //       this.$message.error('请输入组织类型');
        //       return;
        //    }
 
        //    if (!this.formData.Servicetype) {
        //       this.$message.error('请输入服务类型');
        //       return;
        //    }
 
        //    if (!this.formData.OrganizationName) {
        //       this.$message.error('请填写发布单位');
        //       return;
        //    }
           console.log(this.formData,"this.formData");
           this.addActivity()
        },
        async addActivity() {
                let url = "/voluntary/project/admin/update"
                console.log(this.formData,"this.formData");
                let params = {
                    id:this.VolunteerList.id,
                    ...this.formData
             
                }
                const { data, code, msg } = await requestPost(url, params)
                if (code === 0) {
                    this.$message({
                        type: 'success',
                        message: '操作成功'
                    })
                    this.resetData()
                    this.$emit('showEditClose')
                    this.btnDisable = false
                } else {
                    this.btnDisable = false
                    this.$message.error(msg)
                }
            
 
 
        },
        handleCancle() {
             console.log("sdlkfjklsdf ");
            this.$emit('showEditClose')
 
        },
 
        // 地图初始化函数，本例取名为init，开发者可根据实际情况定义
        initMap(latitude, longitude) {
            console.log(latitude, longitude,"564564568");
            map = new daiMap(
                document.getElementById("app_activity"),
                { latitude, longitude },
                {
                    zoom: 16.2, // 设置地图缩放级别
                    pitch: 43.5, // 设置俯仰角
                    rotation: 45, // 设置地图旋转角度
                }
            );           
 
            // 监听地图平移结束
            /*  map.on("dragend", (e) => {
                this.handleMoveCenter(e);
              });*/
            map.on("click", (e) => {
                this.handleMoveCenter(e);
            });
 
            map.setCenter(latitude, longitude);
            map.setMarker(latitude, longitude);
 
        },
 
 
        async handleMoveCenter(e) {
            //修改地图中心点
            // const { lat, lng } = map.getCenter();
            const { lat, lng } = e.latLng;
            this.formData.latitude = lat;
            this.formData.longitude = lng;
            map.setMarker(lat, lng);
 
            let { msg, data } = await map.getAddress(lat, lng);
            if (msg == "success") {
                this.formData.address = data.address;
                this.searchValue=data.address
                console.log(this.formData.address," this.formData.address ");
                
                this.searchValue = data.address
                this.searchOptions = []
                // console.log('data,this.searchValue ', this.searchValue)
 
            }
        },
 
        async remoteMethod(query) {
            console.log(query, "sfsvsdv");
            if (query !== '') {
                this.loading = true;
                const { msg, data } = await map.searchNearby(query);
                this.loading = false;
                this.resultList = []
 
                if (msg == "success" && data.resultList && data.resultList.length > 0) {
 
                    if (data.resultList && data.resultList.length > 0) {
                        this.resultList = data.resultList
                        console.log(this.resultList, "this.resultList");
                        this.searchOptions = this.resultList.map(item => {
                            return { value: `${item.id}`, label: `${item.address + item.title}` };
 
                        });
                        console.log(this.searchOptions, "this.searchOptions");
                    }
                } else {
                    this.searchOptions = [
                        {
                            value: '0',
                            label: '未检索到结果'
                        }
                    ]
                }
            } else {
                this.searchOptions = [];
            }
        },
 
        handleClickKey(index) {
            let selPosition = this.resultList[index]
            let lonlat = selPosition.lonlat.split(" ")
            map.setCenter(lonlat[1], lonlat[0]);
            map.setMarker(lonlat[1], lonlat[0]);
            this.formData.latitude = lonlat[1];
            this.formData.longitude = lonlat[0];
            this.searchValue = selPosition.address + selPosition.name
        },

        // 开启加载动画
        startLoading() {
            loading = Loading.service({
                lock: true, // 是否锁定
                text: '正在加载……', // 加载中需要显示的文字
                background: 'rgba(0,0,0,.7)' // 背景颜色
            })
        },
        // 结束加载动画
        endLoading() {
            // clearTimeout(timer);
            if (loading) {
                loading.close()
            }
        }
    },
    computed: {
        dataRule() {
            return {
 
             OrganizationName: [
                    { required: true, message: '发布单位不能为空', trigger: 'blur' }
                ],
                Servicetype: [
                    { required: true, message: '请选择服务类型', trigger: 'blur' }
                ],
                Organizationaltype: [
                    { required: true, message: '请选择组织类型', trigger: 'blur' }
                ],
                AdministratorName: [
                    { required: true, message: '请输入管理员姓名', trigger: 'blur' }
                ],
                startTime: [
                    { required: true, message: '服务期限不能为空', trigger: 'blur' },
                ],
                Administratorphone: [
                    { required: true, message: '管理员电话不能为空不能为空', trigger: 'blur' },
                    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
                ],
                fileList: [
                    { required: true, message: '请上传组织封面图', trigger: 'blur' }
                ],
                Organizational: [
                    { required: true, message: '请填写项目介绍', trigger: 'blur' }
                ],
                zhaomu: [
                    { required: true, message: '请填写招募要求', trigger: 'blur' }
                ],
                expireTime: [
                    { required: true, message: '请选择招募截止时间', trigger: 'blur' }
                ],
                sumUp: [
                    { required: true, message: '请填写名称', trigger: 'blur' }
                ],
                activityImgs: [
                    { required: true, message: '请选择活动照片', trigger: 'blur' }
                ]
            }
        },
 
    },
    props: {
        VolunteerList: {
            type: Array,
            default: []
        },
    },
    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>