<template>
  <div v-loading="loading" class="customerGood">
    <!-- 搜索部分 -->
    <div>
      <ul class="search-box">
        <li>
          <el-input-group class="search-input">
            <el-input
              size="mini"
              placeholder="请输入关键词"
              v-model="queryParams.productname"
              clearable
              @keyup.enter.native="handleSearch"
            ></el-input>
            <el-button
              slot="append"
              icon="el-icon-search"
              size="mini"
              @click="handleSearch"
            ></el-button>
          </el-input-group>
        </li> 
        <li>
          <span class="search-label">创建日期:</span>
          <el-date-picker
            size="mini"
            style="width: 220px;"
            type="datetimerange"
            align="right"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="['00:00:00', '23:59:59']"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            v-model="dateRange"
            @change="handleDateChange"
          ></el-date-picker>
        </li>
        <li>
          <el-button size="mini" @click="handleReset">重置</el-button>
          <el-button type="primary" size="mini" @click="handleSearch">查询</el-button>
        </li>
      </ul>
    </div>

    <!-- 表格部分 -->
    <el-card class="tableCard">
      <el-table
        :data="tableData"
        style="width: 100%;font-size: 12px"
        height="calc(100vh - 230px)"
        border
        v-loading="loading"
      >
        <el-table-column min-width="90px" align="center" prop="productname" label="产品名称"></el-table-column>
        <el-table-column min-width="150px" align="center" prop="productdesc" label="产品描述" :show-overflow-tooltip="true">
          <template slot-scope="{row}">
            {{ row.productdesc ? row.productdesc : '-' }}
          </template>
        </el-table-column>
        <el-table-column min-width="150px" align="center" prop="orderid" label="订单号" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column min-width="60px" align="center" prop="start_date" label="购买日期"></el-table-column>
        <el-table-column prop="expire_date" label="到期日期">
          <template slot-scope="scope">
            {{ scope.row.expire_date == null ? '-' : scope.row.expire_date }}
          </template>
        </el-table-column>
        <el-table-column prop="" label="操作" align="center" width="120px">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="goJiNanChaoSuan()" v-if="scope.row.providername === '济南超算'">
              <div style="display: flex;justify-content: center;align-items: center">
                <img style="width: 12px;margin-right: 5px;height: 12px;" src="./svg/跳转.svg" alt="">超算产品
              </div>
            </el-button>
            <el-button type="primary" size="mini" @click="goBaiDu(scope.row.product_url)" v-else-if="(scope.row.providername === '百度智能云')">
              <div style="display: flex;justify-content: center;align-items: center">
                <img style="width: 12px;margin-right: 5px;height: 12px;" src="./svg/跳转.svg" alt="">实例使用
              </div>
            </el-button>
            <el-button type="primary" size="mini" @click="goJd" v-else-if="(scope.row.providername === '京东云')">
              <div style="display: flex;justify-content: center;align-items: center">
                <img style="width: 12px;margin-right: 5px;height: 12px;" src="./svg/跳转.svg" alt="">京东产品
              </div>
            </el-button>
            <el-button type="primary" size="mini" @click="goUcloud(scope.row.region)" v-else-if="(scope.row.providername === '优刻得科技股份有限公司')">
              <div style="display: flex;justify-content: center;align-items: center">
                <img style="width: 12px;margin-right: 5px;height: 12px;" src="./svg/跳转.svg" alt="">集群二
              </div>
            </el-button>
            <el-button size="mini" @click="nodeThree(scope.row)" v-else-if="(scope.row.classify === 'E')">
              详情
            </el-button>
            <div v-else-if="scope.row.classify === 'CPCC'">
              <el-button size="mini" type="primary" @click="openCpccDetail(scope.row)">
                容器化详情
              </el-button>
              <el-button size="mini" type="primary" @click="$router.push('/customer/SshTerminal')">
                登录
              </el-button>
            </div>
            <el-button type="primary" size="mini" @click="goCaption()" v-else-if="(scope.row.providername === '北京首都在线科技股份有限公司')">
              <div style="display: flex;justify-content: center;align-items: center">
                <img style="width: 12px;margin-right: 5px;height: 12px;" src="./svg/跳转.svg" alt="">集群一
              </div>
            </el-button>
            <span v-else>-</span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.page_size"
        @pagination="handlePagination"
      />
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog title="详情" :visible.sync="dialogTableVisible">
      <el-table :data="datailList">
        <el-table-column min-width="200px" property="date" label="实例编号/名称">
          <template slot-scope="scope">
            {{ scope.row.id }}
          </template>
        </el-table-column>
        <el-table-column min-width="200px" property="name" label="状态">
          <template slot-scope="scope">
            {{ scope.row.status === "1" ? '运行中' : '已关机' }}
          </template>
        </el-table-column>
        <el-table-column min-width="200px" property="address" label="规格详情">
          <template slot-scope="scope">
            <div class="guige">
              <span>{{ scope.row.productname }}* {{ scope.row.gpu }}卡</span>
              <el-popover placement="top" title="" width="200" trigger="hover">
                <span class="tipStyle" slot="reference">查看详情</span>
                <div>
                  <p>存储: {{ scope.row.storage }} G</p>
                  <p>CPU: {{ scope.row.cpu }} 核</p>
                  <p>内存: {{ scope.row.memory }} G</p>
                  <p>GPU: {{ scope.row.gpu }} 卡</p>
                  <p>显存: {{ scope.row.gpumem }} G</p>
                </div>
              </el-popover>
            </div>
          </template>
        </el-table-column>
        <el-table-column min-width="120px" property="address" label="健康状态">
          <template slot-scope="scope">
            正常
          </template>
        </el-table-column>
        <el-table-column min-width="100px" property="address" label="付费方式">
          <template slot-scope="scope">
            核时
          </template>
        </el-table-column>
        <el-table-column min-width="100px" property="address" label="登录指令">
          <template slot-scope="scope">
            <div class="itemOut">
              <div>登录指令</div>
              <div>ssh ****** <span class="copyBtn">
                  <i @click="copyText('ssh -p ' + scope.row.port + ' ' + scope.row.loginname + '@' + scope.row.ip_region)" class="el-icon-copy-document"></i>
                </span>
              </div>
            </div>
            <div class="itemOut">
              <div>密码</div>
              <div>****** <span class="copyBtn"> <i @click="copyText(scope.row.loginpwd)" class="el-icon-copy-document"></i> </span></div>
            </div>
          </template>
        </el-table-column>
        <el-table-column min-width="150px" fixed="right" property="address" label="操作">
          <template slot-scope="scope">
            <el-popconfirm @confirm="shutDownThree(scope.row)" title="确定将该设备关机吗？">
              <el-button slot="reference" :loading="deleteBtnLoading" type="danger" size="mini">
                关机
              </el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 登录信息对话框 -->
    <el-dialog title="登录信息" :visible.sync="rqyVisible" width="800">
      <el-descriptions title="" direction="vertical" :column="4" border>
        <el-descriptions-item label="实例id">{{ cpccDetail.id }}</el-descriptions-item>
        <el-descriptions-item label="实例名称">{{ cpccDetail.source_name }}</el-descriptions-item>
        <el-descriptions-item label="状态">进行中</el-descriptions-item>
        <el-descriptions-item label="健康状态">
          <el-tag type="success" effect="dark">
            正常
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="登录账号">{{ cpccDetail.source_authuser }}</el-descriptions-item>
        <el-descriptions-item label="密码">
          <div class="pasStyle">
            <span v-if="!isShowPass"> **** </span>
            <span v-if="isShowPass"> {{ cpccDetail.source_authpasswd }}</span>
            <img @click="isShowPass = !isShowPass" v-if="!isShowPass" src="./svg/showEye.svg" alt="">
            <img @click="isShowPass = !isShowPass" v-if="isShowPass" src="./svg/hidenEye.svg" alt="">
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="IP">{{ cpccDetail.source_externalip }}</el-descriptions-item>
        <el-descriptions-item label="端口号">{{ cpccDetail.source_outsideport }}</el-descriptions-item>
        <el-descriptions-item label="内存量">{{ cpccDetail.source_memrate }}</el-descriptions-item>
        <el-descriptions-item label="核心数">{{ cpccDetail.source_cpurate }}</el-descriptions-item>
        <el-descriptions-item label="数据盘">{{ cpccDetail.source_storagelimits }}</el-descriptions-item>
        <el-descriptions-item label="系统盘">{{ cpccDetail.disk_sys_limit }}</el-descriptions-item>
        <el-descriptions-item v-if="cpccDetail.source_gpu !== '0'" label="卡数">{{ cpccDetail.source_gpu }}
        </el-descriptions-item>
      </el-descriptions>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="rqyVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getCustomerGoodsAPI, HpcAccessTimeAPI } from '@/api/customer/userResource'
import { getJinanchaosuanSign } from '@/api/JiNanChaoSuan/jiNanChaoSuanUserList'
import { goJdUrl } from "@/api/product/jdApi";
import { reqDeleteK8sCloud, reqGetInstance } from "@/api/k8s";
import { Terminal } from "xterm";
import SshTerminal from "@/views/customer/userResource/SshTerminal.vue";
import Pagination from '../../components/Pagination/index.vue';

export default {
  name: "userResource",
  components: {
    SshTerminal,
    Pagination
  },
  data() {
    return {
      isShowPass: false,
      cpccDetail: {},
      rqyVisible: false,
      deleteBtnLoading: false,
      visible: false,
      detailBtnLoading: false,
      userid: sessionStorage.getItem("userId"),
      tableData: [],
      loading: false,
      dialogTableVisible: false,
      datailList: [],
      total: 0,
      dateRange: [],
      queryParams: {
        productname: '',        // 搜索关键词
        start_date: '',         // 开始时间
        end_date: '',           // 结束时间
        page: 1,                // 页码
        page_size: 10,          // 每页数量
      }
    };
  },
  mounted() {
    this.loading = true;
    this.getCustomerGoods();
    console.log("用户资源的路由信息是", this.$route);
  },
  methods: {
    // 搜索处理
    handleSearch() {
      this.queryParams.page = 1; // 搜索时重置到第一页
      this.getCustomerGoods();
    },

    // 重置搜索
    handleReset() {
      this.queryParams = {
        productname: '',
        start_date: '',
        end_date: '',
        page: 1,
        page_size: 10,
      };
      this.dateRange = [];
      this.getCustomerGoods();
    },

    // 日期选择处理
    handleDateChange(value) {
      if (value && value.length === 2) {
        this.queryParams.start_date = value[0];
        this.queryParams.end_date = value[1];
      } else {
        this.queryParams.start_date = '';
        this.queryParams.end_date = '';
      }
    },

    // 分页处理
    handlePagination(pagination) {
      this.queryParams.page = pagination.page;
      this.queryParams.page_size = pagination.limit;
      this.getCustomerGoods();
    },

    // 获取用户资源列表
    async getCustomerGoods() {
      this.loading = true;
      try {
        const res = await getCustomerGoodsAPI(this.queryParams);
        if (res.status === true) {
          this.tableData = res.data;
          this.total = res.pagination.total;
        } else {
          this.$message.error('获取数据失败');
        }
      } catch (error) {
        console.error('获取用户资源失败:', error);
        this.$message.error('获取数据失败');
      } finally {
        this.loading = false;
      }
    },

    openCpccDetail(row) {
      this.rqyVisible = true;
      this.cpccDetail = row.instance_info;
    },

    copyText(value) {
      const textarea = document.createElement('textarea');
      textarea.value = value;
      document.body.appendChild(textarea);
      textarea.select();
      document.execCommand('copy');
      document.body.removeChild(textarea);
      this.$message.success('已复制到剪贴板');
    },

    shutDownThree(item) {
      this.deleteBtnLoading = true;
      let ploay = {
        id: item.id,
        podname: item.podname,
        pvcname: item.pvcname,
        customer_goods_id: item.customer_goods_id
      };
      reqDeleteK8sCloud(ploay).then(res => {
        this.deleteBtnLoading = false;
        if (res.status) {
          this.$message.success("删除成功~");
          reqGetInstance({ customer_goods_id: item.id, orgid: sessionStorage.getItem('orgid') }).then(res => {
            if (res.status) {
              this.datailList = res.data;
            }
          });
        } else {
          this.$message.warning("删除失败~");
        }
      });
    },

    nodeThree(row) {
      this.detailBtnLoading = true;
      reqGetInstance({ customer_goods_id: row.id, orgid: sessionStorage.getItem('orgid') }).then(res => {
        this.detailBtnLoading = false;
        if (res.status) {
          this.dialogTableVisible = true;
          this.datailList = res.data;
        }
      });
    },

    goCaption() {
      this.$router.push('/product/gpu/showGpu');
    },

    goUcloud(region) {
      sessionStorage.setItem('region', region);
      this.$router.push('/product/ucloudProduct/showCloudHost');
    },

    goJd() {
      this.loading = true;
      goJdUrl(this.userid).then(res => {
        this.loading = false;
        if (res.status) {
          window.open(res.data);
        } else {
          this.$message.error('跳转京东界面失败');
        }
      });
    },

    goBaiDu(listUrl) {
      this.$store.commit('setRedirectUrl', listUrl);
      localStorage.setItem('redirectUrl', listUrl);
      this.$router.push({
        name: 'baiduProductShow',
        params: {
          listUrl: listUrl,
        }
      });
    },

    HpcAccessTime() {
      HpcAccessTimeAPI({ orgid: sessionStorage.getItem("orgid") }).then(res => {
        if (res.status == true) {
          // 处理访问时间
        }
      });
    },

    goJiNanChaoSuan() {
      this.HpcAccessTime();
      var orgid = sessionStorage.getItem("orgid");
      var username = sessionStorage.getItem("user");
      let ploay = {
        username: username
      };
      getJinanchaosuanSign(ploay).then(res => {
        if (res.status && res.warn_msg == null) {
          window.open(
            'https://hpc.kaiyuancloud.cn/kyy_test/?key=' + res.data,
            "_blank"
          );
        } else if (res.warn_msg != null) {
          this.$message({
            duration: 0,
            showClose: true,
            message: res.warn_msg,
            type: 'warning'
          });
          window.open(
            'https://hpc.kaiyuancloud.cn/kyy_test/?key=' + res.data,
            "_blank"
          );
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.tip {
  color: #ff9120;
  height: 35px;
  img {
    width: 15px;
    height: 15px;
    margin-right: 3px;
  }
  padding-left: 2px;
  background: #fff;
  font-size: 14px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.guige {
  display: flex;
  flex-direction: column;
}

.tipStyle {
  transition: all .3s ease-in-out;
  cursor: pointer;
  &:hover {
    transition: all .3s ease-in-out;
    color: #0a04e1;
  }
}

.itemOut {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.copyBtn {
  transition: all .3s ease-in-out;
  i {
    color: blue;
  }
  &:hover {
    transition: all .3s ease-in-out;
    cursor: pointer;
    color: #a3b3e8;
  }
}

.pasStyle {
  img {
    width: 20px;
    height: 20px;
    cursor: pointer;
    margin-left: 8px;
    &:hover {
      fill: blue;
    }
  }
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.search-input {
  display: flex;
}

.search-box {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  background-color: white;
  padding: 10px;
  margin-bottom: 10px;
  border-radius: 8px;
}

.search-box li {
  margin-right: 15px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.search-label {
  margin-right: 8px;
  font-size: 14px;
  color: #606266;
}

.tableCard {
  margin-top: 20px;
  height: calc(100vh - 180px);
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>
