<template>
    <!-- <view> -->
        <!-- 顶部导航栏 -->
        <!-- <up-navbar leftText="" title="" :placeholder="true" :safeAreaInsetTop="true" @leftClick="leftClick"
            :bgColor="bgColor">
            <template #center>
                <div class="navbarcenter"><span>发布活动</span></div>
            </template>
        </up-navbar> -->
    <!-- </view> -->
    <view class="bgc"></view>
    <up-form :model="form" :rules="rules" ref="uFormRef">
        <view class="cardz">
            <view class="titleInfo">
                <up-form-item label="" prop="title" borderBottom>
                    <up-input placeholder="输入标题会更受欢迎奥~（5~20个字）" v-model="form.title" border="none" maxlength="20"
                        fontSize="34rpx" color="#333333" clearable
                        placeholderStyle="color: #c0c0c0;font-size: 34rpx;"></up-input>
                </up-form-item>
                <view class="xian"></view>
            </view>
            <view class="contentInfo">
                <up-form-item label="" prop="content" borderBottom>
                    <textarea class="text_style" v-model="form.content"
                        placeholder="输入你想发布的内容吧
图片精美、有看点的内容更容易获得推荐（最多发布9张照片）
安全指南：请勿发布带有个人信息（如：住址）" cols="50"
                        rows="10" maxlength="500"
                        placeholderStyle="color: #c0c0c0;font-size: 30rpx; white-space: pre-wrap;" color="#333333"
                        fontSize="30rpx" @linechange="inputtextInfo"></textarea>
                    <view class="char-count">{{ form.content.length }}/500</view>
                </up-form-item>
            </view>


            <up-form-item label="" prop="media" borderBottom>
                <view class="cardzfile">
                    <fileUpload v-model="form.media" :fileTypeInfo="fileTypeInfo1" :limit="9"></fileUpload>
                </view>
            </up-form-item>

        </view>
        <view class="cardx">
            <up-cell-group :border="false">
                <up-form-item label="" prop="startTime" borderBottom  @click="showTabs = !showTabs">
                    <view class="" style="margin-top: 2rpx;width: 100%;height: 30rpx;display: flex;align-items: center;">
						<view v-if="tabs.length == 0" class="flex alignCenter justifyCenter">
							<image  src="../../../static/images/icon/hua-1.png" style="width: 30rpx; height: 32rpx; margin-right: 12rpx;"></image>
							<text class="text-20">添加话题(最多可添加2条)</text>
							<!-- <up-input disabled disabledColor="#ffffff" color="#C9F6F5"
							    placeholder="添加话题(最多可添加2条)" placeholderStyle="color: #333333 !important;font-size: 30rpx;"
							    border="none">
							</up-input> -->
						</view>
						
						<view class="tabView flex alignCenter justifyCenter" v-if="tabs.length != 0" v-for="(item, index) in tabs" :key="index">
							<image src="../../../static/images/icon/hua-2.png" style="width: 30rpx; height: 32rpx; margin-right: 12rpx;"></image>
							<text class="tabText">{{dictTab(item)}}</text>
							<image src="../../../static/images/icon/tu3-5.png" @click.stop="delTabByTabIndex(index)" class="tabClosetIcon" mode=""></image>
						</view>
                        <up-icon style="margin-left: auto;" slot="right" name="arrow-right"></up-icon>
                    </view>
                </up-form-item>
                <up-form-item label="" prop="address" borderBottom @click="showaddres = !showaddres">
                    <view style="margin-top: 2rpx;width: 100%;height: 30rpx;display: flex;align-items: center;">
                        <image v-if="showtext3" :src="tu51" style="width: 30rpx; height: 32rpx;margin-right: 12rpx;">
                        </image>
                        <image v-else :src="tu512" style="width: 30rpx; height: 32rpx; margin-right: 12rpx;"></image>
                        <up-input v-model="form.address" disabledColor="#ffffff" color="#C9F6F5" @change="change1"
                            placeholder="添加定位" placeholderStyle="color: #333333 !important;font-size: 30rpx;"
                            border="none">
                            <span v-if="showtext2">添加定位</span>
                        </up-input>
                        <up-icon slot="right" name="arrow-right" @click="gotomap"></up-icon>
                    </view>
                </up-form-item>
            </up-cell-group>
        </view>
        <up-datetime-picker :show="showStartTime" v-model="newData" :modelValue="newData" @confirm="confirm1"
            format="YYYY-MM-DD HH:mm:ss" @cancel="cancel" mode="datetime"></up-datetime-picker>
        <up-datetime-picker :show="showEndTime" v-model="newData" @confirm="confirm2" :modelValue="newData"
            format="YYYY-MM-DD HH:mm:ss" @cancel="cancel" mode="datetime"></up-datetime-picker>
		<up-popup :round="20" :show="showTabs" @close="closeTabs" @open="openTabs"  mode="bottom">
			<view class="popup-11">
				<view class="view-11 flex alignCenter justifyBetween">
					<image class="image-11" src="../../../static/images/icon/tu3-5.png" @click="closeTabs"></image>
					<text class="text-11">选择话题</text>
					<text class="text-12" @click="confirmTabs">确认</text>
				</view>
				<!-- 搜索栏 -->
				<view class="sousuoBox1 flex alignCenter justifyBetween">
					<view class="sousuoBox flex alignCenter justifyBetween">
						<view class="souBOx flex alignCenter justifyBetween">
							<image src="../../../static/images/icon/tu2-2.png" class="img3"></image>
							<input v-model="keyword" @input="toContent" @confirm="onSearch" class="shuruText"
								:placeholder="placeholderText" type="text">
						</view>
						<!-- <image @click.stop="toScanCode" src="../../static/images/icon/tu2-3.png" class="img4"></image> -->
					</view>
					<view class="category-dropdown flex alignCenter">
						<text class="text1 flex alignCenter" @click="onSearch">搜索</text>
					</view>
				</view>
				<view v-for="(item, index) in filteredTabs" :key="index" class="view-12 flex alignCenter" @click="choiceTab(item)" :class="{ selected: isSelected(item.dictSort) }" >
					<image src="../../../static/images/icon/hua-1.png" style="width: 30rpx; height: 32rpx; margin-right: 12rpx; margin-left: 24rpx;"></image>
					<text class="text-13">{{item.dictLabel}}</text>
				</view>
			</view>
		</up-popup>
        <view class="cardxx">

            <view class="cardxx-btn" @click="publish">
                发布
            </view>
            <view class="cardxx-btn cgText" @click="draft">
                存草稿
            </view>
        </view>
    </up-form>
</template>

<script setup>
import { listInfo, getInfo, delInfo, addInfo, updateInfo } from "@/api/activityInfo/info";
import {
	listPost,
	getPost,
	delPost,
	addPost,
	addApp,
	addAppDraft,
	updatePost,
	updatePostApp,
	getLoginUserinfo
} from "@/api/talk/post";
import {
	getDicts
} from "@/api/system/dict/data";
import fileUpload from '@/pages/common/file/fileUpload'
import { onShow, onLoad } from '@dcloudio/uni-app'
import { ref, reactive, getCurrentInstance, computed, toRefs } from 'vue'
import { useStore } from 'vuex';
const { proxy } = getCurrentInstance();
const iconConfig = proxy.iconConfig;
const tu51 = iconConfig.tu51;
const tu512 = iconConfig.tu512;
const tu52 = iconConfig.tu52;
const tu522 = iconConfig.tu522;
const tu53 = iconConfig.tu53;
const tu532 = iconConfig.tu532;
const title = ref('')
const content = ref('');
const tabs = ref([]);
const choiceTabs = ref([]);
const data = reactive({
    form: {
		id: null,
        title: '',
        content: '',
        media: null,
        status: null,
        tab: null,
        address: null,
        longitude: null,
        latitude: null
    },
    rules: {
        title: [
            { required: true, message: '请输入话题标题', trigger: 'blur' },
            { min: 5, max: 20, message: '标题长度在 5 到 20 个字符', trigger: 'blur' }
        ],
        content: [],
        address: []
    }
});
const { form, rules } = toRefs(data);
const fileTypeInfo1 = ref('image')
const bgColor = ref('');
bgColor.value = 'rgba(170, 0, 0, 0)'
const showTabs = ref(false);
const showEndTime = ref(false);
const showaddres = ref(false);
const StartTime = ref('请选择活动开始时间');
const showtext1 = ref(true);
const showtext2 = ref(true);
const showtext3 = ref(true);
const showtabIcon = ref(true);
const EndTime = ref('请选择活动结束时间');
const newData = ref(new Date().getTime());
const timeFormat = uni.$u.timeFormat;
const dictPostTab = ref([])
const filteredTabs = ref([])
const placeholderText = ref('请输入需要搜索的话题')
const keyword = ref('');

// 字典
const dictTab = (tab) => {
	// console.log('dictPostTab',tab)
	const dict = dictPostTab.value.find((dict) => dict.dictValue == tab);
	return dict ? dict.dictLabel : '未知状态';
}

// 选择tab
const choiceTab = (item) => {
    const index = choiceTabs.value.indexOf(item.dictSort);
    if (index !== -1) {
        choiceTabs.value.splice(index, 1);
    } else if (choiceTabs.value.length < 2) {
        choiceTabs.value.push(item.dictSort);
    }
}

// 检查tab是否被选中
const isSelected = (dictValue) => {
  return choiceTabs.value.includes(dictValue);
}

// 确认tab
const confirmTabs = () => {
	tabs.value = [];
	tabs.value.push(...choiceTabs.value);
	closeTabs();
}

// 删除对应tab - 选择的
const delTabByIndex = (index) => {
	choiceTabs.value.splice(index, 1);
}

const delTabByTabIndex = (index) => {
	tabs.value.splice(index, 1);
}

// tab选择列表弹窗
function openTabs() {  
  choiceTabs.value = [];
  showTabs.value = true;  
}  
  
function closeTabs() {  
  keyword.value = '';
  filteredTabs.value = dictPostTab.value;
  showTabs.value = false;  
}  

// tab搜索功能
const onSearch = () => {
    const key = keyword.value.trim().toLowerCase();
    if (key === '') {
        // 如果关键字为空，则展示全部字典数据
        filteredTabs.value = dictPostTab.value;
    } else {
        // 根据关键字过滤字典数据
        filteredTabs.value = dictPostTab.value.filter(item =>
            item.dictLabel.toLowerCase().includes(key)
        );
    }
}

// 表单引用  
const uFormRef = ref(null);
const update1 = ref(false)
onLoad((options) => {
	const postInfoPublish = uni.getStorageSync('postInfoPublish');
	if (postInfoPublish != null) {
		form.value.id = postInfoPublish.id;
		form.value.title = postInfoPublish.title;
		form.value.content = postInfoPublish.content;
		form.value.media = postInfoPublish.media;
		let splitNumbers = postInfoPublish.tab.split(',');
		let numbers = splitNumbers.map(num => parseInt(num, 10));
		tabs.value = numbers
	}
	getDicts('post_tab').then(e => {
		dictPostTab.value = e.data;
		filteredTabs.value = e.data;
	})
    if(options.id != null){
        update1.value = true;
        console.log("xinxi1:",options.id);
        const _id = options.id;
    getInfo(_id).then(response => {
        form.value = response.data;
        console.log("actiInfo:", form.value);
    });
    }else{
        
    }
    
})

const leftClick = () => {
    proxy.$tab.navigateBack(1)
}

const draft = () => {
    form.value.auditStatus = "5"
    submitForm('draft');
    console.log("存草稿");
}

const publish = () => {
    form.value.auditStatus = "1"
    submitForm('publish');
    console.log("发布");
}
const change1 = (e) => {
    showtext3.value = false;

}
const inputtextInfo = (e) => {
    console.log("测试输入1：", e);

}
const gotomap = () => {
    proxy.$tab.navigateTo('/pages/activity/map')
}

const submitForm = (type) => {
    if (uFormRef.value) {
        uFormRef.value.validate().then(valid => {
			form.value.tab = tabs.value.join(',');
            if (valid) {
                proxy.$modal.loading('正在提交数据，请稍候...');
                // 提交表单数据
                if (type === 'publish') {
                    // 调用发布接口
                    if(update1.value){
                        updatePostApp(form.value).then(response => {
                        rotation(form.value.id);
                    });
                    }else{
                        addApp(form.value).then(response => {
                        rotation(response.data.id);
                    });
                    }
                    
                } else {
                    // 调用存草稿接口
					form.value.status = 5;
                    if(update1.value){
                        updatePost(form.value).then(response => {
                            proxy.$modal.closeLoading();
                            proxy.$modal.msgSuccess("存草稿成功");
                    });
                    }else{
                        addAppDraft(form.value).then(response => {
						if (response.data.id != null) {
							form.value.id = response.data.id;
							update1.value = true;
						}
                        proxy.$modal.closeLoading();
                        proxy.$modal.msgSuccess("存草稿成功");
                    });
                    }
                    
                }
            } else {
                console.log('表单验证失败');
            }
        }).catch(error => {
            console.log('表单验证错误:', error);
        });
    } else {
        console.log('表单引用未定义');
    }
}
//轮训
const rotation = (id) => {
    setTimeout(() => {
		//获取： 0正常 1待脱敏 2待审核 3脱敏未通过 4审核未通过 5草稿
        getPost(id).then(response => {
            console.log("轮训数据：",response.data);
            if (response.data.status === 4) {
                proxy.$modal.closeLoading();
                proxy.$modal.msgError("审核失败");
                proxy.$tab.navigateTo('/pages/common/talkState/auditFailure')
            }else if(response.data.status === 3 ||response.data.status === 2){
                proxy.$modal.closeLoading();
                proxy.$modal.msgSuccess("审核中~");
                proxy.$tab.navigateTo('/pages/common/talkState/audit')
            }else if(response.data.status === 0){
                proxy.$modal.closeLoading();
                proxy.$modal.msgSuccess("发布成功");
                proxy.$tab.navigateTo('/pages/common/talkState/publish')
            }

            else {
                rotation(id);
            }
        });
    }, 1000);
}



const startTime = (e) => {
    showStartTime.value = !showStartTime.value
}

const confirm1 = (e) => {
    showtext1.value = false;
    StartTime.value = e.value
    form.value.startTime = timeFormat(e.value, 'yyyy-mm-dd hh:MM:ss');
    showStartTime.value = !showStartTime.value
}

const confirm2 = (e) => {
    showtext2.value = false;
    EndTime.value = e.value
    form.value.endTime = timeFormat(e.value, 'yyyy-mm-dd hh:MM:ss');
    showEndTime.value = !showEndTime.value
}

const cancel = (e) => {
    showStartTime.value = false;
    showEndTime.value = false;
}
</script>
<style lang="scss">
page {
    background-color: #FFFFFF;
}

.navbarcenter {
    font-weight: 400;
    font-size: 36rpx;
    text-align: left;
    color: #000000;
}

.bgc {
    width: 100%;
    height: 500rpx;
    background: linear-gradient(-180deg, #c9f6f5, #ffffff);
    position: fixed;
    top: 0rpx;
    left: 0rpx;

}

.cardz {
    margin-left: 32rpx;
    margin-right: 32rpx;

    .titleInfo {
        margin-top: 40rpx;

        .xian {
            margin-top: 32rpx;
            height: 2rpx;
            border-radius: 1rpx 1rpx 1rpx 1rpx;
            background: #ffffff;
        }
    }

    .contentInfo {
        margin-top: 46rpx;

        .text_style {
            white-space: pre-wrap;
            width: 100%;
            overflow: auto;


            font-weight: 400;
            font-size: 30rpx;
            line-height: 46rpx;
        }

        .char-count {
            z-index: 1;
            text-align: right;
            font-size: 24rpx;
            color: #999999;
        }
    }

    .cardzfile {
        background-color: #FFFFFF;
    }
}

.cardx {
    background-color: #FFFFFF;
    padding-top: 72rpx;
    margin-left: 32rpx;
    margin-right: 32rpx;

    .c1 {
        margin-top: 2rpx;
        width: 100%;
        height: 102rpx;
        display: flex;
        align-items: center;
    }
}

.cardxx {
    display: flex;
    margin-left: 32rpx;
    margin-right: 32rpx;
    margin-top: 80rpx;
    justify-content: space-between;
    padding-bottom: 32rpx;

    .cardxx-btn {
        width: 330rpx;
        height: 80rpx;
        border-radius: 40rpx 40rpx 40rpx 40rpx;
        background: #c9f6f5;
        font-size: 30rpx;
        font-weight: bold;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #FBFBFB;
    }

    .cgText {
        background-color: #F8F8E3;
        color: #999999;
    }
}

.text2 {
    margin-left: 12rpx;
    font-weight: 400;
    font-size: 30rpx;
    text-align: left;
    color: #C9F6F5 !important;
}

.btnInfo1 {
    width: 330rpx !important;
    height: 80rpx !important;
}

.tabText{
	font-weight: 400;
	font-size: 30rpx;
	color: #C9F5F6;
}

.tabClosetIcon {
	width: 30rpx;
	height: 30rpx;
	margin-left: 16rpx;
}

.tabView {
	margin-right: 32rpx;
}

.popup-11 {
	padding: 0 32rpx;	
	height: 812rpx;
	background: #ffffff;
	border-radius: 32rpx 32rpx 0 0;
}

.view-11 {
	padding: 38rpx 0;
}

.image-11 {
	width: 47rpx;
	height: 47rpx;
}

.text-11 {
	font-weight: 400;
	font-size: 34rpx;
	color: #000000;
}

.text-12 {
	font-weight: 400;
	font-size: 30rpx;
	color: #000000;
}

.sousuoBox1 {
		margin-bottom: 32rpx;
		// width: auto;
	}

	.sousuoBox {
		width: 580rpx;
		height: 60rpx;
		border: #F4F5F6 solid 2rpx;
		border-radius: 30rpx 30rpx 30rpx 30rpx;
		background: #ffffff80;
	}

	.souBOx {
		margin-left: 32rpx;
	}

	.img3 {
		width: 36rpx;
		height: 36rpx;
	}

	.img4 {
		width: 36rpx;
		height: 36rpx;
		margin-right: 16rpx;
	}

	.category-dropdown {
		margin-left: 42rpx;
	}

	.text1 {
		font-weight: 400;
		width: 62rpx;
		font-size: 30rpx;
		text-align: left;
		color: #1B1B1B;
	}

	.img5 {
		width: 26rpx;
		height: 26rpx;
	}
	
	.shuruText {
		font-weight: 400;
		font-size: 28rpx;
		text-align: left;
		margin-left: 18rpx;
		color: #333333;
		flex-grow: 1;
		/* 让输入框占据剩余空间 */
		width: 380rpx;
	}
	
	.text-13 {
		font-weight: 400;
		font-size: 30rpx;
		color: #000000;
	}
	
	.view-12 {
		width: 686rpx;
		height: 78rpx;
		border-radius: 12rpx 12rpx 12rpx 12rpx;
		margin-bottom: 8rpx;
		// background: #c9f6f5;
	}
	
	.selected {
		width: 686rpx;
		height: 78rpx;
		border-radius: 12rpx 12rpx 12rpx 12rpx;
		background: #c9f6f5;
	}
	
	.text-20 {
		font-weight: 400;
		font-size: 30rpx;
		color: #333333;
	}
</style>
