<template>
  <div class="app-container">
    <!-- 受检信息表单 -->
    <ContentWrap title="受检信息">
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="120px" class="p-3">
        <!-- <div class="check-info-label-title">受理单位</div> -->
        <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="请输入单位名称" :maxlength="50" />
              <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="请输入统一社会信用代码" :maxlength="50"/>
            </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="请输入申请单位地址" :maxlength="50"/>
            </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-col :span="8">
            <el-form-item label="检验性质" prop="checkType" label-width="120px">
              <el-select disabled v-model="formData.checkType" placeholder="请选择检验性质" clearable>
                <el-option
                  v-for="(item, key) in checkStatusMap"
                  :key="key"
                  :label="item"
                  :value="key"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="8">
            <el-form-item label="检验性质" prop="checkType" label-width="120px">
              <el-select v-model="formData.checkType" placeholder="请选择检验性质" clearable disabled>
                <el-option
                  v-for="(item, key) in checkStatusMap"
                  :key="key"
                  :label="item"
                  :value="key"
                />
              </el-select>
            </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="请输入使用单位名称" :maxlength="50" @blur="handleChangeUseUnitInput" @keyup.enter="handleChangeUseUnitInput" />
              <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="请输入统一社会信用代码" :maxlength="50"/>
            </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="请输入使用单位地址" :maxlength="50"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 邮政编码 useUnitZipcode -->
            <el-form-item label="使用邮政编码" prop="useUnitZipcode">
              <el-input v-model="formData.useUnitZipcode" placeholder="请输入使用邮政编码" :maxlength="50"/>
            </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="请输入单位联系人" :maxlength="50"/>
            </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="请输入联系人电话" :maxlength="11"/>
            </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">
            <!-- 约检联系人电话email -->
            <el-form-item label="联系人邮箱" prop="email" label-width="120px">
              <el-input v-model="formData.email" placeholder="请输入约检联系人邮箱"/>
            </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">
            <!-- 接收人电话 payerContact -->
            <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"
              />
            </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">
              <el-select disabled v-model="formData.checkType" placeholder="请选择检验性质" clearable class="!w-120px">
                <el-option
                  v-for="(item, key) in checkStatusMap"
                  :key="key"
                  :label="item"
                  :value="key"
                />
              </el-select>
            </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 v-for="(item, key) in PressureFeeTypeMap" :key="key" :value="key" :label="item"/>
              </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="设备信息">

      <!-- 搜索工作栏 -->
      <ContentWrap>
        <el-form
          :model="equipQueryParams"
          ref="equipQueryFormRef"
          :inline="true"
          label-width="80px"
        >
          <!-- 基本信息查询部分 -->
          <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="deptId">
              <DeptSelect
                v-model="equipQueryParams.deptId"
                placeholder="请选择部门"
                clearable
                class="!w-240px"
              />
            </el-form-item>

            <el-form-item label="使用状态" prop="useStatus">
              <el-select
                v-model="equipQueryParams.useStatus"
                placeholder="选择使用状态"
                clearable
                multiple
                collapse-tags
                collapse-tags-tooltip
                class="!w-240px"
              >
                <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.SYSTEM_EQUIP_BOILER_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 boilerTypeOptions"
                    :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="selectedEquips.length === 0" @click="handleRejectEquip">
                <Icon icon="ep:failed" class="mr-5px" /> 拒绝约检
              </el-button>
              <el-button type="primary" @click="handleAddEquip"><Icon icon="ep:plus" class="mr-5px" /> 添加设备</el-button>
              <el-button type="primary" @click="handleBatchEditFn" :disabled="selectedEquips.length === 0">
                <Icon icon="ep:edit" class="mr-5px" /> 批量修改约检联系人
              </el-button>
            </el-form-item>
          </div>
        </el-form>
      </ContentWrap>

      <!-- 设备列表 -->
      <ContentWrap>
        <el-table
          v-loading="equipLoading"
          :data="equipList"
          stripe
          @selection-change="handleEquipSelectionChange"
          @sort-change="handleEquipSortChange"
        >
          <el-table-column type="selection" width="30" />
          <el-table-column label="区域" align="center" prop="equipDistrictName" sortable="custom" min-width="120" />
          <el-table-column label="街道" align="center" prop="equipStreetName" sortable="custom" min-width="120" />
          <el-table-column label="设备注册代码" align="center" prop="equipCode" min-width="190">
            <template #default="{ row }">
              {{ row.equipCode }}
              <dict-tag :type="DICT_TYPE.SYSTEM_EQUIP_BOILER_STATUS" :value="row.status" />
            </template>
          </el-table-column>
          <el-table-column label="是否租借" align="center" prop="isRent" min-width="80">
            <template #default="{ row }">
              {{ row.isRent ? '是' : '否' }}
            </template>
          </el-table-column>
          <el-table-column label="使用证编号" align="center" prop="useRegisterNo" min-width="120" />
          <el-table-column label="出厂编号" align="center" prop="factoryCode" min-width="120" />
          <el-table-column label="约检联系人" align="center" prop="contact" min-width="120" />
          <el-table-column label="约检联系人电话" align="center" prop="contactPhone" min-width="140" />
          <el-table-column label="蒸发量" align="center" prop="maxContinueEvapor" min-width="80" />
          <el-table-column label="型号" align="center" prop="boilerModel" min-width="120" />
<!--          <el-table-column label="吨位" align="center" prop="tonnage" min-width="120" />-->
        </el-table>

        <!-- 分页 -->
        <Pagination
          :total="equipTotal"
          v-model:page="equipQueryParams.pageNo"
          v-model:limit="equipQueryParams.pageSize"
          @pagination="handleEquipQuery"
        />
      </ContentWrap>
    </ContentWrap>



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

    <!-- 拒绝约检弹窗 -->
    <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 selectedEquips" :key="equip.id" class="mb-2">
          设备注册代码：{{ equip.equipCode }}
        </div>
      </div>
      
      <div class="mb-4">
        检验性质：{{ orderDetail?.checkType ? allCheckTypeMap[orderDetail.equipMainType][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.trim="rejectForm.reason"
          type="textarea"
          :rows="4"
          placeholder="请输入"
          resize="none"
          :maxlength="100"
          show-word-limit
        />
      </div>

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

    <!-- 页面底部按钮 -->
    <div class="flex justify-center pb-4">
      <el-button @click="handleClose" :loading="loading">关闭</el-button>
      <el-button v-if="!route.query.id || orderDetail?.createAcceptOrder === false" type="primary" :loading="loading" @click="handleGenerateAcceptance">
        生成受理单
      </el-button>
      <el-button type="primary" @click="handleSave" :loading="loading">保存</el-button>
    </div>
     <batchEditForm ref="batchEditFormRef" @success="()=>handleEquipQuery(true)"/>
       <EquipContainerForm ref="EquipContainerFormRef" />
    <FileUploadModal ref="fileUploadModalRef" @success="handleFileUploadSuccess" />

  </div>
</template>

<script setup lang="tsx">
import { ref, onMounted, computed, watch, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import batchEditForm from '../planNew/components/batchEditForm.vue'
import { BoilerAppointmentConfirmOrderApi, BoilerAppointmentConfirmOrderVO } from '@/api/pressure2/appointmentconfirmorder'
import { EquipBoilerSchedulingEquipVO } from '@/api/pressure2/equipboilerscheduling'
import dayjs from 'dayjs'
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import DeptSelect from '../../pressure2/equipboilerscheduling/components/DeptSelect.vue'
import AreaSelect from '../../system/equipcontainer/components/AreaSelect.vue'
import StreetSelect from '../../system/equipcontainer/components/StreetSelect.vue'
import AddEquipDialog from '../schedule/components/AddEquipDialog.vue'
import { formatArrayDate } from '@/utils/formatTime'
import EquipContainerForm from '@/components/EquipContainerForm/index.vue'
import { useTagsViewStore } from '@/store/modules/tagsView'
import {
  PressureCheckTypeMap,
  PressureFeeTypeMap,
  PressureFeeNatureMap,
  PressureFeeNature,
  allCheckTypeMap
} from '@/utils/constants'
import { useEmitt } from '@/hooks/web/useEmitt'
import { getUnitNewList, getUnitContacts } from '@/api/laboratory/unit'
import { numberToChinese } from '@/utils/formatter'
import FileUploadModal from './components/ImportFile.vue'
import { buildFileUrl } from '@/utils'
import { Icon } from '@/components/Icon'
import { cloneDeep } from 'lodash-es'
import { useUserStoreWithOut } from '@/store/modules/user'
import CheckerSelect, { type CheckerItem } from '@/views/pressure2/components/CheckerSelect'

const { emitter } = useEmitt()

const route = useRoute()
const router = useRouter()
const tagsViewStore = useTagsViewStore()
const userStore = useUserStoreWithOut()
const batchEditFormRef = ref()

const orderDetail = ref<BoilerAppointmentConfirmOrderVO>()

const checkTypeMap = PressureCheckTypeMap

const boilerTypeOptions = getStrDictOptions(DICT_TYPE.SYSTEM_EQUIP_BOILER_TYPE)

const formData = ref<Record<string,any>>({
  checkType: '', //检验性质
  appointmentDate: '',
  teamList: [] as string[],
  unitName: {
    name: '',
    id: ''
  },
  deptName: '',
  equipDistrict: undefined as number | undefined,
  equipDistrictName: '',
  equipStreet: '',
  equipStreetName: '',
  unitContact: '',
  unitCode: '',
  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: '',
  socialCreditCode: '',
  recipient: '',
  recipientPhone: '',
  recipientEmail: '',
  useUnitName: {
    name: '',
    id: ''
  },
  useUnitSocialCreditCode: '',
  useUnitAddress: '',
  useUnitZipcode: '',
  useUnitContact: '',
  useUnitPhone: '',
  deptPhone: '',
  feeNature: '',
  feeDate: 0,
  descritionFile: [],
})
const checkStatusMap = {
  '100': '内检',
  '200': '外检',
  '300': '耐压检',
}

const loading = ref(false)

// 检验员选择相关
const selectedCheckers = ref<CheckerItem[]>([])
const checkerSelectRef = ref()
const EquipContainerFormRef = ref<InstanceType<typeof EquipContainerForm>>()
// 记录每个区域下已选择的街道
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: '',
  productNo: '',
  deptId: '',
  typeList: [] as string[],
  nextDate: [] as string[],
  useStatus: [] as string[],
})

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

// 临检时间相关
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() // 表单引用

/** 约检确认详情 */
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' }
  ],
  // unitPhone: [
  //   { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  // ],
  // recipientPhone: [
  //   { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  // ],
  recipientEmail: [
    { pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '请输入正确的邮箱', trigger: 'blur' }
  ],
  payerContact: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  payerMail: [
    { 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' }
  ],
  checkType: [
    { 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
})

// 获取约检详情
const getDetail = async () => {
  const id = route.query?.id as string
  if (!id) return
  
  loading.value = true
  try {
    const res = await BoilerAppointmentConfirmOrderApi.getAppointmentConfirmOrder(id);
    let { unitCode, payerContact, payerContactName, payerMail, email } = res;
    orderDetail.value = res || {};
    // 更新表单数据
    formData.value = {
      ...formData.value,
      checkType: `${orderDetail.value?.checkType }`,
      appointmentDate: formatArrayDate(orderDetail.value?.appointmentDate || []),
      unitName: {
        name: orderDetail.value?.unitName || '',
        id: ''
      },
      useUnitName: {
        name: orderDetail.value?.useUnitName || '',
        id: ''
      },
      deptName: orderDetail.value?.deptName || '',
      equipDistrict: orderDetail.value?.equipDistrict ? Number(orderDetail.value.equipDistrict) : undefined,
      equipDistrictName: orderDetail.value?.equipDistrictName || '',
      unitContact: orderDetail.value?.unitContact || '',
      unitCode,
      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,
      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: `${orderDetail.value?.feeNature}`,
      feeDate: orderDetail.value?.feeDate || 0,
      payerContact,
      payerContactName,
      payerMail,
      email,
      status: orderDetail.value?.status || 100,
    }
    // 更新异常信息数据
    // 更新检验员数据
    const orderExceptionRespVO = res.orderExceptionRespVO
    if(orderExceptionRespVO){
      exceptionInfo.value = {
        ...orderExceptionRespVO,
        adjustEffectiveDate: orderExceptionRespVO.adjustEffectiveDate ? dayjs(orderExceptionRespVO.adjustEffectiveDate.join('-')).format('YYYY-MM-DD') : '',
      }
    }

    console.log(exceptionInfo.value, 'exceptionInfo')
    const teamList: CheckerItem[] = orderDetail.value?.teamList?.flatMap((team: any) => {
      const teamMembers: CheckerItem[] = []
      
      // 处理组长
      if (team.leaders && team.leaders.length > 0) {
        team.leaders.forEach((leader: any) => {
          if (leader) {
            teamMembers.push({
              groupTeamId: team.groupTeamId,
              memberId: leader.id,
              leaderId: leader.id,
              member: leader,
              isLeader: true
            })
          }
        })
      }
      
      // 处理组员
      if (team.members && team.members.length > 0) {
        team.members.forEach((member: any) => {
          if (member) {
            teamMembers.push({
              groupTeamId: team.groupTeamId,
              memberId: member.id,
              leaderId: team.leaders?.[0]?.id || '',
              member: member,
              isLeader: false
            })
          }
        })
      }
      
      return teamMembers
    }) || []

    if (teamList.length > 0) {
      selectedCheckers.value = teamList
      formData.value.teamList = teamList
    }
    
    // 加载检验员列表（默认当前登录人的部门）
    const deptId = userStore.getUser.deptId?.toString()
    if (deptId) {
      await nextTick()
      checkerSelectRef.value?.getCheckerList(deptId)
    }
  } catch (error) {
    console.error('获取计划详情失败:', error)
    ElMessage.error('获取计划详情失败')
    router.back()
  } finally {
    loading.value = false
  }
}

/** 处理检验员变化 */
const handleCheckerChange = (checkers: CheckerItem[]) => {
  selectedCheckers.value = checkers
  // 同步更新 formData.value.teamList
  formData.value.teamList = checkers
}

/** 禁用日期 */
const disabledDate = (time: Date) => {
  // 获取所有设备的最早检验日期
  const dates = equipList.value.map(item => {
    if (orderDetail.value?.checkType === 100) {
      return item.nextCheckDate ? formatArrayDate(item.nextCheckDate) : null
    } else if (orderDetail.value?.checkType === 200) {
      return item.nextYearCheckDate ? formatArrayDate(item.nextYearCheckDate) : null
    } else {
      return item.nextExpiredCheckDate ? formatArrayDate(item.nextExpiredCheckDate) : null
    }
  }).filter(Boolean) as any
  
  // 如果没有有效日期，则禁用过去的日期
  if (dates.length === 0) {
    return time.getTime() < dayjs().startOf('day').valueOf()
  }
  // 找到最早的检验日期
  const earliestDate = new Date(Math.min(...dates.map(date => new Date(date).getTime())))
  
  // 禁用早于最早检验日期的日期
  return time.getTime() > earliestDate.getTime()
}

// 设备查询相关
const handleEquipQuery = async (isUpdateContact: boolean = false) => {
  loading.value = true
  try {
    const params = {
      pageNo: equipQueryParams.value.pageNo,
      pageSize: equipQueryParams.value.pageSize,
      orderId: orderDetail.value?.id,
      equipCode: equipQueryParams.value.equipCode,
      productNo: equipQueryParams.value.productNo,
      deptId: equipQueryParams.value.deptId,
      equipDistrict: equipQueryParams.value.equipDistrict,
      equipStreet: equipQueryParams.value.equipStreet,
      typeList: equipQueryParams.value.typeList || [],
      nextDate: equipQueryParams.value.nextDate || [],
      useStatus: equipQueryParams.value.useStatus || [],
      unitName: formData.value.useUnitName.name,
    }
    
    // 移除空值
    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 BoilerAppointmentConfirmOrderApi.getAppointmentConfirmOrderEquipmentList(params)
    equipList.value = res.list
    equipTotal.value = res.total

    // 批量修改约检联系人后，申请单位约检联系人与手机号，报告接收人与手机号同步修改。若使用单位与申请单位一致时，也需进行同步修改
    if(isUpdateContact && equipList.value.length > 0){
      const { contact, contactPhone } = equipList.value[0]
      formData.value.unitContact = contact
      formData.value.unitPhone = contactPhone
      formData.value.recipient = contact
      formData.value.recipientPhone = contactPhone
      if(formData.value.unitName.name === formData.value.useUnitName.name){
        formData.value.useUnitContact = contact
        formData.value.useUnitPhone = contactPhone
      }
    try {
    // 组装提交数据
    const submitData = {
      id: orderDetail.value?.id,
      unitContact: formData.value.unitContact,
      unitPhone: formData.value.unitPhone,
      recipient: formData.value.recipient,
      recipientPhone: formData.value.recipientPhone,
      useUnitContact: formData.value.useUnitContact,
      useUnitPhone: formData.value.useUnitPhone,
    }
    await BoilerAppointmentConfirmOrderApi.saveAcceptOrder(submitData)
    } catch (error) {
    ElMessage.error('提交失败')
    } 
    }
      
  } finally {
    loading.value = false
  }
}
const handleEquipCodeFn = (id?: number) => {
  EquipContainerFormRef.value.open(id)
}
const resetEquipQuery = () => {
  // 重置查询参数
  equipQueryParams.value = {
    pageNo: 1,
    pageSize: 50,
    equipDistrict: undefined,
    equipStreet: undefined,
    equipCode: '',
    productNo: '',
    deptId: '',
    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 (selectedEquips.value.length === 0) {
    ElMessage.warning('请选择要拒绝约检的设备')
    return
  }
  rejectForm.value.reasonDict = ''
  rejectForm.value.reason = ''
  rejectDialogVisible.value = true
}
/** 处理批量修改 */
const handleBatchEditFn = () => {
  if (selectedEquips.value.length === 0) {
    ElMessage.warning('请至少选择一条设备数据')
    return
  }
  batchEditFormRef.value.open(selectedEquips.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 = selectedEquips.value.map(e => e.id)
  const submitData = {
    equipIds,
    orderId: orderDetail.value?.id,
    type,
    reasonDict: rejectForm.value.reasonDict,
    reason: rejectForm.value.reason,
    orderNo: orderDetail.value?.appointmentNo,
    checkType: orderDetail.value?.checkType
  }
  let alertText = ''
  switch(type) {
    case 100:
      alertText = '上报市局'
      break
    case 200:
      alertText = '拒绝约检'
      break
    case 300:
      alertText = '无需上报'
      break
    default:
      alertText = ''
  }
  rejectLoading.value = true
  try {
    // 调用api
    const res = await BoilerAppointmentConfirmOrderApi.refuseAppointmentConfirmOrder(submitData)
    ElMessage.success(alertText + '操作成功')
    rejectLoading.value = false
    // 提交成功后重置表单和关闭对话框
    rejectForm.value.reason = ''
    rejectForm.value.reasonDict = ''
    rejectDialogVisible.value = false
    handleEquipQuery() // 刷新设备列表
  } catch (e) {
    rejectLoading.value = false
    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
  }

  // 手动触发表单验证
  formRef.value.validate((valid, fields) => {
    
    if (!valid) {
      ElMessage.warning('请完善必填信息')
      console.log('验证失败的字段:', fields)
      return
    }
    
    // 检查排期时间和检验员
    if (!formData.value.appointmentDate) {
      ElMessage.warning('请选择约检时间')
      return
    }
    
    if(!equipList.value.length){
      ElMessage.warning('请添加设备')
      return
    }
    
    // 二次确认
    ElMessageBox.confirm(
      '确认要生成受理单吗？提交后将无法修改。',
      '操作确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(async () => {
      if(exceptionInfo.value.id){
        await handleSaveException()
      }
      // 确认后提交
      submitAcceptance()
    }).catch(() => {
      // 用户取消操作
      console.log('用户取消操作')
    })
  })
}

/** 提交受理单 */
const submitAcceptance = async () => {
  try {
    let { unitCode='' } = formData.value;
    loading.value = true
    
    // 组装提交数据
    const submitData: Record<string, any> = {
      id: orderDetail.value?.id,
      ...formData.value,
      appointmentDate: formData.value.appointmentDate,
      unitName: formData.value?.unitName?.name,
      unitAddress: formData.value?.unitAddress,
      unitCode,
      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,
      equipMainType: orderDetail.value?.equipMainType,
      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: selectedCheckers.value.reduce((acc, checker) => {
        const existingTeam = acc.find(team => team.groupTeamId === checker.groupTeamId)
        if (existingTeam) {
          if (checker.isLeader) {
            existingTeam.leaderId = checker.memberId
          } else {
            existingTeam.userIds.push(checker.memberId)
          }
        } else {
          acc.push({
            groupTeamId: checker.groupTeamId,
            leaderId: checker.isLeader ? checker.memberId : '',
            userIds: checker.isLeader ? [] : [checker.memberId]
          })
        }
        return acc
      }, []),
      equipIds: equipList.value.map(e => e.id),
    }
    if(exceptionInfo.value.id){
      submitData.boilerOrderExceptionSaveReqVO = cloneDeep({
        ...exceptionInfo.value,
        adjustEffectiveDate: unref(exceptionInfo).adjustEffectiveDate && unref(exceptionInfo).adjustEffectiveDate.split('-').map(item=>Number(item)),
      })
    }
    // console.log('submitData:', submitData);
    
    // 调用API提交受理单
    await BoilerAppointmentConfirmOrderApi.submitAppointmentConfirmOrder(submitData);
    emitter.emit('refresh-list')
    
    ElMessage.success('受理单生成成功')
    handleClose()
  } catch (error) {
    console.error('生成受理单失败:', error)
    ElMessage.error('生成受理单失败')
  } finally {
    loading.value = false
  }
}

/** 保存约检单 */
const handleSave = () => {
  // console.log('开始验证表单', formRef.value)
  // 表单验证
  if (!formRef.value) return ElMessage.warning('表单引用获取失败')

  // 手动触发表单验证
  formRef.value.validate((valid, fields) => {
    if (!valid) return ElMessage.warning('请完善必填信息')
    // 检查排期时间
    if (!formData.value.appointmentDate) return ElMessage.warning('请选择约检时间')
   
    // 二次确认
    ElMessageBox.confirm(
      '确认保存吗？',
      '操作确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(async () => {
      if(exceptionInfo.value.id){
        await handleSaveException()
      }
      saveAcceptance()
    })
  })
}

const saveAcceptance = async () => {
  try {
    loading.value = true
    // 组装提交数据
    let submitData = {
      id: orderDetail.value?.id,
      ...formData.value,
      equipType: orderDetail.value?.equipType,
      equipNum: orderDetail.value?.equipNum,
      unitName: orderDetail.value?.unitName?.name,
      warningDay: orderDetail.value?.warningDay,
      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;
      }, [])
    }
    // 调用API保存
    const res2 = await BoilerAppointmentConfirmOrderApi.saveAcceptOrder(submitData)
    if(res2) {
        ElMessage.success('保存成功')
        handleClose()    
    }
  } catch (error) {
    ElMessage.error('保存失败')
  } finally {
    loading.value = false
  }
}

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

// 清空与单位相关字段的函数
const clearUnitFields = () => {
  formData.value.unitName.name = ''
  formData.value.socialCreditCode = ''
  formData.value.unitAddress = ''
  formData.value.unitContact = ''
  formData.value.unitPhone = ''
  formData.value.recipient = ''
  formData.value.recipientPhone = ''
}

// 监听 useInputUnitName 变化
watch(useInputUnitName, (newValue) => {
  if (newValue) {
    clearUnitFields()
  }
})
// 清空与使用单位相关的字段
const clearUseUnitFields = () => {
  formData.value.useUnitName.name = ''
  formData.value.useUnitSocialCreditCode = ''
  formData.value.useUnitAddress = ''
  formData.value.useUnitZipcode = ''
  formData.value.useUnitContact = ''
  formData.value.useUnitPhone = ''
}

// 监听 useInputUseUnitName 变化
watch(useInputUseUnitName, (newValue) => {
  if (newValue) {
    clearUseUnitFields()
  }
})
// 申请单位名称 change
const handleChangeUnit = async (unitInfo:any) => {
  formData.value.socialCreditCode = unitInfo.socialCreditCode;
  formData.value.unitAddress = unitInfo.addr
  formData.value.zipCode = unitInfo.post
  if(orderDetail.value?.checkType != 200){
    formData.value.feeNature = unitInfo.isExempt === '1' ? `${PressureFeeNature.SMZFC}` : `${PressureFeeNature.BSMZFC}`
  }
  // 获取单位默认联系人
  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
  }
  await handleEquipQuery()
}
// 使用单位名称input框失焦 & 回车按钮进行查询
const handleChangeUseUnitInput = () => {
  handleEquipQuery()
}

/** 关闭 */
const handleClose = () => {
  tagsViewStore.closeSelectedTag(route)
  router.push({
      name: 'OrderConfirm',
  })
}

// 监听表单区域相关字段变化，更新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 = formData.value.id || route.query?.id;
  if(!orderId) {
    // ElMessage.error('请先保存订单')
    return
  }

  BoilerAppointmentConfirmOrderApi.createExceptionInfo({
    orderId: formData.value.id || route.query?.id,
    orderType: 100,
  }).then((res) => {
    if(res) {
      ElMessage.success('生成成功')
      handleGetExceptionInfo(res)
    }
  }).catch((error)=>{
    ElMessage.error(error)
  })
}

const deleteExceptionInfo = () => {
  ElMessageBox.confirm('确定删除异常单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
      BoilerAppointmentConfirmOrderApi.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)),
    }
    BoilerAppointmentConfirmOrderApi.updateExceptionInfo(params).then(res=>{
      resolve(res)
    }).catch((error)=>{
      reject(error)
    })
  })
}

const getExceptionInfoList = () => {
  BoilerAppointmentConfirmOrderApi.getExceptionInfoList({
    orderId: formData.value.id || route.query?.id,
  }).then(res=>{
    console.log('getExceptionInfoList:',res)
  })
}


const handleGetExceptionInfo = (id: string) => {
  BoilerAppointmentConfirmOrderApi.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] = ''
}


// 页面加载时获取详情
onMounted(async () => {
  await getDetail()
  if(route.query?.id) {
    await handleEquipQuery()
    // await handleGetExceptionInfo('eb9a57fe2ed98a45e1a892aef4cc13f0')
  }
})
</script>

<style lang="scss" scoped>
.form-group {
  &:not(:last-child) {
    margin-bottom: 16px;
  }
  
  &-title {
    color: #606266;
    font-size: 13px;
    font-weight: 500;
    margin-bottom: 0;
  }
}
.p-3 {
  padding-top: 0;
}
.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;
        }
      }
    }
  }
}

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