<template>
  <div class="gl-page-content">
    <div class="app-operate">
      <el-button type="primary" @click="editAppInfoFun">新增应用</el-button>
      <el-button type="primary" @click="startLocalAppFun">启动本地插件</el-button>
      <el-button type="" @click="getAppDataFun">刷新</el-button>
    </div>
    <div class="app-content">

      <div class="app-type-list" v-for="item in apptypeList" :key="item.type">
        <div class="app-type-title">{{ item.label }}</div>
        <div v-if="item.apps.length" class="app-type-content">
          <div class="app-type-item" v-for="item_2 in item.apps" :key="item_2.id">

            <div class="item-top">
              <div class="item-top-left">
                <img v-if="item_2.appImage" width="60" :src="getImgPathFun(item_2.appImage)" alt="">
                <appNameBg v-else :app-name="item_2.appName"></appNameBg>
              </div>
              <div class="item-top-right">
                <div class="app-name" :title="item_2.appName">
                  {{ item_2.appName }}
                </div>
                <div class="app-type">
                  <div class="type mr10">
                    <el-tag v-if="item_2.appType === '3'" type="primary">HPC</el-tag>
                    <el-tag v-if="item_2.appType === '2'" type="success">云应用</el-tag>
                    <el-tag v-if="item_2.appType === '1'" type="warning">本地应用</el-tag>
                  </div>

                  <div class="status">

                    <div :class="item_2.appStatus === '1' ? 'point success mr5' : 'point error mr5'"></div>
                    <span>{{ item_2.appStatus === '1' ? '启用' : '禁用' }}</span>

                  </div>
                </div>
              </div>
            </div>
            <div class="item-center">
              {{ item_2?.comment ? item_2.comment : '暂无应用相关描述' }}
            </div>
            <div class="item-bottom">
              <el-button type="primary" @click="startAppFun(item_2)" :disabled="item_2.appStatus != '1'">启动</el-button>
              <div>

                <el-button type="primary" link @click="editAppInfoFun(item_2)">编辑</el-button>
                <el-button type="danger" link @click="deleteAppInfoFun(item_2)">删除</el-button>

              </div>
            </div>

          </div>
        </div>
        <div v-else class="app-type-content">
          <el-empty class="el-empty-style" description="暂无应用" />
        </div>

      </div>

    </div>

    <addOrEditApp
      v-if="detailVisible"
      :table-name="'APP_CENTER'"
      :current-app-info="currentAppInfo"
      @cancel="closeAddOrEditAppFun"
      @submit="updateAppFun"
    ></addOrEditApp>
  </div>
</template>
<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import addOrEditApp from './components/addOrEditApp.vue';
import appNameBg from '@/views/task/appCenter/components/appNameBg.vue';
import { addApplicationApi, deleteApplicationApi, queryApplicationByTypeApi, updateApplicationApi } from '@/api/system/application';
import { execApi, getdeviceuuidApi, startupPlugin } from '@/api/application/application';

const detailVisible = ref(false);
const env = import.meta.env;

const userId = '1980235559149838337';

const apptypeList = ref<any>([
  {
    label: '本地应用',
    type: '1',
    apps: [],
  },
  {
    label: '云应用',
    type: '2',
    apps: [],
  },
  {
    label: 'HPC应用',
    type: '3',
    apps: [],
  },
]);
const getImgPathFun = (fileId: any) => {
  const url = `${env.VITE_API_IMAGE_PREVIEW_URL}/data/previewImage?fileId=${fileId}`;
  return url;
};
const currentAppInfo = ref<any>({});
// 打开编辑应用弹窗
const editAppInfoFun = (data?: any) => {

  if (data) {
    currentAppInfo.value = data;
  } else {
    currentAppInfo.value = {};
  }
  detailVisible.value = true;
  console.log('编辑应用', data);
};

const closeAddOrEditAppFun = () => {
  currentAppInfo.value = {};
  detailVisible.value = false;
};

const deleteAppInfoFun = (data: any) => {

  ElMessageBox.confirm(
    '确认要删除这个应用吗?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {

      const res: any = await deleteApplicationApi({
        appId: data.uuid,
      });

      if (res && res.code === 200) {
        ElMessage.success('删除成功！');
        await getAppDataFun();
      }

    })
    .catch(() => {

    });

};

const updateAppFun = async (data: any) => {

  if (data?.id) {
    detailVisible.value = false;

    const res: any = await updateApplicationApi({
      appName: data.appName,
      appType: Number(data.appType),
      appPath: data.appPath,
      appImage: (data.appImage).toString(),
      appStatus: Number(data.appStatus),
      appVersion: data.appVersion,
      appVendor: data.appVendor,
      machineCode: data.machineCode,
      comment: data.comment,
      uuid: data.uuid,
    });

    if (res && res.code === 200) {

    }

  } else {

    const param = {
      appName: data.appName,
      appType: Number(data.appType),
      appStatus: Number(data.appStatus),
      appPath: data.appPath || '',
      appImage: data?.appImage ? (data.appImage).toString() : '',
      appVersion: data.appVersion || '',
      appVendor: data.appVendor || '',
      machineCode: localStorage.getItem('USER_UUID'),
      comment: data.comment || '',
      creator: userId,
    };

    const res: any = await addApplicationApi(param);
    if (res && res.code === 200) {

    }

  }
  console.log(apptypeList.value, 'apptypeList.value');
  getAppDataFun();
  detailVisible.value = false;

};

const getAppDataFun = async () => {

  const uuid = localStorage.getItem('USER_UUID');

  if (uuid) {

    for (let i = 0; i < apptypeList.value.length; i++) {
      apptypeList.value[i].apps = await getTypeAppData(
        apptypeList.value[i].type,
        uuid,
        userId
      );
    }

  } else {
    await getdeviceuuidFun();
  }

  // const res: any = await queryAllApplicationApi();
  // if (res && res.code === 200) {
  //   tableData.value = res.data.map((item: any) => {
  //     return {
  //       ...item,
  //       appStatus: item.appStatus.toString(),
  //       appType: item.appType.toString(),
  //     };
  //   });

  //   for (let i = 0; i < apptypeList.value.length; i++) {
  //     apptypeList.value[i].apps = [];
  //   }

  //   for (let i = 0; i < apptypeList.value.length; i++) {
  //     for (let j = 0; j < tableData.value.length; j++) {

  //       if (tableData.value[j].appType === apptypeList.value[i].type) {
  //         apptypeList.value[i].apps.push(tableData.value[j]);
  //       }

  //     }

  //   }

  // }
};

const getTypeAppData = async (type:any, machineCode:any, user:any) => {
  const res: any = await queryApplicationByTypeApi({
    appType: type,
    machineCode,
    user,
  });

  if (res && res.code === 200) {
    const result:any = res.data.map((item: any) => {
      return {
        ...item,
        appStatus: item.appStatus.toString(),
        appType: item.appType.toString(),
      };
    });

    return result;
  } else {
    return [];
  }

};

const getdeviceuuidFun = async () => {
  try {
    const res: any = await getdeviceuuidApi();
    if (res) {
      const uuid = res
        .replace('UUID', '')
        .replace(/\ +/g, '')
        .replace(/[\r\n]/g, '');

      localStorage.setItem('USER_UUID', uuid);
    }
  } catch (error) {
    console.log(error);
    localStorage.removeItem('USER_UUID');

    startupPlugin();
  }
};

const startLocalAppFun = async () => {
  await getdeviceuuidFun();

};

const startAppFun = async (data: any) => {

  await getdeviceuuidFun();

  const uuid = localStorage.getItem('USER_UUID');
  if (uuid) {

    const res = await execApi({
      path: data.appPath,
      param: '',
    });

    if (res) {

      ElMessage.success('应用正在启动中，请等待');

    } else {

    }
  } else {
    return;
  }

};

onMounted(() => {
  getAppDataFun();
});

</script>
<style lang="scss" scoped>
.gl-page-content {
  width: 100%;
  height: 100%;

  .app-operate {
    width: 100%;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }

  .app-content {
    width: 100%;
    height: calc(100% - 50px);
    margin-top: 10px;
    overflow: auto;

    .app-type-list {
      width: 100%;
      min-height: 300px;
      margin-bottom: 10px;

      .app-type-title {
        width: 100%;
        height: 40px;
        display: flex;
        align-items: center;
        padding-left: 10px;
        font-size: 16px;
        font-weight: 600;
      }

      .app-type-content {
        width: 100%;
        padding-left: 20px;
        display: flex;
        flex-wrap: wrap;

        .el-empty-style {
          width: 100%;
        }

        .app-type-item {
          width: calc(25% - 20px);
          height: 200px;
          background-color: #fafafa;
          border-radius: 8px;
          margin: 10px 10px 10px 10px;
          padding: 10px;

          .item-top {
            width: 100%;
            height: 70px;
            display: flex;
            align-items: center;

            .item-top-left {
              width: 60px;
              height: 60px;
              display: flex;
              align-items: center;
              justify-content: center;
              margin-right: 10px;
              margin-left: 10px;
              border-radius: 5px;
              background-color: #fff;
              overflow: hidden;
            }

            .item-top-right {
              width: calc(100% - 60px);
              height: 100%;

              .app-name {
                width: 100%;
                height: 30px;
                line-height: 40px;
                font-size: 24px;
                white-space: nowrap;
                /* 防止文本换行 */
                overflow: hidden;
                /* 隐藏溢出的内容 */
                text-overflow: ellipsis;

              }

              .app-type {
                width: 100%;
                height: 40px;
                display: flex;
                align-items: center;

                .status {
                  display: flex;
                  align-items: center;
                  font-size: 12px;

                  .point {
                    width: 8px;
                    height: 8px;
                    border-radius: 50%;
                  }

                  .success {
                    background-color: #67C23A;
                  }

                  .error {
                    background-color: #F56C6C;
                  }

                }

              }
            }
          }

          .item-center {
            width: 100%;
            height: calc(100% - 110px);
            padding: 10px;
            font-size: 12x !important;
            color: darkgray;
            word-break: break-all;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 3;
            /* 超出几行省略 */
            overflow: hidden;
          }

          .item-bottom {
            width: 100%;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 10px;

          }
        }

        .app-type-item:hover {
          box-shadow: 0 4px 16px 0 rgba(0, 0, 0, .08);
        }
      }
    }

  }
}

.flex-center {
  justify-content: center;
  align-items: center;
}

.mr5 {
  margin-right: 5px;
}

.mr10 {
  margin-right: 10px;
}
</style>
