<!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;
      }

      /* 新增考勤记录基本信息页纯转圈加载态 by xu 2026-03-06 */
      .loading {
        min-height: 40vh;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 32px 16px;
      }

      .loading-spinner {
        width: 30px;
        height: 30px;
        border: 3px solid #e8f3ed;
        border-top-color: #40ac6d;
        border-radius: 50%;
        animation: page-spin 0.9s linear infinite;
      }

      @keyframes page-spin {
        from {
          transform: rotate(0deg);
        }
        to {
          transform: rotate(360deg);
        }
      }

      .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;
      }

      .desc-text {
        white-space: pre-wrap;
        line-height: 1.6;
      }
    </style>
  </head>
  <body>
    <div id="app" v-cloak>
      <!-- 新增考勤记录基本信息页纯转圈加载态 by xu 2026-03-06 -->
      <div v-if="loading" class="loading">
        <div class="loading-spinner"></div>
      </div>
      <div v-else-if="error" class="error">{{ error }}</div>
      <!-- 新增考勤记录基本信息回显页 by xu 2026-03-06 -->
      <div v-else class="content-div">
        <div class="section-card">
          <table class="form">
            <tr>
              <th>名称</th>
              <td>{{ displayData.mc || formData.mc || '-' }}</td>
            </tr>
            <tr>
              <th>人员</th>
              <td>{{ displayData.rymc || formData.ryid || '-' }}</td>
            </tr>
            <tr>
              <th>开始时间</th>
              <td>{{ displayData.kssj || '-' }}</td>
            </tr>
            <tr>
              <th>结束时间</th>
              <td>{{ displayData.jssj || '-' }}</td>
            </tr>
            <tr>
              <th>考勤类别</th>
              <td>{{ displayData.kqlb || formData.kqlbm || '-' }}</td>
            </tr>
            <tr>
              <th>班级</th>
              <td>{{ displayData.bjmc || formData.bjid || '-' }}</td>
            </tr>
            <tr>
              <th>描述</th>
              <td class="desc-text">
                {{ displayData.ms || formData.ms || formData.mswj || '-' }}
              </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: {
                mc: "",
                rymc: "",
                kssj: "",
                jssj: "",
                kqlb: "",
                bjmc: "",
                ms: "",
              },
            };
          },
          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) {
                try {
                  params[key] = decodeURIComponent(value);
                } catch (_) {
                  params[key] = String(value);
                }
              }
              return params;
            },

            parseParamObject(paramStr) {
              if (!paramStr) return {};
              if (typeof paramStr === "object") return paramStr;
              try {
                return JSON.parse(paramStr);
              } catch (_) {
                try {
                  const fixed = String(paramStr)
                    .replace(/([{,]\s*)([A-Za-z0-9_]+)\s*:/g, '$1"$2":')
                    .replace(/'/g, '"');
                  return JSON.parse(fixed);
                } catch (error) {
                  console.error("解析param失败:", error);
                  return {};
                }
              }
            },

            async loadData() {
              // 加载考勤记录详情数据并回显 by xu 2026-03-06
              const service = String(
                this.pageParams.service || this.pageParams.ssServ || ""
              ).trim();
              if (!service) {
                this.error = "缺少service参数";
                return;
              }

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

              try {
                const requestData = {
                  ...this.parseParamObject(this.pageParams.param),
                };
                const appendIfMissing = (targetKey, sourceKeys) => {
                  if (
                    requestData[targetKey] !== undefined &&
                    requestData[targetKey] !== null &&
                    requestData[targetKey] !== ""
                  ) {
                    return;
                  }
                  for (let i = 0; i < sourceKeys.length; i += 1) {
                    const value = this.pageParams[sourceKeys[i]];
                    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.pickKqjlData(
                  response && response.data ? response.data : response
                );
                if (!raw) {
                  this.error = "未获取到考勤记录数据";
                  return;
                }

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

            pickKqjlData(data) {
              if (!data) return null;
              if (data.kqjl) return data.kqjl;
              if (data.bjdmKqjl) return data.bjdmKqjl;
              if (
                Array.isArray(data.objectList) &&
                data.objectList.length > 0
              ) {
                return (
                  data.objectList[0].kqjl ||
                  data.objectList[0].bjdmKqjl ||
                  data.objectList[0]
                );
              }
              if (Array.isArray(data.data) && data.data.length > 0) {
                return (
                  data.data[0].kqjl || data.data[0].bjdmKqjl || data.data[0]
                );
              }
              if (typeof data === "object") return data;
              return null;
            },

            async buildDisplayData(raw) {
              // 格式化考勤记录显示字段 by xu 2026-03-06
              this.displayData = {
                mc: raw.mc || "",
                rymc: await this.translateStudentByBj(raw),
                kssj: this.formatDate(raw.kssj),
                jssj: this.formatDate(raw.jssj),
                kqlb: await this.translateDict("kqlb", raw.kqlbm, raw.kqlb),
                bjmc: await this.translateClassName(raw),
                ms: this.normalizeDesc(raw.ms || raw.mswj || ""),
              };
            },

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

            normalizeDesc(value) {
              if (!value) return "";
              return String(value)
                .replace(/<br\s*\/?\>/gi, "\n")
                .replace(/<[^>]+>/g, "")
                .trim();
            },

            async translateStudentByBj(raw) {
              const fallbackName = raw.rymc || raw.xm || "";
              if (fallbackName) return fallbackName;
              if (
                !raw ||
                raw.ryid === undefined ||
                raw.ryid === null ||
                raw.ryid === ""
              )
                return "";
              if (!raw.bjid) {
                return this.translateDict("ry", raw.ryid, fallbackName);
              }

              try {
                // 功能说明：考勤记录基本信息页按班级翻译人员名称，避免同人码本无法按班级定位 by xu 2026-03-18
                const response = await request.post(
                  "/service?ssServ=loadObjpOpt&objectpickerdropdown1=1",
                  {
                    objectpickerparam: JSON.stringify({
                      input: "false",
                      codebook: "xyByBj",
                      bjid: raw.bjid,
                      cascadingLevel: "bjid,ryid",
                    }),
                    objectpickertype: 2,
                    objectpickervalue: raw.ryid,
                    upperValue: raw.bjid,
                  },
                  { loading: false, formData: true }
                );
                if (response && response.data && response.data.result) {
                  const translated =
                    response.data.result[String(raw.ryid)] ||
                    response.data.result[raw.ryid];
                  if (translated) return translated;
                }
              } catch (error) {
                console.error("xyByBj 人员翻译失败:", error);
              }

              return String(raw.ryid);
            },

            async translateClassName(raw) {
              const fallbackName = raw.bjmc || raw.bjname || "";
              if (fallbackName) return fallbackName;
              if (
                !raw ||
                raw.bjid === undefined ||
                raw.bjid === null ||
                raw.bjid === ""
              ) {
                return "";
              }
              const translated = await this.translateDict(
                "adminBj",
                raw.bjid,
                ""
              );
              if (translated && String(translated) !== String(raw.bjid)) {
                return translated;
              }
              return this.translateDict("bj", raw.bjid, fallbackName);
            },

            async translateDict(dictName, value, fallbackName) {
              if (fallbackName) return fallbackName;
              if (value === undefined || value === null || value === "")
                return "";
              try {
                if (typeof window.getDictOptions === "function") {
                  const options = await window.getDictOptions(dictName);
                  const target = (options || []).find(
                    (item) => String(item.v) === String(value)
                  );
                  if (target && target.n) return target.n;
                }
              } catch (error) {
                console.error(`${dictName} 字典翻译失败:`, error);
              }
              return String(value);
            },
          },
        });
      });
    </script>
  </body>
</html>
