<template>
  <view class="manage-container">
    <view class="group-list">
      <view v-for="(item, index) in groups" :key="item._id" class="group-item">
        <view class="left-action" :class="{ disabled: Boolean(item.parentGroupId) || isSort }" @click="handleDelete(item, index)">
          <uni-icons type="minus-filled" size="24" :color="Boolean(item.parentGroupId) || isSort ? '#ddd' : '#ff4d4f'"></uni-icons>
        </view>
        <view class="group-name">
          <view class="name-row">
            <text class="name-text">{{ item.groupName }}</text>
            <text v-if="item.parentGroupId" class="corp-tag">机构</text>
          </view>
          <text v-if="item.description" class="desc">{{ item.description }}</text>
        </view>
        <view class="right-actions">
          <uni-icons type="compose" size="24" :color="isSort ? '#ddd' : '#5d8aff'" class="icon-edit" @click="handleEdit(item, index)"></uni-icons>
          <template v-if="isSort">
            <uni-icons type="arrowup" size="20" color="#5d8aff" class="icon-sort" @click="moveUp(index)"></uni-icons>
            <uni-icons type="arrowdown" size="20" color="#5d8aff" class="icon-sort" @click="moveDown(index)"></uni-icons>
          </template>
          <uni-icons v-else type="bars" size="24" color="#5d8aff" class="icon-drag" @click="enterSort"></uni-icons>
        </view>
      </view>
    </view>

    <!-- Bottom Button -->
    <view class="footer">
      <template v-if="isSort">
        <button class="add-btn plain" @click="cancelSort">取消</button>
        <button class="add-btn" @click="saveSort">保存</button>
      </template>
      <button v-else class="add-btn" @click="handleAdd">添加新分组</button>
    </view>

    <!-- Dialog -->
    <view v-if="showDialog" class="dialog-mask">
      <view class="dialog-content">
        <view class="dialog-header">{{ dialogTitle }}</view>
        <view class="dialog-body">
          <input class="dialog-input" type="text" v-model="inputValue" placeholder="请输入分组名称" />
        </view>
        <view class="dialog-footer">
          <button class="dialog-btn cancel" @click="closeDialog">取消</button>
          <button class="dialog-btn confirm" @click="handleSave">保存</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { storeToRefs } from 'pinia';
import api from '@/utils/api';
import useAccountStore from '@/store/account';
import { hideLoading, loading, toast } from '@/utils/widget';

// State
const groups = ref([]);
const originalGroups = ref([]);
const isSort = ref(false);

const GROUPS_RELOAD_KEY = 'ykt_case_groups_need_reload';
const CURRENT_TEAM_STORAGE_KEY = 'ykt_case_current_team';

const accountStore = useAccountStore();
const { account, doctorInfo } = storeToRefs(accountStore);
const { getDoctorInfo } = accountStore;

function getUserId() {
  const d = doctorInfo.value || {};
  const a = account.value || {};
  return String(d.userid || d.userId || d.corpUserId || a.userid || a.userId || '') || '';
}

function getCorpId() {
  const d = doctorInfo.value || {};
  const a = account.value || {};
  const team = uni.getStorageSync(CURRENT_TEAM_STORAGE_KEY) || {};
  return String(d.corpId || a.corpId || team.corpId || '') || '';
}

function getTeamId() {
  const team = uni.getStorageSync(CURRENT_TEAM_STORAGE_KEY) || {};
  return String(team.teamId || '') || '';
}

function sortGroupList(list) {
  const { orderList, corpList, restList } = (Array.isArray(list) ? list : []).reduce(
    (p, c) => {
      if (typeof c?.sortOrder === 'number') p.orderList.push(c);
      else if (c?.parentGroupId) p.corpList.push(c);
      else p.restList.push(c);
      return p;
    },
    { orderList: [], corpList: [], restList: [] }
  );
  orderList.sort((a, b) => a.sortOrder - b.sortOrder);
  return [...orderList, ...corpList, ...restList];
}

async function ensureDoctor() {
  if (doctorInfo.value) return;
  if (!account.value?.openid) return;
  try {
    await getDoctorInfo();
  } catch (e) {
    // ignore
  }
}

async function loadGroups() {
  await ensureDoctor();
  const corpId = getCorpId();
  const teamId = getTeamId();
  if (!corpId || !teamId) return;

  loading('加载中...');
  try {
    const projection = { _id: 1, groupName: 1, parentGroupId: 1, description: 1, sortOrder: 1 };
    const res = await api('getGroups', { corpId, teamId, page: 1, pageSize: 1000, projection, countGroupMember: false });
    if (!res?.success) {
      toast(res?.message || '获取分组失败');
      return;
    }
    const list = Array.isArray(res.data) ? res.data : Array.isArray(res.data?.data) ? res.data.data : [];
    const sorted = sortGroupList(list);
    groups.value = sorted.map((i) => ({ ...i }));
    originalGroups.value = sorted.map((i) => ({ ...i }));
  } catch (e) {
    toast('获取分组失败');
  } finally {
    hideLoading();
  }
}

const showDialog = ref(false);
const dialogMode = ref('add'); // 'add' or 'edit'
const inputValue = ref('');
const editingIndex = ref(-1);

const dialogTitle = ref('添加新分组');

// Methods
const handleAdd = () => {
  if (isSort.value) return;
  dialogMode.value = 'add';
  dialogTitle.value = '添加新分组';
  inputValue.value = '';
  showDialog.value = true;
};

const handleEdit = (item, index) => {
  if (isSort.value) return;
  dialogMode.value = 'edit';
  dialogTitle.value = '编辑分组名称';
  inputValue.value = item.groupName || '';
  editingIndex.value = index;
  showDialog.value = true;
};

const handleDelete = (item, index) => {
  if (isSort.value) return;
  if (item?.parentGroupId) return;
  uni.showModal({
    title: '提示',
    content: '确定要删除该分组吗？',
    success: async (res) => {
      if (!res.confirm) return;
      const corpId = getCorpId();
      const teamId = getTeamId();
      if (!corpId || !teamId) {
        toast('缺少团队信息');
        return;
      }
      loading('');
      try {
        const delRes = await api('removeGroup', { corpId, id: item._id, teamId, groupType: 'team' });
        if (!delRes?.success) {
          toast(delRes?.message || '删除失败');
          return;
        }
        toast('删除成功');
        uni.setStorageSync(GROUPS_RELOAD_KEY, 1);
        await loadGroups();
      } finally {
        hideLoading();
      }
    },
  });
};

const closeDialog = () => {
  showDialog.value = false;
};

const handleSave = async () => {
  if (!inputValue.value.trim()) {
    uni.showToast({ title: '请输入分组名称', icon: 'none' });
    return;
  }

  await ensureDoctor();
  const corpId = getCorpId();
  const teamId = getTeamId();
  const userId = getUserId();
  if (!corpId || !teamId || !userId) {
    toast('缺少用户/团队信息');
    return;
  }

  loading('保存中...');
  try {
    if (dialogMode.value === 'add') {
      const params = {
        groupName: inputValue.value.trim(),
        teamId,
        groupType: 'team',
        creator: userId,
      };
      const res = await api('createGroup', { corpId, teamId, params });
      if (!res?.success) {
        toast(res?.message || '新增失败');
        return;
      }
      toast('新增成功');
    } else {
      const item = groups.value[editingIndex.value];
      if (!item?._id) return;
      const res = await api('updateGroup', { corpId, id: item._id, params: { groupName: inputValue.value.trim() } });
      if (!res?.success) {
        toast(res?.message || '修改失败');
        return;
      }
      toast('修改成功');
    }
    uni.setStorageSync(GROUPS_RELOAD_KEY, 1);
    closeDialog();
    await loadGroups();
  } finally {
    hideLoading();
  }
};

function enterSort() {
  if (!groups.value.length) return;
  isSort.value = true;
}

function cancelSort() {
  isSort.value = false;
  groups.value = originalGroups.value.map((i) => ({ ...i }));
}

function moveUp(index) {
  if (!isSort.value) return;
  if (index <= 0) return;
  const next = groups.value.slice();
  const tmp = next[index - 1];
  next[index - 1] = next[index];
  next[index] = tmp;
  groups.value = next;
}

function moveDown(index) {
  if (!isSort.value) return;
  if (index >= groups.value.length - 1) return;
  const next = groups.value.slice();
  const tmp = next[index + 1];
  next[index + 1] = next[index];
  next[index] = tmp;
  groups.value = next;
}

async function saveSort() {
  const teamId = getTeamId();
  if (!teamId) return;
  loading('');
  try {
    const data = groups.value.map((i, idx) => ({ _id: i._id, sortOrder: idx }));
    const res = await api('sortGroups', { teamId, data });
    if (!res?.success) {
      toast(res?.message || '保存失败');
      return;
    }
    toast('保存成功');
    uni.setStorageSync(GROUPS_RELOAD_KEY, 1);
    isSort.value = false;
    await loadGroups();
  } finally {
    hideLoading();
  }
}

onLoad(() => {
  loadGroups();
});
</script>

<style lang="scss" scoped>
.manage-container {
  min-height: 100vh;
  background-color: #fff;
  padding-bottom: 80px; // Space for footer
}

.group-list {
  padding: 0 15px;
}

.group-item {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #eee;

  .left-action {
    margin-right: 15px;
    &.disabled {
      opacity: 0.6;
    }
  }

  .group-name {
    flex: 1;
    font-size: 16px;
    color: #333;
    .name-row {
      display: flex;
      align-items: center;
      gap: 8px;
    }
    .corp-tag {
      font-size: 12px;
      padding: 2px 6px;
      border-radius: 10px;
      background: #f0f0f0;
      color: #666;
    }
    .desc {
      display: block;
      margin-top: 4px;
      font-size: 12px;
      color: #999;
    }
  }

  .right-actions {
    display: flex;
    align-items: center;
    gap: 15px;
    
    .icon-edit, .icon-drag {
      padding: 5px; // Increase tap area
    }
    .icon-sort {
      padding: 5px;
    }
  }
}

.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 15px 20px 30px; // Safe area padding
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  
  .add-btn {
    background-color: #5d8aff;
    color: #fff;
    border-radius: 4px;
    font-size: 16px;
    height: 44px;
    line-height: 44px;
    border: none;
    
    &::after {
      border: none;
    }

    &.plain {
      background-color: #fff;
      color: #666;
      border: 1px solid #ddd;
    }
  }
}

// Custom Dialog Styles
.dialog-mask {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 999;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.dialog-content {
  width: 280px;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);

  .dialog-header {
    padding: 20px 0 10px;
    text-align: center;
    font-size: 18px;
    font-weight: 500;
    color: #333;
  }

  .dialog-body {
    padding: 10px 20px 20px;

    .dialog-input {
      border: 1px solid #ddd;
      height: 40px;
      padding: 0 10px;
      border-radius: 4px;
      font-size: 14px;
    }
  }

  .dialog-footer {
    display: flex;
    padding: 0 20px 20px;
    justify-content: space-between;
    gap: 15px;

    .dialog-btn {
      flex: 1;
      height: 36px;
      line-height: 36px;
      font-size: 14px;
      margin: 0;
      
      &.cancel {
        background-color: #fff;
        color: #666;
        border: 1px solid #ddd;
      }
      
      &.confirm {
        background-color: #5d8aff;
        color: #fff;
        border: none; // Remove border for confirm button usually
      }

      &::after {
        border: none;
      }
    }
  }
}
</style>
