<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单号" prop="orderNo">
        <el-input v-model="queryParams.orderNo" placeholder="请输入订单号" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="用户姓名" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入用户姓名" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="负责教练" prop="coachUserName">
        <el-input v-model="queryParams.coachUserName" placeholder="请输入主负责教练姓名" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="是否面签" prop="isSign">
        <el-select v-model="queryParams.isSign" placeholder="请选择面签情况">
          <el-option
            v-for="item in signList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="报名时间">
        <el-date-picker
          v-model="queryParams.timeRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          @change="handleDateChange">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="是否优惠" prop="discountIndex" >
        <el-select v-model="queryParams.discountIndex" placeholder="请选择优惠情况" clearable>
          <el-option
            v-for="item in discountIndexList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="是否确认收款" prop="cashierConfirm" label-width="120px" v-if="showCashierColumn">
        <el-select v-model="queryParams.cashierConfirm" placeholder="请选择收款情况">
          <el-option
            v-for="item in cashierConfirmList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="openForm(undefined)">新增</el-button>
      </el-col>-->
<!--      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-document-add" size="mini" @click="handleAddOrder" >手动报名</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport" >学员及订单信息导出</el-button>
<!--        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading">导出</el-button>-->
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
<!--      <el-table-column label="订单号" align="center" prop="orderNo" />-->
      <el-table-column label="报名时间" align="center" prop="createTime" :formatter="formatDate"/>
      <el-table-column label="用户姓名" align="center" prop="userName" />
      <el-table-column label="用户手机号" align="center" prop="userPhone" />
      <el-table-column label="用户性别" align="center" prop="userSex">
        <template v-slot="scope">
          <dict-tag :type="DICT_TYPE.DICT_SYS_USER_SEX" :value="scope.row.userSex"/>
        </template>
      </el-table-column>
      <el-table-column label="班型" align="center" prop="courseName" />
      <el-table-column label="负责教练" align="center" prop="coachUserName" />

      <el-table-column label="驾照类型" align="center" prop="courseType" />
      <el-table-column label="报名方式" align="center" prop="signType" :formatter="formatSignType"/>
<!--      <el-table-column label="终止时间" align="center" prop="endTime" width="180">-->
<!--        <template v-slot="scope">-->
<!--          <span>{{ parseTime(scope.row.endTime) }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="是否已面签" align="center" prop="isSign">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isSign == 1" type="success">是</el-tag>
          <el-tag v-if="scope.row.isSign == 0" type="danger">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="paymentStatus">
        <template v-slot="scope">
          <dict-tag :type="DICT_TYPE.DRIVE_SCHOOL_ORDER_STATUS" :value="scope.row.paymentStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="订金金额" align="center" prop="reserveMoney" />
      <el-table-column label="尾款" align="center" prop="restMoney" />
      <el-table-column label="优惠金额" prop="discount" align="center" />
      <el-table-column label="实付金额" prop="actualPayment" align="center" />
      <el-table-column label="支付渠道" align="center" prop="payChannel" :formatter="formatPayChannel"/>
      <el-table-column label="支付类型" align="center" prop="payType">
        <template v-slot="scope">
          <dict-tag :type="DICT_TYPE.DRIVE_SCHOOL_PAY_TYPE" :value="scope.row.payType"/>
        </template>
      </el-table-column>

      <el-table-column label="学员是否确认" align="center" prop="ifAgree" :formatter="formatIfAgree"/>
      <el-table-column label="是否终止" align="center" prop="ifEnd">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.ifEnd == 1" type="success">是</el-tag>
          <el-tag v-if="scope.row.ifEnd == 0" type="danger">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="信息" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="viewStudentInfo(scope.row)">学员信息</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="viewContract(scope.row)">合同信息</el-button>
        </template>
      </el-table-column>
<!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button size="mini" type="text"  v-if="scope.row.ifEnd == true">订单已终止</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="openForm(scope.row.id)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="openAssignmentCoach(scope.row)" v-if="scope.row.paymentStatus == 2 && scope.row.ifAssignmentCoach == 0 && scope.row.ifEnd == false">分配教练</el-button>
          <el-button size="mini" type="text" icon="el-icon-close" @click="openEndOrder(scope.row)" v-if="scope.row.paymentStatus == 2 && scope.row.ifEnd == false">终止</el-button>
          <el-button size="mini" type="text" icon="el-icon-plus" @click="openAddForm(scope.row)" v-if="scope.row.paymentStatus == 2 && scope.row.ifEnd == true && scope.row.isCreated == false">快速创建订单</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>-->
      <el-table-column v-if="!showCashierColumnTwo" label="操作" align="center" class-name="small-padding fixed-width" >
        <template v-slot="scope">
          <!-- 如果订单已终止，只显示"订单已终止" -->
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.ifEnd == true"
            disabled
          >
            该订单已终止
          </el-button>

          <!-- 如果订单未终止，显示其他操作按钮 -->
          <template v-if="scope.row.ifEnd == false">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="openForm(scope.row.id)"
            >
              修改
            </el-button>

            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="openAssignmentCoach(scope.row)"
              v-if="scope.row.paymentStatus == 2 && scope.row.ifAssignmentCoach == 0 && scope.row.ifEnd == false"
            >
              分配教练
            </el-button>

            <el-button
              size="mini"
              type="text"
              icon="el-icon-close"
              @click="openEndOrder(scope.row)"
            >
              终止
            </el-button>

            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>

          <!-- 快速创建订单（仅针对已终止订单） -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="openAddForm(scope.row)"
            v-if="scope.row.ifEnd == true && scope.row.isCreated == false"
          >
            快速创建订单
          </el-button>
        </template>
      </el-table-column>
      <el-table-column v-if="showCashierColumn"  label="出纳确认" align="center" class-name="small-padding fixed-width" >
        <template v-slot="scope">
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.ifEnd"
            disabled
          >
            订单已终止
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="openCashierConfirm(scope.row.id)"
            v-if="scope.row.cashierConfirm !== '1' "
          >
            确认收款
          </el-button>
          <el-button
            size="mini"
            type="text"
            style="color: RGB(192, 196, 204)"
            v-else-if="scope.row.cashierConfirm == 1 || scope.row.cashierConfirm == '1'"
            :disabled="true"
          >
            已确认
          </el-button>
        </template>
      </el-table-column>
    </el-table>

<!--    <el-dialog title="合同信息" :visible.sync="viewFlag" width="65%" append-to-body>
      <div
        style="box-sizing: border-box; padding: 15px; overflow: hidden"
        v-html="content"
      ></div>
      <div style="text-align: right;" v-if="userUrl">
        <el-image
          :src="baseImageUrl + userUrl"
          fit="cover"
          :preview-src-list="[baseImageUrl + userUrl]"
          lazy
          alt="身份证照片"
        />
      </div>
    </el-dialog>-->

    <el-dialog
      title="合同信息"
      :visible.sync="viewFlag"
      width="65%"
      append-to-body
      v-if="hasContract"
    >
      <div style="box-sizing: border-box; padding: 15px; overflow: hidden" v-html="content"></div>
      <div style="text-align: right; margin-top: 15px;" v-if="userUrl">
        <el-image
          :src="baseImageUrl + userUrl"
          fit="cover"
          :preview-src-list="[baseImageUrl + userUrl]"
          lazy
          alt="身份证照片"
        />
      </div>
    </el-dialog>

    <!-- 无合同信息的提示弹窗 -->
    <el-dialog
      title="提示"
      :visible.sync="viewFlag"
      width="300px"
      append-to-body
      v-else
    >
      <div style="text-align: center; padding: 20px 0; color: #999;">
        暂无合同信息
      </div>
    </el-dialog>

        <el-dialog :title="studentDialog.title" :visible.sync="studentDialog.visible" width="45%" v-dialogDrag append-to-body id="studentInfoDialog">
          <el-form ref="studentFormRef" :model="studentDialog.studentInfo"  v-loading="studentDialog.loading" label-width="100px">
            <el-form-item label="头像" prop="avatar">
              <el-image
                v-if="studentDialog.studentInfo.avatar"
                :src=" baseImageUrl + studentDialog.studentInfo.avatar"
                style="width: 100px; height: 100px; border-radius: 50%;"
                fit="cover"
              />
              <el-avatar v-else icon="el-icon-user-solid" :size="100" />
            </el-form-item>
            <el-row>
              <el-col :span="12">
                <el-form-item label="姓名" prop="name">
                  <span class="display-text">{{ studentDialog.studentInfo.name || '-' }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="年龄" prop="age">
                  <span class="display-text">{{ studentDialog.studentInfo.age || '-' }}</span>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="性别" prop="sex">
          <span class="display-text">
            {{ getDictLabel(DICT_TYPE.SYSTEM_USER_SEX, studentDialog.studentInfo.sex) || '-' }}
          </span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系电话" prop="phone">
                  <span class="display-text">{{ studentDialog.studentInfo.phone || '-' }}</span>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="身份证号" prop="idCard">
                  <span class="display-text">{{ studentDialog.studentInfo.idCard || '-' }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="工作性质" prop="workName">
                  <span class="display-text">{{ studentDialog.studentInfo.workName || '-' }}</span>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="户籍地址" prop="registAddress">
                  <span class="display-text">{{ studentDialog.studentInfo.registAddress || '-' }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="家庭住址" prop="address">
                  <span class="display-text">{{ studentDialog.studentInfo.address || '-' }}</span>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="8">
                <el-form-item label="渠道" prop="source">
                    <span class="display-text">{{ getSourceLabel(studentDialog.studentInfo.source) }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="招生人" prop="sourceUserId">
                  <span class="display-text">{{ sourceUser || studentDialog.studentInfo.sourceUserId || '-' }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="来源" prop="channel">
                  <span class="display-text">{{ studentDialog.studentInfo.channel || '-' }}</span>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="8">
                <el-form-item label="班型" prop="courseName">
                  <span class="display-text">{{ studentDialog.studentInfo.courseName || '-' }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="订金金额" prop="reserveMoney">
                  <span class="display-text">{{ studentDialog.studentInfo.reserveMoney || '-' }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="尾款" prop="restMoney">
                  <span class="display-text">{{ studentDialog.studentInfo.restMoney || '-' }}</span>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <pre class="display-text remark-text">{{ studentDialog.studentInfo.remark || '-' }}</pre>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="证件照" prop="idPhoto">
              <div style="display: flex; flex-wrap: wrap; gap: 10px;">
                <template v-if="getPhotoList(studentDialog.studentInfo.idPhoto).length > 0">
                  <el-image
                    v-for="(photo, index) in getPhotoList(studentDialog.studentInfo.idPhoto)"
                    :key="'id-'+index"
                    :src="baseImageUrl + photo"
                    style="width: 200px; height: 150px;"
                    :preview-src-list="getPhotoPreviewList(studentDialog.studentInfo.idPhoto)"
                    fit="contain"
                  />
                </template>
                <template v-else>
                  <div style="color: #999;">暂无图片</div>
                </template>
              </div>
            </el-form-item>

            <el-form-item label="生活照" prop="lifePhoto">
              <div style="display: flex; flex-wrap: wrap; gap: 10px;">
                <template v-if="getPhotoList(studentDialog.studentInfo.lifePhoto).length > 0">
                  <el-image
                    v-for="(photo, index) in getPhotoList(studentDialog.studentInfo.lifePhoto)"
                    :key="'life-'+index"
                    :src="baseImageUrl + photo"
                    style="width: 200px; height: 150px;"
                    :preview-src-list="getPhotoPreviewList(studentDialog.studentInfo.lifePhoto)"
                    fit="contain"
                  />
                </template>
                <template v-else>
                  <div style="color: #999;">暂无图片</div>
                </template>
              </div>
            </el-form-item>

            <el-form-item label="其他照片" prop="otherPhoto">
              <div style="display: flex; flex-wrap: wrap; gap: 10px;">
                <template v-if="getPhotoList(studentDialog.studentInfo.otherPhoto).length > 0">
                  <el-image
                    v-for="(photo, index) in getPhotoList(studentDialog.studentInfo.otherPhoto)"
                    :key="'other-'+index"
                    :src="baseImageUrl + photo"
                    style="width: 200px; height: 150px;"
                    :preview-src-list="getPhotoPreviewList(studentDialog.studentInfo.otherPhoto)"
                    fit="contain"
                  />
                </template>
                <template v-else>
                  <div style="color: #999;">暂无图片</div>
                </template>
              </div>
            </el-form-item>
            <el-form-item label="体检报告" prop="examinationReport">
              <div style="display: flex; flex-wrap: wrap; gap: 10px;">
                <template v-if="getPhotoList(studentDialog.studentInfo.examinationReport).length > 0">
                  <el-image
                    v-for="(photo, index) in getPhotoList(studentDialog.studentInfo.examinationReport)"
                    :key="'exam-' + index"
                    :src="baseImageUrl + photo"
                    style="width: 200px; height: 150px;"
                    :preview-src-list="getPhotoPreviewList(studentDialog.studentInfo.examinationReport)"
                    fit="contain"
                  />
                </template>
                <template v-else>
                  <div style="color: #999;">暂无图片</div>
                </template>
              </div>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="studentDialog.visible = false">关闭</el-button>
            <el-button type="primary" @click="printStudentInfo">打印</el-button> <!-- 新增打印按钮 -->
          </div>
        </el-dialog>

    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>
    <!-- 对话框(添加 / 修改) -->
    <SchoolCourseOrderForm ref="formRef" @success="getList" />
    <AssignmentCoach ref="assignmentCoachRef" @success="getList" />
    <EndOrder ref="endOrderRef" @success="getList" />
    <SchoolCourseOrderFastAddForm ref="formFastAddRef" @success="getList" />
    <cashierConfirmForm ref="cashierConfirmRef" @success="getList" />
    <ExportDialog ref="exportDialog" />
    <AddSchoolCourseOrderForm ref="addFormRef" />
  </div>
</template>

<script>
import * as SchoolCourseOrderApi from '@/views/drivingSchool/DriveSchoolPay/api';
import SchoolCourseOrderForm from '@/views/drivingSchool/DriveSchoolPay/form/SchoolCourseOrderForm.vue';
import AddSchoolCourseOrderForm from '@/views/drivingSchool/DriveSchoolPay/form/AddSchoolCourseOrderForm.vue';
import AssignmentCoach from "@/views/drivingSchool/DriveSchoolPay/form/assignmentCoach.vue";
import EndOrder from "@/views/drivingSchool/DriveSchoolPay/form/endOrder.vue";
import SchoolCourseOrderFastAddForm from "@/views/drivingSchool/DriveSchoolPay/form/SchoolCourseOrderFastAddForm.vue";
import { getSourceUserById } from '@/views/drivingSchool/DriveSchoolPay/api'
import CashierConfirmForm from '@/views/drivingSchool/DriveSchoolPay/form/cashierConfirmForm.vue'
import ExportDialog from './form/ExportDialog.vue';
export default {
  name: "SchoolCourseOrder",
  components: {
    ExportDialog,
    CashierConfirmForm,
    SchoolCourseOrderFastAddForm,
    EndOrder,
    AssignmentCoach,
    SchoolCourseOrderForm,
    AddSchoolCourseOrderForm,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 驾照报名订单列表
      list: [],
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 选中行
      currentRow: {},
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        orderNo: null,
        userName: null,
        courseName: null,
        coachUserName: null,
        isSign: null,
        timeRange:null,
        startTimeStr: null,
        endTimeStr: null,
        cashierConfirm:'',
        discountIndex: null,
      },
      // 控制合同查看对话框显示
      viewFlag: false,
      // 合同内容
      content: "",
      // 用户身份证照片URL
      userUrl: "",
      hasContract: false,
      baseImageUrl: "http://122.51.230.86:9000/",
      studentDialog: {
        visible: false,
        title: '学员信息详情',
        loading: false,
        // 学员信息
        studentInfo: {}
      },
      sourceList: this.getDictDatas("drive_school_channel"),
      sourceUser:null,
      signList:[
        {
          label: '未面签',
          value: 0
        },
        {
          label: '已面签',
          value: 1
        }
      ],
      cashierConfirmList: [
        { value: '', label: '全部' },
        { value: '0', label: '未到账' },
        { value: '1', label: '已到账' },
        { value: null, label: '待确认' }
      ],
      discountIndexList: [
        { value: '0', label: '无优惠' },
        { value: '1', label: '有优惠' }
      ],
    };
  },
  created() {
    this.getList();
  },
  computed: {
    // 根据角色判断是否显示对应的列
    showCashierColumn() {
      // return this.$store.getters.roles.includes('cn')
      return ['cn', 'jxzjl'].some(role => this.$store.getters.roles.includes(role));
    },
    showCashierColumnTwo() {
      return this.$store.getters.roles.includes('cn')
    }
  },
  methods: {
    printStudentInfo() {
      // 1. 确保弹窗元素存在
      const dialogElement = document.getElementById("studentInfoDialog");
      if (!dialogElement) {
        console.error("打印失败：未找到 studentInfoDialog 元素");
        return;
      }

      // 2. 克隆弹窗内容（深拷贝）
      const dialogContent = dialogElement.cloneNode(true);

      // 3. 移除不需要打印的元素
      const footer = dialogContent.querySelector(".dialog-footer");
      if (footer) footer.remove();

      const header = dialogContent.querySelector(".el-dialog__header");
      if (header) header.remove();

      // 同时移除可能存在的其他标题元素
      const titleElements = dialogContent.querySelectorAll("[class*='title'], [class*='header']");
      titleElements.forEach(el => el.remove());

      // 4. 创建 iframe 用于打印
      const iframe = document.createElement("iframe");
      iframe.style.position = "absolute";
      iframe.style.width = "0";
      iframe.style.height = "0";
      iframe.style.border = "none";
      document.body.appendChild(iframe);

      // 5. 获取所有样式（包括全局和scoped）
      let allStyles = "";
      const styleSheets = Array.from(document.styleSheets);
      styleSheets.forEach(sheet => {
        try {
          if (sheet.cssRules) {
            Array.from(sheet.cssRules).forEach(rule => {
              allStyles += rule.cssText + "\n";
            });
          }
        } catch (e) {
          console.log("无法读取某些样式:", e);
        }
      });


      // 6. 写入打印内容到iframe
      const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
      iframeDoc.open();
      iframeDoc.write(`
    <!DOCTYPE html>
    <html>
      <head>
        <title>学员信息</title>
        <style>
          /* 基础样式 */
          body {
            margin: 0;
            padding: 20px;
            font-family: Arial, sans-serif;
          }

          /* 继承的样式 */
          ${allStyles}

          /* 打印专用样式 */
          @media print {
            .el-dialog {
              box-shadow: none !important;
              width: 100% !important;
              margin: 0 !important;
            }
            .el-dialog__header, .dialog-footer {
              display: none !important;
            }
            .el-dialog__body {
              padding: 0 !important;
            }
            .el-form-item {
              margin-bottom: 10px !important;
            }
            .el-row {
              display: flex !important;
              flex-wrap: wrap !important;
            }
            .el-col {
              flex: 1 !important;
              min-width: 50% !important;
            }
            .display-text {
              background-color: transparent !important;
              border: 1px solid #ddd !important;
              padding: 5px 10px !important;
              line-height: 1.5 !important;
              height: auto !important;
            }
            .remark-text {
              white-space: pre-wrap !important;
              min-height: auto !important;
              line-height: 1.5 !important;
              padding: 5px 10px !important;
            }
            .el-image {
              max-width: 200px !important;
              height: auto !important;
            }
          }
        </style>
      </head>
      <body>
        ${dialogContent.querySelector(".el-dialog__body").innerHTML}
      </body>
    </html>
  `);
      iframeDoc.close();

      // 7. 打印 iframe 内容
      setTimeout(() => {
        iframe.contentWindow.focus();
        iframe.contentWindow.print();

        // 8. 移除 iframe（延迟确保打印完成）
        setTimeout(() => {
          document.body.removeChild(iframe);
        }, 1000);
      }, 200); // 给iframe一点时间加载内容
    },

    /** 查询列表 */
    async getList() {
      try {
        this.loading = true;
        const res = await SchoolCourseOrderApi.getSchoolCourseOrderPage(this.queryParams);
        this.list = res.data.records;
        this.total = res.data.total;
      } finally {
        this.loading = false;
      }
    },
    handleDateChange(val) {
      if (val && val.length === 2) {
        this.queryParams.startTimeStr = val[0];
        this.queryParams.endTimeStr = val[1];
      } else {
        this.queryParams.startTimeStr = null;
        this.queryParams.endTimeStr = null;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      if(this.queryParams.startTimeStr != null){
        this.queryParams.startTimeStr = this.queryParams.startTimeStr + ' 00:00:01';
        this.queryParams.endTimeStr = this.queryParams.endTimeStr + ' 23:59:59';
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.timeRange = null;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 添加/修改操作 */
    openForm(id) {
      this.$refs["formRef"].open(id);
    },
    /** 添加/修改操作（快速创建订单） */
    openAddForm(data) {
      this.$refs["formFastAddRef"].open(data);
    },
    /** 分配教练*/
    openAssignmentCoach(data) {
      this.$refs["assignmentCoachRef"].open(data);
    },
    /** 分配教练*/
    openEndOrder(data) {
      this.$refs["endOrderRef"].open(data);
    },
    /** 出纳确认*/
    openCashierConfirm(data) {
      this.$refs["cashierConfirmRef"].open(data);
    },
    getPhotoList(photoStr) {
      if (!photoStr) return [];
      return photoStr.split(',').map(item => item.trim());
    },

    // 生成预览列表（带完整URL）
    getPhotoPreviewList(photoStr) {
      if (!photoStr) return [];
      return photoStr.split(',').map(item => this.baseImageUrl + item.trim());
    },
    getSourceLabel(value) {
      const item = this.sourceList.find(item => item.value === value);
      return item ? item.label : value; // 如果找不到匹配项，显示原始值
    },
    getDictLabel(dictType, value) {
      const dict = this.getDictDatas(dictType).find(item => item.value === value);
      return dict ? dict.label : value;
    },
    /* async viewContract(row) {
      try {
        this.loading = true;
        // 假设有一个获取合同详情的API
        const response = await SchoolCourseOrderApi.getContractDetail(row.userId);
        this.content = response.data.content; // 合同内容
        this.userUrl = response.data.userUrl;  // 用户身份证照片
        this.viewFlag = true;                 // 显示对话框
      } finally {
        this.loading = false;
      }
    }, */
    getSourceUserId(userId){
      getSourceUserById(userId).then(res => {
        console.log(res)
        this.sourceUser = res.data.name
      })
    },
    formatReceiptReview(row, column, value) {
      const map = {
        1: '待审核',
        0: '已审核'
      };
      return map[value] ?? '未知类型';
    },
    async viewContract(row) {
      try {
        this.loading = true;
        const response = await SchoolCourseOrderApi.getContractDetail(row.userId);
        this.content = response.data.content || "";
        this.userUrl = response.data.userUrl || "";
        this.hasContract = !!this.content; // 如果有内容，标记为 true
      } catch (error) {
        this.content = "";
        this.userUrl = "";
        this.hasContract = false;
      } finally {
        this.viewFlag = true;
        this.loading = false;
      }
    },
    async viewStudentInfo(row) {
      console.log('row123', row)
      this.studentDialog.visible = true
      this.studentDialog.loading = true

      try {
        // 这里调用API获取学员详细信息
        const res = await SchoolCourseOrderApi.getStudentDetail(row.userId)

        this.studentDialog.studentInfo = {
          ...res.data,
          courseName: row.courseName,
          reserveMoney: row.reserveMoney,
          restMoney: row.restMoney,
        };

        // this.studentDialog.studentInfo = res.data
        if(this.studentDialog.studentInfo.sourceUserId != null){
          this.getSourceUserId(this.studentDialog.studentInfo.sourceUserId)
        }
        console.log('res',res.data)
        console.log('this.studentDialog.studentInfo',this.studentDialog.studentInfo)
      } finally {
        this.studentDialog.loading = false
      }
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      const id = row.id;
      await this.$modal.confirm('是否确认删除驾照报名订单编号为"' + id + '"的数据项?')
      try {
        await SchoolCourseOrderApi.deleteSchoolCourseOrder(id);
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {}
    },
    /** 导出按钮操作 */
    async handleExport() {
      /* await this.$modal.confirm('是否确认导出所有驾照报名订单数据项?');
      try {
        this.exportLoading = true;
        const data = await SchoolCourseOrderApi.exportSchoolCourseOrderExcel(this.queryParams);
        this.$download.excel(data, '驾照报名订单.xls');
      } catch {
      } finally {
        this.exportLoading = false;
      } */
      await this.$refs.exportDialog.open();
    },
    async handleAddOrder() {
      await this.$refs.addFormRef.open();
    },
    formatDate(row, column, cellValue) {
      return this.formatTimestampToDate(cellValue);
    },
    formatTimestampToDate(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');

      return `${year}-${month}-${day}`;
    },

    formatPayChannel(row, column, value) {
      const map = {
        '1': '微信支付',
        '2': '线下支付'
      };
      return map[value] ?? '-';
    },
    formatSignType(row, column, value) {
      const map = {
        '1': '业务经理代报名',
        '2': '教练代报名',
        '3': '员工代报名'
      };
      return map[value] ?? '非代报名';
    },
    formatIfAgree(row, column, value) {
      const map = {
        '0': '未确认',
        '1': '同意',
        '2': '不同意',
        null: '非代报名订单',
        default: '非代报名订单'
      };
      return map[value] ?? '-';
    },

  }
};
</script>

<style scoped>
.display-text {
  display: inline-block;
  padding: 0 15px;
  line-height: 40px;
  height: 40px;
  border-radius: 4px;
  background-color: #f5f7fa;
  color: #606266;
  width: 100%;
}

.remark-text {
  white-space: pre-wrap;
  min-height: 60px;
  line-height: 1.5;
  padding: 10px 15px;
}

@page {
  size: auto;
  margin: 30px;
}

@media print {

  body {
    margin: 0;
    padding: 20px;
    font-family: Arial, sans-serif;
  }


  .el-dialog__title,
  .dialog-title,
  .title,
  h1, h2, h3, h4, h5, h6 {
    display: none !important;
  }

  .el-dialog {
    box-shadow: none !important;
    width: 100% !important;
    margin: 0 !important;
  }

  .el-dialog__header {
    display: none !important;
    height: 0 !important;
    padding: 0 !important;
  }

  .el-dialog__body {
    padding: 0 !important;
  }

  .el-form-item {
    margin-bottom: 10px !important;
  }

  .el-row {
    display: flex !important;
    flex-wrap: wrap !important;
  }

  .el-col {
    flex: 1 !important;
    min-width: 50% !important;
  }

  .display-text {
    background-color: transparent !important;
    border: 1px solid #ddd !important;
    padding: 5px 10px !important;
    line-height: 1.5 !important;
    height: auto !important;
  }

  .remark-text {
    white-space: pre-wrap !important;
    min-height: auto !important;
    line-height: 1.5 !important;
    padding: 5px 10px !important;
  }

  .dialog-footer {
    display: none !important;
  }

  .el-image {
    max-width: 200px !important;
    height: auto !important;
  }

  .el-form-item__label {
    width: 100px !important;
    text-align: left !important;
  }

  .el-form-item__content {
    margin-left: 100px !important;
  }
}


</style>
