<script lang="ts" setup>
import { computed, ref } from 'vue';
import { Page, useVbenModal } from '@vben/common-ui';
import {
  PlusOutlined,
  DeleteOutlined,
  CheckCircleFilled,
} from '@ant-design/icons-vue';
import {
  Button,
  Col,
  InputSearch,
  message,
  Popconfirm,
  Row,
  Tooltip,
  Pagination,
} from 'ant-design-vue';
import { getDiseaseList } from '#/views/doctor/doctor-reception/api';
import { debounce } from 'lodash-es';
import {
  getDoctorMyDiseaseListApi,
  addDoctorMyDiseaseApi,
  deleteDoctorMyDiseaseApi,
} from "#/views/doctor/settings/api";

const searchKey = ref('');
// 存储接口返回的所有诊断数据
const allDiagnosisList = ref([]);
const selectDiagnosisList = ref('');
const setUpdateDiagnosis = ref();

// 分页相关状态
const currentPage = ref(1);
const pageSize = ref(30); // 每页显示30条，tag比较小，可以多显示点

// 计算属性：当前页展示的诊断数据
const paginatedDiagnosisList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return allDiagnosisList.value.slice(start, end);
});

/**
 * 常用诊断列表
 */
const doctorMyDiseaseList = ref([]);
const getDoctorMyDiseaseList = () => {
  getDoctorMyDiseaseListApi().then((res) => {
    doctorMyDiseaseList.value = res.map((item) => {
      item.disease.isSelect = 0;
      if (selectDiagnosisList.value) {
        // 把values的字符串转为数组根据，分解
        const valuesArr = selectDiagnosisList.value.split('，');
        // 判断valuesArr数组中是否有item.disease.name
        valuesArr.forEach((value) => {
          if (value === item.disease.name) {
            item.disease.isSelect = 1;
          }
        });
      }
      return item;
    });
  });
}

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    setUpdateDiagnosis.value(selectDiagnosisList.value);
    modalApi.close();
    message.success('保存成功');
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      setUpdateDiagnosis.value = isOpen ? modalApi.getData()?.updateDiagnosis : null;
      const { values } =
        modalApi.getData<Record<string, any>>();
      if (values) {
        selectDiagnosisList.value = values;
      }
      getDiagnosisList();
      getDoctorMyDiseaseList();
    }
  },
});

/**
 * 获取诊断列表
 * @param searchKey
 */
function getDiagnosisList(searchKey = '') {
  getDiseaseList(searchKey).then((res) => {
    // 处理所有数据
    const processedList = res.map((item) => {
      item.isSelect = 0;
      // 检查是否已在常用诊断中
      item.isInMyList = doctorMyDiseaseList.value.some(
        (myItem) => myItem.disease.id === item.id
      );
      if (selectDiagnosisList.value) {
        // 把values的字符串转为数组根据，分解
        const valuesArr = selectDiagnosisList.value.split('，');
        // 判断valuesArr数组中是否有item.name
        valuesArr.forEach((value) => {
          if (value === item.name) {
            item.isSelect = 1;
          }
        });
      }
      return item;
    });

    // 更新总数据源并重置页码
    allDiagnosisList.value = processedList;
    currentPage.value = 1;
  });
}

const getDiagnosisListChage = debounce(async (searchText = '') => {
  getDiagnosisList(searchText);
}, 300)

/**
 * 选择诊断
 * @param item
 */
function selectDiagnosis(item) {
  // 将当前值转换为数组（过滤空值）
  let arr = selectDiagnosisList.value ? selectDiagnosisList.value.split('，').filter(Boolean) : [];

  if (item.isSelect === 1) {
    // 取消选中：从数组中删除元素
    arr = arr.filter(name => name !== item.name);
    item.isSelect = 0;
  } else {
    // 选中：确保不重复后添加
    if (!arr.includes(item.name)) {
      arr.push(item.name);
    }
    item.isSelect = 1;
  }

  // 将数组转回字符串更新到响应式变量
  selectDiagnosisList.value = arr.join('，');
}

/**
 * 添加到常用诊断
 * @param item 诊断项
 */
async function addToMyDiagnosis(item) {
  try {
    await addDoctorMyDiseaseApi(item.id);
    message.success(`已将「${item.name}」添加到常用诊断`);
    // 刷新常用诊断列表
    await getDoctorMyDiseaseList();
    // 更新搜索结果中的状态
    item.isInMyList = true;
  } catch (error) {
    message.error('添加失败，请重试');
  }
}

/**
 * 从常用诊断中删除
 * @param item 常用诊断项（包含id和disease）
 */
async function removeFromMyDiagnosis(item) {
  try {
    await deleteDoctorMyDiseaseApi(item.id);
    message.success(`已将「${item.disease.name}」从常用诊断中移除`);
    // 刷新常用诊断列表
    await getDoctorMyDiseaseList();

    // 更新总数据源中的状态 (不仅仅是当前页)
    const searchItem = allDiagnosisList.value.find(
      (d) => d.id === item.disease.id
    );
    if (searchItem) {
      searchItem.isInMyList = false;
    }
  } catch (error) {
    message.error('删除失败，请重试');
  }
}

/**
 * 页码改变
 */
function handlePageChange(page: number, size: number) {
  currentPage.value = page;
  pageSize.value = size;
}
</script>

<template>
  <Modal class="w-[60%]" title="常用诊断">
    <Page>
      <Row :gutter="12">
        <Col :span="24" class="mb-4">
          <InputSearch :model="searchKey" allow-clear enter-button placeholder="请输入想要搜索的诊断名称..." size="large"
                       @input="(e) => getDiagnosisListChage(e.target.value)" @search="getDiagnosisList" />
        </Col>

        <Col :span="24">
          <!-- 常用诊断列表 -->
          <div class="section-header" v-if="doctorMyDiseaseList.length > 0">
            <span class="section-title">常用诊断</span>
            <span class="section-count">{{ doctorMyDiseaseList.length }}</span>
          </div>

          <div class="tag-container" v-if="doctorMyDiseaseList.length > 0">
            <div
              v-for="item in doctorMyDiseaseList"
              :key="item.id"
              class="smart-tag"
              :class="{ 'is-selected': item.disease.isSelect === 1 }"
              @click="selectDiagnosis(item.disease)"
            >
              <span class="tag-text">{{ item.disease.name }}</span>

              <!-- Action Area -->
              <div class="tag-action-wrapper" @click.stop>
                <Popconfirm
                  title="确定从常用诊断中移除吗？"
                  placement="topRight"
                  @confirm="removeFromMyDiagnosis(item)"
                >
                  <Tooltip title="移除常用">
                    <span class="action-icon delete">
                      <DeleteOutlined />
                    </span>
                  </Tooltip>
                </Popconfirm>
              </div>
            </div>
          </div>

          <!-- 搜索结果列表 -->
          <div class="section-header mt-6" v-if="allDiagnosisList.length > 0">
            <span class="section-title">搜索结果</span>
            <span class="section-count">共 {{ allDiagnosisList.length }} 条</span>
          </div>

          <div class="tag-container">
            <div
              v-for="item in paginatedDiagnosisList"
              :key="item.id"
              class="smart-tag"
              :class="{ 'is-selected': item.isSelect === 1 }"
              @click="selectDiagnosis(item)"
            >
              <span class="tag-text">{{ item.name }}</span>

              <div class="tag-action-wrapper" @click.stop>
                <Tooltip v-if="!item.isInMyList" title="加入常用">
                  <span class="action-icon add" @click="addToMyDiagnosis(item)">
                    <PlusOutlined />
                  </span>
                </Tooltip>
                <Tooltip v-else title="已在常用列表">
                  <span class="action-icon added">
                    <CheckCircleFilled />
                  </span>
                </Tooltip>
              </div>
            </div>

            <div v-if="allDiagnosisList.length === 0 && searchKey" class="empty-state">
              暂无相关诊断
            </div>

            <!-- 分页组件 -->
            <div v-if="allDiagnosisList.length > 0" class="pagination-wrapper">
              <Pagination
                v-model:current="currentPage"
                v-model:pageSize="pageSize"
                :total="allDiagnosisList.length"
                :show-total="total => `共 ${total} 条`"
                show-size-changer
                show-quick-jumper
                size="small"
                @change="handlePageChange"
              />
            </div>
          </div>
        </Col>
      </Row>
    </Page>
  </Modal>
</template>

<style lang="scss" scoped>
/* Section Headers */
.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;

  .section-title {
    font-size: 15px;
    font-weight: 600;
    color: #1f2937;
    position: relative;
    padding-left: 10px;

    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 4px;
      height: 14px;
      background-color: #3b82f6;
      border-radius: 2px;
    }
  }

  .section-count {
    margin-left: 8px;
    font-size: 12px;
    color: #9ca3af;
    background: #f3f4f6;
    padding: 1px 6px;
    border-radius: 10px;
  }
}

.dark .section-header {
  .section-title {
    color: #e5e7eb;
  }
  .section-count {
    background: #374151;
    color: #9ca3af;
  }
}

/* Tag Container */
.tag-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  min-height: 40px;
  align-content: flex-start;
}

/* Smart Tag Styles */
.smart-tag {
  position: relative;
  display: inline-flex;
  align-items: center;
  padding: 6px 14px;
  background-color: #f9fafb;
  border: 1px solid #e5e7eb;
  border-radius: 9999px; /* Pill shape */
  cursor: pointer;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  user-select: none;
  max-width: 100%;

  &:hover {
    background-color: #f3f4f6;
    border-color: #d1d5db;
    transform: translateY(-1px);
    box-shadow: 0 2px 4px rgba(0,0,0,0.05);

    .tag-action-wrapper {
      max-width: 24px;
      margin-left: 8px;
      opacity: 1;
    }
  }

  /* Selected State */
  &.is-selected {
    background-color: #eff6ff;
    border-color: #3b82f6;
    color: #2563eb;
    font-weight: 500;

    &:hover {
      background-color: #dbeafe;
    }

    .tag-text {
      color: #2563eb;
    }
  }

  /* Text Styling */
  .tag-text {
    font-size: 14px;
    color: #4b5563;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    transition: color 0.2s;
  }
}

.dark .smart-tag {
  background-color: #1f2937;
  border-color: #374151;

  .tag-text {
    color: #d1d5db;
  }

  &:hover {
    background-color: #374151;
    border-color: #4b5563;
  }

  &.is-selected {
    background-color: rgba(59, 130, 246, 0.15);
    border-color: #3b82f6;

    .tag-text {
      color: #60a5fa;
    }
  }
}

/* Action Area (The Delete/Add buttons) */
.tag-action-wrapper {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  max-width: 0;
  overflow: hidden;
  opacity: 0;
  transition: all 0.3s ease;
  margin-left: 0;

  /* Show existing "Added" checkmark always or control via props?
     Here we keep it hidden until hover for cleaner look,
     OR we can make "Added" status distinct.
     Let's keep the slide-in effect for actions. */
}

/* Specifically for "Already Added" checkmark - maybe always show it?
   To keep UI clean, let's show it on hover or if it's "isInMyList"
   but the requirement is to optimize hover. */
.action-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  font-size: 12px;
  transition: all 0.2s;

  &.delete {
    color: #9ca3af;
    &:hover {
      background-color: #fee2e2;
      color: #ef4444;
    }
  }

  &.add {
    color: #9ca3af;
    &:hover {
      background-color: #dbeafe;
      color: #3b82f6;
    }
  }

  &.added {
    color: #10b981;
    cursor: default;
  }
}

.empty-state {
  width: 100%;
  text-align: center;
  padding: 20px;
  color: #9ca3af;
  font-size: 14px;
}

.pagination-wrapper {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
  padding-top: 12px;
  border-top: 1px dashed #e5e7eb;
}

.dark .pagination-wrapper {
  border-color: #374151;
}
</style>
