<script setup lang="ts">
import { ref, watch, nextTick, h, onMounted, reactive } from 'vue';
import { type VxeTablePropTypes, type VxeTableEvents, VxeUI } from 'vxe-table';
import { getDictionaryMethod } from '@/request/api/dictionary.api';
import { getConditioningDeviceDetailMethod, updateConditioningSchemeMethod } from '@/request/api/care.api';
import type { ConditioningSchemeModel } from '@/model/care.model';
import { useRequest } from 'alova/client';
import { message, notification } from 'ant-design-vue';
import { MenuUnfoldOutlined } from '@ant-design/icons-vue';
import CustomConfiguration from '@/service/CustomConfiguration.vue';
type ConditioningModel = Partial<ConditioningSchemeModel>;
  (notification.config as any)({
  zIndex: 10000, // 直接设置层级
});
// 定义表格行数据类型
interface TableRowData {
  isCustomize: boolean;
  conditioningProgramType: string;
  isHaveForInfer: string | null;
  knowledgeCpShowType: string;
  showCount: number;
  isChecked: boolean;
  selectedCpIds?: string[];
  isShowForInfer: string;
  isNewRow?: boolean; // 用于标识是否是新添加的行
  previousChecked?: boolean; // 上一次“确认后”的勾选状态
  backupSelectedCpIds?: string[]; // 打开弹窗前的已选项目快照（用于取消还原）
}
const emits = defineEmits<{
  submit: [success: boolean, data?: Array<TableRowData>];
}>();
let formattedData: any[] = [];

const { loading: submitting, send: submit } = useRequest(updateConditioningSchemeMethod, {
  immediate: false,
});
const props = defineProps<{ data: ConditioningModel }>();
// 表格数据
const tableData = ref<TableRowData[]>([]);
const typeOptionsLoading = ref<boolean>(false);
const typeOptions = ref<{ label: string; value: string }[]>([]);
// 获取方案类型
async function getConditioningProgramType() {
  typeOptionsLoading.value = true;
  try {
    const res = await getDictionaryMethod('condition_type');
    if (res?.length > 0) {
      typeOptions.value = res; // 直接使用返回的数据
    }
  } catch (error) {
    console.error('获取方案类型列表失败:', error);
  } finally {
    typeOptionsLoading.value = false;
  }
}
// 监听方案类型 tableData 中的方案类型
watch(
  tableData,
  (newVal) => {
    // 获取所有已使用的方案类型值
    const usedTypes = newVal.map((row) => row.conditioningProgramType).filter((type) => type && type !== '');
    // 过滤掉已经在表格中使用的方案类型
    typeOptions.value = typeOptions.value.filter((option) => !usedTypes.includes(option.value) && !usedTypes.includes(option.label));
  },
  { deep: true }
);
// 全局项目条数上限
const globalItemLimit = ref(3);

// 监听 globalItemLimit 变化，同步所有行的 showCount
watch(globalItemLimit, (newVal) => {
  tableData.value.forEach((row) => {
    row.showCount = Number(newVal);
  });
});

// 添加新行
const addRow = () => {
  tableData.value.push({
    conditioningProgramType: '',
    knowledgeCpShowType: '1', // 1-展示 2-不展示 3-定制项目无结果时展示
    showCount: globalItemLimit.value,
    isChecked: false,
    isShowForInfer: 'N',
    isHaveForInfer: null,
    isCustomize: false,
    isNewRow: true, //新行
  });
};

// 删除行
const deleteRow = (row: any) => {
  const index = tableData.value.indexOf(row);
  if (index > -1) {
    tableData.value.splice(index, 1);
  }
};

// 保存
const saveData = async () => {
  // 数据验证和格式化
  formattedData = tableData.value.map((row) => ({
    ...row,
    knowledgeCpShowType: row.knowledgeCpShowType,
    showCount: row.showCount || globalItemLimit.value,
    isHaveForInfer: row.isHaveForInfer,
  }));

  if (formattedData.length === 0) {
    notification.error({
      message: '请至少添加一个方案类型',
    });
    return;
  }
  if (formattedData.some((row) => !row.conditioningProgramType)) {
    notification.error({
      message: '请完善方案类型',
    });
    return;
  }

  if (!props.data.insId) {
    notification.error({
      message: '未找到机构ID',
    });
    return;
  }

  // 使用 async/await 确保正确处理成功和失败
  try {
    await submit(props.data.insId, formattedData);
    // 成功时通知父组件
    emits('submit', true, formattedData);
  } catch (error) {
    // 失败时也通知父组件
    emits('submit', false);
  }
  VxeUI.modal.close(`configured-modal`);
};

// 取消
const cancelEdit = () => {
  VxeUI.modal.close(`configured-modal`);
};

// 方案类型选择处理
const handleSolutionTypeChange = (row: any) => {
  const option = typeOptions.value.find((opt) => opt.value === row.conditioningProgramType);
  if (option) {
    row.conditioningProgramType = option.label;
  }
};

const rowConfig = reactive<VxeTablePropTypes.RowConfig>({
  drag: true,
});
const columnConfig = reactive<VxeTablePropTypes.ColumnConfig>({});
const rowDragstartEvent: VxeTableEvents.RowDragstart = ({ row }) => {};

const rowDragendEvent: VxeTableEvents.RowDragend = ({ newRow, oldRow }) => {
  const oldIndex = tableData.value.indexOf(oldRow as TableRowData);
  const newIndex = tableData.value.indexOf(newRow as TableRowData);

  if (oldIndex > -1 && newIndex > -1 && oldIndex !== newIndex) {
    const moved = tableData.value.splice(oldIndex, 1)[0];
    tableData.value.splice(newIndex, 0, moved);
  }
};
const organizationName = ref('');
const insName = ref('');
const insId = ref<number>(0);
onMounted(async () => {
  console.log(props.data, 'props.onMounted');
  getConditioningProgramType();
  const res: any = await getConditioningDeviceDetailMethod(props.data);
  organizationName.value = res.orgName ?? '';
  insName.value = res.insName ?? '';
  insId.value = res.insId ?? 0;
  tableData.value = res.items ?? [];
  tableData.value.forEach((row) => {
    // 只有 isHaveForInfer 不是 null 的情况下才是定制项目
    if (row.isHaveForInfer === null || row.isHaveForInfer === undefined) {
      // 不是定制项目，什么都不设置
      row.isCustomize = false;
    } else if (row.isHaveForInfer === 'Y') {
      // 是定制项目且展示
      row.isCustomize = true;
      // row.showListIcon = true; // 已勾选，显示列表图标
    } else if (row.isHaveForInfer === 'N') {
      // 是定制项目但不展示
      row.isCustomize = true;
      // row.showListIcon = false; // 未勾选，隐藏列表图标
    }
    // row.showListIcon =
    row.isChecked = row.previousChecked = row.selectedCpIds && row.selectedCpIds.length > 0 ? true : false;
  });
});

// 只允许输入数字的全局项目条数上限输入框 keydown 事件
const handleGlobalItemLimitKeydown = (params: any) => {
  const event = params.$event;
  // 添加安全检查
  if (!event) {
    return;
  }
  const allowedKeys = ['Backspace', 'Delete', 'Tab', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Enter'];
  const isNumber = /^[0-9]$/.test(event.key);
  const isAllowedKey = allowedKeys.includes(event.key);

  // 只允许数字和功能键
  if (!isNumber && !isAllowedKey) {
    event.preventDefault();
    event.stopPropagation();
    return false;
  }
};
// 全局项目条数上限输入框 keypress 事件
const handleGlobalItemLimitKeypress = (params: any) => {
  const event = params.$event;

  if (!event) {
    return;
  }

  // 只允许数字字符
  const isNumber = /^[0-9]$/.test(event.key);

  if (!isNumber) {
    event.preventDefault();
    event.stopPropagation();
    return false;
  }
};

// 全局项目条数上限输入框 beforeinput 事件
const handleGlobalItemLimitBeforeInput = (params: any) => {
  const event = params.$event;
  if (!event || typeof event.inputType === 'undefined') {
    return;
  }

  const inputType = event.inputType;
  const data = event.data;

  // 如果是插入文本，检查是否为数字
  if (inputType === 'insertText' && data) {
    if (!/^[0-9]+$/.test(data)) {
      event.preventDefault();
      return false;
    }
  }
};

// input 事件
const handleGlobalItemLimitInput = (params: any) => {
  // 只保留数字
  const numericValue = String(params.value).replace(/[^0-9]/g, '');
  let value = numericValue ? Number(numericValue) : 1;
  if (value < 1) value = 1;
  globalItemLimit.value = value;
};

const handleGlobalItemLimitChange = (params: any) => {
  const value = params.value;
  if (value < 1) {
    globalItemLimit.value = 1;
  } else {
    globalItemLimit.value = value;
  }
};

//paste 事件
const handleGlobalItemLimitPaste = (params: any) => {
  const event = params.$event;

  if (!event) {
    return;
  }

  const clipboardData = event.clipboardData || (window as any).clipboardData;
  const pastedData = clipboardData.getData('Text');

  // 检查粘贴的内容是否只包含数字
  if (!/^[0-9]+$/.test(pastedData)) {
    event.preventDefault();
    event.stopPropagation();
    return false;
  }
};

//keydown 事件
const handleItemLimitKeydown = (params: any) => {
  const event = params.$event;

  // 添加安全检查
  if (!event) {
    return;
  }

  const allowedKeys = ['Backspace', 'Delete', 'Tab', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Enter'];
  const isNumber = /^[0-9]$/.test(event.key);
  const isAllowedKey = allowedKeys.includes(event.key);

  // 严格限制：只允许数字和功能键，其他所有字符都阻止
  if (!isNumber && !isAllowedKey) {
    event.preventDefault();
    event.stopPropagation();
    return false;
  }
};

// 行内项目条数上限输入框 keypress 事件
const handleItemLimitKeypress = (params: any) => {
  const event = params.$event;

  // 添加安全检查
  if (!event) {
    return;
  }

  // 只允许数字字符
  const isNumber = /^[0-9]$/.test(event.key);

  if (!isNumber) {
    event.preventDefault();
    event.stopPropagation();
    return false;
  }
};

// beforeinput 事件
const handleItemLimitBeforeInput = (params: any) => {
  const event = params.$event;
  if (!event || typeof event.inputType === 'undefined') {
    return;
  }

  const inputType = event.inputType;
  const data = event.data;

  // 如果是插入文本，检查是否为数字
  if (inputType === 'insertText' && data) {
    if (!/^[0-9]+$/.test(data)) {
      event.preventDefault();
      return false;
    }
  }
};

// 行内项目条数上限 input 事件
const handleItemLimitInput = (params: any, row: any) => {
  // 获取当前输入的值
  const currentValue = params.value;
  // 只保留数字
  const numericValue = String(currentValue).replace(/[^0-9]/g, '');
  let finalValue = numericValue ? Number(numericValue) : 1;
  if (finalValue < 1) finalValue = 1;

  row.showCount = finalValue;
};

// 行内项目条数上限 paste 事件
const handleItemLimitPaste = (params: any) => {
  const event = params.$event;

  if (!event) {
    return;
  }

  const clipboardData = event.clipboardData || (window as any).clipboardData;
  const pastedData = clipboardData.getData('Text');

  // 检查粘贴的内容是否只包含数字
  if (!/^[0-9]+$/.test(pastedData)) {
    event.preventDefault();
    event.stopPropagation();
    return false;
  }
};
// 处理复选框变化
function handleCheckboxChange(row: TableRowData) {
  // 无论是勾选还是取消，都弹出定制项目弹窗；
  // 真正的状态变更在弹窗“确认”时生效，“取消”会还原到打开前的项目选择
  handleCustomProjectTrue(row);
}

const handleCustomProjectTrue = (row: any) => {
  // 打开弹窗前先对项目选择做一份快照，供取消时还原
  row.backupSelectedCpIds = row.selectedCpIds ? [...row.selectedCpIds] : [];

  VxeUI.modal.open({
    title: '定制项目',
    width: 1100,
    height: 750,
    id: 'custom-configuration-modal',
    remember: true,
    storage: true,
    slots: {
      default() {
        return h(CustomConfiguration, {
          data: { ...row, insId: insId.value },
          onSubmit: (data: any) => {
            tableData.value.forEach((item: any) => {
              if (item.conditioningProgramType === row.conditioningProgramType) {
                item.selectedCpIds = data.selectedProjects.map((item: any) => item.projectId) as string[];
              }
            });
            // 根据是否有选中项目决定是否展示
            const hasSelected = row.selectedCpIds && row.selectedCpIds.length > 0;
            row.isChecked = !!hasSelected;
            row.isShowForInfer = hasSelected ? 'Y' : 'N';

            // 确认后更新“上一次确认”的状态和快照
            row.previousChecked = row.isChecked;
            row.backupSelectedCpIds = row.selectedCpIds ? [...row.selectedCpIds] : [];
            VxeUI.modal.close('custom-configuration-modal');
          },
          onClose: () => {
            // 取消时还原到打开弹窗前的项目选择
            row.selectedCpIds = row.backupSelectedCpIds ? [...row.backupSelectedCpIds] : [];

            // 根据还原后的已选项目恢复展示状态（是否显示仅由是否有选中项目决定）
            const hasSelected = row.selectedCpIds && row.selectedCpIds.length > 0;
            row.isChecked = !!hasSelected;
            row.isShowForInfer = hasSelected ? 'Y' : 'N';
            VxeUI.modal.close('custom-configuration-modal');
          },
        
        });
      },
    },
  });
};
</script>

<template>
  <div class="edit-configured">
    <!-- 组织名称 -->
    <div class="flex">
      <div class="organization-name mr-15" v-if="organizationName">组织名称：{{ organizationName }}</div>
      <div class="organization-name" v-if="insName">机构名称：{{ insName }}</div>
    </div>
    <!-- 表格 -->
    <vxe-table
      border
      :data="tableData"
      :row-config="rowConfig"
      :column-config="columnConfig"
      @row-dragstart="rowDragstartEvent"
      @row-dragend="rowDragendEvent"
      class="solution-table"
    >
      <!-- 方案类型列 -->
      <vxe-column field="conditioningProgramType" title="方案类型 (拖拽调整排序)" width="220" drag-sort>
        <template #default="{ row }">
          <div v-if="row.isCustomize" class="solution-type-row">
            <span>{{ row.conditioningProgramType }}</span>
          </div>
          <div v-else-if="row.conditioningProgramType && !row.isNewRow" class="solution-type-row">
            <span>{{ row.conditioningProgramType }}</span>
          </div>
          <div v-else class="solution-type-row">
            <a-select
              class="solution-type-select"
              style="width: 100%"
              v-model:value="row.conditioningProgramType"
              :options="typeOptions"
              placeholder="请选择"
              allowClear
              :loading="typeOptionsLoading"
              @change="handleSolutionTypeChange(row)"
            />
          </div>
        </template>
      </vxe-column>

      <!-- 定制项目列 -->
      <vxe-column field="isHaveForInfer" title="定制项目" width="160" align="center">
        <template #default="{ row }">
          <div class="custom-project-indicator">
            <div v-if="row.isCustomize" class="custom-project-true-container">
              <a-checkbox v-model:checked="row.isChecked" @change="handleCheckboxChange(row)"> 展示 </a-checkbox>
              <div v-if="row.isChecked" class="flex items-center custom-project-true" @click="handleCustomProjectTrue(row)">
                <MenuUnfoldOutlined />
              </div>
            </div>

            <div v-else class="custom-project-false">
              <div class="red-x-icon">×</div>
            </div>
          </div>
        </template>
      </vxe-column>

      <!-- 智能推荐项目列 -->
      <vxe-column field="knowledgeCpShowType" title="智能推荐项目" width="330" align="center">
        <template #default="{ row }">
          <div class="smart-recommend-custom">
            <label>
              <input type="radio" v-model="row.knowledgeCpShowType" value="1" />
              展示
            </label>
            <label v-if="row.isCustomize">
              <input type="radio" v-model="row.knowledgeCpShowType" value="3" />
              定制项目无结果时展示
            </label>
            <label>
              <input type="radio" v-model="row.knowledgeCpShowType" value="2" />
              不展示
            </label>
          </div>
        </template>
      </vxe-column>

      <!-- 项目条数上限列 -->
      <vxe-column field="showCount" title="项目条数上限" width="218" align="center">
        <template #header>
          <div class="item-limit-header">
            项目条数上限
            <vxe-input
              v-model="globalItemLimit"
              type="number"
              size="mini"
              style="width: 60px; margin-left: 8px"
              min="1"
              @keydown="handleGlobalItemLimitKeydown"
              @keypress="handleGlobalItemLimitKeypress"
              @beforeinput="handleGlobalItemLimitBeforeInput"
              @input="handleGlobalItemLimitInput"
              @change="handleGlobalItemLimitChange"
              @paste="handleGlobalItemLimitPaste"
            />
            <span style="margin-left: 4px">条</span>
          </div>
        </template>
        <template #default="{ row }">
          <vxe-input
            v-model="row.showCount"
            type="number"
            size="mini"
            style="width: 80px"
            @keydown="handleItemLimitKeydown"
            @keypress="(params) => handleItemLimitKeypress(params)"
            @beforeinput="(params) => handleItemLimitBeforeInput(params)"
            @input="(params) => handleItemLimitInput(params, row)"
            @paste="handleItemLimitPaste"
            min="1"
          />
          <span style="margin-left: 4px">条</span>
        </template>
      </vxe-column>

      <!-- 操作列 -->
      <vxe-column title="操作" width="120" align="center">
        <template #default="{ row }">
          <vxe-button v-if="!row.isCustomize" mode="text" status="primary" @click="deleteRow(row)"> 删除 </vxe-button>
        </template>
      </vxe-column>
    </vxe-table>

    <!-- 添加按钮 -->
    <div class="add-button-container">
      <vxe-button type="primary" size="large" @click="addRow" class="add-button"> + </vxe-button>
    </div>

    <!-- 底部操作按钮 -->
    <div class="action-buttons">
      <vxe-button @click="cancelEdit">取消</vxe-button>
      <vxe-button type="primary" status="warning" @click="saveData" :loading="submitting">保存</vxe-button>
    </div>
  </div>
</template>

<style scoped>
.edit-configured {
  padding: 15px;
  background: #fff;
}

.organization-name {
  font-size: 15px;
  margin-bottom: 20px;
  color: #333;
}

.solution-table {
  margin-bottom: 20px;
}

.custom-project-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}
.custom-project-true-container {
  display: flex;
  align-items: center;
}
.custom-project-true {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background-color 0.2s ease;
}

.custom-project-true:hover {
  background-color: rgba(24, 144, 255, 0.05);
}

.blue-checkbox {
  width: 16px;
  height: 16px;
  background: #1890ff;
  border-radius: 2px;
  position: relative;
}

.blue-checkbox::after {
  content: '';
  position: absolute;
  left: 5px;
  top: 2px;
  width: 4px;
  height: 8px;
  border: 2px solid white;
  border-top: none;
  border-left: none;
  transform: rotate(45deg);
}

.custom-project-false {
  display: flex;
  align-items: center;
  gap: 8px;
}

.red-x-icon {
  width: 16px;
  height: 16px;
  background: #ff4d4f;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 12px;
  font-weight: bold;
}

.smart-recommend-custom,
.smart-recommend-non-custom {
  display: flex;
  align-items: center;
  gap: 10px;
}

.smart-recommend-custom label,
.smart-recommend-non-custom label {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  margin-left: 10px;
}

.item-limit-header {
  display: flex;
  align-items: center;
  justify-content: center;
}

.add-button-container {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 80px;
}

/* vxe-table 样式调整 */
:deep(.vxe-table) {
  border: 1px solid #e8e8e8;
}

:deep(.vxe-table--header) {
  background: #fafafa;
}

:deep(.vxe-table--body) {
  background: #fff;
}

:deep(.vxe-table--row) {
  border-bottom: 1px solid #f0f0f0;
}

:deep(.vxe-table--cell) {
  padding: 12px 8px;
}

:deep(.vxe-table:not([data-calc-col]) .vxe-cell--wrapper) {
  display: flex;
}
/* 下拉选择框样式 */
select {
  width: 100%;
  padding: 4px 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  background: #fff;
  margin-left: 8px;
}

select:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

/* 添加按钮样式优化 */
.add-button {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  font-size: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  color: #1890ff;
  cursor: pointer;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 80px;
}

.action-buttons .vxe-button {
  min-width: 80px;
  height: 36px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.action-buttons .vxe-button:first-child {
  background: #f5f5f5;
  border: 1px solid #d9d9d9;
  color: #666;
}

.action-buttons .vxe-button:first-child:hover {
  background: #e6e6e6;
  border-color: #bfbfbf;
  color: #333;
}
:deep(.vxe-input) {
  border-radius: 4px;
  transition: all 0.3s ease;
}

:deep(.vxe-input:focus) {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.solution-type-row {
  display: flex;
  align-items: center;
  margin-left: 8px;
  width: 100%;
}

:deep(.vxe-table .vxe-cell--wrapper) {
  align-items: center;
}
</style>
