<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>SIM卡信息查询</title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <link rel="stylesheet" href="../lib/layui-v2.6.3/css/layui.css" media="all">
  <link rel="stylesheet" href="../css/public.css" media="all">
</head>
<body>
<div class="layuimini-container">
  <div class="layuimini-main">
    <fieldset class="table-search-fieldset">
      <legend>SIM卡相关信息聚合查询</legend>
      <div style="margin: 10px 10px 10px 10px">
        <form class="layui-form layui-form-pane" action="" id="searchForm">
          <div class="layui-form-item">
            <label class="layui-form-label">搜索类型</label>
            <div class="layui-input-inline">
              <select id="searchType" name="searchType" lay-search="" lay-filter="searchType">
                <option value="iccid">ICCID</option>
                <option value="deviceId">设备ID</option>
                <option value="simNumber">SIM卡号</option>
              </select>
            </div>
          </div>
          <div class="layui-form-item">
            <label class="layui-form-label">搜索内容</label>
            <div class="layui-input-block">
              <input type="text" id="searchInput" name="searchContent" autocomplete="off" placeholder="搜索内容" lay-verify="required" class="layui-input">
            </div>
          </div>
          <div class="layui-form-item">
            <div class="layui-inline">
              <button type="button" class="layui-btn" onclick="searchSIM()" lay-submit lay-filter="searchSubmit"><i class="layui-icon">&#xe615;</i>搜索</button>
              <button type="button" class="layui-btn layui-btn-primary" lay-submit lay-filter="data-export-btn"><i class="layui-icon">&#xe67d;</i> 导出</button>
            </div>
          </div>
        </form>
      </div>
    </fieldset>

    <div id="resultContainer" class="result-container layui-hide">
      <div class="layui-card">
        <div class="layui-card-body" id="resultContent">

        </div>
      </div>
    </div>

</div>
</div>
<script src="../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script>
  layui.use(['form', 'layer', 'element'], function(){
    var form = layui.form;
    var layer = layui.layer;
    var element = layui.element;

    form.render();
    form.on('submit(searchSubmit)', function(data){
      searchSIM();
      return false;
    });
    
    form.on('submit(data-export-btn)', function (data) {
      const searchInput = document.getElementById('searchInput');
      const searchContent = searchInput.value.trim();
      const searchType = document.querySelector('select[name="searchType"]').value;
      
      if (!searchContent) {
        layer.msg('请输入搜索内容');
        return false;
      }
      
      if (searchType === 'iccid' && !/^\d{19,20}$/.test(searchContent)) {
        layer.msg('ICCID必须是19-20位数字');
        return false;
      }
      
      if (searchType === 'simNumber' && !/^\d{11,13}$/.test(searchContent)) {
        layer.msg('SIM卡号必须是11-13位数字');
        return false;
      }
      
      window.location.href = `/sim/query/export?type=${searchType}&content=${encodeURIComponent(searchContent)}`;
      return false;
    });
  });

  function searchSIM() {
    const searchInput = document.getElementById('searchInput');
    const searchContent = searchInput.value.trim();
    const searchType = document.querySelector('select[name="searchType"]').value;

    if (!searchContent) {
      layer.msg('请输入搜索内容');
      return;
    }

    if (searchType === 'iccid' && !/^\d{19,20}$/.test(searchContent)) {
      layer.msg('ICCID必须是19-20位数字');
      return;
    }

    if (searchType === 'simNumber' && !/^\d{11,13}$/.test(searchContent)) {
      layer.msg('SIM卡号必须是11-13位数字');
      return;
    }
    const loadingIndex = layer.load(1, {
      shade: [0.1, '#fff']
    });

    fetch(`/api/proxy/sim/query?type=${searchType}&content=${searchContent}`)
            .then(response => {
              if (!response.ok) {
                throw new Error('Network response was not ok');
              }
              return response.json();
            })
            .then(result => {
              layer.close(loadingIndex);
              console.log('API Response:', result);

              if (result.Status === 1 && result.Data) {
                displayResult(result.Data);
              } else {
                layer.msg(result.Message || '查询失败');
              }
            })
            .catch(error => {
              layer.close(loadingIndex);
              console.error('Error:', error);
              layer.msg('请求处理失败：' + error.message);
            });
  }

  function displayResult(data) {
    const resultContainer = document.getElementById('resultContainer');
    const resultContent = document.getElementById('resultContent');

    if (!resultContainer || !resultContent) {
      console.error('Result container elements not found');
      return;
    }

    resultContainer.classList.remove('layui-hide');

    // 格式化状态和其他信息
    const statusText = getStatusText(data.status);
    const statusClass = getStatusClass(data.status);
    const operatorText = getOperatorText(data.operatortype);

    // 格式化流量数据
    const gprsInfo = {
      total: parseFloat(data.gprs?.total) || 0,
      used: parseFloat(data.gprs?.used) || 0,
      left: parseFloat(data.gprs?.left) || 0
    };

    const usagePercentage = calculateUsagePercentage(gprsInfo);

    resultContent.innerHTML = `
        <table class="layui-table">
            <tbody>
                <tr>
                    <td width="120">运营商</td>
                    <td>${operatorText}</td>
                </tr>
                <tr>
                    <td>ICCID</td>
                    <td>${data.iccid || '-'}</td>
                </tr>
                <tr>
                    <td>SIM卡号</td>
                    <td>${data.msisdn || '-'}</td>
                </tr>
                <tr>
                    <td>IMSI</td>
                    <td>${data.imsi || '-'}</td>
                </tr>
                <tr>
                    <td>套餐信息</td>
                    <td>
                        ID: ${data.packageid || '-'}<br>
                        名称: ${data.packagename || '-'}
                    </td>
                </tr>
                <tr>
                    <td>时间信息</td>
                    <td>
                        激活时间: ${data.activetime || '-'}<br>
                        有效期: ${data.starttime || '-'} 至 ${data.stoptime || '-'}<br>
                        沉默期结束: ${data.silentdate || '-'}
                    </td>
                </tr>
                <tr>
                    <td>状态</td>
                    <td><span class="layui-badge ${statusClass}">${statusText}</span></td>
                </tr>
                <tr>
                    <td>APN信息</td>
                    <td>
                        ${data.apn ? `
                            <div>ID: ${data.apn.apnid || '-'}</div>
                            <div>状态: ${data.apn.status === '01' ?
            '<span class="layui-badge layui-bg-green">在线</span>' :
            '<span class="layui-badge layui-bg-gray">离线</span>'}</div>
                            <div>IP: ${data.apn.ip || '-'}</div>
                            <div>网络: ${getNetworkText(data.apn.rat)}</div>
                            <div>设备状态: ${data.apn.onoffstatus === '1' ?
            '<span class="layui-badge layui-bg-green">开机</span>' :
            '<span class="layui-badge layui-bg-gray">关机</span>'}</div>
                        ` : '-'}
                    </td>
                </tr>
                <tr>
                <td>GPRS流量</td>
                <td>
                    <div class="layui-row">
                        <div class="layui-col-md4">总流量: ${formatFlowSize(gprsInfo.total)} MB</div>
                        <div class="layui-col-md4">已用: ${formatFlowSize(gprsInfo.used)} MB</div>
                        <div class="layui-col-md4">剩余: ${formatFlowSize(gprsInfo.left)} MB</div>
                    </div>
                    <div class="layui-progress layui-progress-big"  style="margin-top: 10px;">
                        <div class="layui-progress-bar ${getProgressBarColor(gprsInfo)}"
                             style="width: ${usagePercentage}%">
                        </div>
                    </div>
                </td>
            </tr>
            </tbody>
        </table>
    `;

    // 重新渲染进度条
    layui.element.render('progress');
  }

  function getStatusText(status) {
    const statusMap = {
      1: '待激活',
      2: '已激活',
      3: '停机',
      4: '注销',
      5: '库存',
      6: '可测试',
      7: '失效'
    };
    return statusMap[status] || '未知状态';
  }
  function getOperatorText(type) {
    const operatorMap = {
      1: '中国移动',
      2: '中国联通',
      3: '中国电信'
    };
    return operatorMap[type] || '未知运营商';
  }
  function getNetworkText(rat) {
    const networkMap = {
      '1': '3G',
      '2': '2G',
      '6': '4G',
      '8': 'NB'
    };
    return networkMap[rat] || '未知网络';
  }
  function getStatusClass(status) {
    const classMap = {
      1: 'layui-bg-orange',  // 待激活
      2: 'layui-bg-green',   // 已激活
      3: 'layui-bg-red',     // 停机
      4: 'layui-bg-gray',    // 注销
      5: 'layui-bg-blue',    // 库存
      6: 'layui-bg-cyan',    // 可测试
      7: 'layui-bg-black'    // 失效
    };
    return classMap[status] || 'layui-bg-gray';
  }

  function getProgressBarColor(gprsInfo) {
    const percentage = calculateUsagePercentage(gprsInfo);
    if (percentage >= 90) return 'layui-bg-red';
    if (percentage >= 70) return 'layui-bg-orange';
    return 'layui-bg-green';
  }

  function calculateUsagePercentage(gprsInfo) {
    // 确保所有值都是数字，并且total不为0
    const total = parseFloat(gprsInfo.total) || 0;
    const used = parseFloat(gprsInfo.used) || 0;

    if (total <= 0) return 0;

    const percentage = (used / total) * 100;
    return Math.min(100, Math.round(percentage));
  }
  function formatFlowSize(size) {
    if (typeof size !== 'number' || isNaN(size)) return '0.00';
    return size.toFixed(2);
  }

  // 按回车键触发查询
  document.getElementById('searchInput').addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
      e.preventDefault();
      searchSIM();
    }
  });
</script>
</body>
</html>