<template>
  <div style="padding: 10px">
    <q-card inline class="fit shadow-6">
      <q-card-main>
        <div class="row fit">
          <!-- 左侧：应用分组列表 -->
          <div class="col-4" style="border-right: 1px solid #e0e0e0; padding-right: 10px">
            <div class="row items-center justify-between q-mb-md">
              <div class="text-h6">应用分组</div>
              <q-btn color="primary" icon="add" size="sm" @click="openAddGroupDialog">
                添加分组
              </q-btn>
            </div>

            <q-list bordered separator class="group-list-container">
              <draggable
                v-model="applicationsGroups"
                @end="onGroupDragEnd"
                animation="200"
                handle=".drag-handle"
              >
                <q-item
                  v-for="group in applicationsGroups"
                  :key="group.id"
                  clickable
                  :active="selectedGroup && selectedGroup.id === group.id"
                  class="group-item"
                  :class="{
                    'selected-group': selectedGroup && selectedGroup.id === group.id,
                  }"
                >
                  <q-item-main>
                    <div class="row items-center justify-between">
                      <div class="col">
                        <div class="text-left text-weight-medium">
                          {{ group.groupName }}
                        </div>
                        <div class="text-left text-caption text-grey-7">
                          {{ group.groupCode }}
                        </div>
                      </div>
                      <div class="col-auto">
                        <q-icon
                          name="drag_indicator"
                          class="drag-handle cursor-move text-grey-6 drag-icon-visible"
                          size="18px"
                        ></q-icon>
                      </div>
                    </div>
                  </q-item-main>
                  <q-item-side right>
                    <q-btn
                      flat
                      round
                      dense
                      icon="apps"
                      size="sm"
                      color="primary"
                      @click.stop="selectGroup(group)"
                    />
                    <q-btn
                      flat
                      round
                      dense
                      icon="edit"
                      size="sm"
                      @click.stop="editGroup(group)"
                    />
                    <q-btn
                      flat
                      round
                      dense
                      icon="delete"
                      size="sm"
                      color="negative"
                      @click.stop="deleteGroup(group)"
                    />
                  </q-item-side>
                </q-item>
              </draggable>
            </q-list>
          </div>

          <!-- 右侧：应用管理 -->
          <div class="col-8" style="padding-left: 10px">
            <div v-if="selectedGroup">
              <div class="row items-center justify-between q-mb-md">
                <div class="text-h6">{{ selectedGroup.groupName }} - 应用管理</div>
                <div>
                  <q-btn color="primary" icon="add" @click="openAddApplicationDialog">
                    添加应用
                  </q-btn>
                </div>
              </div>

              <!-- 拖拽排序提示 -->
              <!-- <div class="row items-center q-mb-sm text-caption text-grey-6">
                <q-icon name="drag_indicator" size="16px" class="q-mr-xs" />
                提示：拖拽
                <q-icon name="drag_indicator" size="16px" class="q-mx-xs" />
                图标可调整应用排序
              </div> -->

              <!-- 应用列表 - 使用draggable实现拖拽排序 -->
              <q-card flat bordered class="application-list-card">
                <draggable
                  v-model="groupApplications"
                  @end="onApplicationDragEnd"
                  animation="200"
                  handle=".app-drag-handle"
                  ghost-class="sortable-ghost"
                  class="application-draggable-list"
                >
                  <q-item
                    v-for="(app, index) in groupApplications"
                    :key="app.id"
                    class="application-list-item"
                  >
                    <q-item-main>
                      <div class="row items-center justify-between">
                        <div class="col">
                          <div class="row items-center">
                            <!-- 排序序号 -->
                              {{ index + 1 }}
                            <!-- 应用名称 -->
                            <div class="text-left text-weight-medium q-ml-sm">
                              {{ app.title }}
                            </div>
                          </div>
                          <div class="text-left text-caption text-grey-7">
                            <div class="row items-center q-gutter-sm ellipsis">
                              <span v-if="app.wechatUrl" class="ellipsis">
                                <q-icon name="smartphone" size="14px" />
                                <span class="ellipsis" :title="app.wechatUrl" style="max-width: 240px;">{{ app.wechatUrl }}</span>
                              </span>
                            </div>
                          </div>
                        </div>
                        <div class="col-auto">
                          <!-- 拖拽手柄 -->
                          <q-icon
                            name="drag_indicator"
                            class="app-drag-handle cursor-move text-grey-6"
                            size="24px"
                          ></q-icon>
                        </div>
                      </div>
                    </q-item-main>
                    <q-item-side right>
                      <q-btn
                        flat
                        round
                        dense
                        icon="edit"
                        size="sm"
                        @click.stop="editApplication(app)"
                      />
                      <q-btn
                        flat
                        round
                        dense
                        icon="delete"
                        size="sm"
                        color="negative"
                        @click.stop="removeApplicationFromGroup(app)"
                      />
                    </q-item-side>
                  </q-item>
                </draggable>

                <div v-if="groupApplications.length === 0" class="flex flex-center" style="height: 200px">
                  <div class="text-center text-grey">
                    <q-icon name="apps" size="48px" />
                    <div class="q-mt-sm">该分组下暂无应用</div>
                  </div>
                </div>
              </q-card>
            </div>

            <div v-else class="flex flex-center" style="height: 400px">
              <div class="text-center">
                <q-icon name="info" size="48px" color="grey" />
                <div class="text-h6 q-mt-md">请选择一个应用分组</div>
                <div class="text-grey">
                  点击左侧分组
                  <span><q-icon name="apps"></q-icon></span>
                  查看和管理应用
                </div>
              </div>
            </div>
          </div>
        </div>
      </q-card-main>
    </q-card>

    <!-- 添加应用对话框 -->
    <q-modal v-model="addApplicationDialog" maximized>
      <q-modal-layout>
        <q-toolbar slot="header">
          <q-btn flat round dense @click="addApplicationDialog = false" icon="reply" />
          <q-toolbar-title> 添加应用到分组 </q-toolbar-title>
        </q-toolbar>
        <q-toolbar slot="footer">
          <q-toolbar-title> </q-toolbar-title>
          <q-btn
            round
            color="red"
            :disabled="selectedApplications.length === 0"
            @click="addSelectedApplications"
            >添加</q-btn
          >
          <q-btn round @click="addApplicationDialog = false">{{ $t("Cancel") }}</q-btn>
        </q-toolbar>
        <div class="layout-padding">
          <div class="row q-mb-md">
            <q-input
              v-model="applicationFilter"
              type="text"
              placeholder="搜索应用名称"
              class="col-4"
              clearable
            >
              <template v-slot:prepend>
                <q-icon name="search" />
              </template>
            </q-input>
          </div>

          <q-table
            :data="filteredApplications"
            :columns="availableApplicationColumns"
            row-key="id"
            selection="multiple"
            :selected.sync="selectedApplications"
            :loading="loadingApplications"
            :no-data-label="$t('No data')"
            separator="cell"
            :pagination.sync="tablePagination"
            rows-per-page-label="每页显示"
          >
            <template slot="body-cell-title" slot-scope="props">
              <q-td :props="props">
                <div class="row items-center">
                  <!-- <q-icon :name="'apps'" size="20px" class="q-mr-sm" /> -->
                  {{ props.value }}
                </div>
              </q-td>
            </template>

            <template slot="body-cell-status" slot-scope="props">
              <q-td :props="props">
                <span
                  class="text-caption"
                  :class="props.row.qyflag === '1' ? 'text-positive' : 'text-negative'"
                >
                  {{ props.row.qyflag === "1" ? "启用" : "停用" }}
                </span>
              </q-td>
            </template>
          </q-table>
        </div>
      </q-modal-layout>
    </q-modal>
  </div>
</template>

<script>
import draggable from "vuedraggable";
import {
  getApplicationsGroupList,
  addApplicationsGroup,
  updateApplicationsGroup,
  delApplicationsGroup,
  updateApplicationsGroupSortIndex,
} from "@/service/permission/platformapplicationsGroup";
import {
  getPlatformApplicationsPagedList,
  saveapp,
  updateWechatNum,
} from "@/service/permission/platformapplications";
import { Icon } from "ant-design-vue";

export default {
  name: "PlatformApplicationsGroupManager",
  components: {
    draggable,
  },
  data() {
    return {
      applicationsGroups: [],
      selectedGroup: null,
      groupApplications: [],
      allApplications: [],
      loading: false,
      loadingApplications: false,
      addApplicationDialog: false,
      applicationFilter: "",
      selectedApplications: [],
      tablePagination: {
        rowsPerPage: 10,
      },

      applicationColumns: [
        {
          name: "title",
          required: true,
          label: "应用名称",
          align: "left",
          field: "title",
          sortable: true,
        },
        {
          name: "href",
          required: true,
          label: "入口地址",
          align: "left",
          field: "href",
          sortable: true,
        },
        {
          name: "status",
          required: true,
          label: "状态",
          align: "left",
          field: "qyflag",
          sortable: true,
        },
        {
          name: "addtime",
          required: true,
          label: "添加时间",
          align: "left",
          field: "addtime",
          sortable: true,
        },
        {
          name: "actions",
          required: true,
          label: "操作",
          align: "left",
          field: "id",
          sortable: false,
        },
      ],

      availableApplicationColumns: [
        {
          name: "title",
          required: true,
          label: "应用名称",
          align: "left",
          field: "title",
          sortable: true,
        },
        {
          name: "appid",
          required: true,
          label: "应用标识",
          align: "left",
          field: "appid",
          sortable: true,
        },
        {
          name: "status",
          required: true,
          label: "状态",
          align: "left",
          field: "qyflag",
          sortable: true,
        },
        {
          name: "addtime",
          required: true,
          label: "添加时间",
          align: "left",
          field: "addtime",
          sortable: true,
        },
      ],
    };
  },
  computed: {
    filteredApplications() {
      if (!this.applicationFilter) {
        return this.allApplications.filter(
          (app) => !this.groupApplications.some((groupApp) => groupApp.id === app.id)
        );
      }
      return this.allApplications.filter(
        (app) =>
          app.title.toLowerCase().includes(this.applicationFilter.toLowerCase()) &&
          !this.groupApplications.some((groupApp) => groupApp.id === app.id)
      );
    },
  },
  mounted() {
    this.loadApplicationsGroups();
    this.loadAllApplications();
  },
  methods: {
    async loadApplicationsGroups() {
      try {
        const response = await getApplicationsGroupList({});
        this.applicationsGroups = response.data.data || [];
      } catch (error) {
        console.error("Failed to load applications groups:", error);
        this.$q.notify({
          type: "negative",
          message: "加载应用分组失败",
          position: "bottom-right",
        });
      }
    },

    async loadAllApplications() {
      try {
        this.loadingApplications = true;
        const response = await getPlatformApplicationsPagedList({
          pageNum: 1,
          pageSize: 1000,
          title: "",
        });
        this.allApplications = response.data.data.list || [];
      } catch (error) {
        console.error("Failed to load applications:", error);
        this.$q.notify({
          type: "negative",
          message: "加载应用列表失败",
          position: "bottom-right",
        });
      } finally {
        this.loadingApplications = false;
      }
    },

    async selectGroup(group) {
      // console.log(group, "======selectGroup=====");
      this.selectedGroup = group;
      await this.loadGroupApplications();
    },

    async loadGroupApplications() {
      if (!this.selectedGroup) return;

      try {
        this.loading = true;
        // 使用现有的API，通过groupCode过滤应用
        const response = await getPlatformApplicationsPagedList({
          pageNum: 1,
          pageSize: 1000,
          title: "",
        });

        // 过滤出当前分组的应用并按 wechatNum 排序
        this.groupApplications = (response.data.data.list || [])
          .filter((app) => app.groupCode === this.selectedGroup.groupCode)
          .sort((a, b) => {
            const numA = a.wechatNum ? parseInt(a.wechatNum) : 999;
            const numB = b.wechatNum ? parseInt(b.wechatNum) : 999;
            return numA - numB;
          });
      } catch (error) {
        console.error("Failed to load group applications:", error);
        this.$q.notify({
          type: "negative",
          message: "加载分组应用失败",
          position: "bottom-right",
        });
      } finally {
        this.loading = false;
      }
    },

    async onGroupDragEnd() {
      // 更新排序索引
      this.applicationsGroups.forEach((group, index) => {
        group.sortIndex = index + 1;
      });
      console.log(this.applicationsGroups, "=========onGroupDragEnd=========");
      try {
        // 批量更新排序（这里需要后端支持批量更新）
        await updateApplicationsGroupSortIndex(this.applicationsGroups);
        this.$q.notify({
          type: "positive",
          message: "分组排序已更新",
          position: "bottom-right",
        });
      } catch (error) {
        console.error("Failed to update group sort:", error);
        this.$q.notify({
          type: "negative",
          message: "更新分组排序失败",
          position: "bottom-right",
        });
      }
    },

    async onApplicationDragEnd() {
      // 更新组内应用排序编号
      const orderList = this.groupApplications.map((app, index) => ({
        id: app.id,
        wechatNum: String(index + 1),
      }));
      console.log(orderList, "=========onApplicationDragEnd=========");
      try {
        await updateWechatNum(orderList);
        this.$q.notify({
          type: "positive",
          message: "应用排序已更新",
          position: "bottom-right",
        });
      } catch (error) {
        console.error("Failed to update application sort:", error);
        this.$q.notify({
          type: "negative",
          message: "更新应用排序失败",
          position: "bottom-right",
        });
        // 重新加载分组应用列表以恢复原始顺序
        this.loadGroupApplications();
      }
    },

    async openAddGroupDialog() {
      try {
        const name = await this.$q.dialog({
          title: "添加应用分组",
          prompt: {
            model: "",
            type: "text",
            isValid: (val) => val && val.trim().length > 0,
          },
          ok: { label: "添加", push: true },
          cancel: { label: "取消", push: true },
        });

        if (name) {
          await addApplicationsGroup({ groupName: name });
          this.$q.notify({
            type: "positive",
            message: "添加成功",
            position: "bottom-right",
          });
          this.loadApplicationsGroups();
        }
      } catch (e) {
        // user cancelled
      }
    },

    editGroup(group) {
      // 实现编辑分组功能
      this.$q
        .dialog({
          title: "编辑应用分组",
          prompt: {
            model: group.groupName,
            type: "text",
            isValid: (val) => val && val.trim().length > 0,
          },
          ok: { label: "保存", push: true },
          cancel: { label: "取消", push: true },
        })
        .then(async (name) => {
          try {
            await updateApplicationsGroup({
              id: group.id,
              groupName: name,
              sortIndex: group.sortIndex,
            });
            this.$q.notify({
              type: "positive",
              message: "修改成功",
              position: "bottom-right",
            });
            this.loadApplicationsGroups();
          } catch (error) {
            this.$q.notify({
              type: "negative",
              message: "修改失败",
              position: "bottom-right",
            });
          }
        });
    },

    async deleteGroup(group) {
      try {
        await this.$q.dialog({
          title: "删除确认",
          message: `确定要删除分组"${group.groupName}"吗？`,
          ok: { label: "删除", push: true, color: "negative" },
          cancel: { label: "取消", push: true },
        });

        await delApplicationsGroup({ id: group.id });
        this.$q.notify({
          type: "positive",
          message: "删除成功",
          position: "bottom-right",
        });

        if (this.selectedGroup && this.selectedGroup.id === group.id) {
          this.selectedGroup = null;
          this.groupApplications = [];
        }

        this.loadApplicationsGroups();
      } catch (error) {
        // user cancelled or error
      }
    },

    openAddApplicationDialog() {
      this.selectedApplications = [];
      this.addApplicationDialog = true;
    },

    async addSelectedApplications() {
      if (!this.selectedGroup || this.selectedApplications.length === 0) return;

      try {
        // 批量更新应用的分组
        for (let application of this.selectedApplications) {
          await saveapp({
            ...application,
            groupCode: this.selectedGroup.groupCode,
          });
        }

        this.$q.notify({
          type: "positive",
          message: `成功添加 ${this.selectedApplications.length} 个应用到分组`,
          position: "bottom-right",
        });

        this.addApplicationDialog = false;
        this.loadGroupApplications();
      } catch (error) {
        console.error("Failed to add applications to group:", error);
        this.$q.notify({
          type: "negative",
          message: "添加应用到分组失败",
          position: "bottom-right",
        });
      }
    },

    editApplication(application) {
      // 跳转到应用编辑页面
      this.$router.push({
        path: "/permission/platformapplications",
        query: { editId: application.id },
      });
    },

    async removeApplicationFromGroup(application) {
      try {
        await this.$q.dialog({
          title: "移除确认",
          message: `确定要从分组中移除应用"${application.title}"吗？`,
          ok: { label: "移除", push: true, color: "negative" },
          cancel: { label: "取消", push: true },
        });

        // 将应用的分组设置为空
        await saveapp({
          ...application,
          groupCode: null,
        });

        this.$q.notify({
          type: "positive",
          message: "移除成功",
          position: "bottom-right",
        });

        this.loadGroupApplications();
      } catch (error) {
        // user cancelled or error
      }
    },
  },
};
</script>

<style scoped>
.group-list-container {
  min-height: 500px;
  max-height: 600px;
  overflow-y: auto;
}

.group-item {
  transition: all 0.3s ease;
  border-left: 3px solid transparent;
}

.group-item:hover {
  background-color: #f5f5f5;
}

.group-item.sortable-ghost {
  opacity: 0.5;
  background-color: #e3f2fd;
}

.selected-group {
  background-color: #e3f2fd !important;
  border-left: 3px solid #2196f3;
}

.drag-handle {
  width: 200px;
  cursor: move;
  color: #22a19b;
  padding: 4px;
  border-radius: 4px;
}

.drag-handle:hover {
  color: #333;
  background-color: rgba(0, 0, 0, 0.05);
}

.fixed-height-table {
  height: 600px;
}

.q-list {
  max-height: 600px;
  overflow-y: auto;
}

/* 应用拖拽列表样式 */
.application-list-card {
  min-height: 200px;
}

.application-draggable-list {
  min-height: 50px;
}

.application-list-item {
  border-bottom: 1px solid #e0e0e0;
  transition: all 0.2s ease;
}

.application-list-item:hover {
  background-color: #f5f5f5;
}

.application-list-item.sortable-ghost {
  opacity: 0.5;
  background-color: #e3f2fd;
}

.application-list-item.sortable-chosen {
  background-color: #bbdefb;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

/* 应用拖拽手柄样式 */
.app-drag-handle {
  cursor: move;
  color: #22a19b;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.app-drag-handle:hover {
  color: #1976d2;
  background-color: rgba(25, 118, 210, 0.1);
}

/* 表格行样式 */
.q-table tbody tr {
  transition: all 0.2s ease;
}

.q-table tbody tr:hover {
  background-color: #f5f5f5;
}
</style>
