<template>
  <div class="p-2" style="overflow-x: hidden;">
    <!--查询区域-->
    <div class="jeecg-basic-table-form-container">
      <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="instructionTagId">
              <template #label><span title="分类标签">分类标签</span></template>
              <j-dict-select-tag v-model:value="queryParam.instructionTagId" v-if="showJSCom"
                :orgCode="sourceOrgInfo?.orgCode"
                :dictCode="`nu_config_service_instruction_tag,instruction_name,id,del_flag = 0 and iz_enabled = 0 order by sort asc`"
                placeholder="请选择分类标签" allowClear :ignoreDisabled="true" @select="reload()" />
            </a-form-item>
          </a-col>

          <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="showJSCom"
                :orgCode="sourceOrgInfo?.orgCode"
                :dictCode="`nu_config_service_category,category_name,id,del_flag = 0 and iz_enabled = 0 and instruction_id = '${queryParam.instructionTagId || ''}' order by sort asc`"
                placeholder="请选择服务类别" allowClear :ignoreDisabled="true" @select="reload()" />
            </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="showJSCom"
                :orgCode="sourceOrgInfo?.orgCode"
                :dictCode="`nu_config_service_type,type_name,id,del_flag = 0 and iz_enabled = 0 and category_id = '${queryParam.categoryId || ''}' order by sort asc`"
                placeholder="请选择服务类型" allowClear :ignoreDisabled="true" @select="reload()" />
            </a-form-item>
          </a-col>
          <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="bodyTags">
              <template #label><span title="体型标签">体型标签</span></template>
              <j-dict-select-tag type='list' v-model:value="queryParam.bodyTags"
                :dictCode="`nu_config_body_tag,tag_name,id,del_flag = '0' and iz_enabled = 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>
              <j-dict-select-tag type="list" v-model:value="queryParam.emotionTags"
                :dictCode="`nu_config_emotion_tag,tag_name,id,del_flag = '0' and iz_enabled = 0 order by sort asc`" :ignoreDisabled="true"
                placeholder="请选择情绪标签" allowClear />
            </a-form-item>
          </a-col> -->
          <!-- <a-col :lg="6">
            <a-form-item name="izEnabled">
              <template #label><span title="是否启用">是否启用</span></template>
              <j-dict-select-tag type='list' v-model:value="queryParam.izEnabled" dictCode="iz_enabled"
                :ignoreDisabled="true" placeholder="请选择是否启用" allowClear @select="reload()" />
            </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>
    </div>
    <a-row :gutter="24" style="margin-top: -10px;padding-left: 20px;padding-right: 20px;">
      <a-col :lg="3" :push="21">
        <a-button type="primary" @click="selectAll">一键全选</a-button>
        <a-button type="default" @click="removeAll" style="margin-left: 8px">全部移除</a-button>
      </a-col>
    </a-row>
    <a-row :gutter="24" style="padding-left: 20px;padding-right: 20px;">
      <a-col :lg="12" :sm="24">
        <!-- 引用表格 -->
        <a-tag color="blue" style="margin-left: 10px;margin-top: 10px;">源数据 - {{ sourceOrgInfo.departName }}</a-tag>
        <a-radio-group v-model:value="sourceType" size="small" @change="sourceTypeChanged">
          <a-radio-button value="all">全部</a-radio-button>
          <a-radio-button value="unsel">未选择</a-radio-button>
        </a-radio-group>
        <BasicTable @register="registerTable" :dataSource="leftList" size="small" :rowClassName="rowClassName"
          :scroll="{ y: '46vh' }">
          <template #tableTitle></template>
          <template v-slot:bodyCell="{ column, record, index, text }">
            <template v-if="column.dataIndex === 'bodyTagList'">
              <span :title="text.map((item) => item.tagName).join('、')">{{text.map((item) =>
                item.tagName).join('、')}}</span>
            </template>
            <template v-if="column.dataIndex === 'emotionTagList'">
              <span :title="text.map((item) => item.tagName).join('、')">{{text.map((item) =>
                item.tagName).join('、')}}</span>
            </template>
          </template>
          <template #action="{ record }">
            <a-button type="link" v-if="!selectedRecordIds.includes(record.id)" @click="selectRecord(record)"
              size="small">选择</a-button>
            <a-button type="link" v-else @click="removeRecord(record)" size="small">移除</a-button>
          </template>
        </BasicTable>
      </a-col>
      <a-col :lg="12" :sm="24">
        <a-tag color="green" style="margin-left: 10px;margin-top: 10px;">已选择 {{ rightList.length }} 条</a-tag>
        <BasicTable :dataSource="rightList" :columns="sourceColumns" size="small" :scroll="{ y: '46vh' }"
          :pagination="{ current: 1, pageSize: 50, total: rightList.length, showSizeChanger: true, pageSizeOptions: ['15', '50', '80', '100'] }">
        </BasicTable>
      </a-col>
    </a-row>

  </div>
</template>

<script lang="ts" name="serviceDirective-configServiceDirective" setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { BasicTable, TableAction } from '/@/components/Table';
import { useListPage } from '/@/hooks/system/useListPage';
import { columns, sourceColumns, superQuerySchema } from './ConfigServiceDirective.data';
import { listByDS } from './ConfigServiceDirective.api';
import { useUserStore } from '/@/store/modules/user';
import JInput from "/@/components/Form/src/jeecg/components/JInput.vue";
import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
import { cloneDeep } from "lodash-es";
import { getFileAccessHttpUrl } from '/@/utils/common/compUtils';

const leftList = ref<any[]>([]);  // 左侧列表的数据
const rightList = ref<any[]>([]);  // 右侧列表的数据
const sourceOrgInfo = ref({})//源数据机构信息
const sourceType = ref('all')
const showJSCom = ref(false)
const selectedRecordIds = ref<string[]>([]);  // 存储已选择记录的 ID
const formRef = ref();
const queryParam = reactive<any>({});
const toggleSearchStatus = ref<boolean>(false);
const registerModal = ref();
const userStore = useUserStore();
//注册table数据
const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
  tableProps: {
    title: '服务指令',
    api: listByDS,
    columns: sourceColumns,
    canResize: false,
    useSearchForm: false,
    showIndexColumn: true,
    showTableSetting: false,
    immediate: false,
    pagination: {
      current: 1,
      pageSize: 10,
      pageSizeOptions: ['15', '50', '80', '100'],
    },
    beforeFetch: async (params) => {
      queryParam.izEnabled = '0'
      return Object.assign(params, queryParam);
    },
    actionColumn: {
      width: 80,
      fixed: 'right',
    },
  },
});
const [registerTable, { reload, collapseAll, updateTableDataRecord, findTableDataRecord, getDataSource }, { rowSelection, selectedRowKeys }] = tableContext;
const labelCol = reactive({
  xs: 24,
  sm: 6,
  xl: 6,
  xxl: 6
});
const wrapperCol = reactive({
  xs: 24,
  sm: 18,
});

/**
 * 查询
 */
function searchQuery() {
  reload();
}

/**
 * 重置
 */
function searchReset() {
  formRef.value.resetFields();
  selectedRowKeys.value = [];
  //刷新数据
  reload();
}

function init(record) {
  sourceOrgInfo.value = record.orgInfo
  //初始化各参数
  {
    rightList.value = []
    leftList.value = []
    selectedRecordIds.value = []
    formRef.value.resetFields();
    selectedRowKeys.value = [];
    sourceType.value = 'all'
  }
  queryParam.dataSourceCode = record.orgInfo.orgCode;
  reload();
}

// 选择记录
function selectRecord(record: any) {
  if (!selectedRecordIds.value.includes(record.id)) {
    selectedRecordIds.value.push(record.id);  // 记录 ID
    rightList.value.push(record);              // 将记录添加到右侧
    leftList.value = leftList.value.filter(item => item.id !== record.id);  // 从左侧移除
    rightList.value = [...rightList.value];    // 强制更新引用，确保视图更新
    leftList.value = [...leftList.value];      // 强制更新引用，确保视图更新
  }
}

// 移除记录
function removeRecord(record: any) {
  if (selectedRecordIds.value.includes(record.id)) {
    selectedRecordIds.value = selectedRecordIds.value.filter(id => id !== record.id);  // 移除记录 ID
    leftList.value.push(record);  // 添加回左侧
    rightList.value = rightList.value.filter(item => item.id !== record.id);  // 从右侧移除
    rightList.value = [...rightList.value];    // 强制更新引用，确保视图更新
    leftList.value = [...leftList.value];      // 强制更新引用，确保视图更新
  }
}

// 行样式
function rowClassName(record: any) {
  return selectedRecordIds.value.includes(record.id) ? 'selected-row' : '';
}

/**
 * 一键全选，将所有左侧数据移至右侧
 */
function selectAll() {
  listByDS({
    ...queryParam,
    pageNo: 1,
    pageSize: -1,
  }).then(res => {
    const allRecords = res.records || [];
    // 只添加没有选择的记录到右侧
    const unselectedRecords = allRecords.filter(record => !selectedRecordIds.value.includes(record.id));
    if (unselectedRecords.length) {
      // 把新记录推到右侧列表
      rightList.value.push(...unselectedRecords);
      // 把新记录的 id 推入已选 id 列表
      selectedRecordIds.value.push(...unselectedRecords.map(r => r.id));
      // 刷新引用，确保视图更新
      rightList.value = [...rightList.value];
      selectedRecordIds.value = [...selectedRecordIds.value];
    }
  })
}

/**
 * 全部移除，将右侧数据移回左侧
 */
function removeAll() {
  rightList.value = [];  // 清空右侧列表
  selectedRecordIds.value = []
}

function sourceTypeChanged(val_) {
  if (val_.target.value == 'all') {
    //全部
    queryParam.excludeIds = null
  } else {
    //未选择
    queryParam.excludeIds = selectedRecordIds.value.join(',')
  }
  reload()
}

watch(
  () => queryParam.directiveName,
  (newVal) => {
    reload()
  }
);

function controlShowJSCom() {
  showJSCom.value = false
  setTimeout(() => {
    showJSCom.value = true
  }, 1000)
}

defineExpose({
  init,
  rightList,
  controlShowJSCom,
});
</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%;
  }
}

audio::-webkit-media-controls-timeline {
  display: none;
}

audio::-webkit-media-controls-current-time-display,
audio::-webkit-media-controls-time-remaining-display {
  display: none;
}

.btnPrivate {
  height: 34px;
  margin-left: 4px;
}

/* 添加深度选择器确保样式能穿透组件 */
:deep(.ant-table-tbody) {
  tr.selected-row {
    td {
      background-color: #e6f7ff !important;
    }

    &:hover td {
      background-color: #e6f7ff !important;
    }
  }
}

:deep .ant-table-title {
  display: none;
}

:deep .jeecg-basic-table-form-container .ant-form {
  padding: 0px;
  padding-right: 20px;
}
</style>
