<template>
  <div class="application-management">
    <!-- 右侧主内容区 -->
    <div class="main-content">
      <!-- 过滤条件区域 -->
      <div class="filter-section">
        <!-- 应用范围过滤 -->
        <div class="filter-group">
          <span class="filter-title">应用范围：</span>
          <el-radio-group v-model="scopeFilter" size="small" @change="handleScopeFilterChange" v-for="item in buffOptions" :key="item.value">
            <el-radio-button :label="item.label">{{ item.value }}</el-radio-button>
            <!-- <el-radio-button label="district">区级</el-radio-button>
            <el-radio-button label="street">街道</el-radio-button>
            <el-radio-button label="community">社区</el-radio-button> -->
          </el-radio-group>
        </div>

        <!-- 应用状态过滤 -->
        <div class="filter-group">
          <span class="filter-title">应用状态：</span>
          <el-radio-group v-model="statusFilter" size="small" @change="handleStatusFilterChange" v-for="item in statusOptions" :key="item.value">
            <el-radio-button :label="item.label">{{ item.value }}</el-radio-button>
            <!-- <el-radio-button label="online">在等</el-radio-button>
            <el-radio-button label="offline">在建</el-radio-button>
            <el-radio-button label="suspended">在维</el-radio-button>
            <el-radio-button label="expired">停用</el-radio-button>  -->
          </el-radio-group>
        </div>

        <!-- 应用标签过滤 -->
        <div class="filter-group">
          <span class="filter-title">应用标签：</span>
          <el-radio-group v-model="tagFilter" size="small" @change="handleTagFilterChange" v-for="item in tagOptions" :key="item.value">
            <el-radio-button :label="item.label">{{ item.value }}</el-radio-button>
            <!-- <el-radio-button label="special">特色应用</el-radio-button>
            <el-radio-button label="code">代码平台</el-radio-button>
            <el-radio-button label="government">仅供演示</el-radio-button>
            <el-radio-button label="demo">示范应用</el-radio-button>
            <el-radio-button label="water">水务</el-radio-button>
            <el-radio-button label="test">测试</el-radio-button> -->
          </el-radio-group>
        </div>
      </div>

      <!-- 搜索栏区域 -->
      <div class="search-section">
        <el-input 
          placeholder="请输入应用名称关键字" 
          v-model="searchKeyword" 
          class="search-input" 
          clearable
        >
          <template #prepend><el-icon><search /></el-icon></template>
        </el-input>
        <el-button type="primary" class="search-btn"  @click="handleSearchClick">搜索</el-button>
        <el-button class="reset-btn" @click="handleResetClick">重置</el-button>
        <el-button type="success" class="add-btn" @click="handleAddClick">+ 新增应用</el-button>
      </div>

      <!-- 应用列表区域 -->
      <div class="applications-section">
        <div class="section-header">
          <span class="total-count">共检索{{total}}个应用</span>
          <div class="sort-control">
            <span>排序：</span>
            <el-select v-model="sortByValue" size="small" style="width: 120px;" @change="handleSortChange">
              <el-option label="上架时间(升序)" value="1"></el-option>
              <el-option label="上架时间(降序)" value="2"></el-option>
            </el-select>
          </div>
        </div>

        <!-- 应用列表 -->
        <div class="applications-list">
          <div class="application-item" v-for="(app, index) in applications" :key="index">
            <div class="app-info">
              <div class="app-logo">
                <img :src="curUrl + app.c_picture" :alt="app.title" />
              </div>
              <div class="app-details">
                <div class="app-header">
                  <h3 class="app-name">{{ app.title }}</h3>
                  <span class="app-version">{{ app.version }}</span>
                </div>
                <div class="app-tags">
                  <!-- <el-tag size="small" type="primary" v-if="app.isPublic">区属应用</el-tag> -->
                  <!-- <el-tag size="small" v-if="app.tag">{{ app.tag }}</el-tag> -->
                  <el-tag size="small" v-for="tag in app.tags" :key="tag">{{ tag }}</el-tag>
                </div>
              </div>
            </div>

            <div class="app-metrics">
              <div class="metric-item">
                <span class="metric-label">应用范围</span>
                <span class="metric-value">{{ app.buffName }}</span>
              </div>
              <div class="metric-item">
                <span class="metric-label">应用状态</span>
                <span class="metric-value" :class="`status-${app.appstauts}`">{{ app.appstautName }}</span>
              </div>
              <div class="metric-item">
                <span class="metric-label">使用单位</span>
                <span class="metric-value">{{ app.sydw }}</span>
              </div>
              <div class="metric-item">
                <span class="metric-label">所属部门</span>
                <span class="metric-value">{{ app.ssbm }}</span>
              </div>
              <div class="metric-item">
                <span class="metric-label">负责人</span>
                <span class="metric-value">{{ app.ywfzr }}</span>
              </div>
              <div class="metric-item">
                <span class="metric-label">联系方式</span>
                <span class="metric-value">{{ app.phone }}</span>
              </div>
              <div class="metric-item">
                <span class="metric-label">创建时间</span>
                <span class="metric-value">{{ app.createTime }}</span>
              </div>
              <div class="metric-item">
                <span class="metric-label">上架时间</span>
                <span class="metric-value">{{ app.frameTime }}</span>
              </div>
            </div>

            <div class="app-actions">
              <!-- <span class="app-date">{{ app.createDate }}</span> -->
              <el-button type="primary" size="small" class="detail-btn" @click="getContentById(app)">查看详情</el-button>
            </div>
          </div>
        </div>

        <!-- 分页控件 -->
        <div class="pagination-section">
          <span class="total-text">共{{total}}个应用</span>
          <el-pagination
            layout="prev, pager, next, jumper, total"
            :total="total"
            :current-page="currentPage"
            :page-size="pageSize"
            @current-change="handleCurrentChange"
          >
          </el-pagination>
        </div>
      </div>

      <editManage
      v-if="isContentShow"
      :isShow="isContentShow"
      :column-model="columnModel"
      :column="columnData"
      :item="contentItem"
      :is-view="isContentView"
      :close="handleEditClose"
    ></editManage>
    </div>
    
  </div>
</template>

<script>
import { defineAsyncComponent } from "vue";
import appCenter from "@/api/appCenter";
import moment from 'moment';
export default {
  name: "ApplicationManagement",
   components: {
    editManage: defineAsyncComponent(() =>
      import("@/views/yygl/manage/editManage.vue")
    )
  },
  data() {
    return {
      // 过滤条件
      scopeFilter: 'all',
      statusFilter: 'all',
      tagFilter: 'all',
      searchKeyword: '',
      curUrl:systemConfig.dmsDataProxy,
      buffOptions: [],
      tagOptions: [],
      statusOptions: [],
      // 排序条件  1 升序 2 降序
      sortByValue: '1',
      modelId: 1667, // 应用中心模型id
      columnId: 1659, // 应用中心栏目id

      isContentShow: false,
      isContentView: false,
      columnModel: {},
      columnData: {
        title: "",
      },
      contentItem: {},
      
      // 分页信息
      currentPage: 1,
      pageSize: 10,
      total:10,
      
      itemApplications: [],
      // 应用列表数据
      applications: []
    }
  },
  mounted () {
    this.initData();
  },
  methods: {
    //关闭编辑弹窗
    handleEditClose(flag) {
      this.isContentShow = false;
      this.isContentView = false;
      // this.columnModel = [];
      this.contentItem = {};
      if (flag) {
        this.getDmsDataList();
      }
    },
    // 新增应用
    handleAddClick() {
      this.isContentShow = true;
    },
    // 处理分页变化
    handleCurrentChange(page) {
      this.currentPage = page;
      // 这里可以添加分页数据加载逻辑
      this.getDmsDataList();
    },
    initData () {
      this.getDmsCNameAType('applevel');
      this.getDmsCNameAType('appstatus');
      this.getDmsTagSName();
      this.getModelById();
      this.getDmsDataList();
    },
    //根据模型id查询模型详情
    getModelById(){
      let requestParams = {
        modelId: this.modelId, // 应用中心模型id
      };
      appCenter.getModelById(requestParams).then(res => {
        if (res.code === 200) {
          this.columnModel = res.content;
          this.columnModel.modelId = this.modelId;
          this.columnModel.columnId = this.columnId;
          this.columnData = this.columnModel;
        }
      })
    },
    //根据内容id查询内容详情
    getContentById(item){
      let that = this;
      let requestParams = {
          columnId: item.column_id,
          contentId: item.id,
      };
      console.log(item);
      appCenter.getContentById(requestParams).then((data) => {
          if (data.code === 200) {
            that.contentItem = data.content;
            that.contentItem.phone = this.formatPhoneNumber(that.contentItem.phone);
            that.isContentShow = true;
            that.isContentView = false;
          }
      });
    },
    // 处理应用范围过滤变化
    handleScopeFilterChange() {
      this.getDmsDataList();
    },
    // 处理应用状态过滤变化
    handleStatusFilterChange() {
      this.getDmsDataList();
    },
    // 处理应用标签过滤变化
    handleTagFilterChange() {
      this.getDmsDataList();
    },
    // 处理搜索点击事件
    handleSearchClick() {
      this.getDmsDataList();
    },
    //重置过滤条件
    handleResetClick() {
      this.scopeFilter = 'all';
      this.statusFilter = 'all';
      this.tagFilter = 'all';
      this.searchKeyword = '';
      this.getDmsDataList();
    },
    // 处理排序条件变化
    handleSortChange() {
      this.getDmsDataList();
    },
    getDmsTagSName(){
      let requestParams = {
        sName: 'tag',
      };
      appCenter.getDmsSName(requestParams).then(res => {
        if (res.code === 200) {
            this.tagOptions = res.content.map(item => ({
              label: item.index,
              value: item.name
            }));
            let allOption = {
              label: 'all',
              value: '全部'
            }
            this.tagOptions.unshift(allOption);
            
        }
      })
    },
    getDmsCNameAType(param) {
      let requestParams = {
        cName: param,
        type: 0
      };
      
      appCenter.getDmsCNameAType(requestParams).then(res => {
        if (res.code === 200) {
            let option = res.content.map(item => ({
              label: item.index,
              value: item.name
            }));
            let allOption = {
              label: 'all',
              value: '全部'
            }
            if(param === 'applevel'){
              this.buffOptions = option;
              this.buffOptions.unshift(allOption);
            }else{
              this.statusOptions = option;
              this.statusOptions.unshift(allOption);
            }
        }
      })
    },
    getDmsDataList() {
      let requestParams = {
        columnId: this.columnId,
        states: 0,
        orderBy: JSON.stringify([{"field":"frame_time","orderByType":this.sortByValue}]),
        pageSize: this.pageSize,
        page: (this.currentPage-1)
      };
      if (this.searchKeyword) {
        requestParams.search = JSON.stringify([
          ...(requestParams.search ? JSON.parse(requestParams.search) : []),
          {
            field: "title",
            searchType: 2,
            content: { value: "%" + this.searchKeyword + "%" },
          },
        ]);
      }
      if (this.scopeFilter !== 'all') {
        requestParams.search = JSON.stringify([
          ...(requestParams.search ? JSON.parse(requestParams.search) : []),
          {
            field: "appbuff",
            searchType: 2,
            content: { value: this.scopeFilter},
          },
        ]);
      }
      if (this.statusFilter !== 'all') {
        requestParams.search = JSON.stringify([
          ...(requestParams.search ? JSON.parse(requestParams.search) : []),
          {
            field: "appstauts",
            searchType: 2,
            content: { value: this.statusFilter},
          },
        ]);
      }
      if (this.tagFilter !== 'all') {
        requestParams.search = JSON.stringify([
          ...(requestParams.search ? JSON.parse(requestParams.search) : []),
          {
            field: "apptags",
            searchType: 2,
            content: { value: this.tagFilter},
          },
        ])
      }
      appCenter.getDmsDataList(requestParams).then(res => {
        if (res.code === 200) {
          this.total = res.content.count;
          this.itemApplications = res.content.data.map(item => ({
            ...item,
            buffName: this.buffOptions.find(info => info.label == item.appbuff.trim())?.value || '',
            appstautName: this.statusOptions.find(info => info.label == item.appstauts.trim())?.value || '',
            tags: item.apptags.split(',').map(tag => this.tagOptions.find(info => info.label == tag.trim())?.value || ''),
            createTime: moment(item.create_time).format('YYYY-MM-DD HH:mm:ss'),
            frameTime: moment(item.frame_time).format('YYYY-MM-DD HH:mm:ss'),
            phone: this.formatPhoneNumber(item.phone),
          }))
          this.applications = this.itemApplications;
        }else{
          this.total = 0;
          this.applications = [];
        }
      })
    },
     formatPhoneNumber(phone) {
      if (!phone) return '';
        return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
    }
  }
}
</script>

<style lang="less" scoped>
.application-management {
  width: 100%;
  background-color: #08224a;
  color: #ffffff;
}

/* 右侧主内容区 */
.main-content {
  padding: 20px 30px;
  overflow-y: auto;
}

/* 过滤条件区域 */
.filter-section {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  // margin-bottom: 20px;
  padding-bottom: 15px;
  // border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.filter-title {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
}

/* 搜索栏区域 */
.search-section {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 25px;
}

.search-input {
  // width: 400px;
  margin-right: 10px;
}

.search-btn, .reset-btn, .add-btn {
  padding: 8px 16px;
  font-size: 14px;
}

/* 应用列表区域 */
.applications-section {
  background-color: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  padding: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 0px 10px 5px 10px;
}

.total-count {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
}

.sort-control {
  display: flex;
  align-items: center;
  gap: 0px;
  margin-right: 8px;
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
}

/* 应用列表 */
.applications-list {
  margin-bottom: 20px;
  height: 500px;
  overflow: auto;
  padding: 0px 10px 0px 10px;
}

.application-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  margin-bottom: 10px;
  background-color: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 6px;
  transition: all 0.3s ease;
  
  &:hover {
    border-color: rgba(24, 144, 255, 0.4);
    background-color: rgba(24, 144, 255, 0.05);
  }
}

.app-info {
  display: flex;
  align-items: center;
  // flex: 1;
  width: 400px;
  gap: 15px;
}

.app-logo {
  width: 60px;
  height: 60px;
  border-radius: 6px;
  overflow: hidden;
  
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.app-details {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.app-header {
  display: flex;
  align-items: center;
  gap: 10px;
}

.app-name {
  font-size: 16px;
  font-weight: bold;
  margin: 0;
  color: #ffffff;
}

.app-version {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.6);
  background-color: rgba(255, 255, 255, 0.1);
  padding: 2px 6px;
  border-radius: 4px;
}

.app-tags {
  display: flex;
  gap: 5px;
}

/* 应用指标 */
.app-metrics {
  display: flex;
  gap: 40px;
  flex: 1;
  justify-content: space-around;
  padding-right: 20px;
}

.metric-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 3px;
}

.metric-label {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.6);
}

.metric-value {
  font-size: 14px;
  font-weight: bold;
  color: #ffffff;
}

.status-online {
  color: #67c23a;
}

.status-offline {
  color: #e6a23c;
}

.status-suspended {
  color: #909399;
}

.status-expired {
  color: #f56c6c;
}

/* 应用操作 */
.app-actions {
  display: flex;
  align-items: center;
  gap: 20px;
}

.app-date {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.6);
}

.detail-btn {
  padding: 4px 12px;
  font-size: 12px;
}

/* 分页控件 */
.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 0px 15px 0px 10px;
  // padding-top: 15px;
  // border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.total-text {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .app-metrics {
    gap: 20px;
  }
}

@media (max-width: 992px) {
  .main-content {
    padding: 15px 20px;
  }
  
  .filter-section {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .search-input {
    width: 300px;
  }
  
  .application-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .app-metrics {
    width: 100%;
    justify-content: space-around;
  }
  
  .app-actions {
    width: 100%;
    justify-content: space-between;
  }
}
</style>