<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title></title>
    <!-- 优先引入配置文件 -->
    <script src="./config/adminTool.config.js"></script>
    <!-- 引入工具函数 -->
    <script src="./js/utils.js"></script>
    <!-- 引入css -->
    <link rel="stylesheet" href="./css/_reset.css" />
    <link rel="stylesheet" href="./css/base.css" />
    <!-- 引入axios -->
    <script src="./lib/axios.min.js"></script>
    <!-- 引入request.js -->
    <script src="./js/request.js"></script>
    <!-- 引入Tailwind CSS(CDN方式,无需工程化) -->
    <script src="./lib/tailwindcss.min.js"></script>
    <!-- 引入vue3 -->
    <script src="./lib/vue@3.js"></script>
    <!-- 引入pagination.js -->
    <script src="./lib/ElementPlus/icons-vue.js"></script>
    <!-- 引入Element Plus -->
    <script src="./lib/ElementPlus/element-plus.js"></script>
    <link rel="stylesheet" href="./lib/ElementPlus/index.css" />
    <!-- 引入Element Plus 中文语言包 -->
    <script src="./lib/ElementPlus/locale/zh-cn.js"></script>
    <!-- 引入vue-i18n -->
    <script src="./lib/vue-i18n.global.js"></script>

    <!-- 组件 -->
    <script src="./js/components/common/departmentTree.js"></script>
    <script src="./js/components/common/userSelect.js"></script>
    <script src="./js/components/common/roleUserAuth.js"></script>
    <script src="./js/components/addApplication.js"></script>
    <!-- 引入base.css -->
    <link rel="stylesheet" href="./css/base.css" />
    <!-- 确保 VueI18n 在全局可用 -->
    <script>
      // vue-i18n.global.js 创建了全局变量 VueI18n,确保它在 window 上也可用
      if (
        typeof VueI18n !== "undefined" &&
        typeof window !== "undefined" &&
        !window.VueI18n
      ) {
        window.VueI18n = VueI18n;
      }
    </script>
    <!-- 引入i18n -->
    <script src="./js/i18n/index.js" type="module"></script>
    <!-- 可选:Tailwind自定义配置 -->
    <script>
      tailwind.config = {
        theme: {
          extend: {
            colors: {
              primary: "#4F46E5", // 自定义主色
              secondary: "#10B981",
            },
          },
        },
      };
    </script>
    <!-- 自定义工具类(可选) -->
    <style type="text/tailwindcss">
      @layer utilities {
        .content-auto {
          content-visibility: auto;
        }
        .card-shadow {
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
        }
      }
    </style>
  </head>
  <body>
    <div id="app"></div>
    <template id="softwareCpn">
        <div class="px-2">  
            <!-- <div class="baseInfo">
                <div class="title smallHeader py-2 border-b border-gray-200 box-border">
                    基础功能配置
                </div>
                <div class="content">
                    <el-checkbox v-model="baseInfo.flowCenterEnable">流程中心</el-checkbox>
                </div>
            </div> -->

            <div class="list">
                <div class="title smallHeader py-2 border-b border-gray-200 box-border">
                    自定义软件配置
                </div>
                <div class="content">
                    <div class="search flex align-center py-2 justify-between">
                        <div class="left flex align-center">
                            <el-input v-model="list.params.name" placeholder="请输入软件名称"></el-input>
                            <el-button type="primary" @click="searchSoftware" class="ml-2">搜索</el-button>
                            <el-button @click="resetSoftware" class="ml-2">重置</el-button>
                        </div>
                        <div class="right flex align-center">
                            <el-button type="primary" @click="openAddApplication">添加</el-button>
                            <el-button type="danger" @click="deleteSoftware">移除</el-button>
                        </div>
                    </div>
                    <div class="table" style="width: 100%;">
                        <el-table :data="list.data" stripe @selection-change="handleSelectionChange">
                            <el-table-column type="selection" width="55"></el-table-column>
                            <el-table-column prop="name" label="软件名称"></el-table-column>
                            <el-table-column label="模式" width="85">
                                <template #default="scope">
                                    <el-link :type="scope.row.type == 0 ? 'success' : 'primary'">
                                        {{ scope.row.type == 0 ? '常规模式' : '平台模式' }}
                                    </el-link>
                                </template>
                            </el-table-column>
                            <el-table-column label="描述" prop="description"></el-table-column>
                            <el-table-column label="状态" width="100" >
                                <template #default="scope">
                                    <el-tag v-if="scope.row.activated" type="success">激活</el-tag>
                                    <el-tag v-else type="danger">失效</el-tag>
                                </template>
                            </el-table-column>
                            <!-- <el-table-column label="操作" width="180">
                                <template #default="scope">
                                  <el-button v-if="scope.row.type == 0" 
                                             @click.stop="openUserSelect(scope.row)" 
                                             type="primary" 
                                             plain 
                                             
                                  >
                                    添加角色
                                  </el-button>
                                  <el-button v-if="scope.row.type == 1"
                                             @click.stop="onBpmModeConf(scope.row)"
                                            type="primary" 
                                            plain 
                                            
                                  >
                                    平台模式配置
                                  </el-button>
                                </template>
                              </el-table-column> -->
                              <!-- <el-table-column label="导出操作" width="360">
                                <template #default="scope">
                                    <el-button type="primary" 
                                               plain 
                                               @click.stop="exportbasicdataauthority(scope.row, 'basicData')"
                                    >
                                        基础数据
                                    </el-button>
                                    <el-button @click.stop="exportrolemenuauthority(scope.row, 'roleMenu')"
                                            type="primary" 
                                            plain 
                                            
                                    >
                                        角色&菜单
                                    </el-button>
                                    <el-button @click.stop="exportroleuserauthority(scope.row, 'roleAuth')"
                                            type="primary" 
                                            plain 
                                            
                                    >
                                        角色&用户
                                    </el-button>
                                </template>
                              </el-table-column> -->
                        </el-table>
                        <div class="pagination py-2 flex justify-end">
                            <el-pagination
                                @size-change="handleSizeChange"
                                @current-change="handleCurrentChange"
                                :current-page="list.currpage"
                                :page-sizes="[10, 20, 50, 100]"
                                :page-size="list.pagelines"
                                layout="total, sizes, prev, pager, next, jumper"
                                :total="list.total"
                            ></el-pagination>
                        </div>
                    </div>
                </div>

            </div>
        </div>
        <role-user-auth v-model="applicationRole.visible" :application="applicationRole.data"></role-user-auth>
        <add-application v-model="addApplication.visible"
                         v-if="addApplication.visible"
                         @success="getBindSoftwareList"
        ></add-application>
    </template>
    <script>
      // 等待 DOM 和所有脚本加载完成
      document.addEventListener("DOMContentLoaded", function () {
        let checkCount = 0;
        const maxChecks = 40; // 最多检查 40 次(约 2 秒)
        
        // 检查依赖和 iframe 尺寸是否准备好
        function checkDependencies() {
          checkCount++;
          
          const depsReady = 
            typeof Vue !== "undefined" &&
            typeof userSelectComponent !== "undefined" &&
            typeof useRoleUserAuthComponent !== "undefined" &&
            typeof useAddApplicationComponent !== "undefined";
          
          // 检查是否在 iframe 中,如果是则检查尺寸
          const isInIframe = window.self !== window.top;
          let sizeReady = true;
          
          if (isInIframe) {
            // 检查 iframe 尺寸是否已正确设置(至少要有一定的宽度和高度)
            const minSize = 100; // 最小尺寸阈值
            sizeReady = window.innerWidth >= minSize && window.innerHeight >= minSize;
          }
          
          if (depsReady && sizeReady) {
            initApp();
          } else if (checkCount < maxChecks) {
            // 如果依赖或尺寸未准备好,等待后重试
            // 在 iframe 中需要等待尺寸设置完成
            setTimeout(checkDependencies, 50);
          } else {
            // 超时后强制初始化(即使尺寸可能不完美)
            console.warn('依赖检查超时,强制初始化应用');
            if (depsReady) {
              initApp();
            }
          }
        }
        
        // 等待模块脚本加载完成
        function initApp() {
          // 检查必要的函数和对象是否已加载
          if (typeof Vue === "undefined") {
            console.error("Vue 未加载");
            return;
          }

          if(typeof userSelectComponent === "undefined") {
            console.error("userSelectComponent 未加载");
            return;
          }
          const userSelect = userSelectComponent();
          if(typeof useRoleUserAuthComponent === "undefined") {
            console.error("roleUserAuthComponent 未加载");
            return;
          }
          const roleUserAuth = useRoleUserAuthComponent();
          if(typeof useAddApplicationComponent === "undefined") {
            console.error("addApplicationComponent 未加载");
            return;
          }
          const addApplication = useAddApplicationComponent();
          // 等待 Vue 和 Element Plus 加载完成
          const softwareCpn = Vue.createApp({
            template: "#softwareCpn",
            components: {
              userSelect: userSelect,
              roleUserAuth: roleUserAuth,
              addApplication: addApplication
            },
            data() {
              return {
                baseInfo: {
                    flowCenterEnable: false,
                },
                list: {
                    data: [],
                    total: 10,
                    currpage: 1,
                    pagelines: 10,
                    params: {
                        name: '',
                    }
                },
                applicationRole: {
                    visible: false,
                    data: null
                },
                addApplication: {
                    visible: false,
                },
                selectedSoftware: [],
              }
            },
            created() {
              // 延迟数据加载,优先显示页面
              this.$nextTick(() => {
                this.searchSoftware();
              });
            },
            methods: {
                handleSelectionChange(val) {
                    this.selectedSoftware = val;
                },
                async getBindSoftwareList() {
                    try {
                        this.list.load = true;
                        const res = await API.getBindSoftwareList({
                            name: this.list.params.name,
                            currpage: this.list.currpage,
                            pagelines: this.list.pagelines
                        });
                        if(res.data.errcode == 0) {
                            this.list.data = res.data.data.datas;
                            this.list.total = res.data.data.rowCount;
                            this.list.currpage = res.data.data.pageNo;
                            this.selectedSoftware = [];
                        } else {
                            this.$message.error(res.data.errmsg || '获取已绑定的软件列表失败');
                        }
                    }
                    catch (error) {
                        console.error(error);
                    }
                    finally {
                        this.list.load = false;
                    }
                },
                searchSoftware() {
                    this.list.currpage = 1;
                    this.getBindSoftwareList();
                },
                resetSoftware() {
                    this.list.params.name = '';
                    this.searchSoftware();
                },
                handleSizeChange(val) {
                    this.list.pagelines = val;
                    this.getBindSoftwareList();
                },
                handleCurrentChange(val) {
                    this.list.currpage = val;
                    this.getBindSoftwareList();
                },
                // 导出数据
                exportbasicdataauthority(row, type) {
                    const msgMap = {
                        'basicData': '基础数据',
                        'roleMenu': '角色&菜单',
                        'roleAuth': '角色&用户',
                    }
                    let msg = `确定要导出 ${msgMap[type] ? msgMap[type] : '所选'} 数据吗?`;
                    // 获取domain id
                    const domainId = getQueryParams().domainId;
                    if(!domainId) {
                        this.$message.error('请先选择域');
                        return;
                    }
                    this.$confirm(msg, '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                    }).then(() => {
                        console.log('确定');
                    }).catch(() => {
                        console.log('取消');
                    });
                },
                openUserSelect(row) {
                    this.applicationRole.data = row;
                    this.applicationRole.visible = true;
                },
                openAddApplication() {
                    this.addApplication.visible = true;
                },
                deleteSoftware() {
                    if(this.selectedSoftware.length == 0) {
                        this.$message.error('请选择要删除的软件');
                        return;
                    }
                    this.$confirm('确定删除选中的软件吗?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                    }).then(async () => {
                        const applicationIds = this.selectedSoftware.map(item => item.id);
                        const res = await API.deleteSoftware(applicationIds);
                        if(res.data.errcode == 0) {
                            this.$message.success('删除软件成功');
                            this.selectedSoftware = [];
                            this.getBindSoftwareList();
                        } else {
                            this.$message.error(res.data.errmsg || '删除软件失败');
                        }
                    }).catch(() => {
                        this.$message.error('删除软件失败');
                    }); 
                }
            }
          });

          // 全局注册图标组件
          if (typeof ElementPlusIconsVue !== "undefined") {
            // 保留的 HTML 元素名,不能用作组件名
            const reservedElements = ['filter', 'link', 'menu', 'picture', 'select', 'switch', 'view'];
            
            // 将 PascalCase 转换为 kebab-case 的辅助函数
            const toKebabCase = (str) => {
              return str
                .replace(/([A-Z])/g, "-$1")
                .toLowerCase()
                .replace(/^-/, "");
            };

            for (const [key, component] of Object.entries(
              ElementPlusIconsVue
            )) {
              // 检查是否是保留的 HTML 元素名
              const kebabKey = toKebabCase(key);
              const lowerKey = key.toLowerCase();
              const isReserved = reservedElements.includes(kebabKey) || reservedElements.includes(lowerKey);
              
              if (!isReserved) {
                // 注册原始名称(PascalCase),如 StarFilled
                softwareCpn.component(key, component);

                // 同时注册 kebab-case 格式,如 star-filled
                if (kebabKey !== key) {
                  softwareCpn.component(kebabKey, component);
                }

                // 同时注册全小写格式,如 starfilled(Vue 3 模板解析时会转换为全小写)
                if (lowerKey !== key && lowerKey !== kebabKey) {
                  softwareCpn.component(lowerKey, component);
                }
              }
            }
          } else {
            console.error(
              "ElementPlusIconsVue 未加载,请检查 icons-vue.js 是否正确引入"
            );
          }

          if (typeof useI18n !== "undefined") {
            const i18n = useI18n();
            if (i18n) {
              softwareCpn.use(i18n);
            }
          }

          // 如果 Element Plus 需要注册到 Vue app
          // 配置中文语言
          let zhCnLocale = null;

          // 尝试从全局获取中文语言包
          if (typeof ElementPlusLocaleZhCn !== "undefined") {
            zhCnLocale = ElementPlusLocaleZhCn;
          } else if (window.ElementPlusLocaleZhCn) {
            zhCnLocale = window.ElementPlusLocaleZhCn;
          } else if (ElementPlus && ElementPlus.locale) {
            // 尝试从 ElementPlus 对象中获取
            zhCnLocale =
              ElementPlus.locale.zhCn ||
              ElementPlus.locale.zhCN ||
              ElementPlus.locale.zh_CN;
          }

          // 使用中文语言包配置 Element Plus
          if (zhCnLocale) {
            softwareCpn.use(ElementPlus, { locale: zhCnLocale });
            console.log("Element Plus 已配置为中文");
          } else {
            softwareCpn.use(ElementPlus);
            console.warn("未找到 Element Plus 中文语言包,使用默认语言");
          }

          softwareCpn.mount("#app");
        }
        
        // 开始检查依赖
        checkDependencies();
      });
    </script>
  </body>
</html>