<template>
  <div class="gl-page-content">
    <div class="gl-page-content-title">
      <div class="return-button">
        <el-icon class="ft28" @click="backUpFun">
          <ArrowLeft />
        </el-icon>
      </div>
      <div class="app-img mr12">
        <img
          v-if="currentAppInfo?.appImage"
          width="40"
          :src="getImgPathFun(currentAppInfo?.appImage)"
          alt=""
        />
        <div v-else class="app-bg-content">
          <appNameBg :app-name="currentAppInfo.appName" :size="20"></appNameBg>
        </div>
      </div>
      <div class="app-name mr12">
        {{ currentAppInfo.appName }}
      </div>
      <div class="app-status mr12">
        <div
          :class="currentAppInfo.appStatus === '1' ? 'point success mr5' : 'point error mr5'"
        ></div>
        <span>{{ currentAppInfo.appStatus === '1' ? '启用' : '禁用' }}</span>
      </div>
      <div class="app-type mr12">
        <el-tag v-if="currentAppInfo.appType === '3'" type="primary">{{
          getTypeNameFun(currentAppInfo.appType)
        }}</el-tag>
        <el-tag v-else-if="currentAppInfo.appType === '2'" type="success">{{
          getTypeNameFun(currentAppInfo.appType)
        }}</el-tag>
        <el-tag v-else-if="currentAppInfo.appType === '1'" type="warning">{{
          getTypeNameFun(currentAppInfo.appType)
        }}</el-tag>
        <el-tag v-else type="primary">{{ getTypeNameFun(currentAppInfo.appType) }}</el-tag>
      </div>
    </div>

    <div class="page-content">
      <div class="filter-box">
        <el-form :model="filterFormData">
          <el-form-item label="配置名称：">
            <el-select
              v-model="filterFormData.configName"
              class="select-style"
              @change="configChangeFun"
            >
              <el-option
                v-for="item in configList"
                :value="item.id"
                :key="item.id"
                :label="item.configName"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="addConfigFun">新增配置</el-button>
            <el-button :disabled="!filterFormData.configName" type="danger" @click="delConfigFun"
              >删除配置</el-button
            >
            <el-button
              type="primary"
              :disabled="!filterFormData.configName"
              @click="openAddParamFun"
              >配置参数</el-button
            >
          </el-form-item>
        </el-form>
      </div>

      <!-- APP_CONFIG_TABLE -->
      <div class="page-table-content">
        <FlowNodeParamTable hideButtons :node-params="tableData"> </FlowNodeParamTable>
      </div>
    </div>

    <addConfig
      v-if="appConfigVisible"
      :config-info="configData"
      @cancel="appConfigVisible = false"
      @submit="addConfigInfo"
    >
    </addConfig>

    <addConfigParam
      v-if="appConfigParamVisible"
      :current-config="currentConfigInfo"
      @cancel="appConfigParamVisible = false"
      @submit="addConfigParamFun"
      :table-name="'APP_CONFIG_TABLE'"
    >
    </addConfigParam>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, reactive, onMounted } from 'vue';
import appNameBg from '@/views/task/appCenter/components/appNameBg.vue';
import addConfig from './addConfig.vue';
import {
  addApplicationConfigApi,
  deleteApplicationConfigAPi,
  queryApplicationConfigApi,
  updateApplicationConfigAPi,
} from '@/api/system/application';
import addConfigParam from './addConfigParam.vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getDictionaryDataApi } from '@/api/system/systemData';
import FlowNodeParamTable from '@/components/flow/flowNodeParamTable.vue';

const props = defineProps(['appInfo']);
const emits = defineEmits(['backUp']);
const env = import.meta.env;
const currentAppInfo = ref<any>({});

const appConfigVisible = ref(false);
const appConfigParamVisible = ref(false);

const getImgPathFun = (fileId: any) => {
  const url = `${env.VITE_API_IMAGE_PREVIEW_URL}/data/previewImage?fileId=${fileId}`;
  return url;
};

const currentConfigInfo = ref<any>({
  pageConfigList: [],
});

const filterFormData = reactive<any>({
  configName: '',
});

const configChangeFun = () => {
  currentConfigInfo.value = configList.value.find((item: any) => {
    return item.id === filterFormData.configName;
  });
  const pageConfigList: any = currentConfigInfo.value.configValue?.length
    ? JSON.parse(currentConfigInfo.value.configValue)
    : [];

  currentConfigInfo.value.pageConfigList = pageConfigList;

  getConfigTableDataFun(currentConfigInfo.value.configValue);
};

const configList = ref<any>([]);

const configData = ref<any>({});
const addConfigFun = () => {
  configData.value = {};

  appConfigVisible.value = true;
};

const addConfigInfo = async (data: any) => {
  const res: any = await addApplicationConfigApi({
    appName: currentAppInfo.value.appName,
    appId: currentAppInfo.value.uuid,
    configName: data.configName,
    configValue: '',
    configType: data.configType,
    appVendor: currentAppInfo.value.appVendor,
    machineCode: currentAppInfo.value.machineCode,
    comment: data.comment,
  });

  if (res && res.code === 200) {
    getAppConfigListFun();
    ElMessage.success('新增成功');
  }
  appConfigVisible.value = false;
};

const getAppConfigListFun = async () => {
  const res: any = await queryApplicationConfigApi({
    appId: currentAppInfo.value.uuid,
  });
  if (res && res.code === 200) {
    configList.value = res.data;

    if (configList.value.length) {
      if (!filterFormData.configName) {
        filterFormData.configName = configList.value[0].id;
      }
      configChangeFun();
    } else {
      tableData.value = [];
    }
  }
};

const tableData = ref<any>([]);
const getConfigTableDataFun = (val: any) => {
  if (val) {
    tableData.value = JSON.parse(val);
  } else {
    tableData.value = [];
  }

  // baseTableRef.value.setDataFun(tableData.value);
};

const backUpFun = () => {
  emits('backUp');
};

const pageType = ref('add');
const openAddParamFun = () => {
  appConfigParamVisible.value = true;

  if (currentConfigInfo.value?.configValue?.length) {
    pageType.value = 'edit';
  } else {
    pageType.value = 'add';
  }
};

const addConfigParamFun = async (data: any) => {
  tableData.value = data;
  let res: any = {};

  const param: any = {};

  for (const key in currentConfigInfo.value) {
    if (key != 'pageConfigList') {
      param[key] = currentConfigInfo.value[key];
    }
  }
  param.configValue = JSON.stringify(tableData.value);

  if (pageType.value === 'add') {
    res = await updateApplicationConfigAPi(param);
  } else {
    res = await updateApplicationConfigAPi(param);
  }

  if (res && res.code === 200) {
    ElMessage.success('操作成功');
    await getAppConfigListFun();
  }

  appConfigParamVisible.value = false;
};

const delConfigFun = async () => {
  if (filterFormData.configName) {
    ElMessageBox.confirm('确认要删除配置吗?', '警告', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        const res: any = await deleteApplicationConfigAPi({
          configId: filterFormData.configName,
        });

        if (res && res.code === 200) {
          filterFormData.configName = '';
          ElMessage.success('删除成功');
          getAppConfigListFun();
        }
      })
      .catch(() => {});
  } else {
    ElMessage.error('请选择应用配置后删除！');
  }
};

const appTypeList = ref<any>([]);
const getDictionaryDataFun = async () => {
  const res: any = await getDictionaryDataApi({
    dictClass: 'APP_TYPE',
  });
  if (res && res.code === 200) {
    appTypeList.value = res.data;
  }
};

const getTypeNameFun = (type: any) => {
  const str =
    appTypeList.value.find((item: any) => {
      return item.dictValue === type;
    })?.dictName || '';

  return str;
};

watch(
  () => props.appInfo,
  async (newVal) => {
    currentAppInfo.value = newVal;
    await getAppConfigListFun();
  },
  {
    immediate: true,
    deep: true,
  }
);

onMounted(async () => {
  await getDictionaryDataFun();
});
</script>

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

  .gl-page-content-title {
    width: 100%;
    height: 50px;
    display: flex;
    align-items: center;

    .ft28 {
      font-size: 28px;
      margin-right: 12px;
      cursor: pointer;
    }

    .mr12 {
      margin-right: 12px;
    }

    .mr5 {
      margin-right: 5px;
    }

    .app-name {
      font-size: 30px;
      min-width: 100px;
    }

    .app-status {
      height: 100%;
      display: flex;
      align-items: center;
    }

    .app-bg-content {
      width: 40px;
      height: 40px;
      border-radius: 5px;
      overflow: hidden;
    }

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

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

    .error {
      background-color: #f56c6c;
    }
  }

  .page-content {
    width: 100%;
    height: calc(100% - 60px);
    margin-top: 10px;

    .filter-box {
      width: 100%;
      height: 40px;

      .el-form {
        display: flex;

        .select-style {
          width: 200px;
          margin-right: 12px;
        }
      }
    }

    .page-table-content {
      width: 100%;
      height: calc(100% - 50px);
      margin-top: 10px;
    }
  }
}
</style>
