<template>
    <div>

        <div class="dialog-h-content scroll-h">
            <el-form ref="ref_form" :inline="true" :model="formData" :rules="dataRule" :disabled="formType === 'detail'"
                class="form">
                <el-form-item label="活动类型" label-width="150px" prop="gridId">
                    <el-select class="item_width_1" v-model.trim="formData.gridId" placeholder="请选择" clearable>
                        <el-option v-for="item in typeList" :key="item.typeName" :label="item.typeName"
                            :value="item.typeName">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="活动名称" prop="activityName" label-width="150px">
                    <el-input v-model.trim="formData.activityName" size="small" clearable placeholder="请输入活动名称"
                        class="u-item-width-normal"></el-input>
                </el-form-item>

                <el-form-item label="活动时间" prop="timeRange" label-width="130px">
                    <el-date-picker v-model.trim="timeRange" size="small" style="width: 260px;" type="daterange"
                        value-format="yyyy-MM-dd HH:mm:ss" @change="handleTimeChange" range-separator="至"
                        start-placeholder="开始时间" end-placeholder="结束时间">
                    </el-date-picker>
                </el-form-item>

                <!-- <el-form-item label="协办方" prop="assistingParty" label-width="150px">
                    <el-cascader v-model.trim="formData.assistingParty" :options="corganizerList"
                        :props="{ label: 'label', value: 'name', multiple: true, emitPath: false }"
                        clearable collapse-tags size="small" class="u-item-width-normal"></el-cascader>
                </el-form-item> -->

                <el-form-item label="协办方" prop="assistingParty" label-width="150px">
                    <el-cascader v-model.trim="formData.assistingParty" :options="corganizerList"
                        :props="{ label: 'label', value: 'name'}" clearable collapse-tags size="small"
                        class="u-item-width-normal"></el-cascader>
                </el-form-item>

                <el-form-item label="活动封面图" label-width="140px" prop="fileList" >
                    <template>
                        <upload-image :defaultFileList="fileList" :limit="6" @change="onChangeFileList"></upload-image>
                    </template>
                </el-form-item>


                <el-form-item label="活动内容" prop="contentt" label-width="150px" style="display: block">
                    <div class="item_width_1">
                        <Tinymce class="tinymce_view " v-if="formType != 'detail'" v-model.trim="formData.content"
                            :height="250" placeholder="在这里输入文字" />
                        <p v-else class="text_p" v-html="formData.content"></p>
                    </div>
                </el-form-item>

                <el-form-item label="活动地点" prop="searchValue" label-width="150px" style="display: block">
                    <div style="width: 500px">
                        <el-select v-model.trim="searchValue" filterable style="width: 500px" remote
                            :reserve-keyword="true" placeholder="请输入关键词" :remote-method="remoteMethod"
                            :loading="loading">
                            <el-option v-for="(item, index) in searchOptions" @click.native="handleClickKey(index)"
                                :key="item.value" :label="item.label" :value="item.value">
                            </el-option>
                        </el-select>
                        <div id="app_activity" class="div_map"></div>
                    </div>
                </el-form-item>

                <el-form-item label="线上报名" style="display: block" prop="peopleCount" label-width="150px">
                    <el-switch v-model="formData.online" @change="handleOnlineRegistration"></el-switch>
                    <!-- <el-switch v-model="formData.isOn" active-text="已报名" inactive-text="未报名" @change="handleOnlineRegistration"></el-switch> -->
                </el-form-item>

                <div v-if="online">
                    <el-form-item label="报名截止时间" label-width="140px" prop="cutOffTime">
                        <el-date-picker v-model.trim="formData.cutOffTime" type="date" value-format="yyyy-MM-dd"
                            format="yyyy-MM-dd" placeholder="选择报名截止时间" style="width:280px">
                        </el-date-picker>
                    </el-form-item>

                    <el-form-item label="活动积分" label-width="140px" prop="points">
                        <el-input-number v-model="formData.points" @change="handleChange" :min="1" :max="10"
                            label="描述文字"></el-input-number>
                    </el-form-item>

                    <el-form-item label="活动人数" label-width="140px">
                        <el-input-number v-model="formData.participants" @change="handleChange" :min="1" :max="10"
                            label="描述文字"></el-input-number>
                    </el-form-item>

                    <el-form-item label="消息推送" label-width="140px">
                        <el-checkbox-group v-model="formData.sendMessage">
                            <el-checkbox label="是否通过公众号推送给社区居民"></el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                </div>





            </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 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() {
        let initFormData = () => {
            let _form = {
                // gridId: '',
                // serviceMatter: '',//服务事项
                // serviceMatterList: [],
                // unitId: '',//单位ID
                // unitIdList: [],
                // title: '',//活动标题
                // target: '',//活动目标
                // content: '',//活动内容
                // activityTime: '',//活动时间
                // peopleCount: 0,//服务人数
                // result: '', //活动结果
                // address: '', //详细地址
                // endDate: '',
                // longitude: this.$store.state.user.longitude, //经度
                // latitude: this.$store.state.user.latitude,//纬度

                id: "1790263323837440002",
                typeId: "1111111111",
                activityName: "",//活动名称
                status: 0,//状态
                assistingParty: "",//协办方
                startTime: "",//开始时间
                endTime: "",//结束时间
                coverPic: "",//封面图片地址
                content: "",//活动内容
                address: "",//地址
                online: 0,//开关
                cutOffTime: "",//截止时间
                points: 0,//积分
                participants: 1,//活动人数
                sendMessage: 0,//推送数
                sumUp: "",//活动总结
                activityImgs: [],//图片列表
                longitude: this.$store.state.user.longitude, //经度
                latitude: this.$store.state.user.latitude//纬度
            }

            return _form
        }
        return {
            fileList: [],//图片
            formType: 'add', //表单操作类型 add新增，edit编辑，detail详情
            searchOptions: [],
            searchValue: '',
            resultList: [],
            num: 0,
            loading: false,
            timeRange: [],
            online: false,

            btnDisable: false,

            keyWords: '',
            activityId: '',
            formData: initFormData(),
            serviceList: [],
            // gridList: [],
            agencyId: '',

            demandOptions: [],
            typeList: [],
            corganizerList: []

        }
    },
    components: { Tinymce, UploadImage },
    mounted() {
        this.activityType()
        this.listServerOrg()

    },

    methods: {
        async listServerOrg() {
            const url = "/actual/base/serviceitem/listServerOrgNewTask";
            let params = {
                serverOrgCategoryCode: "",
                serverOrgType: "party_unit",
                serverParentOrgCategoryCode: ""
            };

            let { data, code, msg } = await requestPost(url, params);
            if (code == 0) {
                this.corganizerList = data;
                // console.log("datadata",this.corganizerList)
            } else if (code >= 8000) {
                this.$message.error(msg);
            }
        },
        async activityType() {
            const url = "/actual/base/activityType/page"
            let params = {
                // agencyId: this.agencyId
                pageSize: 20,
                pageNo: 1,
                typeName: "",
                enabled: 0
            }
            const { data, code, msg } = await requestPost(url, params)
            if (code === 0) {
                this.typeList = data.list
            } else {
                this.$message.error(msg)
            }
        },

        handleOnlineRegistration(value) {
            console.log(value)
            if (value) {
                this.online = true;
            } else {
                this.online = false;
            }
        },

        onChangeFileList(e) {
            console.log('onChangeFileList', e)
            if (e.length > 0) {
                let item = e[0];
                let ob = {
                    fileType: '0',
                    fileUrl: item.response.data.url
                };
                this.formData.coverPic = [ob];
            }
        },

        handleChange(value) {
            console.log(value);
        },
        handleTimeChange(time) {
            if (time) {
                const startTimeArray = util.dateFormatter(time[0], 'date').split('-')
                const endTimeArray = util.dateFormatter(time[1], 'date').split('-')

                this.formData.startTime = startTimeArray[0] + '-' + startTimeArray[1] + '-' + startTimeArray[2] + ' 00:00:00'
                this.formData.endTime = endTimeArray[0] + '-' + endTimeArray[1] + '-' + endTimeArray[2] + ' 23:59:59'

                // 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.$refs.ref_form.resetFields();


            //获取服务事项
            await this.getDemandOptions()

            let { latitude, longitude } = this.$store.state.user;

            this.formType = type
            if (activityId) {
                this.activityId = activityId
                this.formData.id = activityId
                await this.loadFormData()
            } else {
                this.formData.latitude = latitude
                this.formData.longitude = longitude
            }
            this.$nextTick(() => {
                if (!map) {
                    this.initMap(this.formData.latitude, this.formData.longitude);
                } else {
                    map.setCenter(this.formData.latitude, this.formData.longitude);
                    map.setMarker(this.formData.latitude, this.formData.longitude);
                }
            })
            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 {
                        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;
            });
            // console.log('arrr-oppp', arr2)
            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
                console.log(this.formData.content)
                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:120px;'")
                    // let array=this.formData.content.split('<img')

                }
                console.log(this.formData.content)

            } else {
                this.$message.error(msg)
            }
        },

        async handleComfirm() {
            this.btnDisable = true
            setTimeout(() => {
                this.btnDisable = false
            }, 10000)
            this.$refs['ref_form'].validate((valid, messageObj) => {
                if (!valid) {
                    app.util.validateRule(messageObj)
                    this.btnDisable = false
                } else {
                    this.addActivity()
                }
            })
        },
        async addActivity() {
            let url = '/actual/base/communityActivity/save'
            const { data, code, msg } = await requestPost(url, this.formData)
            console.log("data/actual/base/communityActivity/save",data)
            if (code === 0) {
                this.$message({
                    type: 'success',
                    message: '操作成功'
                })
                this.resetData()
                this.$emit('dialogOk')
                this.btnDisable = false
            } else {
                this.btnDisable = false
                this.$message.error(msg)
            }

        },

        handleCancle() {

            this.resetData()
            this.$emit('dialogCancle')

        },

        // 地图初始化函数，本例取名为init，开发者可根据实际情况定义
        initMap(latitude, longitude) {

            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
                this.searchOptions = []

            }
        },

        async remoteMethod(query) {

            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
                        this.searchOptions = this.resultList.map(item => {
                            return { value: `${item.hotPointID}`, label: `${item.address + item.name}` };

                        });
                    }
                } 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.formData.address = selPosition.address + selPosition.name
        },

        resetData() {
            this.searchValue = ''
            this.searchOptions = []
            this.resultList = []
            this.activityId = ''
            this.keyWords = ''
            this.formData = {
                id: "1790263323837440002",
                typeId: "1111111111",
                activityName: "",//活动名称
                status: 0,//状态
                assistingParty: "",//协办方
                startTime: "",//开始时间
                endTime: "",//结束时间
                coverPic: "",//封面图片地址
                content: "",//活动内容
                address: "",//地址
                online: 0,//开关
                cutOffTime: "",//截止时间
                points: 0,//积分
                participants: 1,//活动人数
                sendMessage: 0,//推送数
                sumUp: "",//活动总结
                activityImgs: [],//图片列表
                longitude: this.$store.state.user.longitude, //经度
                latitude: this.$store.state.user.latitude//纬度
            }

        },
        // 开启加载动画
        startLoading() {
            loading = Loading.service({
                lock: true, // 是否锁定
                text: '正在加载……', // 加载中需要显示的文字
                background: 'rgba(0,0,0,.7)' // 背景颜色
            })
        },
        // 结束加载动画
        endLoading() {
            // clearTimeout(timer);
            if (loading) {
                loading.close()
            }
        }
    },
    computed: {
        dataRule() {
            return {
                activityName: [
                    { required: true, message: '活动名称不能为空', trigger: 'blur' }
                ],
                gridId:[
                    { required: true, message: '请选择活动类型', trigger: 'blur' }
                ],
                timeRange:[
                    { required: true, message: '请选择活动时间', trigger: 'blur' }
                ],
                fileList:[
                    { required: true, message: '请选择活动封面图', trigger: 'blur' }
                ],
                contentt: [
                    { required: true, message: '活动内容不能为空', trigger: 'blur' }
                ],
                searchValue: [
                    { required: true, message: '请选择活动地点', trigger: 'blur' }
                ],
                longitude: [
                    { required: true, message: '坐标不能为空', trigger: 'blur' }
                ],
                cutOffTime: [
                    { required: true, message: '请选择报名截止时间', trigger: 'blur' }
                ],
                points: [
                    { required: true, message: '请选择活动积分', trigger: 'blur' }
                ]
            }
        },

    },
    props: {

        unitList: {
            type: Array,
            default: []
        },
        gridList: {
            type: Array,
            default: []
        },


    }
}
</script>


<style lang="scss" scoped>
@import "@/assets/scss/modules/visual/communityManageForm.scss";
</style>
<style lang="scss" scoped>
.item_width_1 {
    width: 560px;

    /deep/.tox .tox-dialog {
        z-index: 20000;
    }
}

.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>