<template>
    <SyncComponent ref="syncComRef" :selectedSize="Array.from(selectedItems.values()).length"
        @changeShowJMCom="changeShowJMCom" @sourceOrgCodeChanged="sourceOrgCodeChanged"
        @viewTypeChanged="viewTypeChanged" @orgChanged="orgChanged">
        <!-- 表单 -->
        <template #searchFormSlot>
            <a-form ref="formRef" @keyup.enter.native="searchQuery" :model="queryParam" :label-col="labelCol"
                :wrapper-col="wrapperCol">
                <a-row :gutter="24">
                    <a-col :lg="6">
                        <a-form-item name="categoryId">
                            <template #label><span title="服务类别">服务类别</span></template>
                            <j-dict-select-tag type="list" v-model:value="queryParam.categoryId" v-if="showJMCom"
                                :orgCode="sourceOrgCode"
                                :dictCode="`nu_config_service_category,category_name,id,del_flag = 0 order by sort asc`"
                                :ignoreDisabled="true" placeholder="请选择服务类别" allow-clear />
                        </a-form-item>
                    </a-col>
                    <a-col :lg="6">
                        <a-form-item name="typeId">
                            <template #label><span title="服务类型">服务类型</span></template>
                            <j-dict-select-tag type="list" v-model:value="queryParam.typeId" v-if="showJMCom"
                                :orgCode="sourceOrgCode"
                                :dictCode="`nu_config_service_type,type_name,id,del_flag = 0 order by sort asc`"
                                placeholder="请选择服务类型" :ignoreDisabled="true" allowClear />
                        </a-form-item>
                    </a-col>
                    <!-- <template v-if="toggleSearchStatus"> -->
                    <a-col :lg="6">
                        <a-form-item name="directiveName">
                            <template #label><span title="服务指令">服务指令</span></template>
                            <JInput v-model:value="queryParam.directiveName" placeholder="请输入服务指令名称" allowClear />
                        </a-form-item>
                    </a-col>
                    <a-col :lg="6">
                        <a-form-item name="instructionTagId">
                            <template #label><span title="分类标签">分类标签</span></template>
                            <j-dict-select-tag v-model:value="queryParam.instructionTagId" v-if="showJMCom"
                                :orgCode="sourceOrgCode" dictCode="instruction_tag" :ignoreDisabled="true"
                                placeholder="请选分类标签" allowClear />
                        </a-form-item>
                    </a-col>
                    <a-col :lg="6">
                        <a-form-item name="bodyTags">
                            <template #label><span title="体型标签">体型标签</span></template>
                            <JSelectMultiple type="list" v-model:value="queryParam.bodyTags" v-if="showJMCom"
                                :orgCode="sourceOrgCode"
                                :dictCode="`nu_config_body_tag,tag_name,id,del_flag = '0' order by sort asc`"
                                :ignoreDisabled="true" placeholder="请选择体型标签" allowClear />
                        </a-form-item>
                    </a-col>
                    <a-col :lg="6">
                        <a-form-item name="emotionTags">
                            <template #label><span title="情绪标签">情绪标签</span></template>
                            <JSelectMultiple type="list" v-model:value="queryParam.emotionTags" v-if="showJMCom"
                                :orgCode="sourceOrgCode"
                                :dictCode="`nu_config_emotion_tag,tag_name,id,del_flag = '0' order by sort asc`"
                                :ignoreDisabled="true" placeholder="请选择情绪标签" allowClear />
                        </a-form-item>
                    </a-col>
                    <a-col :xl="6" :lg="7" :md="8" :sm="24">
                        <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
                            <a-col :lg="6">
                                <a-button type="primary" preIcon="ant-design:search-outlined"
                                    @click="searchQuery">查询</a-button>
                                <a-button type="primary" preIcon="ant-design:reload-outlined" @click="searchReset"
                                    style="margin-left: 8px">重置</a-button>
                            </a-col>
                        </span>
                    </a-col>
                </a-row>
            </a-form>
        </template>

        <!-- 试验田数据列表 -->
        <template #sourceTableSlot>
            <ConfigServiceDirectiveList @select-change="handleSelectChange" ref="listComRef" :queryParams="queryParam"
                :initialDataIds="initialDataIds" />
        </template>

        <!-- 需要同步的机构的数据列表 -->
        <template #businessTableSlot>
            <a-table size="small" :columns="selectedColumns" :dataSource="Array.from(selectedItems.values())"
                :pagination="false" :scroll="{ y: '55vh' }">
                <template #bodyCell="{ column, record }">
                    <template v-if="column.dataIndex === 'action'">
                        <a-popconfirm placement="left" ok-text="确认" cancel-text="取消"
                            @confirm="handleRemoveFromRight(record.id)">
                            <template #title>
                                <span>是否确认移除</span>
                            </template>
                            <a-button type="link" danger size="small"
                                :disabled="initialDataIds.includes(record.id)">移除</a-button>
                        </a-popconfirm>
                    </template>
                    <template v-else-if="column.dataIndex === 'mp3File'">
                        <span v-if="!record.mp3File" style="font-size: 12px;font-style: italic;">无文件</span>
                        <audio controls v-else style="width: 100%; max-width: 300px; height: 40px;">
                            <source :src="getFileAccessHttpUrl(record.mp3File)">
                        </audio>
                    </template>
                    <template v-else-if="column.dataIndex === 'mp4File'">
                        <span v-if="!record.mp4File" style="font-size: 12px;font-style: italic;">无文件</span>
                        <a-button v-else type="primary" size="small" @click="openVideoModal(record.mp4File)">
                            播放视频
                        </a-button>
                    </template>
                    <template v-else-if="column.dataIndex === 'bodyTagList'">
                        <span v-if="!record.bodyTagList || record.bodyTagList.length === 0"
                            style="font-size: 12px;font-style: italic;">-</span>
                        <template v-else>
                            {{record.bodyTagList.map(item => item.tagName).join('、')}}
                        </template>
                    </template>
                    <template v-else-if="column.dataIndex === 'emotionTagList'">
                        <span v-if="!record.emotionTagList || record.emotionTagList.length === 0"
                            style="font-size: 12px;font-style: italic;">-</span>
                        <template v-else>
                            {{record.emotionTagList.map(item => item.tagName).join('、')}}
                        </template>
                    </template>
                    <template v-else-if="column.dataIndex === 'previewFile'">
                        <span v-if="!record.previewFile" style="font-size: 12px;font-style: italic;">无图片</span>
                        <img v-else :src="getFileAccessHttpUrl(record.previewFile)"
                            style="max-width: 100px; max-height: 60px;" />
                    </template>
                    <template v-else-if="column.dataIndex === 'immediateFile'">
                        <span v-if="!record.immediateFile" style="font-size: 12px;font-style: italic;">无图片</span>
                        <img v-else :src="getFileAccessHttpUrl(record.immediateFile)"
                            style="max-width: 100px; max-height: 60px;" />
                    </template>
                </template>
            </a-table>
        </template>
    </SyncComponent>

    <a-modal v-model:visible="showVideoModal" title="视频播放" :footer="null" @cancel="closeVideoModal"
        :bodyStyle="{ padding: '0', maxHeight: '80vh', overflow: 'auto' }">
        <video controls style="width: 100%; max-height: '70vh'; display: block; margin: 0 auto;">
            <source :src="videoUrl">
            您的浏览器不支持视频播放。
        </video>
    </a-modal>
</template>

<script setup name="synchronization-directive2" lang="ts">
// ↓↓↓↓↓ 组件自带
import { ref, reactive } from 'vue'
import SyncComponent from '/@/components/Sync/SyncComponent.vue'
import JInput from "/@/components/Form/src/jeecg/components/JInput.vue";
import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
import JSelectMultiple from '/@/components/Form/src/jeecg/components/JSelectMultiple.vue';
import { useMessage } from "/@/hooks/web/useMessage";
// ↑↑↑↑↑ 组件自带
// ↓↓↓↓↓ 服务指令用
import { list, asyncFunc } from '@/views/services/serviceDirective/ConfigServiceDirective.api';
import ConfigServiceDirectiveList from '@/views/services/serviceDirective/ConfigServiceDirectiveList.vue'
import { getFileAccessHttpUrl } from '/@/utils/common/compUtils'
import { selectedColumns } from './org.data';
// ↑↑↑↑↑ 服务指令用

// >>>>>>>>>>>>>组件：无需处理代码
const { createMessage } = useMessage();
const syncComRef = ref(null)
const sourceOrgCode = ref('')
const showJMCom = ref(false)
const labelCol = reactive({
    xs: 24,
    sm: 4,
    xl: 6,
    xxl: 4
});
const wrapperCol = reactive({
    xs: 24,
    sm: 20,
});

/**
 * 获取到了试验田的机构编码
 * @param v_ 
 */
const sourceOrgCodeChanged = (v_) => {
    sourceOrgCode.value = v_
}
/**
 * 是否展示设计dict的cj框架封装的组件（因为需要获取的是对应试验田的数据字典，当接口数据请求未返回时如果展示组件会报错）
 * 跟sourceOrgCodeChanged方法相配合
 * @param v_ 
 */
const changeShowJMCom = (v_) => {
    showJMCom.value = v_
}
// <<<<<<<<<<<<<组件：无需处理代码
/**
 * 机构变更
 */
const orgChanged = async (org) => {
    // 清空当前选择
    selectedItems.value.clear();
    // 清空初始化数据
    initialDataIds.value = [];
    try {
        // 加载新机构数据
        const res = await list({ dataSourceCode: org.orgCode, pageNo: 1, pageSize: -1 });
        // 如果有数据，更新右侧列表
        if (res.records && res.records.length > 0) {
            const newRecords = res.records;
            newRecords.forEach(record => {
                selectedItems.value.set(record.id, record);
                if (!syncComRef.value.orgData.value?.operationStartTime || new Date() >= new Date(syncComRef.value.orgData.value?.operationStartTime)) {
                    initialDataIds.value.push(record.id);
                }
            });

            // 更新左侧列表的选中状态
            listComRef.value?.updateSelection?.(newRecords);
        } else {
            // 没有数据时也确保清空
            selectedItems.value.clear();
            listComRef.value?.updateSelection?.([]);
        }

        // 切换视图
        syncComRef.value.resetOrgSelectedCon(false);

        console.log("🌊 ~ orgChanged ~ selectedItems.value:", selectedItems.value)
    } catch (err) {
        console.error('机构数据查询失败:', err);
        createMessage.error('机构数据查询失败');
        // 失败时也确保清空状态
        selectedItems.value.clear();
        listComRef.value?.updateSelection?.([]);
    }
}
// >>>>>>>>>>>>>组件：需要处理代码
// <<<<<<<<<<<<<组件：需要处理代码

// >>>>>>>>>>>>>非组件代码
const listComRef = ref();
const selectedItems = ref(new Map<string | number, any>());
const queryParam = ref({ viewType: 'all' })//源数据查询参数
const initialDataIds = ref<string[]>([]);
const showVideoModal = ref(false);
const videoUrl = ref('');

/**
 * 查询
 */
function searchQuery() {
    listComRef.value.reload();
}
/**
 * 重置
 */
function searchReset() {
    let vt = queryParam.value.viewType
    queryParam.value = { viewType: vt }
    listComRef.value?.reload();
}

/**
 * 源数据的全部、已选择、未选择变更时触发
 * @param v_ all、selected、unselected
 */
const viewTypeChanged = (v_) => {
    queryParam.value.viewType = v_
    //组件内部监听了queryParam值的变化，自动刷新
}
const handleSelectChange = (items: Map<string | number, any>) => {
    selectedItems.value = new Map(items);
};

const handleRemoveFromRight = (key: string | number) => {
    selectedItems.value.delete(key);
    listComRef.value?.removeSelectedItem?.(key);
};

const openVideoModal = (url: string) => {
    videoUrl.value = getFileAccessHttpUrl(url);
    showVideoModal.value = true;
};

const closeVideoModal = () => {
    showVideoModal.value = false;
    videoUrl.value = '';
};
// <<<<<<<<<<<<<非组件代码
</script>

<style lang="less" scoped>
.jeecg-basic-table-form-container {
    padding: 0;

    .table-page-search-submitButtons {
        display: block;
        margin-bottom: 24px;
        white-space: nowrap;
    }

    .query-group-cust {
        min-width: 100px !important;
    }

    .query-group-split-cust {
        width: 30px;
        display: inline-block;
        text-align: center
    }

    .ant-form-item:not(.ant-form-item-with-help) {
        margin-bottom: 16px;
        height: 32px;
    }

    :deep(.ant-picker),
    :deep(.ant-input-number) {
        width: 100%;
    }
}

.selected-list-container {
    :deep(.ant-table) {
        width: 100% !important;
        max-width: 100%;
    }
}
</style>