<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0, user-scalable=no"
    />
    <title>基本信息</title>
    <script src="/js/mp_base/base.js"></script>

    <style>
      [v-cloak] {
        display: none !important;
      }

      #app {
        background: #f5f5f5;
        min-height: 100vh;
        padding-top: 8px;
        box-sizing: border-box;
      }

      .loading {
        text-align: center;
        padding: 50px;
        color: #999;
      }

      .error {
        text-align: center;
        padding: 50px;
        color: #ff4d4f;
      }

      .section-card {
        margin: 0 8px 10px;
        background: #ffffff;
        border-radius: 8px;
        overflow: hidden;
      }

      .form {
        width: 100%;
        border-collapse: collapse;
      }

      .form th {
        width: 140px;
        max-width: 170px;
      }

      .reason-text {
        white-space: pre-wrap;
        line-height: 1.6;
      }
    </style>
  </head>
  <body>
    <div id="app" v-cloak>
      <div v-if="loading" class="loading">加载中...</div>
      <div v-else-if="error" class="error">{{ error }}</div>
      <!-- 新增学员请假基本信息回显页 by xu 2026-02-28 -->
      <div v-else class="content-div">
        <div class="section-card">
          <table class="form">
            <tr>
              <th>请假类别</th>
              <td>{{ displayData.rclb || '-' }}</td>
            </tr>
            <tr>
              <th>学员</th>
              <td>
                {{ displayData.studentName || displayData.fzrymc ||
                displayData.xm || displayData.fzryid || '-' }}
              </td>
            </tr>
            <tr>
              <th>请假开始时间</th>
              <td>{{ displayData.kssj || '-' }}</td>
            </tr>
            <tr>
              <th>请假结束时间</th>
              <td>{{ displayData.jssj || '-' }}</td>
            </tr>
            <tr>
              <th>事由</th>
              <td class="reason-text">{{ displayData.ms || '-' }}</td>
            </tr>
          </table>
        </div>
      </div>
    </div>

    <script>
      window.SS.ready(function () {
        window.SS.dom.initializeFormApp({
          el: "#app",
          data() {
            return {
              pageParams: {},
              loading: false,
              error: "",
              formData: {},
              displayData: {
                rclb: "",
                fzrymc: "",
                xm: "",
                kssj: "",
                jssj: "",
                ms: "",
                fjid: "",
              },
            };
          },
          async mounted() {
            this.pageParams = this.getUrlParams();
            await this.loadData();
          },
          methods: {
            getUrlParams() {
              const params = {};
              const urlSearchParams = new URLSearchParams(
                window.location.search
              );
              for (const [key, value] of urlSearchParams) {
                params[key] = decodeURIComponent(value);
              }
              return params;
            },

            parseParamObject(paramStr) {
              if (!paramStr) return {};
              try {
                return JSON.parse(paramStr);
              } catch (err) {
                try {
                  const fixed = paramStr.replace(
                    /([,{]\s*)([a-zA-Z_][a-zA-Z0-9_]*)\s*:/g,
                    '$1"$2":'
                  );
                  return JSON.parse(fixed);
                } catch (err2) {
                  console.error("解析param失败:", err2);
                  return {};
                }
              }
            },

            async loadData() {
              // 加载请假详情数据并回显 by xu 2026-02-28
              const service = this.pageParams.service;
              if (!service) {
                this.error = "缺少service参数";
                return;
              }

              this.loading = true;
              this.error = "";

              try {
                const paramObj = this.parseParamObject(this.pageParams.param);
                const requestData = {
                  ...paramObj,
                };
                const appendIfMissing = (targetKey, sourceKeys) => {
                  if (
                    requestData[targetKey] !== undefined &&
                    requestData[targetKey] !== null &&
                    requestData[targetKey] !== ""
                  ) {
                    return;
                  }
                  for (let i = 0; i < sourceKeys.length; i += 1) {
                    const sourceKey = sourceKeys[i];
                    const value = this.pageParams[sourceKey];
                    if (value !== undefined && value !== null && value !== "") {
                      requestData[targetKey] = value;
                      return;
                    }
                  }
                };
                appendIfMissing("sqid", ["sqid"]);
                appendIfMissing("shid", ["shid"]);
                appendIfMissing("ssObjName", ["ssObjName", "ssobjname"]);
                appendIfMissing("ssObjId", ["ssObjId", "ssobjid"]);
                appendIfMissing("bdlbm", ["bdlbm"]);
                appendIfMissing("dataType", ["dataType", "datatype"]);
                appendIfMissing("encode_shid", ["encode_shid"]);
                appendIfMissing("jdmc", ["jdmc"]);
                appendIfMissing("ssToken", ["ssToken"]);

                const response = await request.post(
                  `/service?ssServ=${service}&ssDest=data`,
                  requestData,
                  { loading: false, formData: true }
                );

                const raw = this.pickLeaveData(response?.data);
                if (!raw) {
                  this.error = "未获取到请假数据";
                  return;
                }

                this.formData = raw;
                await this.buildDisplayData(raw);
              } catch (error) {
                console.error("加载请假基本信息失败:", error);
                this.error = "加载失败：" + (error.message || "未知错误");
              } finally {
                this.loading = false;
              }
            },

            pickLeaveData(data) {
              if (!data) return null;
              if (data.xyqj) return data.xyqj;
              if (data.rcqj) return data.rcqj;
              if (data.qj) return data.qj;
              if (Array.isArray(data.objectList) && data.objectList.length > 0)
                return data.objectList[0];
              if (Array.isArray(data.data) && data.data.length > 0)
                return data.data[0];
              if (typeof data === "object") return data;
              return null;
            },

            async buildDisplayData(raw) {
              const cloned = { ...raw };
              cloned.kssj = this.formatDate(raw.kssj);
              cloned.jssj = this.formatDate(raw.jssj);
              cloned.rclb = await this.translateLeaveType(raw.rclbm, raw.rclb);
              cloned.studentName = await this.resolveStudentName(raw);
              this.displayData = {
                ...this.displayData,
                ...cloned,
              };
            },
            async resolveStudentName(raw) {
              const direct = raw.fzrymc || raw.xm || raw.rymc || raw.xmmc || "";
              if (direct) return direct;

              const idValue = String(raw.fzryid || "").trim();
              if (!idValue) return "";

              try {
                if (typeof window.getDictOptions === "function") {
                  const options = await window.getDictOptions("ry");
                  const target = (options || []).find(
                    (item) => String(item.v) === String(idValue)
                  );
                  if (target && target.n) return target.n;
                }
              } catch (error) {
                console.error("学员姓名翻译失败:", error);
              }

              const dictCache = [
                this.pageParams,
                this.formData,
                raw,
                this.displayData,
              ];
              for (let i = 0; i < dictCache.length; i += 1) {
                const src = dictCache[i] || {};
                const candidate =
                  src[`${idValue}_name`] ||
                  src[`${idValue}Name`] ||
                  src.fzryName ||
                  src.fzrymc;
                if (candidate) return candidate;
              }

              return idValue;
            },

            formatDate(value) {
              if (!value) return "";
              if (
                window.H5FieldFormatter &&
                typeof window.H5FieldFormatter.formatDate === "function"
              ) {
                return window.H5FieldFormatter.formatDate(
                  value,
                  "YYYY-MM-DD HH:mm"
                );
              }
              return value;
            },

            async translateLeaveType(rclbm, fallbackName) {
              if (fallbackName) return fallbackName;
              if (!rclbm) return "";
              try {
                if (typeof window.getDictOptions === "function") {
                  const options = await window.getDictOptions("xyqjlb");
                  const target = (options || []).find(
                    (item) => String(item.v) === String(rclbm)
                  );
                  return target ? target.n : rclbm;
                }
                return rclbm;
              } catch (error) {
                console.error("请假类别翻译失败:", error);
                return rclbm;
              }
            },
          },
        });
      });
    </script>
  </body>
</html>
