<script lang="ts" setup>
import { ref } from 'vue';
import { Page, useVbenModal } from '@vben/common-ui';
import {
  PlusOutlined,
  DeleteOutlined,
  EnterOutlined,
} from '@ant-design/icons-vue';
import {
  Button,
  Col,
  Input,
  message,
  Popconfirm,
  Row,
  Tooltip,
} from 'ant-design-vue';

import { getDoctorOrderList } from '#/views/doctor/doctor-reception/api';
import {
  createDoctorOrderApi,
  deleteDoctorOrderApi,
} from '#/views/doctor/settings/api';

const searchKey = ref('');
const doctorOrderCommonList = ref([]);
const doctorOrderMyList = ref([]);
const selectDiagnosisList = ref('');
const setUpdateDoctorOrder = ref();

// 新增医嘱相关
const newOrderContent = ref('');
const showAddInput = ref(false);

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

/**
 * 获取医嘱列表
 */
function getDoctorOrderListData() {
  getDoctorOrderList().then((res) => {
    doctorOrderCommonList.value = res.common.map((item) => {
      item.isSelect = 0;
      if (selectDiagnosisList.value) {
        // 把values的字符串转为数组根据，分解
        const valuesArr = selectDiagnosisList.value.split('，');
        // 判断valuesArr数组中是否有item.name
        valuesArr.forEach((value) => {
          if (value === item.name) {
            item.isSelect = 1;
          }
        });
      }
      return item;
    });
    doctorOrderMyList.value = res.my.map((item) => {
      item.isSelect = 0;
      if (selectDiagnosisList.value) {
        // 把values的字符串转为数组根据，分解
        const valuesArr = selectDiagnosisList.value.split('，');
        // 判断valuesArr数组中是否有item.name
        valuesArr.forEach((value) => {
          if (value === item.content) {
            item.isSelect = 1;
          }
        });
      }
      return item;
    });
  });
}

/**
 * 选择医嘱
 * @param item
 * @param type 1=我的医嘱(content字段), 2=公共医嘱(name字段)
 */
function selectDoctorOrder(item, type = 1) {
  // 将当前值转换为数组（过滤空值）
  let arr = selectDiagnosisList.value ? selectDiagnosisList.value.split('，').filter(Boolean) : [];

  if (type === 1) {
    if (item.isSelect === 1) {
      // 取消选中：从数组中删除元素
      arr = arr.filter(name => name !== item.content);
      item.isSelect = 0;
    } else {
      // 选中：确保不重复后添加
      if (!arr.includes(item.content)) {
        arr.push(item.content);
      }
      item.isSelect = 1;
    }
  } else {
    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('，');
}

/**
 * 添加自定义医嘱
 */
async function addMyDoctorOrder() {
  if (!newOrderContent.value.trim()) {
    message.warning('请输入医嘱内容');
    return;
  }

  try {
    await createDoctorOrderApi(newOrderContent.value.trim());
    message.success('添加成功');
    newOrderContent.value = '';
    showAddInput.value = false;
    // 刷新列表
    await getDoctorOrderListData();
  } catch (error) {
    message.error('添加失败，请重试');
  }
}

/**
 * 删除我的医嘱
 * @param item 医嘱项
 */
async function deleteMyDoctorOrder(item) {
  try {
    await deleteDoctorOrderApi(item.id);
    message.success('删除成功');
    // 刷新列表
    await getDoctorOrderListData();
  } catch (error) {
    message.error('删除失败，请重试');
  }
}

/**
 * 取消添加
 */
function cancelAdd() {
  newOrderContent.value = '';
  showAddInput.value = false;
}
</script>

<template>
  <Modal class="w-[60%]" title="常用医嘱">
    <Page>
      <Row :gutter="12">
        <!-- 我的医嘱 -->
        <Col :span="24" class="mb-4">
          <div class="section-header">
            <span class="section-title">我的医嘱</span>
          </div>

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

              <!-- Action Area -->
              <div class="tag-action-wrapper" @click.stop>
                <Popconfirm
                  title="确定删除这条医嘱吗？"
                  placement="topRight"
                  @confirm="deleteMyDoctorOrder(item)"
                >
                  <Tooltip title="删除医嘱">
                    <span class="action-icon delete">
                      <DeleteOutlined />
                    </span>
                  </Tooltip>
                </Popconfirm>
              </div>
            </div>

            <!-- Add New Button/Input Area -->
            <div class="add-tag-wrapper" :class="{ 'is-input': showAddInput }">
              <div v-if="!showAddInput" class="add-btn-tag" @click="showAddInput = true">
                <PlusOutlined class="mr-1"/> 添加医嘱
              </div>

              <div v-else class="add-input-container">
                <Input
                  v-model:value="newOrderContent"
                  placeholder="输入内容后回车"
                  size="small"
                  class="custom-input"
                  ref="inputRef"
                  @pressEnter="addMyDoctorOrder"
                  @blur="!newOrderContent && cancelAdd()"
                />
                <span class="enter-icon" @click="addMyDoctorOrder">
                  <EnterOutlined />
                </span>
              </div>
            </div>
          </div>
        </Col>

        <!-- 公共医嘱 -->
        <Col :span="24">
          <div class="section-header" v-if="doctorOrderCommonList.length > 0">
            <span class="section-title">公共医嘱</span>
          </div>

          <div class="tag-container">
            <div
              v-for="item in doctorOrderCommonList"
              :key="item.id"
              class="smart-tag"
              :class="{ 'is-selected': item.isSelect === 1 }"
              @click="selectDoctorOrder(item, 2)"
            >
              <span class="tag-text">{{ item.name }}</span>
            </div>
          </div>
        </Col>
      </Row>
    </Page>
  </Modal>
</template>

<style lang="scss" scoped>
/* Common 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;
    }
  }
}

.dark .section-header .section-title {
  color: #e5e7eb;
}

/* Tag Layout */
.tag-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
}

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

  &:hover {
    background-color: #f3f4f6;
    border-color: #d1d5db;
    transform: translateY(-1px);

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

  &.is-selected {
    background-color: #eff6ff;
    border-color: #3b82f6;
    color: #2563eb;

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

  .tag-text {
    font-size: 14px;
    color: #4b5563;
  }
}

.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 Icon slide-in logic */
.tag-action-wrapper {
  display: inline-flex;
  align-items: center;
  max-width: 0;
  overflow: hidden;
  opacity: 0;
  transition: all 0.25s ease;
  margin-left: 0;
}

.action-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  font-size: 12px;

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

/* Add New Tag Button Area */
.add-tag-wrapper {
  height: 34px;
  display: inline-flex;
  align-items: center;
  transition: all 0.3s;

  &.is-input {
    width: 200px; /* Expand width when typing */
  }
}

.add-btn-tag {
  display: inline-flex;
  align-items: center;
  padding: 0 14px;
  height: 100%;
  border: 1px dashed #d1d5db;
  border-radius: 9999px;
  color: #6b7280;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.2s;

  &:hover {
    border-color: #3b82f6;
    color: #3b82f6;
    background-color: rgba(59, 130, 246, 0.05);
  }
}

.dark .add-btn-tag {
  border-color: #4b5563;
  color: #9ca3af;
  &:hover {
    border-color: #3b82f6;
    color: #3b82f6;
  }
}

.add-input-container {
  position: relative;
  width: 100%;
  height: 100%;

  .custom-input {
    height: 100%;
    border-radius: 9999px;
    padding-right: 30px; /* Space for enter icon */
    font-size: 13px;

    &:focus {
      box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
    }
  }

  .enter-icon {
    position: absolute;
    right: 8px;
    top: 50%;
    transform: translateY(-50%);
    color: #9ca3af;
    cursor: pointer;
    font-size: 12px;
    padding: 2px;

    &:hover {
      color: #3b82f6;
    }
  }
}
</style>
