<template>
  <div class="app-container">
    <!-- 受检信息表单 -->
    <ContentWrap title="管道受检信息">
      <el-form :disabled="pageType === 'detail'" :model="formData" :rules="formRules" ref="formRef" label-width="120px" class="p-3">
        <div class="check-info-label-title">单位信息</div>
        <el-row class="form-group" :gutter="24">
          <el-col :span="8">
            <!-- 申请单位名称 unitName -->
            <el-form-item label="申请单位名称" prop="unitName" class="unit-form-item">
              <el-input v-if="useInputUnitName" v-model="formData.unitName.name" placeholder="请输入单位名称" />
              <CustomLargeListSelect
                v-else
                v-model:modelValue="formData.unitName"
                :fetchFunc="getUnitNewList"
                label-key="name"
                value-key="id"
                searchKeyProp="name"
                @change="handleChangeUnit"
              />
              <el-button type="primary" link @click="() => useInputUnitName = !useInputUnitName">{{useInputUnitName ? '选择单位' : '手动输入'}}</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 统一社会信用代码 socialCreditCode -->
            <el-form-item label="统一社会信用代码" prop="socialCreditCode"  label-width="120px">
              <el-input v-model="formData.socialCreditCode" placeholder="请输入统一社会信用代码"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 申请单位地址 unitAddress -->
            <el-form-item label="申请单位地址" prop="unitAddress" label-width="120px">
              <el-input v-model="formData.unitAddress" placeholder="请输入申请单位地址"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 邮政编码 zipCode -->
            <el-form-item label="邮政编码" prop="zipCode">
              <el-input v-model="formData.zipCode" placeholder="请输入邮政编码" :maxlength="50"/>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <div class="check-info-label-title">使用单位</div> -->
        <el-row class="form-group" :gutter="24">
          <el-col :span="8">
            <!-- 使用单位名称 useUnitName -->
            <el-form-item label="使用单位名称" prop="useUnitName" class="unit-form-item">
              <el-input v-if="useInputUseUnitName" v-model="formData.useUnitName.name" placeholder="请输入使用单位名称" />
              <CustomLargeListSelect
                v-else
                v-model:modelValue="formData.useUnitName"
                :fetchFunc="getUnitNewList"
                label-key="name"
                value-key="id"
                searchKeyProp="name"
                @change="handleChangeUseUnit"
              />
              <el-button type="primary" link @click="() => useInputUseUnitName = !useInputUseUnitName">{{useInputUseUnitName ? '选择单位' : '手动输入'}}</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 统一社会信用代码 -->
            <el-form-item label="统一社会信用代码" prop="useUnitSocialCreditCode" label-width="120px">
              <el-input v-model="formData.useUnitSocialCreditCode" placeholder="请输入统一社会信用代码"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 使用单位地址 useUnitAddress -->
            <el-form-item label="使用单位地址" prop="useUnitAddress" label-width="120px">
              <el-input v-model="formData.useUnitAddress" placeholder="请输入使用单位地址"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 邮政编码 useUnitZipcode -->
            <el-form-item label="邮政编码" prop="useUnitZipcode">
              <el-input v-model="formData.useUnitZipcode" placeholder="请输入邮政编码"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 单位联系人 useUnitContact -->
            <el-form-item label="单位联系人" prop="useUnitContact" label-width="120px">
              <el-input v-model="formData.useUnitContact" placeholder="请输入单位联系人"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 联系人电话 useUnitPhone -->
            <el-form-item label="联系人电话" prop="useUnitPhone" label-width="120px">
              <el-input v-model="formData.useUnitPhone" placeholder="请输入联系人电话"/>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="check-info-label-title">联系人信息</div>
        <el-row class="form-group" :gutter="24">
          <el-col :span="8">
            <!-- 约检联系人 unitContact -->
            <el-form-item label="约检联系人" prop="unitContact">
              <el-input v-model="formData.unitContact" placeholder="请输入约检联系人" :maxlength="50"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 约检联系人电话unitPhone -->
            <el-form-item label="联系人电话" prop="unitPhone" label-width="120px">
              <el-input v-model="formData.unitPhone" placeholder="请输入约检联系人电话" :maxlength="11"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系人邮箱" prop="email" label-width="120px">
              <el-input v-model="formData.email" placeholder="请输入约检联系人邮箱" :maxlength="11"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 电子报告接收人 recipient -->
            <el-form-item label="电子报告接收人" prop="recipient" label-width="120px">
              <el-input v-model="formData.recipient" placeholder="请输入电子报告接收人" :maxlength="50"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 接收人电话 recipientPhone -->
            <el-form-item label="接收人电话" prop="recipientPhone">
              <el-input v-model="formData.recipientPhone" placeholder="请输入接收人电话" :maxlength="11"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="接收人邮箱" prop="recipientEmail">
              <el-input v-model="formData.recipientEmail" placeholder="请输入接收人邮箱"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="缴费联系人" prop="payerContactName" label-width="120px">
              <el-input v-model="formData.payerContactName" placeholder="请输入缴费联系人" :maxlength="50"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 接收人电话 recipientPhone -->
            <el-form-item label="缴费人电话" prop="payerContact">
              <el-input v-model="formData.payerContact" placeholder="请输入缴费人电话" :maxlength="11"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="缴费人邮箱" prop="payerMail">
              <el-input v-model="formData.payerMail" placeholder="请输入缴费人邮箱"/>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="check-info-label-title">受理信息</div>
        <el-row class="form-group" :gutter="24">
          <el-col :span="8">
            <!-- 检验部门 deptId -->
            <el-form-item label="检验部门" prop="deptId">
              <!-- <el-input v-model="formData.deptId" placeholder="请输入检验部门"/> -->
              <DeptSelect
                v-model="formData.deptId"
                placeholder="请选择部门"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 联系电话 deptPhone -->
            <el-form-item label="联系电话" prop="deptPhone" label-width="120px">
              <el-input v-model="formData.deptPhone" placeholder="请输入联系电话" :maxlength="20"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 约检时间 appointmentDate -->
            <el-form-item label="约检时间" prop="appointmentDate" label-width="120px">
              <el-date-picker
                v-model="formData.appointmentDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择约检时间"
                :disabled-date="disabledDate"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <!-- 检验员 teamList -->
            <el-form-item label="检验员" prop="teamList">
<!--              <CheckerSelect-->
<!--                ref="checkerSelectRef"-->
<!--                v-model="selectedCheckers"-->
<!--                :dept-id="userStore.getUser.deptId?.toString() || '1'"-->
<!--                :disabled="false"-->
<!--                :has-data="true"-->
<!--                empty-text="暂无检验员数据"-->
<!--                :multiple="true"-->
<!--                @change="handleCheckerChange"-->
<!--              />-->
              <div v-if="formattedCheckers.length > 0" class="selected-checkers">
                <el-tag
                  v-for="checker in formattedCheckers"
                  :key="checker.id"
                  effect="plain"
                  class="mr-8px mb-8px"
                >
                  {{ checker.label }}
                </el-tag>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="check-info-label-title">异常信息</div>
        <el-row class="m-b-20px">
          <el-button v-if="!exceptionInfo.id" type="primary" @click="addExceptionInfo">添加异常单</el-button>
          <el-button v-else type="primary" @click="deleteExceptionInfo">删除异常单</el-button>
        </el-row>
        <el-row v-if="exceptionInfo.id" class="form-group" :gutter="24">
            <el-col :span="8">
              <el-form-item label="有效日期调整原因" prop="effectiveDateAdjustReason">
                <el-input v-model="exceptionInfo.effectiveDateAdjustReason" placeholder="请输入有效日期调整原因"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="受理建议" prop="acceptSuggeston">
                <el-input v-model="exceptionInfo.acceptSuggeston" placeholder="请输入受理建议"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="调整有效日期" prop="adjustEffectiveDate">
                <el-date-picker
                  v-model="exceptionInfo.adjustEffectiveDate"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择调整有效日期"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="情况说明" prop="descrition">
                <component :is="getExceptionItem('descrition', 'descritionAttach')" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="重启表" prop="restartTable">
                <component :is="getExceptionItem('restartTable', 'restartTableAttach')" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="指令书" prop="instrustionBook">
                <component :is="getExceptionItem('instrustionBook', 'instrustionBookAttach')" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="受理回执" prop="acceptReceipt">
                <component :is="getExceptionItem('acceptReceipt', 'acceptReceiptAttach')" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="其他" prop="other">
                <component :is="getExceptionItem('other', 'otherAttach')" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="提前检验申请函" prop="earlyCheckApply">
                <component :is="getExceptionItem('earlyCheckApply', 'earlyCheckApplyAttach')" />
              </el-form-item>
            </el-col>
          </el-row>
        <div class="check-info-label-title">检验收费</div>
        <el-row class="form-group" :gutter="24">
          <el-col :span="24">
            <!-- 定期检查&超年限检查 -->
            <el-form-item label="检验性质" prop="checkType" label-width="120px" v-if="orderDetail?.checkType">
              <span>{{ PressurePipeCheckTypeMap[orderDetail.checkType] }}</span>
            </el-form-item>
            <!-- 收费性质 feeNature -->
            <el-form-item prop="feeNature" >
              <template #label>
                <div class="flex flex-col text-right">
                  <span>收费性质</span>
                  <span>(行政事业收费)</span>
                </div>
              </template>
              <el-radio-group v-model="formData.feeNature">
                <el-radio v-for="(item, key) in PressureFeeNatureMap" :key="key" :value="key" :label="item"/>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <!-- 收费形式 feeType -->
            <el-form-item label="收费形式" prop="feeType">
              <el-radio-group v-model="formData.feeType">
                <el-radio label="100">非合同收费</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <!-- 收费金额 actualAmount -->
            <!--            <el-form-item label="收费金额" prop="actualAmount" class="actualAmountFormItem">
                          <el-input-number
                            :controls="false"
                            v-model="formData.actualAmount"
                            placeholder="请输入收费金额"
                            :min="0"
                          />
                          <div style="padding-left: 8px;">大写（{{numberToChinese(formData.actualAmount)}}）含税</div>
                        </el-form-item>-->
            <div class="flex items-center gap-32 ml-40px text-14px">
              <span>应收法定金额: {{ formData.shouldAmount }}</span>
              <span>服务收费金额:{{ formData.serviceAmount }}</span>
              <span>免征费用: {{ formData.reduceFee }}</span>
            </div>
          </el-col>
          <!--          <el-col :span="24">
                      &lt;!&ndash; 年度检查 &ndash;&gt;
                      <el-form-item label="" prop="feeDate" label-width="30" v-if="orderDetail?.checkType == 200">
                        <div class="feeDate_box">
                          甲方在本服务单签订之日起
                            <el-input-number :controls="false" v-model="formData.feeDate" placeholder="请输入" :maxlength="50"/>
                          日内一次性支付。
                        </div>
                      </el-form-item>
                    </el-col>-->
        </el-row>
      </el-form>
    </ContentWrap>

    <!-- 设备清单 -->
    <ContentWrap title="设备信息">
      <!-- 搜索工作栏 -->
      <el-form
        :model="equipQueryParams"
        ref="equipQueryFormRef"
        :disabled="pageType === 'detail'"
        :inline="true"
        label-width="80px"
        class="border-b border-gray-200 border-b-solid pb-4"
      >
        <!-- 基本信息查询部分 -->
        <div class="flex flex-wrap items-start gap-x-2">
<!--          <el-form-item label="设备代码" prop="equipCode">-->
<!--            <el-input-->
<!--              v-model="equipQueryParams.equipCode"-->
<!--              placeholder="请输入设备注册代码"-->
<!--              clearable-->
<!--              @keyup.enter="handleEquipQuery"-->
<!--              class="!w-240px"-->
<!--            />-->
<!--          </el-form-item>-->
<!--          <el-form-item label="出厂编号" prop="factoryCode">-->
<!--            <el-input-->
<!--              v-model="equipQueryParams.factoryCode"-->
<!--              placeholder="请输入出厂编号"-->
<!--              clearable-->
<!--              @keyup.enter="handleEquipQuery"-->
<!--              class="!w-240px"-->
<!--            />-->
<!--          </el-form-item>-->
          <el-form-item label="部门" prop="relateDepartment">
            <DeptSelect
              v-model="equipQueryParams.relateDepartment"
              placeholder="请选择部门"
              clearable
              class="!w-240px"
            />
          </el-form-item>

          <!-- <el-form-item label="运行状态" prop="status">
            <el-select
              v-model="equipQueryParams.status"
              placeholder="选择运行状态"
              clearable
              multiple
              collapse-tags
              collapse-tags-tooltip
              class="!w-240px"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.SYSTEM_EQUIP_CONTAINER_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item> -->

          <el-form-item label="临检时间" prop="nextDate">
            <div class="flex items-center gap-x-2">
              <el-select v-model="datePickerType" class="!w-[90px]">
                <el-option label="时间段" value="daterange" />
                <el-option label="月份" value="month" />
              </el-select>
              <el-date-picker
                v-if="datePickerType === 'daterange'"
                v-model="daterange"
                type="daterange"
                value-format="YYYY-MM-DD"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                class="!w-[210px]"
                @change="handleDateChange"
              />
              <el-date-picker
                v-else
                v-model="month"
                type="month"
                value-format="YYYY-MM"
                placeholder="选择月份"
                class="!w-[140px]"
                @change="handleMonthChange"
              />
            </div>
          </el-form-item>
        </div>

        <!-- 区域和时间查询部分 -->
        <div class="flex flex-wrap items-start gap-x-2">
          <el-form-item label="区域" prop="equipDistrict">
            <AreaSelect
              v-model="equipQueryParams.equipDistrict"
              placeholder="请选择区域"
              class="!w-[240px]"
              multiple
              collapse-tags
              collapse-tags-tooltip
              :clearable="true"
              @clear="handleAreaClear"
              @change="handleAreaChange"
            />
          </el-form-item>

          <el-form-item label="街道" prop="equipStreet">
            <StreetSelect
              v-model="equipQueryParams.equipStreet"
              :district-ids="equipQueryParams.equipDistrict"
              placeholder="请选择街道"
              class="!w-[240px]"
              multiple
              collapse-tags
              collapse-tags-tooltip
              :clearable="true"
              @clear="handleStreetClear"
              @change="handleStreetChange"
            />
          </el-form-item>
        </div>

        <!-- 容器相关查询条件 -->
        <div class="">
          <el-form-item label="管道归类" prop="typeList" class="mb-2">
            <div class="flex items-center flex-1">
              <el-checkbox-group
                v-model="equipQueryParams.typeList"
                class="flex flex-wrap gap-2"
              >
                <el-checkbox
                  v-for="dict in containerTypeOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-checkbox-group>
            </div>
          </el-form-item>
        </div>

        <!-- 操作按钮 -->
        <div class="flex justify-center">
          <el-form-item class="!mb-0">
            <el-button @click="handleEquipQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
            <el-button @click="resetEquipQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
            <!-- 删除设备 -->
            <el-button type="danger" :disabled="selectedDetailRows.length === 0" @click="handleRejectEquip">
              <Icon icon="ep:failed" class="mr-5px" /> 拒绝约检
            </el-button>
            <el-button :disabled="orderDetail?.createAcceptOrder === true" type="primary" @click="handleAddEquip">
              <Icon icon="ep:plus" class="mr-5px" /> 添加设备
            </el-button>
            <el-button
              type="primary"
              @click="handleBatchEditFn"
              :disabled="selectedRows.length === 0"
            >
              <Icon icon="ep:edit" class="mr-5px" /> 批量修改约检联系人
            </el-button>
          </el-form-item>
        </div>
      </el-form>

      <!-- 设备列表 -->
      <el-table
        v-loading="loading"
        ref="tableRef"
        :data="equipList"
        stripe
        border
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
        :row-key="(row) => row.id"
      >
        <el-table-column type="selection" width="50" fixed="left"/>
        <el-table-column type="expand" width="1">
          <template #default="props">
            <div class="ml-15px mr-15px">

              <el-table :data="props.row.detailSaveReqVOS" border
                        :header-cell-style="{background: '#f5f7fa', color: '#606266'}"
                        :ref="(el) => setDetailTableRef(el, props.row.id)"
                        @selection-change="(selection) => handleDetailSelectionChange(selection, props.row)"

              >
                <el-table-column type="selection" width="50" fixed="left"/>
                <el-table-column type="index" label="序号" width="60" align="center" :index="indexMethod1" />
                <el-table-column label="管道编号" prop="pipeNo" align="center" min-width="100" />
                <el-table-column label="注册代码" prop="equipCode" align="center" min-width="120" />
                <el-table-column label="管道名称" prop="pipeName" align="center" min-width="150" />
                <el-table-column label="管道级别" prop="pipeLevel" align="center" min-width="80" />
                <el-table-column label="规格" align="center" min-width="180">
                  <el-table-column label="公称直径mm" prop="nominalDiameter" align="center" min-width="80" />
                  <el-table-column label="公称壁厚mm" prop="nominalWallThickness" align="center" min-width="80" />
                  <el-table-column label="管道长度m" prop="pipeLength" align="center" min-width="80" />
                </el-table-column>
                <el-table-column label="管道材质" prop="pipeMaterial" align="center" min-width="100" />
                <el-table-column label="材料标准" prop="materialStandard" align="center" min-width="100" />
                <el-table-column label="设计 / 允许 (监控) 工作条件" align="center" min-width="300">
                  <el-table-column label="压力MPa" prop="designPressure" align="center" min-width="100" />
                  <el-table-column label="温度℃" prop="designTemperature" align="center" min-width="100" />
                  <el-table-column label="介质" prop="pipeMedium" align="center" min-width="100" />
                </el-table-column>
                <el-table-column label="焊口数量" prop="weldCount" align="center" min-width="80" />
                <el-table-column label="起止点" prop="startEndPoint" align="center" min-width="200" />
                <el-table-column label="安全状况等级" prop="safetyStatusLevel" align="center" min-width="100" />
              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="60" align="center" :index="indexMethod" />
        <el-table-column
          label="工程号"
          align="center"
          prop="projectNo"
          min-width="120"
        >
          <template #default="{ row }">
            <div
              v-if="row.projectNo"
              class="cursor-pointer"
              @click="toggleExpand(row)"
            >
              <div class="flex items-center justify-center gap-1 schedule-link">
                <span class="text-xs color-blue">{{row.projectNo}}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="工程名称"
                         align="center"
                         prop="projectName"
                         min-width="120"
                         show-overflow-tooltip
        />
        <!-- 区域 -->
        <el-table-column
          label="区域/街道"
          align="center"
          prop="pipeStreet"
          min-width="120"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <span class="text-xs">{{ row.equipStreetName ?? row.equipDistrictName}}</span>
          </template>
        </el-table-column>
        <!-- 管道类别 -->
        <el-table-column label="管道类别" align="center" prop="pipeCategory">
          <template #default="scope">
            {{ containerTypeOptions.find(i => i.value == scope.row.pipeCategory)?.label }}
          </template>
        </el-table-column>

        <el-table-column
          label="约检联系人"
          align="center"
          prop="contact"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          label="约检联系人电话"
          align="center"
          prop="contactPhone"
          min-width="140"
          show-overflow-tooltip
        />
      </el-table>
    </ContentWrap>
    <!-- 设备清单 -->
    <ContentWrap title="备注">
      <el-row>
        <el-col :span="12">
          <el-form-item class="!mb-0" label="上次退回原因" prop="reason">
            <el-input type="textarea" :rows="4" v-model="formData.reason" readonly/>
          </el-form-item>
        </el-col>
      </el-row>
    </ContentWrap>



    <!-- 添加设备弹窗 -->
    <PipeAddEquipDialog
      v-model:visible="addEquipVisible"
      type="acceptOrder"
      :target-id="orderDetail?.id || ''"
      @success="handleAddEquipSuccess"
      :unit-code="orderDetail?.unitCode || ''"
      :unit-name="orderDetail?.unitName || ''"
    />

    <!-- 拒绝约检弹窗 -->
    <el-dialog
      v-model="rejectDialogVisible"
      title="拒绝约检"
      width="600px"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <div class="mb-4">
        <div v-for="equip in selectedRows" :key="equip.id" class="mb-2">
          设备注册代码：{{ equip.equipCode }}
        </div>
      </div>

      <div class="mb-4">
        检验性质：{{ orderDetail?.checkType ? checkTypeMap[orderDetail.checkType] : '' }}
      </div>
      <div class="mb-4 flex flex-start items-center">
        <div class="!w-80px">拒绝原因：</div>
        <el-select v-model="rejectForm.reasonDict" placeholder="请选择拒绝原因" @change="() => {rejectForm.reason = ''}">
          <el-option
            v-for="dict in getStrDictOptions('refuseInspectedCategory')"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </div>
      <div class="mb-4" v-if="rejectForm.reasonDict == '5'">
        <div class="mb-2">说明：</div>
        <el-input
          v-model="rejectForm.reason"
          type="textarea"
          :rows="4"
          placeholder="请输入"
          resize="none"
        />
      </div>

      <template #footer>
        <div class="flex justify-end items-center">
          <el-button type="primary" :loading="rejectLoading" @click="handleRejectConfirm(100)">上报市局</el-button>
          <!--          <el-button v-if="orderDetail.checkType === 100 || orderDetail.checkType === 300" type="primary" :loading="rejectLoading" @click="handleRejectConfirm(100)">上报市局</el-button>-->
          <!--          <el-button v-else type="primary" :loading="rejectLoading" @click="handleRejectConfirm(200)">上报拒检</el-button>-->
          <el-button type="warning" @click="handleRejectConfirm(300)">无需上报</el-button>
          <el-button @click="rejectDialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 页面底部按钮 -->
    <div class="flex justify-center pb-4 footer-btn-box">
      <el-button @click="handleClose">关闭</el-button>
      <el-button :disabled="pageType === 'detail'" type="primary" :loading="submitLoading" @click="handleGenerateAcceptance">
        重新提交
      </el-button>
      <!-- <el-button type="primary" plain @click="handlePrintPDF">打印受理单PDF</el-button> -->
    </div>
    <PipeBatchEditForm ref="batchEditFormRef" @success="handleEquipQuery"/>
    <!--     <EquipContainerForm ref="EquipContainerFormRef" />-->
    <FileUploadModal ref="fileUploadModalRef" @success="handleFileUploadSuccess" />
  </div>
</template>

<script setup lang="tsx">
import { ref, onMounted, computed, watch, unref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { BoilerAcceptOrderApi } from '@/api/pressure2/boileracceptorder'
import PipeBatchEditForm from '@/views/pressure2/planNew/components/PipeBatchEditForm.vue'
import { BoilerAppointmentConfirmOrderEquipmentVO } from '@/api/pressure2/appointmentconfirmorder'
import { type CheckerItem } from '@/views/pressure2/components/CheckerSelect'
import dayjs from 'dayjs'
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import DeptSelect from '../../pressure2/planNew/components/DeptSelect.vue'
import AreaSelect from '../../system/equipcontainer/components/AreaSelect.vue'
import StreetSelect from '../../system/equipcontainer/components/StreetSelect.vue'
import PipeAddEquipDialog from '../schedule/components/PipeAddEquipDialog.vue'
import {formatArrayDate, formatDate} from '@/utils/formatTime'
import { PressureBoilerCheckTypeMap, PressureFeeTypeMap, PressureSendTypeMap, PressureVehicleTypeMap, PressureAcceptTypeMap, PressureFeeNatureMap, PressureFeeNature, PressureBoilerCheckType} from '@/utils/constants'
import { getUnitNewList, getUnitContacts } from '@/api/laboratory/unit'
import EquipContainerForm from '@/components/EquipContainerForm/index.vue'
import { numberToChinese } from '@/utils/formatter'
import FileUploadModal from '@/views/pressure2/orderConfirm/components/ImportFile.vue'
import { buildFileUrl } from '@/utils'
import { useRoute } from 'vue-router'
import { Icon } from '@/components/Icon'
import { cloneDeep } from 'lodash-es'
import {
  PipeEquipmentApi,
  PipeEquipmentDetailVO,
  PipeEquipmentVO
} from "@/api/pressure2/pipeequipment";
import {PipeAcceptOrderApi} from "@/api/pressure2/pipeacceptorder";
import {PipeAppointmentConfirmOrderApi} from "@/api/pressure2/pipeappointmentconfirmorder";
import {UserQualificationsApi} from "@/api/pressure2/userQualifications";
import { useUserStore } from '@/store/modules/user'
import {PressurePipeCheckTypeMap} from "../../../utils/constants";
const route = useRoute()
const userStore = useUserStore()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  id: {
    type: String,
    default: ''
  },
  pageType: {
    type: String,
    default: ''
  }
})
const emit = defineEmits(['update:visible', 'success'])
// const EquipContainerFormRef = ref<InstanceType<typeof EquipContainerForm>>()
const orderDetail = ref()
const batchEditFormRef = ref()
const checkTypeMap = {
  [PressureBoilerCheckType.IN]: '内部检查',
  [PressureBoilerCheckType.OUT]: '外部检查',
  [PressureBoilerCheckType.PRESSURE]: '耐压检查'
}
const formData = ref<Record<string, any>>({
  appointmentDate: '',
  teamList: [] as string[],
  unitName: {
    name: '',
    id: ''
  },
  useUnitName: {
    name: '',
    id: ''
  },
  deptName: '',
  equipDistrict: undefined as number | undefined,
  equipDistrictName: '',
  equipStreet: '',
  equipStreetName: '',
  unitContact: '',
  unitContactDept: '',
  unitAddress: '',
  unitPhone: '',
  zipCode: '',
  mobile: '',
  remark: '',
  email: '',
  isAttach: false,
  sendType: '100',
  vehicle: '100',
  feeType: '100',
  acceptType: '100',
  actualAmount: 0,
  serviceAmount: 0,
  shouldAmount: 0,
  reduceFee: 0,
  planMaker: '',
  deptId: '',
  operator: '',
  areaDisplay: '',
  reason: '',
  socialCreditCode: '',
  recipient: '',
  recipientPhone: '',
  recipientEmail: '',
  useUnitSocialCreditCode: '',
  useUnitAddress: '',
  useUnitZipcode: '',
  useUnitContact: '',
  useUnitPhone: '',
  deptPhone: '',
  feeNature: '',
  feeDate: 0,
})

const userList = ref<any[]>([])

// 检验员组件引用
const checkerSelectRef = ref()

// 选中的检验员对象列表
const selectedCheckers = ref<CheckerItem[]>([])

const loading = ref(false)
const submitLoading = ref(false) // 提交按钮 loading

// 记录每个区域下已选择的街道
const areaStreetMap = ref(new Map<number, number[]>())

// 设备查询相关
const equipQueryParams = ref({
  pageNo: 1,
  pageSize: 50,
  equipDistrict: undefined as number[] | undefined,
  equipStreet: undefined as number[] | undefined,
  equipCode: '',
  factoryCode: '',
  relateDepartment: '',
  typeList: [] as string[],
  nextDate: [] as string[],
  useStatus: [] as string[],
})

const equipQueryFormRef = ref()
const equipLoading = ref(false)
const equipList = ref<BoilerAppointmentConfirmOrderEquipmentVO[]>([])
// 选中的设备
const selectedEquips = ref<BoilerAppointmentConfirmOrderEquipmentVO[]>([])
const equipTotal = ref(0)
const equipCategoryOptions = getStrDictOptions(DICT_TYPE.SYSTEM_EQUIP_CONTAINER_EQUIP_CATEGORY)
const containerTypeOptions = getStrDictOptions(DICT_TYPE.PIPE_TYPE)

const selectedRows = ref<BoilerAppointmentConfirmOrderEquipmentVO[]>([]) // 选中的行
const selectedDetailRows = ref<PipeEquipmentDetailVO[]>([]) // 选中的行

// 临检时间相关
const datePickerType = ref<'daterange' | 'month'>('month')
const daterange = ref<string[]>([])
const month = ref<string>('')

// 添加设备相关
const addEquipVisible = ref(false)

// 拒绝约检相关
const rejectDialogVisible = ref(false)
const rejectLoading = ref(false)
const rejectForm = ref({
  reason: '',
  reasonDict: ''
})

const formRef = ref() // 表单引用

const indexMethod = (index: number) => {
  return index + 1
}

const indexMethod1 = (index: number) => {
  return index + 1
}

/** 约检确认详情 */
defineOptions({ name: 'OrderConfirmDetail' })

// 表单验证规则
const formRules = {
  // unitContact: [
  //   { required: true, message: '请输入单位联系人', trigger: 'blur' }
  // ],
  // unitPhone: [
  //   { required: true, message: '请输入单位联系电话', trigger: 'blur' },
  // ],
  // mobile: [
  //   { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  // ],
  email: [
    { pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '请输入正确的邮箱', trigger: 'blur' }
  ],
  sendType: [
    { required: true, message: '请选择送达方式', trigger: 'blur' }
  ],
  // feeType: [
  //   { required: true, message: '请选择收费类型', trigger: 'blur' }
  // ],
  acceptType: [
    { required: true, message: '请选择受理方式', trigger: 'blur' }
  ],
  vehicle: [
    { required: true, message: '请选择交通工具', trigger: 'blur' }
  ]
}

// 区域显示属性，与formData.areaDisplay分离
const areaDisplay = computed(() => {
  const district = formData.value.equipDistrictName || ''
  const street = formData.value.equipStreetName || ''
  if (district && street) {
    return `${district}-${street}`
  }
  return district
})

type scheduleType = 'regular' | 'year' | ''
const tableRef = ref()
const currentEquip = ref<PipeEquipmentVO>()
const currentCheckType = ref<scheduleType>('')

// 存储所有子表引用的对象
const detailTableRefs = ref<Record<string, any>>({})
const setDetailTableRef = (el: any, parentId: string) => {
  if (el) {
    detailTableRefs.value[parentId] = el;
  }
}
const getDetailTableRef = (parentId: string) => {
  return detailTableRefs.value[parentId];
}

// 已展开行
const expandRowKeys = ref<string[]>([])
const expandRows = ref([])
const toggleExpand = async (row: any) => {
  const key = row.id
  // 第一次点击展开，第二次点击同一行收起
  if (expandRowKeys.value.includes(key)) {
    expandRowKeys.value = expandRowKeys.value.filter((key) => key !== key)
    expandRows.value = expandRows.value.filter((row) => row.id !== key)
    selectedDetailRows.value = selectedDetailRows.value.filter((row) => row.pipeEquipmentId !== key)
    tableRef.value.toggleRowExpansion(row, false)
    tableRef.value.toggleRowSelection(row, false)
  } else {
    expandRowKeys.value.push(key)
    expandRows.value.push(row)
    tableRef.value.toggleRowExpansion(row, true)
    await PipeAcceptOrderApi.getPipeEquipmentDetailListByPipeEquipmentId(orderDetail.value.id,key).then((res) => {
      let find = equipList.value.find(item => item.id === key);
      find.detailSaveReqVOS = res.list
    })
  }

}

const handleDetailSelectionChange = (selection: any[], mainRow: any) => {
  selectedDetailRows.value = selectedDetailRows.value.filter((item) => item.equipPipeId !== mainRow.id)
  selectedDetailRows.value = [...selectedDetailRows.value.filter(row => !selection.some(sel => sel.id === row.id)), ...selection]
  // tableRef.value.toggleRowSelection(mainRow, true)
  // 如果子表有选中项，则自动选中主表行；否则取消选中主表行
  nextTick(() => {
    if (selection.length > 0) {
      // 子表有选中项，选中主表行
      tableRef.value.toggleRowSelection(mainRow, true);
    }else if (!selectedDetailRows.value.map(row => row.equipPipeId).includes(mainRow.id)){
      const currentlySelected = selectedRows.value.some(row => row.id === mainRow.id);
      if (currentlySelected && selection.length === 0) {
        // 只有当主行当前是选中状态且子表没有任何选中项时才取消主行选择
        tableRef.value.toggleRowSelection(mainRow,false);
      }
    }
  });
}

/** 表格选择框变化 */
const handleSelectionChange = async (selection: BoilerAppointmentConfirmOrderEquipmentVO[]) => {
  // 计算取消选择的行
  const deselectedRows = selectedRows.value.filter(
    item => !selection.includes(item)
  );
  selectedRows.value = selection
  // 每一个勾选了主表的要找到对应的子表
  for (const item of selection) {
    // 如果没有子表,展开当前子表
    if (!expandRowKeys.value.includes(item.id)) {
      await toggleExpand(item)
    }
    // 如果没有勾选,勾选子表
    if (selectedDetailRows.value.findIndex(selectedDetailRow => selectedDetailRow.equipPipeId === item.id) === -1){
      getDetailTableRef(item.id)?.toggleAllSelection(true)
    }
  }
  deselectedRows.forEach(item => {
    getDetailTableRef(item.id)?.clearSelection()
  })
}

/** 处理表格排序 */
const handleSortChange = ({ prop, order }) => {
  if (!prop || !order) {
    equipList.value.sort((a, b) => 0) // 重置排序
    return
  }

  equipList.value.sort((a, b) => {
    const aValue = a[prop] || ''
    const bValue = b[prop] || ''

    if (order === 'ascending') {
      return aValue > bValue ? 1 : -1
    } else {
      return aValue < bValue ? 1 : -1
    }
  })
}


// 获取约检详情
const getDetail = async () => {
  const id = props.id as string
  if (!id) {
    ElMessage.warning('约检信息不存在')
    return
  }

  loading.value = true
  try {
    const res = await PipeAcceptOrderApi.getAcceptOrder(id)
    orderDetail.value = res
    let { payerContact, payerContactName, payerMail, email } = res;
    // 更新表单数据
    formData.value = {
      ...formData.value,
      appointmentDate: formatArrayDate(orderDetail.value?.appointmentDate || []),
      deptName: orderDetail.value?.deptName || '',
      equipDistrict: orderDetail.value?.equipDistrict ? Number(orderDetail.value.equipDistrict) : undefined,
      equipDistrictName: orderDetail.value?.equipDistrictName || '',
      unitContact: orderDetail.value?.unitContact || '',
      unitAddress: orderDetail.value?.unitAddress || '',
      unitPhone: orderDetail.value?.unitPhone || '',
      zipCode: orderDetail.value?.zipCode || '',
      mobile: orderDetail.value?.mobile || '',
      remark: orderDetail.value?.remark || '',
      email: orderDetail.value?.email || '',
      isAttach: orderDetail.value?.isAttach || false,
      sendType: String(orderDetail.value?.sendType) || '100',
      vehicle: String(orderDetail.value?.vehicle) || '100',
      feeType: String(orderDetail.value?.feeType) || '100',
      acceptType: String(orderDetail.value?.acceptType) || '100',
      actualAmount: orderDetail.value?.actualAmount || 0,
      serviceAmount: orderDetail.value?.serviceAmount || 0,
      shouldAmount: orderDetail.value?.shouldAmount || 0,
      reduceFee: orderDetail.value?.reduceFee || 0,
      deptId: orderDetail.value?.deptId || '',
      operator: orderDetail.value?.operator || '',
      equipStreetName: orderDetail.value?.equipStreetName || '',
      areaDisplay: areaDisplay.value,
      reason: orderDetail.value.reason,
      unitName: {
        name: orderDetail.value?.unitName || '',
        id: ''
      },
      useUnitName: {
        name: orderDetail.value?.useUnitName || '',
        id: ''
      },
      socialCreditCode: orderDetail.value?.socialCreditCode,
      recipient: orderDetail.value?.recipient,
      recipientPhone: orderDetail.value?.recipientPhone,
      recipientEmail: orderDetail.value?.recipientEmail,
      useUnitSocialCreditCode: orderDetail.value?.useUnitSocialCreditCode,
      useUnitAddress: orderDetail.value?.useUnitAddress,
      useUnitZipcode: orderDetail.value?.useUnitZipcode,
      useUnitContact: orderDetail.value?.useUnitContact,
      useUnitPhone: orderDetail.value?.useUnitPhone,
      deptPhone: orderDetail.value?.deptPhone,
      feeNature: String(orderDetail.value?.feeNature),
      feeDate: orderDetail.value?.feeDate || 0,
      payerContact,
      payerContactName,
      payerMail,
    }
    // 更新异常单信息
    const orderExceptionRespVO = res.orderExceptionRespVO
    if(orderExceptionRespVO){
      exceptionInfo.value = {
        ...orderExceptionRespVO,
        adjustEffectiveDate: orderExceptionRespVO.adjustEffectiveDate ? dayjs(orderExceptionRespVO.adjustEffectiveDate.join('-')).format('YYYY-MM-DD') : '',
      }
    }

    userList.value = await UserQualificationsApi.getUserPipeAll()

    // 获取检验员列表
    const deptId = formData.value.deptId || userStore.getUser.deptId?.toString() || '1'
    await nextTick()
    checkerSelectRef.value?.getCheckerList(deptId)

    const teamList = orderDetail.value?.teamList?.flatMap((team: any) => {
      const teamMembers: any[] = []

      // 处理组长
      if (team.leaders && team.leaders.length > 0) {
        team.leaders.forEach((leader: any) => {
          if (leader) {
            teamMembers.push({
              memberId: leader.id,
              groupTeamId: team.groupTeamId,
              isLeader: true,
              member: leader
            })
          }
        })
      }

      // 处理组员
      if (team.members && team.members.length > 0) {
        team.members.forEach((member: any) => {
          if (member) {
            teamMembers.push({
              memberId: member.id,
              groupTeamId: team.groupTeamId,
              isLeader: false,
              member: member
            })
          }
        })
      }

      return teamMembers
    }) || []

    if (teamList.length > 0) {
      selectedCheckers.value = teamList
      formData.value.teamList = teamList
    }

  } catch (error) {
    console.error('获取计划详情失败:', error)
    ElMessage.error('获取计划详情失败')
  } finally {
    loading.value = false
  }
}

/** 处理检验员变化 */
const handleCheckerChange = (checkers: CheckerItem[]) => {
  selectedCheckers.value = checkers
  // 同步更新 formData.value.teamList
  formData.value.teamList = checkers
}
const handleEquipQuery = async () => {
  loading.value = true
  try {
    const params = {
      pageNo: equipQueryParams.value.pageNo,
      pageSize: equipQueryParams.value.pageSize,
      orderId: orderDetail.value?.id,
      equipCode: equipQueryParams.value.equipCode,
      factoryCode: equipQueryParams.value.factoryCode,
      relateDepartment: equipQueryParams.value.relateDepartment,
      equipDistrict: equipQueryParams.value.equipDistrict,
      equipStreet: equipQueryParams.value.equipStreet,
      typeList: equipQueryParams.value.typeList || [],
      nextDate: equipQueryParams.value.nextDate || [],
      useStatus: equipQueryParams.value.useStatus || [],
    }

    expandRows.value.forEach(row => {
      tableRef.value?.toggleRowExpansion(row, false)
    })
    // 清空展开行记录
    expandRowKeys.value = []
    expandRows.value = []

    selectedRows.value = []
    selectedDetailRows.value = []

    // 移除空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === undefined || params[key] === null) {
        delete params[key]
      }
      // 处理空数组
      if (Array.isArray(params[key]) && params[key].length === 0) {
        delete params[key]
      }
    })

    // 调用后端API获取数据
    const res = await PipeAcceptOrderApi.getAcceptOrderEquipmentList(params)
    equipList.value = res.list
    equipTotal.value = res.total

  } finally {
    loading.value = false
  }
}

// 页面加载时获取详情
onMounted(async () => {
  await getDetail()
  await handleEquipQuery()
})



/** 禁用日期 */
const disabledDate = (time: Date) => {
  // 禁用过去的日期
  return time.getTime() < dayjs().startOf('day').valueOf()
}

// const handleEquipCodeFn = (id?: number) => {
//   EquipContainerFormRef.value.open(id)
// }
const resetEquipQuery = () => {
  // 重置查询参数
  equipQueryParams.value = {
    pageNo: 1,
    pageSize: 50,
    equipDistrict: undefined,
    equipStreet: undefined,
    equipCode: '',
    factoryCode: '',
    relateDepartment: '',
    typeList: [],
    nextDate: [],
    useStatus: [],
  }

  // 重置区域-街道映射
  areaStreetMap.value.clear()

  // 重置日期相关字段
  daterange.value = []
  month.value = ''
  datePickerType.value = 'month'

  // 重新查询数据
  handleEquipQuery()
}

const handleEquipSelectionChange = (selection) => {
  // 实现设备选择逻辑
  selectedEquips.value = selection
}

const handleEquipSortChange = (sort) => {
  // 实现设备排序逻辑
}

/** 处理区域变化 */
const handleAreaChange = (areas: number[]) => {
  // 获取移除的区域（通过比较之前的区域列表和现在的区域列表）
  const prevAreas = Array.from(areaStreetMap.value.keys())
  const removedAreas = prevAreas.filter(area => !areas.includes(area))

  // 移除取消选择的区域下的街道
  if (removedAreas.length > 0) {
    const currentStreets = equipQueryParams.value.equipStreet || []
    removedAreas.forEach(areaId => {
      const streetsToRemove = areaStreetMap.value.get(areaId) || []
      // 从当前选中的街道中移除这些街道
      equipQueryParams.value.equipStreet = currentStreets.filter(
        streetId => !streetsToRemove.includes(streetId)
      )
      // 从映射中移除该区域
      areaStreetMap.value.delete(areaId)
    })
  }
}

/** 处理区域清空 */
const handleAreaClear = () => {
  // 清空所有选中的街道
  equipQueryParams.value.equipStreet = []
  // 清空区域-街道映射
  areaStreetMap.value.clear()
}

/** 处理街道变化 */
const handleStreetChange = (streets: number[], areaId: number) => {
  // 更新区域-街道映射
  if (equipQueryParams.value.equipDistrict?.includes(areaId)) {
    areaStreetMap.value.set(areaId, streets)
  }
}

/** 处理街道清空 */
const handleStreetClear = () => {
  // 清空所有区域下的街道选择
  areaStreetMap.value.clear()
}

/** 处理日期范围变化 */
const handleDateChange = (val: [string, string] | null) => {
  daterange.value = val || []
  equipQueryParams.value.nextDate = val
    ? [
      dayjs(val[0]).startOf('day').format('YYYY-MM-DD HH:mm:ss'),
      dayjs(val[1]).endOf('day').format('YYYY-MM-DD HH:mm:ss')
    ]
    : []
}

/** 处理月份变化 */
const handleMonthChange = (val: string | null) => {
  if (!val) {
    equipQueryParams.value.nextDate = []
    return
  }

  const date = dayjs(val)
  equipQueryParams.value.nextDate = [
    date.startOf('month').format('YYYY-MM-DD HH:mm:ss'),
    date.endOf('month').format('YYYY-MM-DD HH:mm:ss')
  ]
  month.value = val
}

// 监听日期类型变化
watch(datePickerType, (newVal) => {
  // 清空日期相关字段
  daterange.value = []
  month.value = ''
  equipQueryParams.value.nextDate = []
})

/** 拒绝约检 */
const handleRejectEquip = async () => {
  if (selectedRows.value.length === 0 || selectedDetailRows.value.length === 0) {
    ElMessage.warning('请选择要拒绝约检的设备')
    return
  }
  rejectForm.value.reasonDict = ''
  rejectForm.value.reason = ''
  rejectDialogVisible.value = true
}
/** 处理批量修改 */
const handleBatchEditFn = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条设备数据')
    return
  }
  batchEditFormRef.value.open(selectedRows.value, '1')
}
/** 确认拒绝约检 */
const handleRejectConfirm = async (type) => {
  if (!rejectForm.value.reasonDict) {
    ElMessage.warning('请选择拒绝原因')
    return
  }
  if (rejectForm.value.reasonDict == '5' && !rejectForm.value.reason) {
    ElMessage.warning('请输入说明')
    return
  }
  const equipIds = selectedRows.value.map(e => e.id)
  const submitData = {
    equipIds,
    orderId: orderDetail.value?.id,
    detailEquipRows: selectedDetailRows.value,
    type,
    reason: rejectForm.value.reason,
    reasonDict: rejectForm.value.reasonDict,
  }

  let alertText = ''
  switch(type) {
    case 100:
      alertText = '上报市局'
      break
    case 200:
      alertText = '拒绝约检'
      break
    case 300:
      alertText = '无需上报'
      break
    default:
      alertText = ''
  }
  try {
    // 调用api
    const res = await PipeAcceptOrderApi.refuseAcceptOrder(submitData)

    ElMessage.success(alertText + '操作成功')

    // 提交成功后重置表单和关闭对话框
    rejectForm.value.reason = ''
    rejectForm.value.reasonDict = ''
    rejectDialogVisible.value = false
    handleEquipQuery() // 刷新设备列表
  } catch (e) {
    ElMessage.error(alertText + '操作失败')
  }
}

/** 添加设备 */
const handleAddEquip = () => {
  addEquipVisible.value = true
}

/** 添加设备成功 */
const handleAddEquipSuccess = (selectedEquips) => {
  ElMessage.success('添加设备成功')
  // 更新设备列表
  handleEquipQuery()
}

/** 生成受理单 */
const handleGenerateAcceptance = () => {
  console.log('开始验证表单', formRef.value)

  // 表单验证
  if (!formRef.value) {
    ElMessage.warning('表单引用获取失败')
    return
  }

  submitLoading.value = true
  // 手动触发表单验证
  formRef.value.validate((valid, fields) => {

    if (!valid) {
      ElMessage.warning('请完善必填信息')
      console.log('验证失败的字段:', fields)
      submitLoading.value = false
      return
    }

    // 检查排期时间（检验员改为非必选，任务单阶段才必选）
    if (!formData.value.appointmentDate) {
      ElMessage.warning('请选择排期时间')
      submitLoading.value = false
      return
    }

    // 二次确认
    ElMessageBox.confirm(
      '确认重新提交受理单吗？',
      '操作确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(async () => {
      if(exceptionInfo.value.id){
        await handleSaveException()
      }
      // 确认后提交
      submitAcceptance()
    }).catch(() => {
      // 用户取消操作
      console.log('用户取消操作')
      submitLoading.value = false
    })
  })
}

/** 提交受理单 */
const submitAcceptance = async () => {
  try {
    loading.value = true

    // 组装提交数据
    const submitData = {
      id: orderDetail.value?.id,
      ...formData.value,
      appointmentDate: formData.value.appointmentDate,
      unitName: orderDetail.value?.unitName?.name,
      unitAddress: orderDetail.value?.unitAddress,
      unitContact: formData.value.unitContact,
      unitContactDept: formData.value.unitContactDept,
      unitPhone: formData.value.unitPhone,
      equipDistrict: orderDetail.value?.equipDistrict,
      equipStreet: orderDetail.value?.equipStreet,
      zipCode: formData.value.zipCode,
      checkType: orderDetail.value?.checkType,
      equipType: orderDetail.value?.equipType,
      deptId: orderDetail.value?.deptId,
      email: formData.value.email,
      mobile: formData.value.mobile,
      remark: formData.value.remark,
      isAttach: formData.value.isAttach,
      sendType: formData.value.sendType,
      vehicle: formData.value.vehicle,
      feeType: formData.value.feeType,
      acceptType: formData.value.acceptType,
      actualAmount: formData.value.actualAmount,
      serviceAmount: formData.value.serviceAmount,
      shouldAmount: formData.value.shouldAmount,
      reduceFee: formData.value.reduceFee,
      useUnitName: formData.value?.useUnitName?.name,
      teamList: formData.value.teamList.reduce((acc: any[], item: any) => {
        const existingGroup = acc.find(
          group => group.groupTeamId === item.groupTeamId
        );
        if (existingGroup) {
          // 避免重复添加相同的 userId，且不添加 leaderId
          if (!item.isLeader && !existingGroup.userIds.includes(item.memberId)) {
            existingGroup.userIds.push(item.memberId);
          }
        } else {
          acc.push({
            groupTeamId: item.groupTeamId,
            leaderId: item.isLeader ? item.memberId : '',
            userIds: item.isLeader ? [] : [item.memberId]
          });
        }
        return acc;
      }, [])
    }
    if(exceptionInfo.value.id){
      submitData.boilerOrderExceptionSaveReqVO = cloneDeep({
        ...exceptionInfo.value,
        adjustEffectiveDate: unref(exceptionInfo).adjustEffectiveDate && unref(exceptionInfo).adjustEffectiveDate.split('-').map(item=>Number(item)),
      })
    }

    // 调用API提交受理单
    await PipeAcceptOrderApi.resubmitAcceptOrder(submitData)
    emit('success')
    ElMessage.success('提交成功')
    handleClose()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    loading.value = false
    submitLoading.value = false
  }
}

// 打印受理单
const handlePrintPDF = async () => {
  const id = props.id as string
  if(!id) return ElMessage.error('未找到受理单ID！')
  try {
    const pdfBlob = await BoilerAcceptOrderApi.printAcceptOrderPdf({id})
    if(pdfBlob) {
      const url = URL.createObjectURL(pdfBlob)
      let a = document.createElement('a')
      a.download = '受理单' +  orderDetail.value?.acceptNo + '.pdf' //指定下载的文件名
      a.href = url //  URL对象
      a.click() // 模拟点击
      URL.revokeObjectURL(a.href) // 释放URL 对象
    }
  } catch (error) {
    ElMessage.error('下载失败！')
  }
}

// 手动输入单位
const useInputUseUnitName = ref(false)
const useInputUnitName = ref(false)

// 申请单位名称 change
const handleChangeUnit = async (unitInfo:any) => {
  console.log('申请单位名称 change:', unitInfo)
  formData.value.socialCreditCode = unitInfo.socialCreditCode;
  formData.value.unitAddress = unitInfo.addr
  formData.value.zipCode = unitInfo.post
  // 获取单位默认联系人
  const {list: unitDefaultContact} = await getUnitContacts({
    pageNo: 1,
    pageSize: 10,
    unitId: unitInfo.id,
    isDefault: '1'
  })
  if(unitDefaultContact && unitDefaultContact?.length > 0) {
    formData.value.unitContact = unitDefaultContact[0].contactName
    formData.value.unitPhone = unitDefaultContact[0].contactPhone
    formData.value.recipient = unitDefaultContact[0].contactName
    formData.value.recipientPhone = unitDefaultContact[0].contactPhone
  }
}
// 使用单位名称 change
const handleChangeUseUnit = async (unitInfo:any) => {
  console.log('使用单位名称 change:', unitInfo)
  formData.value.useUnitSocialCreditCode = unitInfo.socialCreditCode;
  formData.value.useUnitAddress = unitInfo.addr
  formData.value.useUnitZipcode = unitInfo.post
  // 获取单位默认联系人
  const {list: unitDefaultContact} = await getUnitContacts({
    pageNo: 1,
    pageSize: 10,
    unitId: unitInfo.id,
    isDefault: '1'
  })
  if(unitDefaultContact && unitDefaultContact?.length > 0) {
    formData.value.useUnitContact = unitDefaultContact[0].contactName
    formData.value.useUnitPhone = unitDefaultContact[0].contactPhone
  }
}

/** 关闭 */
const handleClose = () => {
  emit('update:visible', false)
}

// 监听表单区域相关字段变化，更新areaDisplay
watch([() => formData.value.equipDistrictName, () => formData.value.equipStreetName], () => {
  formData.value.areaDisplay = areaDisplay.value
})

const exceptionInfo = ref<Record<string, any>>({})

const getExceptionItem = (field: string, fieldAttr: string)=>{
  const fileUrl = exceptionInfo.value[fieldAttr] && buildFileUrl(exceptionInfo.value[fieldAttr])
  const fileName = exceptionInfo.value[field]
  if(fileUrl) {
    return (
      <>
        <div class="flex items-center w-full p-l-10px p-r-10px hover:bg-gray-100 rounded-6px">
          {/* <el-tooltip content={fileName}>  */}
          <span class="flex-1 text-ellipsis overflow-hidden whitespace-nowrap">{fileName}</span>
          {/* </el-tooltip>  */}
          <div class="ml-10px">
            <el-link href={fileUrl} underline={false} download target="_blank" type="primary">下载</el-link>
          </div>
          <div class="ml-10px">
            <el-button link type="danger" onClick={()=>handleRemove(field, fieldAttr)}>删除</el-button>
          </div>
        </div>
      </>
    )
  } else {
    return (
      <el-button type="primary" onClick={()=>handleOpenFileUploadModal(field, fieldAttr)}>
        <Icon icon="ep:upload-filled" />
        <span>附件上传</span>
      </el-button>
    )
  }
}

const addExceptionInfo = () => {
  const orderId = orderDetail.value?.id || props.id;
  if(!orderId) {
    // ElMessage.error('请先保存订单')
    return
  }

  PipeAppointmentConfirmOrderApi.createExceptionInfo({
    orderId: orderDetail.value?.id || props.id,
    orderType: 200,
  }).then((res) => {
    if(res) {
      ElMessage.success('生成成功')
      handleGetExceptionInfo(res)
    }
  }).catch((error)=>{
    ElMessage.error(error)
  })
}

const deleteExceptionInfo = () => {
  ElMessageBox.confirm('确定删除异常单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    PipeAppointmentConfirmOrderApi.deleteExceptionInfo(exceptionInfo.value.id).then(res=>{
      if(res) {
        ElMessage.success('删除成功')
        exceptionInfo.value = {}
      }
    })

  }).catch(() => {
    // 取消删除
  });

}
// 更新异常信息
const handleSaveException=()=>{
  return new Promise((resolve, reject)=>{
    const { adjustEffectiveDate } = unref(exceptionInfo)
    const params = {
      ...exceptionInfo.value,
      adjustEffectiveDate: adjustEffectiveDate && adjustEffectiveDate.split('-').map(item=>Number(item)),
    }
    PipeAppointmentConfirmOrderApi.updateExceptionInfo(params).then(res=>{
      resolve(res)
    }).catch((error)=>{
      reject(error)
    })
  })
}

const getExceptionInfoList = () => {
  PipeAppointmentConfirmOrderApi.getExceptionInfoList({
    orderId: orderDetail.value?.id || props.id,
  }).then(res=>{
    console.log('getExceptionInfoList:',res)
  })
}


const handleGetExceptionInfo = (id: string) => {
  PipeAppointmentConfirmOrderApi.getExceptionInfo(id).then((res) => {
    if(res) exceptionInfo.value = {
      ...res,
      adjustEffectiveDate: res.adjustEffectiveDate?.join('-')
    }
  }).catch((error)=>{
    console.log(error, '-----error--->')
    ElMessage.error(error)
  })
}

const fileUploadModalRef = ref<InstanceType<typeof FileUploadModal>>();
const currentUploadMap = reactive({
  field: '',
  fieldAttr: '',
})

const handleOpenFileUploadModal = (type: string, attach: string) => {
  currentUploadMap.field = type
  currentUploadMap.fieldAttr = attach
  fileUploadModalRef.value?.open()
}
const handleFileUploadSuccess = (fileInfo:{fileName: string, fileUrl: string}) => {
  exceptionInfo.value[currentUploadMap.field] = fileInfo.fileName
  exceptionInfo.value[currentUploadMap.fieldAttr] = fileInfo.fileUrl
  console.log('handleFileUploadSuccess:', exceptionInfo.value)
}

const handleRemove = (type: string, attach: string) => {
  exceptionInfo.value[type] = ''
  exceptionInfo.value[attach] = ''
}

const formattedCheckers = computed(() => {
  const teamList = formData.value.teamList
  console.log("teamList",teamList)
  if (!teamList || !Array.isArray(teamList) || teamList.length === 0) return []

  const result: { id: string; label: string }[] = []
  teamList.forEach((team: any, teamIndex: number) => {
    if (team.isLeader) {
      result.push({
        id: `leader-${team.member.id || teamIndex}`,
        label: `组长: ${team.member.nickname || ''}`
      })
    }else{
      result.push({
        id: `member-${team.member.id || teamIndex}`,
        label: `${team.member.nickname || ''}`
      })
    }
  })
  return result
})

</script>

<style lang="scss" scoped>
.app-container {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: 1001;
  overflow-y: auto;
  background: #fff;
  padding: 20px 20px 0;
}
.form-group {
  &:not(:last-child) {
    margin-bottom: 16px;
  }

  &-title {
    color: #606266;
    font-size: 13px;
    font-weight: 500;
    margin-bottom: 12px;
  }
}
.check-info-label-title {
  width: 100%;
  line-height: 32px;
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  &::before {
    content: '';
    display: inline-block;
    width: 4px;
    height: 16px;
    background: var(--el-color-primary);
    margin-right: 8px;
  }
}
.feeDate_box {
  color: #606266;
  :deep(.el-input-number) {
    width: 120px !important;
  }
}
.unit-form-item {
  :deep(.el-form-item__content) {
    display: flex;
    align-items: center;
    flex-wrap: nowrap;
    .el-button {
      margin-left: 8px;
    }
  }
}
.unit-name {
  display: flex;
  align-items: center;
  padding: 0 0 8px;

  .label {
    width: 90px;
    color: #606266;
    font-size: 13px;
    text-align: right;
    padding-right: 12px;
  }

  .value {
    flex: 1;
    font-size: 14px;
    color: #303133;
  }
}


:deep(.el-form) {
  .el-form-item {
    margin-bottom: 12px;
    align-items: center;
    &__label {
      height: auto;
      font-size: 13px;
      line-height: 20px;
      color: #606266;
      padding-right: 8px;
    }
    .el-date-editor.el-input, .el-input-number {
      width: 100%;
      .el-input__inner {
        text-align: left;
      }
    }
    &.actualAmountFormItem {
      .el-form-item__content {

        display: flex;
        .el-input-number  {
          width: 300px;
        }
      }
    }
  }
}

.selected-checkers {
  display: inline-flex;
  flex-wrap: wrap;
  gap: 8px;
  min-height: 32px;
  padding: 4px 8px;

  .el-tag {
    margin: 0;
    height: 24px;
    line-height: 22px;

    &:hover {
      cursor: default;
    }
  }
}

.leader-tag {
  display: inline-block;
  width: 16px;
  height: 16px;
  line-height: 14px;
  text-align: center;
  border: 1px solid #4475d6;
  font-size: 12px;
  margin-right: 4px;
  color: #4475d6;
}

.reject-dialog {
  :deep(.el-dialog__header) {
    margin: 0;
    padding: 16px 20px;
    border-bottom: 1px solid #dcdfe6;
  }

  :deep(.el-dialog__body) {
    padding: 20px;
  }

  .reject-content {
    .equip-list {
      margin-bottom: 20px;
      color: #606266;
      line-height: 1.6;
    }

    .check-type {
      color: #606266;
    }

    .reject-reason {
      .reason-label {
        color: #606266;
      }

      :deep(.el-textarea__inner) {
        background-color: #f5f7fa;
        border-color: #e4e7ed;

        &:focus {
          background-color: #fff;
        }
      }
    }
  }

  .reject-footer {
    margin-top: 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .time-tag {
      :deep(.el-tag) {
        height: 32px;
        line-height: 30px;
        font-size: 16px;
        padding: 0 12px;
      }
    }

    .action-buttons {
      .el-button + .el-button {
        margin-left: 12px;
      }
    }
  }
}
.footer-btn-box {
  position: sticky;
  bottom: 0;
  left: 0;
  right: 0;
  padding-top: 16px;
  background-color: #fff;
  z-index: 1002;
}
:deep(.el-table__expand-icon) {
  display: none !important;
}
</style> 
