<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>
                <q-btn color="primary" icon="add" @click="openAddApplicationDialog">
                  添加应用
                </q-btn>
              </div>

              <q-table
                :data="groupApplications"
                :columns="applicationColumns"
                row-key="id"
                :loading="loading"
                :no-data-label="$t('No data')"
                separator="cell"
              >
                <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-href" slot-scope="props">
                  <q-td :props="props">
                    <div v-if="props.row.href">
                      <q-icon name="computer" size="16px" />
                      {{ props.row.href }}
                    </div>
                    <div v-if="props.row.wechatUrl">
                      <q-icon name="chat" size="16px" />
                      {{ props.row.wechatUrl }}
                    </div>
                    <div v-if="!props.row.href && !props.row.wechatUrl">
                      <span class="text-grey-7 text-caption">无入口</span>
                    </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>

                <template slot="body-cell-actions" slot-scope="props">
                  <q-td :props="props" style="width: 100px">
                    <q-btn-dropdown color="secondary" label="操作" no-wrap>
                      <q-list link>
                        <q-item
                          v-close-overlay
                          @click.native="editApplication(props.row)"
                        >
                          <q-item-main>
                            <q-item-tile sublabel>修改</q-item-tile>
                          </q-item-main>
                        </q-item>
                        <q-item
                          v-close-overlay
                          @click.native="removeApplicationFromGroup(props.row)"
                        >
                          <q-item-main>
                            <q-item-tile sublabel>从分组移除</q-item-tile>
                          </q-item-main>
                        </q-item>
                      </q-list>
                    </q-btn-dropdown>
                  </q-td>
                </template>
              </q-table>
            </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"
          >
            <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,
} 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: [],

      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: "",
        });

        // 过滤出当前分组的应用
        this.groupApplications = (response.data.data.list || []).filter(
          (app) => app.groupCode === this.selectedGroup.groupCode
        );
      } 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 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;
}
</style>
