<template>
    <div>
        <!-- <el-tabs v-if="!isEdit" v-model="ruleForm.type" class="demo-tabs" @tab-change="handleChange">

            <el-tab-pane v-for="item in materialTypes" :label="item.label" :key="item.value" :name="item.value">

            </el-tab-pane>
        </el-tabs> -->
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules">
            <el-form-item label="标题" prop="title">
                <el-input placeholder="请输入标题" v-model="ruleForm.title"></el-input>
            </el-form-item>
            <el-form-item label="描述" prop="description">
                <el-input type="textarea" placeholder="请输入描述" v-model="ruleForm.description"></el-input>
            </el-form-item>
            <!-- 文本 -->
            <el-form-item label="内容" prop="content.message" v-if="ruleForm.type == 1" :rules="{
                required: true,
                message: '请输入文本内容',
                trigger: 'blur',
            }">
                <el-input type="textarea" placeholder="请输入文本内容" v-model="ruleForm.content.message"></el-input>
                <V3Emoji @click-emoji="onEmojiSelect" :recent="true"></V3Emoji>
            </el-form-item>
            <!-- 图片 -->
            <el-form-item label="图片" prop="content.img_url" v-if="ruleForm.type == 2" :rules="{
                required: true,
                message: '请上传图片',
                trigger: 'change',
            }">
                <Upload v-model="ruleForm.content.img_url" type="image" accept="image/*" :action="robotHost"
                @change="changeFile"
                @success="uploadSuccess" @error="uploadError"></Upload>
            </el-form-item>
            <!-- 卡片 -->
            <el-form-item label="名片" prop="content.card_user_id" v-if="ruleForm.type == 9" :rules="{
                required: true,
                message: '请选择名片',
                trigger: 'change',
            }">
                <el-select-v2 v-model="ruleForm.content.card_user_id" popper-class="costom-select" :options="cardList"
                    placeholder="请选择名片" style="width: 500px" :props="v2props" @change="changeCard" filterable>
                    <template #default="{ item }">
                        <div class="costom-select-item">
                            <el-image :src="item.avatar"></el-image>
                            <span>{{ item.nickname }}</span>
                        </div>
                    </template>
                    <template #footer v-if="cardTotal > 100">
                        <el-pagination v-model:current-page="cardPage" :page-size="100" size="small" background
                            layout="prev, pager, next" :total="cardTotal" class="mt-4"
                            @current-change="currentChange" />
                    </template>
                </el-select-v2>
                <el-input style="width: 0;height: 0;" v-model="ruleForm.content.card_user_name"></el-input>

            </el-form-item>

            <!-- 链接 -->
            <template v-if="ruleForm.type == 7">
                <el-form-item label="链接标题" prop="content.title" :rules="{
                    required: true,
                    message: '请输入链接标题',
                    trigger: 'blur',
                }">
                    <el-input type="text" v-model="ruleForm.content.title" placeholder="请输入链接标题" />
                </el-form-item>
                <el-form-item label="链接内容" prop="content.content" :rules="{
                    required: true,
                    message: '请输入链接内容',
                    trigger: 'blur',
                }">
                    <el-input type="textarea" row="3" v-model="ruleForm.content.content" placeholder="请输入链接内容" />
                </el-form-item>
                <el-form-item label="链接图片" prop="content.img_url" :rules="{
                    required: true,
                    message: '请上传图片',
                    trigger: 'change',
                }">
                    <Upload v-model="ruleForm.content.img_url" type="image" accept="image/*" :action="robotHost"
                    @change="changeFile"
                    @success="uploadSuccess" @error="uploadError">
                    </Upload>

                </el-form-item>
                <el-form-item label="链接链接地址" prop="content.url" :rules="{
                    required: true,
                    message: '请输入链接地址',
                    trigger: 'blur',
                }">
                    <el-input type="text" v-model="ruleForm.content.url" placeholder="请输入链接地址" />
                </el-form-item>
            </template>
            <!-- 位置 -->
            <div v-if="ruleForm.type == '6'">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="所在地区" prop="content.address" :rules="{
                            required: true,
                            message: '请输入地区',
                            trigger: 'blur',
                        }">
                            <el-input id="mapInput" type="text" v-model="ruleForm.content.address"
                                placeholder="请输入地区" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="详细地址" prop="content.detailed_address" :rules="{
                            required: true,
                            message: '请输入详细地址门牌号等',
                            trigger: 'blur',
                        }">
                            <el-input type="text" v-model="ruleForm.content.detailed_address"
                                placeholder="请输入详细地址门牌号等" />
                        </el-form-item>
                    </el-col>
                </el-row>


                <div id="mapContainer" style="height: 360px; margin-bottom: 20px;"></div>
            </div>
            <!-- 小程序 -->
            <template v-if="ruleForm.type == 5">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="app_id" prop="content.app_id" :rules="{
                            required: true,
                            message: '请输入app_id',
                            trigger: 'blur',
                        }">
                            <p class="tip">请在企业微信手机客户端将小程序发送给自己，即可获取。</p>
                            <el-select v-model="ruleForm.content.msg_id" @change="changeAppId" placeholder="请选择"
                                style="width: 80%; margin-right: 12px;">
                                <el-option v-for="item in appList" :key="item.msg_id" :label="item.des"
                                    :value="item.msg_id">
                                </el-option>
                            </el-select>
                            <el-button type="primary" @click="getAppList">刷新</el-button>
                            <!-- <el-input type="text" v-model="ruleForm.content.app_id" placeholder="请输入app_id" /> -->
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="page_path" prop="content.page_path" :rules="{
                            required: true,
                            message: '请输入page_path',
                            trigger: 'blur',
                        }">
                            <el-input type="text" v-model="ruleForm.content.page_path" placeholder="请输入page_path" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="des" prop="content.des" :rules="{
                            required: true,
                            message: '请输入des',
                            trigger: 'blur',
                        }">
                            <el-input type="text" v-model="ruleForm.content.des" placeholder="请输入des" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="head_img_url" prop="content.head_img_url" :rules="{
                            required: true,
                            message: '请输入head_img_url',
                            trigger: 'blur',
                        }">
                            <el-input type="text" v-model="ruleForm.content.head_img_url"
                                placeholder="请输入head_img_url" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="size" prop="content.size" :rules="{
                            required: true,
                            message: '请输入size',
                            trigger: 'blur',
                        }">
                            <el-input type="text" v-model="ruleForm.content.size" placeholder="请输入size" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="thumb_aes_key" prop="content.thumb_aes_key" :rules="{
                            required: true,
                            message: '请输入thumb_aes_key',
                            trigger: 'blur',
                        }">
                            <el-input type="text" v-model="ruleForm.content.thumb_aes_key"
                                placeholder="请输入thumb_aes_key" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="thumb_file_id" prop="content.thumb_file_id" :rules="{
                            required: true,
                            message: '请输入thumb_file_id',
                            trigger: 'blur',
                        }">
                            <el-input type="text" v-model="ruleForm.content.thumb_file_id"
                                placeholder="请输入thumb_file_id" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="thumb_md5" prop="content.thumb_md5" :rules="{
                            required: true,
                            message: '请输入thumb_md5',
                            trigger: 'blur',
                        }">
                            <el-input type="text" v-model="ruleForm.content.thumb_md5" placeholder="请输入thumb_md5" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="title" prop="content.title" :rules="{
                            required: true,
                            message: '请输入title',
                            trigger: 'blur',
                        }">
                            <el-input type="text" v-model="ruleForm.content.title" placeholder="请输入title" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="wechat_id" prop="content.wechat_id" :rules="{
                            required: true,
                            message: '请输入wechat_id',
                            trigger: 'blur',
                        }">
                            <el-input type="text" v-model="ruleForm.content.wechat_id" placeholder="请输入wechat_id" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </template>

            <!-- 视频 -->
            <template v-if="ruleForm.type == 4">
                <el-form-item label="视频文件" prop="content.file_url" :rules="{
                    required: true,
                    message: '请上传视频文件',
                    trigger: 'change',
                }">
                    <div>
                        <Upload v-model="ruleForm.content.file_url" type="button" accept="video/*" :action="robotHost"
                        @change="changeFile"
                        @success="uploadSuccess" @error="uploadError">
                        </Upload>
                        <p style="margin-top: 10px;">{{ ruleForm.content.file_name }}</p>
                    </div>
                </el-form-item>

            </template>
            <!-- GIF -->
            <template v-if="ruleForm.type == 8">
                <el-form-item label="GIF文件" prop="content.img_url" :rules="{
                    required: true,
                    message: '请上传GIF图片',
                    trigger: 'change',
                }">
                    <Upload v-model="ruleForm.content.img_url" type="image" accept="image/gif" :action="robotHost" 
                    @change="changeFile"
                    @success="uploadSuccess" @error="uploadError">
                    </Upload>
                </el-form-item>

            </template>
            <template v-if="ruleForm.type == 10">
                <el-form-item label="文件" prop="content.file_url" :rules="{
                    required: true,
                    message: '请上传文件',
                    trigger: 'change',
                }">
                    <div>
                        <Upload v-model="ruleForm.content.file_url" type="button" accept="" :action="robotHost"
                        @change="changeFile"
                        @success="uploadSuccess" @error="uploadError"></Upload>
                        <p style="margin-top: 10px;">{{ ruleForm.content.file_name }}</p>
                    </div>

                </el-form-item>
            </template>
            <!-- 语音 -->
            <template v-if="ruleForm.type == 3">
                <el-form-item label="aes_key" prop="content.aes_key" :rules="{
                    required: true,
                    message: '请输入aes_key',
                    trigger: 'blur',
                }">
                    <p class="tip">请在企业微信手机客户端将语音发送给自己，即可获取。</p>
                    <el-select v-model="ruleForm.content.aes_key" @change="changeVoice" placeholder="请选择"
                        style="width: 60%;margin-right: 12px;">
                        <el-option v-for="item in voiceList" :key="item.aes_key" :label="item.aes_key"
                            :value="item.aes_key">
                        </el-option>
                    </el-select>
                    <el-button type="primary" @click="getVoiceList">刷新</el-button>
                    <!-- <el-input type="text" v-model="ruleForm.content.aes_key" placeholder="请输入aes_key" /> -->
                </el-form-item>
                <el-form-item label="md5" prop="content.md5" :rules="{
                    required: true,
                    message: '请输入md5',
                    trigger: 'blur',
                }">
                    <el-input type="text" v-model="ruleForm.content.md5" placeholder="请输入md5" />
                </el-form-item>
                <el-form-item label="size" prop="content.size" :rules="{
                    required: true,
                    message: '请输入size',
                    trigger: 'blur',
                }">
                    <el-input type="text" v-model="ruleForm.content.size" placeholder="请输入size" />
                </el-form-item>
                <el-form-item label="voice_id" prop="content.voice_id" :rules="{
                    required: true,
                    message: '请输入voice_id',
                    trigger: 'blur',
                }">
                    <el-input type="text" v-model="ruleForm.content.voice_id" placeholder="请输入voice_id" />
                </el-form-item>
                <el-form-item label="voice_time" prop="content.voice_time" :rules="{
                    required: true,
                    message: '请输入voice_time',
                    trigger: 'blur',
                }">
                    <el-input type="text" v-model="ruleForm.content.voice_time" placeholder="请输入voice_time" />
                </el-form-item>


            </template>

        </el-form>
        <div class="submit-btn">
            <el-button type="primary" @click="submitForm" :class="{ 'no-click': mhtLoading }">
                <el-icon v-if="mhtLoading" class="mht-loading" style="margin-right: 4px;">
                    <Loading />
                </el-icon>
                提 交
            </el-button>
        </div>
    </div>
</template>

<script setup>

import { ref, reactive, onMounted, onUnmounted, computed } from 'vue'
import { addMaterial, updataMaterial, deletaMaterial } from '@/api/material'
import { userList } from '@/api/user'
import { minis, voices } from '@/api/selfMiniVoice'
import Upload from '@/components/Upload/index.vue'
import robotStore from '@/store/modules/robotStore'
import { uploadProps } from 'element-plus'
import V3Emoji from "vue3-emoji";
import "vue3-emoji/dist/style.css";
const emits = defineEmits(['hideMaterial'])
const userRobotStore = robotStore()
const materialTypes = [{
    label: '文本',
    value: 1
}, {
    label: '图片',
    value: 2
}, {
    label: '语音',
    value: 3
}, {
    label: '视频',
    value: 4
}, {
    label: '位置',
    value: 6
}, {
    label: '链接',
    value: 7
}, {
    label: 'GIF图片',
    value: 8
}, {
    label: '名片',
    value: 9
}, {
    label: '文件',
    value: 10
}]
const ruleFormRef = ref()
const ruleForm = ref({
    type: 1,
    content: {}
})
const rules = ref({
    title: [
        {
            required: true,
            message: '请输入标题',
            trigger: 'blur',
        }
    ],
    description: [
        {
            required: true,
            message: '请输入描述',
            trigger: 'blur',
        }
    ],

})
const v2props = {
    value: 'user_id',
    label: 'nickname'
}


const props = defineProps({
    editData: {
        type: Object,
        default: null
    },
    type: ''
})
const appList = ref([])
const voiceList = ref([])
let isEdit = false

let map = null
let AutoComplete = null
var autoOptions = {
    input: "mapInput"
};

let marker = null

const onEmojiSelect = (emoji) => {
    // if (inputRef.value) {
    //     inputRef.value.focus();
    //     const start = inputRef.value.selectionStart;
    //     const end = inputRef.value.selectionEnd;
    //     const text = inputRef.value.value;
    //     inputRef.value.value = `${text.slice(0, start)}${emoji}${text.slice(end)}`;
    //   }
    if(ruleForm.value.content.message){
        ruleForm.value.content.message += emoji
    } else {
        ruleForm.value.content.message = emoji
    }
}


const show = (data) => {
    isEdit = true
    ruleForm.value = data

}
const handleChange = () => {
    ruleForm.value.title = ''
    ruleForm.value.content = {}
    ruleForm.value.description = ''
}
const mhtLoading = ref(false)
const submitForm = async () => {

    ruleFormRef.value.validate(async (valid, fields) => {

        if (valid) {
           
            const copyFrom = JSON.parse(JSON.stringify(ruleForm.value))
            copyFrom.content = JSON.stringify(copyFrom.content)
            mhtLoading.value = true
            if (!isEdit) {
                await addMaterial(copyFrom)
                mhtLoading.value = false
            } else {

                delete copyFrom.id
                delete copyFrom.created_at
                delete copyFrom.created_user
                delete copyFrom.updated_at
                delete copyFrom.updated_user
                await updataMaterial(copyFrom, ruleForm.value.id)
                mhtLoading.value = false
            }
            emits('hideMaterial')
        }
    })
}

const cardList = ref([])

const cardTotal = ref(0)
const cardPage = ref(1)
const getCards = async () => {

    const res = await userList({
        robot_id: userRobotStore.robotInfo.id,
        page: cardPage.value,
        page_size: 100
    })
    cardList.value = res.list
    cardTotal.value = res.total
}

const currentChange = (e) => {
    cardPage.value = e
    getCards()
}
const robotHost = computed(() => {
    return userRobotStore.robotInfo.server_ip
})

const changeCard = (e) => {
    cardList.value.forEach((el) => {
        if (e == el.user_id) {
            ruleForm.value.content.userInfo = el
            ruleForm.value.content.card_user_name = el.nickname
        }
    })

}
const disabledBtn = ref(false)
const changeFile = () => {
    disabledBtn.value = true
}
const uploadSuccess = (e) => {
    ruleForm.value.content.file_name = e.file
    ruleForm.value.content.file_path = e.file_path
    ruleForm.value.content.file_size = e.file_size
    disabledBtn.value = false
}
const uploadError = () => {
    disabledBtn.value = false
}
const changeAppId = (e) => {
    let data = appList.value.filter((el) => {
        return el.msg_id == e
    })[0]
    ruleForm.value.content = {
        msg_id: e,
        app_id: data.app_id,
        "title": data.title,
        "des": data.des,
        "head_img_url": data.head_img_url,
        "page_path": data.page_path,
        "wechat_id": data.wechat_id,
        "thumb_file_id": data.thumb_file_id,
        "thumb_md5": data.thumb_md5,
        "thumb_aes_key": data.thumb_aes_key,
        "size": data.size,
        "send_time": data.send_time
    }

}
const changeVoice = (e) => {
    ruleForm.value.content = e
    let data = voiceList.value.filter((el) => {
        return el.aes_key == e
    })[0]
    ruleForm.value.content = {
        "voice_id": data.voice_id,
        "md5": data.md5,
        "aes_key": data.aes_key,
        "size": data.size,
        "voice_time": data.voice_time,
        "send_time": data.send_time
    }
}
let geocoder = null

const getVoiceList = async () => {
    try {
        const res = await voices(userRobotStore.robotInfo.id)
        voiceList.value = res.list
        ElNotification({
            type: 'success',
            message: '刷新成功'
        })
    } catch {
        ElNotification({
            type: 'error',
            message: '刷新失败'
        })
    }

}
const getAppList = async () => {
    try {
        const res = await minis(userRobotStore.robotInfo.id)
        appList.value = res.list
        ElNotification({
            type: 'success',
            message: '刷新成功'
        })
    } catch {
        ElNotification({
            type: 'error',
            message: '刷新失败'
        })
    }
}
defineExpose({ show })
onMounted(async () => {
    ruleForm.value.type = props.type
    if (props.type == 3) {
        const res = await voices(userRobotStore.robotInfo.id)
        voiceList.value = res.list
    }
    if (props.type == 5) {
        const res = await minis(userRobotStore.robotInfo.id)
        appList.value = res.list
    }

    if (ruleForm.value.type == 9) {
        getCards()
    }
    if (ruleForm.value.type == '6') {
       
    }
})
onUnmounted(() => {
    map && map.destroy();
});
</script>

<style lang="scss" scoped>
.costom-select-item {

    font-size: 14px;

    .el-image {
        height: 30px;
        width: 30px;
        margin-right: 8px;
        border-radius: 4px;
        vertical-align: middle;
        transform: translateY(-1px);
    }
}

.submit-btn {
    text-align: right;
}

.tip {
    width: 100%;
    font-size: 13px;
    // margin-bottom: 10px;
    color: var(--el-color-danger);
}
</style>