<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="公司名" prop="companyName">
        <el-input
          v-model="queryParams.companyName"
          placeholder="请输入公司名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属部门" prop="deptId">
        <el-select v-model="queryParams.deptId" placeholder="请选择所属部门" clearable size="small">
          <el-option
            v-for="item in deptOptions"
            :key="item.deptId"
            :label="item.deptName"
            :value="item.deptId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="联系电话" prop="companyMobile">
        <el-input
          v-model="queryParams.companyMobile"
          placeholder="请输入联系电话"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

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

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['his:company:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['his:company:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['his:company:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['his:company:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="multiple"
          @click="handleMiniProgram"
        >批量修改小程序
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" border :data="companyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="ID" align="center" prop="companyId"/>
      <el-table-column label="企业名" align="center" prop="companyName"/>
      <el-table-column label="商务负责人" align="center" prop="manager"/>
      <el-table-column label="联系人" align="center" prop="linkName"/>

      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="statusOptions" :value="scope.row.status"/>
        </template>
      </el-table-column>

      <el-table-column label="余额" align="center" prop="money"/>
      <el-table-column label="红包余额" align="center" prop="redPackageMoney"/>
      <el-table-column label="企业类型" align="center" prop="companyType">
        <template slot-scope="scope">
          <dict-tag :options="companyTypeOptions" :value="scope.row.companyType"/>
        </template>
      </el-table-column>
      <el-table-column label="管理员账号" align="center" prop="userName"/>
      <el-table-column label="限制用户数量" align="center" prop="limitUserCount"/>
      <el-table-column label="限制pad数量" align="center" prop="maxPadNum" :formatter="padNumFormatter" v-if="this.$store.state.user.medicalMallConfig.resource"/>
      <el-table-column label="占用pad数量" align="center" prop="usedNum" v-if="this.$store.state.user.medicalMallConfig.resource"/>
      <el-table-column label="所属部门" align="center" prop="deptId" v-if="this.$store.state.user.medicalMallConfig.resource">
        <template slot-scope="scope">
          <el-tag prop="deptId" v-for="(item, index) in deptOptions" :key="'deptId'+index"
                  v-if="scope.row.deptId===item.deptId"
          >{{ item.deptName }}
          </el-tag>
        </template>
      </el-table-column>
      <!--  看课休息    -->
      <el-table-column label="看课休息开关" align="center" prop="isOpenRestReminder">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isOpenRestReminder==1" type="success">开启</el-tag>
          <el-tag v-if="scope.row.isOpenRestReminder==0" type="success">关闭</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="开始时间" align="center" prop="startTime" width="180"/>
      <el-table-column label="到期时间" align="center" prop="limitTime" width="180"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180"/>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180"/>
      <el-table-column v-if="'济南联志健康'==signProjectName"  align="center" width="180" label="分公司配置商户号" prop="mchId" />
      <!--      <el-table-column label="主机重启时间" align="center" prop="restartTime" width="180" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="220px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['his:company:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleResetPwd(scope.row)"
            v-hasPermi="['his:company:pass']"
          >重置密码
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['his:company:remove']"
          >删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleRecharge(scope.row)"
            v-hasPermi="['his:company:recharge']"
          >充值
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDeduct(scope.row)"
            v-hasPermi="['his:company:deduct']"
          >扣款
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleRedRecharge(scope.row)"
            v-if="hstInfo !== 'hst'"
            v-hasPermi="['his:company:redRecharge']"
          >红包充值
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleRedDeduct(scope.row)"
            v-hasPermi="['his:company:redDeduct']"
            v-if="hstInfo !== 'hst'"
          >红包扣款
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleRevenue(scope.row)"
            v-hasPermi="['company:company:revenue']"
            v-if="hstInfo !== 'hst'"
          >分账配置</el-button>

          <el-button
            v-if="!scope.row.accountId && hstInfo !== 'hst'"
            size="mini"
            type="text"
            icon="el-icon-link"
            @click="handleBindXsy(scope.row)"

          >绑定销售易
          </el-button>

          <el-button
            v-if="scope.row.accountId && hstInfo !== 'hst'"
            size="mini"
            type="text"
            icon="el-icon-close"
            @click="handleUnbindXsy(scope.row)"
          >解绑销售易
          </el-button>


          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleRedPacket(scope.row)"
            v-hasPermi="['company:company:redPacket']"
            v-if="hstInfo !== 'hst'"
          >绑定红包商户</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleAppRedPacket(scope.row)"
            v-hasPermi="['company:company:AppRedPacket']"
            v-if="hstInfo !== 'hst'"
          >绑定app提现商户</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleSidebarChange(scope.row)"
            v-if="hstInfo !== 'hst'"
          >侧边栏封面设置</el-button>


        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改诊所管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>

      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="公司名称" prop="companyName">
          <el-input v-model="form.companyName" placeholder="请输入公司名称"/>
        </el-form-item>
        <el-form-item label="公司类型" prop="companyType">
          <el-select
            v-model="form.companyType"
            placeholder="请选择"
            clearable
            size="small"
          >
            <el-option
              v-for="item in companyTypeOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <!-- 所属部门 -->
        <el-form-item label="所属部门" prop="deptId" v-if="this.$store.state.user.medicalMallConfig.resource">
          <el-select
            v-model="form.deptId"
            placeholder="请选择"
            clearable
            size="small"
          >
            <el-option
              v-for="item in deptOptions"
              :key="item.deptId"
              :label="item.deptName"
              :value="item.deptId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商务负责人" prop="manager">
          <el-input v-model="form.manager" placeholder="请输入商务负责人"/>
        </el-form-item>
        <el-form-item label="联系人" prop="linkName">
          <el-input v-model="form.linkName" placeholder="请输入联系人"/>
        </el-form-item>
        <el-form-item label="联系电话" prop="companyMobile">
          <el-input v-model="form.companyMobile" placeholder="请输入联系电话"/>
        </el-form-item>
        <el-form-item label="员工数量" prop="limitUserCount">
          <el-input-number v-model="form.limitUserCount" :min="1" :max="10000"></el-input-number>
        </el-form-item>
        <el-form-item label="pad数量" prop="maxPadNum" v-if="this.$store.state.user.medicalMallConfig.resource">
          <el-input-number v-model="form.maxPadNum" :min="-1" :max="10000"></el-input-number>
          <span class="pad-tips">
            注：-1表示不做限制
          </span>
        </el-form-item>
        <el-form-item label="坐席数量" prop="voiceCallerNumber">
          <el-input-number v-model="form.voiceCallerNumber" :min="0" :max="10000"></el-input-number>
        </el-form-item>
        <el-form-item label="sip分机号" prop="sipExtNumIds">
          <div v-if="!form.sipExtNumIds || form.sipExtNumIds === ''">
            <el-button type="primary" size="small" icon="el-icon-plus" @click="handleAddSipExtNum">添加分机号</el-button>
          </div>
          <div v-else>
            <el-button type="primary" size="small" icon="el-icon-view" @click="handleViewSipExtNum">查看分机</el-button>
            <span style="margin-left: 10px; color: #909399;">{{ getSipExtNumDisplay() }}</span>
          </div>
        </el-form-item>
        <el-form-item label="管理员帐号" prop="userName" v-if="form.companyId==null">
          <el-input v-model="form.userName" placeholder="请输入管理员帐号"/>
        </el-form-item>
        <el-form-item label="管理员密码" prop="password" v-if="form.companyId==null">
          <el-input type="password" v-model="form.password" placeholder="请输入管理员密码"/>
        </el-form-item>
        <el-form-item label="掉线通知群名" prop="groupName">
          <el-input v-model="form.groupName" :maxlength="15" placeholder="请输入掉线通知群名"/>
        </el-form-item>
        <el-form-item label="地址" prop="companyAddress">
          <el-input v-model="form.companyAddress" placeholder="请输入地址"/>
        </el-form-item>
        <el-form-item label="套餐包分类" prop="packageCateIds">
          <el-select v-model="form.packageCateIds" multiple filterable placeholder="请选择套餐包分类"
                     style="width: 300px;"
          >
            <el-option
              v-for="item in cateList"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="随访医生" prop="followDoctorIds">
          <el-select v-model="form.followDoctorIds" multiple filterable placeholder="请选择随访医生"
                     style="width: 300px;"
          >
            <el-option
              v-for="item in followDoctorList"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="医生" prop="doctorIds">
          <el-select v-model="doctorIds" multiple filterable placeholder="请选择医生" style="width: 300px;">
            <el-option
              v-for="item in doctor"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictValue">{{ dict.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="通话API接口" prop="voiceApiId">
          <el-select
            v-model="form.voiceApiId"
            placeholder="请选择"
            clearable
            size="small"
          >
            <el-option
              v-for="item in voiceApis"
              :key="item.apiId"
              :label="item.apiName"
              :value="item.apiId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable size="small"
                          v-model="form.startTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择开始时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="到期时间" prop="limitTime">
          <el-date-picker clearable size="small"
                          v-model="form.limitTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择到期时间"
          >
          </el-date-picker>
        </el-form-item>
        <!--      <el-form-item label="主机重启时间" prop="restartTime" >-->
        <!--        <el-time-select style="width: 150px;" placeholder="主机重启时间（不填默认1点10分）" v-model="form.restartTime" :picker-options="{-->
        <!--                              start: '00:00',-->
        <!--                              step: '00:05',-->
        <!--                              end: '24:00'-->
        <!--                            }"></el-time-select>-->
        <!--      </el-form-item>-->
        <el-form-item label="自定义小程序" prop="customMiniAppId">
          <el-select
            v-model="form.customMiniAppId"
            placeholder="请选择自定义小程序"
            clearable
            size="small"
          >
            <el-option
              v-for="item in customAppList"
              :key="item.appId"
              :label="item.appName"
              :value="item.appId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="服务号点播配置" prop="courseMaAppId">
          <el-select
            v-model="form.courseMaAppId"
            placeholder="请选择服务号"
            clearable
            size="small"
          >
            <el-option
              v-for="item in maAppList"
              :key="item.appId"
              :label="item.appName"
              :value="item.appId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="小程序点播配置" prop="courseMiniAppId">
          <el-select
            v-model="form.courseMiniAppId"
            placeholder="请选择小程序"
            clearable
            size="small"
          >
            <el-option
              v-for="item in miniAppList"
              :key="item.appId"
              :label="item.appName"
              :value="item.appId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="主要小程序" prop="miniAppMaster">
          <el-select
            v-model="form.miniAppMaster"
            multiple
            :multiple-limit="1"
            placeholder="请选择"
            clearable
            size="small"
          >
            <el-option
              v-for="item in miniAppList"
              :key="item.appId"
              :label="item.appName"
              :value="item.appId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备用小程序" prop="miniAppServer">
          <el-select
            v-model="form.miniAppServer"
            multiple
            :multiple-limit="1"
            placeholder="请选择"
            clearable
            size="small"
          >
            <el-option
              v-for="item in miniAppList"
              :key="item.appId"
              :label="item.appName"
              :value="item.appId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="看课休息开关" >
          <el-radio-group v-model="form.isOpenRestReminder">
            <el-radio :label="1" >开</el-radio>
            <el-radio :label="0">关</el-radio>
          </el-radio-group>
          <span>（默认为空，走系统配置）</span>
        </el-form-item>




        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="请输入备注"/>
        </el-form-item>
         <el-form-item label="可用外呼网关" prop="showGatewayIds">
            <!-- <el-input v-model="" placeholder="请输入DeepSeekChat模型名称"></el-input> -->
             <el-select v-model="form.showGatewayIds" multiple filterable placeholder="请选择系统可见外呼网关">
              <el-option
                v-for="item in gatewayList"
                :key="item.id"
                :label="item.gwDesc"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="分账商户" prop="subMerchantId">
          <el-select
            v-model="form.subMerchantId"
            placeholder="请选择"
            clearable
            size="small"
          >
            <el-option
              v-for="item in subMerchantList"
              :key="item.id"
              :label="item.merchantName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>


      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :loading="submitFormLoading" >确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="侧边栏封面图" :visible.sync="sidebarFrom.open" width="500px" append-to-body>
      <image-upload v-model="sidebarFrom.imageUrl" :limit="1"/>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handSaveSidebarCompanyImage">提交</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="recharge.title" :visible.sync="recharge.open" width="500px" append-to-body>
      <el-form ref="rechargeForm" :rules="rechargeRules" :model="rechargeForm" label-width="80px">
        <el-form-item label="公司">
          <el-input v-model="rechargeForm.companyName" disabled/>
        </el-form-item>
        <el-form-item label="余额">
          <el-input v-model="rechargeForm.balance" disabled/>
        </el-form-item>
        <el-form-item label="充值金额" prop="money">
          <el-input-number v-model="rechargeForm.money" :min="0.01" placeholder="请输入充值金额"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="rechargeForm.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRechargeForm">确 定</el-button>
        <el-button @click="recharge.open=false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="redRecharge.title" :visible.sync="redRecharge.open" width="500px" append-to-body>
      <el-form ref="redRechargeForm" :rules="redRechargeRules" :model="redRechargeForm" label-width="80px">
        <el-form-item label="公司">
          <el-input v-model="redRechargeForm.companyName" disabled/>
        </el-form-item>
        <el-form-item label="余额">
          <el-input v-model="redRechargeForm.balance" disabled/>
        </el-form-item>
        <el-form-item label="充值金额" prop="money">
          <el-input-number v-model="redRechargeForm.money" :min="0.01" placeholder="请输入充值金额"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="redRechargeForm.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRedRechargeForm" :disabled="redSubmit">确 定</el-button>
        <el-button @click="redRecharge.open=false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="deduct.title" :visible.sync="deduct.open" width="500px" append-to-body>
      <el-form ref="deductForm" :rules="deductRules" :model="deductForm" label-width="80px">
        <el-form-item label="公司">
          <el-input v-model="deductForm.companyName" disabled/>
        </el-form-item>
        <el-form-item label="余额">
          <el-input v-model="deductForm.balance" disabled/>
        </el-form-item>
        <el-form-item label="扣款金额" prop="money">
          <el-input-number v-model="deductForm.money" :min="0.01" placeholder="请输入扣款金额"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="deductForm.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDeductForm">确 定</el-button>
        <el-button @click="deduct.open=false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="redDeduct.title" :visible.sync="redDeduct.open" width="500px" append-to-body>
      <el-form ref="redDeductForm" :rules="redDeductRules" :model="redDeductForm" label-width="80px">
        <el-form-item label="公司">
          <el-input v-model="redDeductForm.companyName" disabled/>
        </el-form-item>
        <el-form-item label="余额">
          <el-input v-model="redDeductForm.balance" disabled/>
        </el-form-item>
        <el-form-item label="扣款金额" prop="money">
          <el-input-number v-model="redDeductForm.money" :min="0.01" placeholder="请输入扣款金额"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="redDeductForm.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRedDeductForm">确 定</el-button>
        <el-button @click="redDeduct.open=false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="revenue.title" :visible.sync="revenue.open" width="800px" append-to-body>
      <el-form ref="revenueForm"  :model="revenueForm" label-width="150px">
        <el-form-item label="公司">
          <el-input v-model="revenueForm.companyName" disabled/>
        </el-form-item>

        <el-form-item label="开启分账">
          <el-switch
            v-model="revenueForm.divFlag"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-value="1"
            inactive-value="0"
          >
          </el-switch>
        </el-form-item>

        <el-form-item label="分账模式" v-if="revenueForm.divFlag == 1">
          <el-radio v-model="revenueForm.delayAcctFlag" label="N">实时分账</el-radio>
          <el-radio v-model="revenueForm.delayAcctFlag" label="Y">延时分账</el-radio>
        </el-form-item>
        <el-form-item label="是否使用百分比分账" v-if="revenueForm.divFlag == 1">
          <el-switch
            v-model="revenueForm.percentageFlag"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-value="Y"
            inactive-value="N"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="是否净值分账" v-if="revenueForm.percentageFlag == 'Y'">
          <el-switch
            v-model="revenueForm.iscCleanSplit"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-value="Y"
            inactive-value="N"
          >
          </el-switch>
        </el-form-item>
        <div v-if="revenueForm.divFlag == 1">
            <el-form-item label="分账接收方配置">
              <el-tooltip content="批量设置分账接收账户" placement="top">
                <el-button type="primary" icon="el-icon-plus" @click="addAcctInfo" style="margin-bottom: 5px;">
                  添加新接收方
                </el-button>
              </el-tooltip>

            </el-form-item>

            <div v-for="(account, index) in revenueForm.acctInfos" :key="index"
                 style="border: 1px solid #dcdfe6; padding: 20px; margin-bottom: 20px; border-radius: 4px;"
            >
              <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
                <div style="margin: 0; color: #409eff;">账户 {{ index + 1 }}</div>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeAcctInfo(index)"
                  v-if="revenueForm.acctInfos.length > 0"
                >
                  删除账户
                </el-button>
              </div>

              <el-form-item label="分账接收方ID" :prop="`acctInfos.${index}.huifuId`">
                <el-input v-model="account.huifuId"   placeholder="斗拱开户时生成；示例值：6666000123120001"></el-input>
              </el-form-item>
              <el-form-item label="账户号" :prop="`acctInfos.${index}.acctId`" >
                <el-input v-model="account.acctId"  placeholder="可指定账户号，仅支持基本户、现金户，不填默认为基本户；示例值：F00598600"></el-input>
              </el-form-item>

              <el-form-item label="分账百分比%" v-if="revenueForm.percentageFlag == 'Y'" :prop="`acctInfos.${index}.percentageDiv`"  >
                <el-input-number v-model="account.percentageDiv" :precision="2" :step="0.1" :min="0" :max="100" placeholder="示例值：23.50，表示23.50%。acct_infos中全部分账百分比之和必须为100.00%。"></el-input-number>
              </el-form-item>
              <el-form-item label="分账金额" v-if="revenueForm.percentageFlag == 'N'" :prop="`acctInfos.${index}.divAmt`"  >
                <el-input-number v-model="account.divAmt" :precision="2" :step="1" :min="0.01" placeholder="单位元，需保留小数点后两位，示例值：1.00 ，最低传入0.01"></el-input-number>
              </el-form-item>

            </div>
          </div>



      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRevenueForm">确 定</el-button>
        <el-button @click="revenue.open=false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 批量修改小程序 -->
    <el-dialog :title="miniProgram.title" :visible.sync="miniProgram.open" width="700px" append-to-body>

      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="小程序点播配置" prop="courseMiniAppId">
          <el-select
            v-model="form.courseMiniAppId"
            placeholder="请选择小程序"
            clearable
            size="small"
          >
            <el-option
              v-for="item in miniAppList"
              :key="item.appId"
              :label="item.appName"
              :value="item.appId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="主要小程序" prop="miniAppMaster">
          <el-select
            v-model="form.miniAppMaster"
            multiple
            :multiple-limit="1"
            placeholder="请选择"
            clearable
            size="small"
          >
            <el-option
              v-for="item in miniAppList"
              :key="item.appId"
              :label="item.appName"
              :value="item.appId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备用小程序" prop="miniAppServer">
          <el-select
            v-model="form.miniAppServer"
            multiple
            :multiple-limit="1"
            placeholder="请选择"
            clearable
            size="small"
          >
            <el-option
              v-for="item in miniAppList"
              :key="item.appId"
              :label="item.appName"
              :value="item.appId"
            />
          </el-select>
        </el-form-item>
      </el-form>


      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitMiniProgramForm">确 定</el-button>
        <el-button @click="cancelMiniProgram">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 绑定销售易账号 -->
    <!-- 绑定销售易账号 -->
    <el-dialog :title="xsyBindDialog.title" :visible.sync="xsyBindDialog.open" width="500px" append-to-body>
      <el-form ref="xsyBindFormRef" :model="xsyBindForm" label-width="100px">
        <el-form-item label="公司名称">
          <el-input v-model="xsyBindForm.companyName" disabled />
        </el-form-item>
        <el-form-item label="销售易账号" prop="accountId">
          <el-select
            v-model="xsyBindForm.accountId"
            filterable
            clearable
            placeholder="请选择销售易账号"
            style="width: 100%;"
            :loading="xsyBindDialog.loading"
          >
            <el-option
              v-for="item in xsyAccountList"
              :key="item.id"
              :label="item.accountName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBindXsy">确 定</el-button>
        <el-button @click="cancelBindXsy">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 红包商户配置   -->
    <el-dialog :title="redPacketConfigOpen.title" :visible.sync="redPacketConfigOpen.open" width="800px" append-to-body>
      <el-form ref="redPacketConfig" :model="redPacketConfig"  label-width="150px">
        <el-form-item   label="红包接口类型" prop="isNew">
          <el-radio-group v-model="redPacketConfig.isNew">
            <el-radio label="0">商家转账到零钱(旧)</el-radio>
            <el-radio label="1">商家转账(新)</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item   label="公众号appid" prop="appId">
          <el-input   v-model="redPacketConfig.appId"  label="请输入appId"></el-input>
        </el-form-item>
        <el-form-item   label="小程序appid" prop="appId">
          <el-input   v-model="redPacketConfig.miniappId"  label="请输入appId"></el-input>
        </el-form-item>
        <el-form-item   label="商户号" prop="mchId">
          <el-input   v-model="redPacketConfig.mchId"  label="请输入mchId"></el-input>
        </el-form-item>
        <el-form-item   label="商户密钥" prop="mchKey">
          <el-input   v-model="redPacketConfig.mchKey"  label="mchKey"></el-input>
        </el-form-item>
        <el-form-item   label="p12证书路径" prop="keyPath">
          <el-input   v-model="redPacketConfig.keyPath"  label="请输入keyPath"></el-input>
        </el-form-item>
        <el-form-item   label="apiV3密钥" prop="apiV3Key">
          <el-input   v-model="redPacketConfig.apiV3Key"  label="请输入apiV3Key"></el-input>
        </el-form-item>
        <el-form-item   label="公钥ID" prop="publicKeyId">
          <el-input   v-model="redPacketConfig.publicKeyId"  label="请输入公钥ID"></el-input>
        </el-form-item>
        <el-form-item   label="公钥证书" prop="publicKeyPath">
          <el-input   v-model="redPacketConfig.publicKeyPath"  label="请输入publicKeyPath"></el-input>
        </el-form-item>
        <el-form-item   label="key路径" prop="privateKeyPath">
          <el-input   v-model="redPacketConfig.privateKeyPath"  label="请输入"></el-input>
        </el-form-item>
        <el-form-item   label="cert路径" prop="privateCertPath">
          <el-input   v-model="redPacketConfig.privateCertPath"  label="请输入"></el-input>
        </el-form-item>
        <el-form-item   label="回调地址" prop="notifyUrl">
          <el-input   v-model="redPacketConfig.notifyUrl"  label="请输入"></el-input>
        </el-form-item>

        </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onSubmitCompanyRedPacket">提交</el-button>
      </div>
    </el-dialog>

    <!-- app提现配置   -->
    <el-dialog :title="hisAppRedPacketOpen.title" :visible.sync="hisAppRedPacketOpen.open" width="800px" append-to-body>
      <el-form ref="hisAppRedPacket" :model="hisAppRedPacket"  label-width="150px">
        <el-form-item   label="红包接口类型" prop="isNew">
          <el-radio-group v-model="hisAppRedPacket.isNew">
            <el-radio label="0">商家转账到零钱(旧)</el-radio>
            <el-radio label="1">商家转账(新)</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item   label="公众号appid" prop="appId">
          <el-input   v-model="hisAppRedPacket.appId"  label="请输入appId"></el-input>
        </el-form-item>
        <el-form-item   label="小程序appid" prop="appId">
          <el-input   v-model="hisAppRedPacket.miniappId"  label="请输入appId"></el-input>
        </el-form-item>
        <el-form-item   label="商户号" prop="mchId">
          <el-input   v-model="hisAppRedPacket.mchId"  label="请输入mchId"></el-input>
        </el-form-item>
        <el-form-item   label="商户密钥" prop="mchKey">
          <el-input   v-model="hisAppRedPacket.mchKey"  label="mchKey"></el-input>
        </el-form-item>
        <el-form-item   label="p12证书路径" prop="keyPath">
          <el-input   v-model="hisAppRedPacket.keyPath"  label="请输入keyPath"></el-input>
        </el-form-item>
        <el-form-item   label="apiV3密钥" prop="apiV3Key">
          <el-input   v-model="hisAppRedPacket.apiV3Key"  label="请输入apiV3Key"></el-input>
        </el-form-item>
        <el-form-item   label="公钥ID" prop="publicKeyId">
          <el-input   v-model="hisAppRedPacket.publicKeyId"  label="请输入公钥ID"></el-input>
        </el-form-item>
        <el-form-item   label="公钥证书" prop="publicKeyPath">
          <el-input   v-model="hisAppRedPacket.publicKeyPath"  label="请输入publicKeyPath"></el-input>
        </el-form-item>
        <el-form-item   label="key路径" prop="privateKeyPath">
          <el-input   v-model="hisAppRedPacket.privateKeyPath"  label="请输入"></el-input>
        </el-form-item>
        <el-form-item   label="cert路径" prop="privateCertPath">
          <el-input   v-model="hisAppRedPacket.privateCertPath"  label="请输入"></el-input>
        </el-form-item>
        <el-form-item   label="回调地址" prop="notifyUrl">
          <el-input   v-model="hisAppRedPacket.notifyUrl"  label="请输入"></el-input>
        </el-form-item>

        </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onSubmitAppRedPacket">提交</el-button>
      </div>
    </el-dialog>

    <!-- SIP分机号选择对话框 -->
    <el-dialog title="选择SIP分机号" :visible.sync="sipExtDialog.open" width="900px" append-to-body>
      <el-form :model="sipExtDialog.queryParams" ref="sipExtQueryForm" :inline="true" label-width="100px">
        <el-form-item label="分机号起始" prop="startExtNum">
          <el-input
            v-model="sipExtDialog.queryParams.startExtNum"
            placeholder="请输入起始分机号"
            clearable
            size="small"
            @keyup.enter.native="getSipExtList"
          />
        </el-form-item>
        <el-form-item label="分机号结束" prop="endExtNum">
          <el-input
            v-model="sipExtDialog.queryParams.endExtNum"
            placeholder="请输入结束分机号"
            clearable
            size="small"
            @keyup.enter.native="getSipExtList"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="getSipExtList">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetSipExtQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table
        v-loading="sipExtDialog.loading"
        :data="sipExtDialog.extList"
        @selection-change="handleSipExtSelectionChange"
        height="400"
        border
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="60" align="center" />
        <el-table-column label="分机号" align="center" prop="extNum" />
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <el-tag :type="'success'" size="small">
              空闲
            </el-tag>
          </template>
        </el-table-column>
      </el-table>

      <div v-if="sipExtDialog.selectedExts.length > 0" style="margin-top: 10px; text-align: center; color: #409EFF; font-size: 14px;">
        已选中 {{ sipExtDialog.selectedExts.length }} 条数据
      </div>

      <pagination
        v-show="sipExtDialog.total > 0"
        :total="sipExtDialog.total"
        :page.sync="sipExtDialog.queryParams.pageNum"
        :limit.sync="sipExtDialog.queryParams.pageSize"
        :page-sizes="[10, 100, 500]"
        @pagination="getSipExtList"
      />

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmSipExtSelection">确 定</el-button>
        <el-button @click="sipExtDialog.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看已选SIP分机号对话框 -->
    <el-dialog title="已选SIP分机号" :visible.sync="sipExtViewDialog.open" width="900px" append-to-body>
      <!-- 搜索条件 -->
      <el-form :model="sipExtViewDialog.queryParams" ref="sipExtViewQueryForm" :inline="true" label-width="100px" style="margin-bottom: 10px;">
        <el-form-item label="分机号" prop="extNum">
          <el-input
            v-model="sipExtViewDialog.queryParams.extNum"
            placeholder="请输入分机号"
            clearable
            size="small"
            @keyup.enter.native="handleSipExtViewSearch"
          />
        </el-form-item>
        <el-form-item label="销售名称" prop="userName">
          <el-input
            v-model="sipExtViewDialog.queryParams.userName"
            placeholder="请输入销售名称"
            clearable
            size="small"
            @keyup.enter.native="handleSipExtViewSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleSipExtViewSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetSipExtViewQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="sipExtViewDialog.loading" :data="sipExtViewDialog.pagedExtList" height="400" border @selection-change="handleSipExtViewSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="60" align="center" />
        <el-table-column label="分机号" align="center" prop="extNum" />
        <el-table-column label="分机密码" align="center" prop="extPass">
          <template slot-scope="scope">
            <span @click="togglePasswordVisibility(scope.$index)" style="cursor: pointer; user-select: none;">
              <i :class="scope.row.showPassword ? 'el-icon-view' : 'el-icon-lock'"></i>
              {{ scope.row.showPassword ? scope.row.extPass : '******' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="userCode">
          <template slot-scope="scope">
            <el-tag :type="scope.row.userCode ? 'danger' : 'success'" size="small">
              {{ scope.row.userCode ? '占用' : '空闲' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="绑定销售" align="center" prop="userCode" />
        <el-table-column label="操作" align="center" width="120">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-unlock"
              @click="handleUnbindSipExt(scope.row)"
            >解绑</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="sipExtViewDialog.total > 0"
        :total="sipExtViewDialog.total"
        :page.sync="sipExtViewDialog.pageNum"
        :limit.sync="sipExtViewDialog.pageSize"
        :page-sizes="[10, 100, 500]"
        @pagination="handleSipExtViewPageChange"
      />

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" icon="el-icon-plus" @click="handleAppendSipExt">添加分机号</el-button>
        <el-button
          type="danger"
          icon="el-icon-unlock"
          :disabled="sipExtViewDialog.selectedExts.length === 0"
          @click="handleBatchUnbindSipExt"
        >批量解绑({{ sipExtViewDialog.selectedExts.length }})</el-button>
        <el-button @click="sipExtViewDialog.open = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCompany,
  getCompany,
  delCompany,
  addCompany,
  updateCompany,
  recharge,
  redRecharge,
  deduct,
  redDeduct,
  exportCompany,
  resetPwd,
  getDivConfig,
  setDiv, exitMiniProgram,getGatewayCompanyList
} from '@/api/his/company'
import { getFollowDoctorList, getPrescribeDoctorSelect } from '@/api/his/doctor'
import { docList } from '@/api/his/doctor'
import { getVoiceApiList } from '@/api/company/companyVoiceApi'
import { editCompanyConfig,getCompanyConfigKey } from '@/api/company/companyConfig'
import { getCitysArea, getSidebarCompanyImage, saveSidebarCompanyImage } from '../../../api/company/company'
import { cateList } from '@/api/his/packageCate'
import { getConfigByKey } from '@/api/system/config'
import { listDept } from '@/api/system/dept'
import { listAll } from '@/api/course/coursePlaySourceConfig'
import{ getSignProjectName } from '@/api/course/qw/courseWatchLog'
import { listXsyAccount, bindXsyAccount, unbindXsyAccount } from '@/api/xsy/xsy'
import { merchantOptions } from "@/api/his/merchant";
import { companyBatchUnbindSipExt, getSipExtDetail, getUnBindExtnumPage } from '@/api/aiSipCall/aiSipCallUser'
export default {
  name: 'Company',
  data() {
    return {
      hstInfo: process.env.VUE_APP_FS_USER_INFO,
      uploadUrl:process.env.VUE_APP_BASE_API+"/common/uploadOSS",
      redPacketConfigOpen:{
        open: false,
        title: '红包商户配置'
      },

      hisAppRedPacketOpen:{
        open: false,
        title: 'app提现商户配置'
      },

      redPacketConfig:{},
      hisAppRedPacket:{},

      redPacketConfigForm:{},
      hisAppRedPacketForm:{},

      gatewayList:[],
      projectFrom:process.env.VUE_APP_HSY_SPACE,

      signProjectName:"",
      redSubmit: false,
      //分账参数
      revenue:{
          open: false,
          title: '分账配置'
      },
      revenueForm:{
        acctInfos: []
      },
      // 表单参数
      deductForm: {
        money: 0
      },
      // 表单参数
      redDeductForm: {
        money: 0
      },
      doctorIds: [],
      doctor: [],
      recharge: {
        open: false,
        title: '后台充值'
      },
      redRecharge: {
        open: false,
        title: '红包充值'
      },
      showRedPacket: false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 诊所管理表格数据
      companyList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 状态字典
      statusOptions: [],
      // 企业类型字典
      companyTypeOptions: [],
      //部门字典
      deptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyName: null,
        companyMobile: null,
        status: null,
        companyType: null,
        limitUserCount: null,
        maxPadNum: -1
      },
      voiceApis: [],
      // 表单参数
      rechargeForm: {
        money: 0
      },
      // 红包充值表单参数
      redRechargeForm: {
        money: 0
      },
      followDoctorList: [],
      cateList: [],
      // 表单参数
      form: {
        restartTime: '13:10',
        customMiniAppId: null,
        courseMaAppId: null,
        courseMiniAppId: null,
        miniAppMaster: [],
        miniAppServer: [],
        miniAppList: []
      },
      // 表单校验
      rules: {
        companyName: [
          { required: true, message: '公司名称不能为空', trigger: 'blur' }
        ],
        companyType: [
          { required: true, message: '公司类型不能为空', trigger: 'blur' }
        ],
        companyMobile: [
          { required: true, message: '公司电话不能为空', trigger: 'blur' }
        ],
        companyAddress: [
          { required: true, message: '公司地址不能为空', trigger: 'blur' }
        ],
        limitUserCount: [
          { required: true, message: '用户数量不能为空', trigger: 'blur' }
        ],
        maxPadNum: [
          { required: true, message: '最大Pad数量不能为空', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '状态不能为空', trigger: 'blur' }
        ],
        startTime: [
          { required: true, message: '开始时间不能为空', trigger: 'blur' }
        ],
        limitTime: [
          { required: true, message: '到期时间不能为空', trigger: 'blur' }
        ],
        userName: [
          { required: true, message: '管理员账号不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '管理员密码不能为空', trigger: 'blur' },
          {
            pattern: /^(?=.*[A-Za-z])(?=.*\d)(?=.*[^A-Za-z0-9]).{8,20}$/,
            message: '密码长度为8-20 位，必须包含字母、数字和特殊字符',
            trigger: ['blur', 'change']
          }
        ],
        manager: [
          { required: true, message: '商务负责人不能为空', trigger: 'blur' }
        ],
        linkName: [
          { required: true, message: '联系人不能为空', trigger: 'blur' }
        ]
        // followDoctorIds: [
        //   { required: true, message: "不能为空", trigger: "blur" }
        // ],
        // packageCateIds: [
        //    { required: true, message: "套餐包分类不能为空", trigger: "blur" }
        //  ],
      },
      // 表单校验
      deductRules: {
        money: [
          { required: true, message: '扣款金额不能为空', trigger: 'blur' }
        ]
      },
      // 表单校验
      redDeductRules: {
        money: [
          { required: true, message: '扣款金额不能为空', trigger: 'blur' }
        ]
      },
      rechargeRules: {
        money: [
          { required: true, message: '扣款金额不能为空', trigger: 'blur' }
        ]
      },
      redRechargeRules: {
        money: [
          { required: true, message: '扣款金额不能为空', trigger: 'blur' }
        ]
      },
      deduct: {
        open: false,
        title: '后台扣款'
      },
      redDeduct: {
        open: false,
        title: '红包扣款'
      },
      maAppList: [],
      miniAppList: [],
      customAppList: [],
      //分账参数
      miniProgram:{
        open: false,
        title: '批量修改小程序'
      },
      // 销售易绑定弹窗
      xsyBindDialog: {
        open: false,
        title: '绑定销售易账号',
        loading: false
      },
      // 销售易账号列表
      xsyAccountList: [],
      // 绑定表单
      xsyBindForm: {
        companyId: null,
        companyName: '',
        accountId: null
      },
      subMerchantList: [],

      //侧边栏图片
      sidebarFrom:{
        open:false,
        companyId:null,
        imageUrl:null
      },
      submitFormLoading:false,
      // SIP分机号选择对话框
      sipExtDialog: {
        open: false,
        loading: false,
        extList: [],
        total: 0,
        selectedExts: [],
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          startExtNum: null,
          endExtNum: null
        }
      },
      // 查看已选SIP分机号对话框
      sipExtViewDialog: {
        open: false,
        extList: [],
        pagedExtList: [],
        pageNum: 1,
        pageSize: 10,
        total: 0,
        loading: false,
        selectedExts: [],
        queryParams: {
          extNum: null,
          userName: null
        }
      },
      // 原始sipExtNumIds值（用于比较新旧值）
      originalSipExtNumIds: null
    }
  },
  created() {
    merchantOptions().then(res=>{
      this.subMerchantList = res.data;
    });
    getGatewayCompanyList().then(res=>{
        this.gatewayList = res.data;
    }).catch(res=>{});

    cateList().then((response) => {
      if (this.projectFrom =='mengniu-2114522511'){

        this.getDicts('store_product_package_cate').then(response => {
          this.cateList = response.data
        })
      }else {
        this.cateList = response.rows
      }
    })

    getSignProjectName()
    .then(res=>{
      this.signProjectName = res.signProjectName;
    })
    .catch(res=>{})
    this.getList()
    this.getDicts('sys_company_status').then(response => {
      this.statusOptions = response.data
    })
    this.getDicts('sys_company_type').then(response => {
      this.companyTypeOptions = response.data
    })
    getVoiceApiList().then((response) => {
      this.voiceApis = response.data
    })
    getFollowDoctorList().then((response) => {
      this.followDoctorList = response.rows
    })
    // cateList().then((response) => {
    //   this.cateList = response.rows
    // })

    listDept().then(response => {
      this.deptOptions = response.data
    })
    getConfigByKey("course.config").then(response => {
      if(response.data && response.data.configValue) {
        const  config = JSON.parse(response.data.configValue);
        if( config.isRedPackageBalanceDeduction && config.isRedPackageBalanceDeduction==1){
          this.showRedPacket=true
        }
      } else {
        this.showRedPacket = false;
      }
    });
    docList().then(response => {
      this.doctor = response.rows
    })
  },
  methods: {
    // 添加分账账户
    addAcctInfo() {
      this.revenueForm.acctInfos.push({
        huifuId: '',
        acctId: '',
        percentageDiv: null,
        divAmt: null
      })
    },
    // 删除接收方账户
    removeAcctInfo(index) {
      this.$confirm('确认删除该接收方账户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.revenueForm.acctInfos.splice(index, 1)
        this.$message.success('删除成功')
      }).catch(() => {
      })
    },
    handleRevenue(row){
      const companyId = row.companyId
      //查询配置
      this.revenueForm.isAdd = 1
      getDivConfig(companyId).then(response => {
        if(response.data){
          this.revenueForm = response.data
          if(response.data.acctInfos == null){
            this.revenueForm.acctInfos = []
          }
          if(response.data.divFlag){
            this.revenueForm.divFlag = String(response.data.divFlag)
          }
        }
      })
      this.revenueForm.companyId = companyId
      this.revenueForm.companyName = row.companyName
      if(row.divFlag){
        this.revenueForm.divFlag == "0"
      }
      this.revenue.open = true
    },
    handleRecharge(row) {
      const companyId = row.companyId
      this.rechargeForm.companyId = row.companyId
      this.rechargeForm.companyName = row.companyName
      this.rechargeForm.balance = row.money
      this.rechargeForm.money = null
      this.recharge.open = true
    },
    // 红包充值
    handleRedRecharge(row) {
      this.redSubmit=false
      this.redRechargeForm.companyId = row.companyId
      this.redRechargeForm.companyName = row.companyName
      this.redRechargeForm.balance = row.redPackageMoney
      this.redRechargeForm.money = null
      this.redRecharge.open = true
    },
    handleDeduct(row) {
      const companyId = row.companyId
      this.deductForm.companyId = row.companyId
      this.deductForm.companyName = row.companyName
      this.deductForm.balance = row.money
      this.deductForm.money = null
      this.deduct.open = true
    },
    handleRedDeduct(row) {
      this.redDeductForm.companyId = row.companyId
      this.redDeductForm.companyName = row.companyName
      this.redDeductForm.balance = row.redPackageMoney
      this.redDeductForm.money = null
      this.redDeduct.open = true
    },
    /** 提交按钮 */
    submitRechargeForm() {
      this.$refs['rechargeForm'].validate(valid => {
        if (valid) {
          recharge(this.rechargeForm).then(response => {
            if (response.code === 200) {
              this.msgSuccess(response.msg)
              this.recharge.open = false
              this.getList()
            }
          })
        }
      })
    },
    /** 红包充值提交按钮 */
    submitRedRechargeForm() {
      this.$refs['redRechargeForm'].validate(valid => {
        if (valid) {
          this.redSubmit=true
          redRecharge(this.redRechargeForm).then(response => {
            if (response.code === 200) {
              this.msgSuccess(response.msg)
              this.redRecharge.open = false
              this.getList()
            }
          })
        }
      })
    },
    submitRevenueForm(){
      var param = this.revenueForm;
      if(param.companyId && param.divFlag){
        setDiv(param).then(response => {
            if (response.code === 200) {
              this.msgSuccess(response.msg)
              this.revenue.open = false
              this.getList()
            }
          })
      }
    },
    /** 提交按钮 */
    submitDeductForm() {
      this.$refs['deductForm'].validate(valid => {
        if (valid) {
          deduct(this.deductForm).then(response => {
            if (response.code === 200) {
              this.msgSuccess(response.msg)
              this.deduct.open = false
              this.getList()
            }
          })
        }
      })
    },
    /** 提交按钮 */
    submitRedDeductForm() {
      this.$refs['redDeductForm'].validate(valid => {
        if (valid) {
          redDeduct(this.redDeductForm).then(response => {
            if (response.code === 200) {
              this.msgSuccess(response.msg)
              this.redDeduct.open = false
              this.getList()
            }
          })
        }
      })
    },

    onSubmitAppRedPacket(){
      this.hisAppRedPacketForm.configValue=JSON.stringify(this.hisAppRedPacket);
          editCompanyConfig(this.hisAppRedPacketForm).then(response => {
            if (response.code === 200) {
              this.msgSuccess("修改成功");
              this.hisAppRedPacketOpen.open=false;
            }
          })

    },

    onSubmitCompanyRedPacket(){
      this.redPacketConfigForm.configValue=JSON.stringify(this.redPacketConfig);
          editCompanyConfig(this.redPacketConfigForm).then(response => {
            if (response.code === 200) {
              this.msgSuccess("修改成功");
              this.redPacketConfigOpen.open=false;
            }
          })
    },
    getList() {
      this.loading = true
      listCompany(this.queryParams).then(response => {
        this.companyList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        companyId: null,
        companyName: null,
        companyMobile: null,
        companyAddress: null,
        addressId: null,
        createTime: null,
        updateTime: null,
        status: 0,
        startTime: null,
        limitTime: null,
        restartTime: '13:10',
        balance: null,
        companyType: null,
        groupName: null,
        userId: null,
        remark: null,
        isOpenRestReminder: null,
        linkName: null,
        limitUserCount: null,
        maxPadNum: -1,
        miniAppMaster: [],
        miniAppList: [],
        isDel: null,
        courseMaAppId: null,
        courseMiniAppId: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },

    handleResetPwd(row) {
      const companyIds = row.companyId || this.ids
      this.$confirm('是否确认重复密码为cq654321!!', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return resetPwd(companyIds)
      }).then(() => {
        this.getList()
        this.msgSuccess('修改成功')
      }).catch(function() {
      })

    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.companyId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.getAppList(null)
      this.open = true
      this.doctorIds = []
      this.title = '添加公司'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const companyId = row.companyId || this.ids
      this.reset()
      this.getAppList(companyId)
      this.doctorIds = []
      getCompany(companyId).then(async response => {
        // 获取处方医生列表
        await getPrescribeDoctorSelect().then((response) => {
          this.prescribeDoctorList = response.data || [];
          this.prescribeDoctorList = this.prescribeDoctorList.map(doctor => ({
            ...doctor,
            doctorId: Number(doctor.doctorId),
            doctorName: doctor.doctorName || '未指定'
          }));

        });

        this.form = response.data;

        // 保存原始的sipExtNumIds值（确保有值时才赋值）
        if (this.form.sipExtNumIds && this.form.sipExtNumIds !== '') {
          this.originalSipExtNumIds = this.form.sipExtNumIds;
        } else {
          this.originalSipExtNumIds = null;
        }

        this.open = true;
        this.title = "修改公司";

        if(this.form.status != null){
          this.form.status = String(this.form.status);
        }

        // ✅ 修复：简化医生IDs处理
        if(this.form.doctorIds != null && this.form.doctorIds !== ''){
          if(typeof this.form.doctorIds === 'string'){
            this.form.doctorIds = this.form.doctorIds.split(',').map(id => Number(id));
          }
        } else {
          this.form.doctorIds = [];
        }

        // ✅ 修复：简化处方医生IDs处理
        if(this.form.prescribeDoctorIds != null && this.form.prescribeDoctorIds !== ''){
          if(typeof this.form.prescribeDoctorIds === 'string'){
            this.form.prescribeDoctorIds = this.form.prescribeDoctorIds.split(',').map(id=> Number(id))
          }
        } else {
          this.form.prescribeDoctorIds = [];
        }

        // 其他字段处理
        if(this.form.followDoctorIds != null && this.form.followDoctorIds !== ''){
          try {
            this.form.followDoctorIds = JSON.parse(this.form.followDoctorIds);
          } catch(e) {
            this.form.followDoctorIds = [];
          }
        } else {
          this.form.followDoctorIds = [];
        }
        if(this.form.packageCateIds != null && this.form.packageCateIds !== ''){
          try {
            this.form.packageCateIds = JSON.parse(this.form.packageCateIds);
          } catch(e) {
            this.form.packageCateIds = [];
          }
        } else {
          this.form.packageCateIds = [];
        }

        if(this.form.companyType != null){
          this.form.companyType = String(this.form.companyType);
        }

      });
    },
    getAppList(companyId) {
      this.maAppList = []
      this.miniAppList = []
      this.customAppList = []
      listAll().then(response => {
        const { code, data } = response
        if (code === 200) {
          if (data) {
            this.maAppList = data.filter(v => v.type == 2).map(v => {
              return { appId: v.appid, appName: v.name }
            })
            this.miniAppList = data.filter(v => v.type == 1).map(v => {
              return { appId: v.appid, appName: v.name }
            })
            this.customAppList = data.filter(v => v.type == 3).map(v => {
              return { appId: v.appid, appName: v.name }
            })
          }
        }
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {

          // 创建提交数据的副本，避免修改原始表单数据
          const submitData = { ...this.form };

          // 添加原始sipExtNumIds值到提交数据中
          submitData.originalSipExtNumIds = this.originalSipExtNumIds;

          // 处理随访医生
          if(submitData.followDoctorIds != null){
            submitData.followDoctorIds = JSON.stringify(submitData.followDoctorIds);
          }

          // 处理套餐包分类
          if(submitData.packageCateIds != null){
            submitData.packageCateIds = JSON.stringify(submitData.packageCateIds);
          }

          // ✅ 修复：正确处理医生IDs - 不修改原始表单数据
          if(this.form.doctorIds != null && this.form.doctorIds.length > 0){
            submitData.doctorIds = this.form.doctorIds.join(',')
          } else {
            submitData.doctorIds = '';
          }

          // 处理sipExtNumIds字段：如果不为空，进行从小到大排序后再组成字符串
          if (submitData.sipExtNumIds && submitData.sipExtNumIds !== '') {
            // 将逗号分隔的字符串拆分为数组
            const extNumArray = submitData.sipExtNumIds.split(',').filter(id => id.trim() !== '');
            // 转换为数字并排序（从小到大）
            const sortedExtNums = extNumArray.map(Number).sort((a, b) => a - b);
            // 重新组合为字符串
            submitData.sipExtNumIds = sortedExtNums.join(',');
          }

          this.submitFormLoading = true;
          if (submitData.companyId != null) {
            updateCompany(submitData).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.submitFormLoading = false;
            }).catch(res=>{
              this.submitFormLoading = false;
            });
          } else {
            addCompany(submitData).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.submitFormLoading = false;
            }).catch(res=>{
              this.submitFormLoading = false;
            });
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const companyIds = row.companyId || this.ids
      this.$confirm('是否确认删除公司管理编号为"' + companyIds + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delCompany(companyIds)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有公司管理数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.exportLoading = true
        return exportCompany(queryParams)
      }).then(response => {
        this.download(response.msg)
        this.exportLoading = false
      }).catch(() => {
      })
    },
    padNumFormatter(row){
      // console.log(row.maxPadNum.type)
      return row.maxPadNum === -1 ? '不限' : row.maxPadNum
    },
    handleMiniProgram() {
      this.getAppList(null);
      this.miniProgram.open = true;
      this.form = {
        ...this.form,
        courseMiniAppId:null,
        miniAppMaster: null,
        miniAppServer: null
      };
    },
    // 取消按钮
    cancelMiniProgram() {
      this.miniProgram.open = false;
      this.reset()
    },
    submitMiniProgramForm(){
      this.form.ids = this.ids;
      exitMiniProgram(this.form).then(response => {
        if (response.code === 200) {
          this.miniProgram.open = false;
          this.msgSuccess('修改小程序成功')
          this.getList()
        }
      });
    },
    // 打开绑定销售易账号弹窗
    handleBindXsy(row) {
      this.xsyBindForm = {
        companyId: row.companyId,
        companyName: row.companyName,
        accountId: null
      }
      this.xsyAccountList = []
      this.xsyBindDialog.open = true
      this.xsyBindDialog.loading = true

      listXsyAccount({
        pageNum: 1,
        pageSize: 9999
      }).then(res => {
        this.xsyAccountList = res.rows || []
      }).finally(() => {
        this.xsyBindDialog.loading = false
      })
    },

    // 取消绑定
    cancelBindXsy() {
      this.xsyBindDialog.open = false
      this.xsyBindForm = {
        companyId: null,
        companyName: '',
        accountId: null
      }
    },

    // 提交绑定
    submitBindXsy() {
      if (!this.xsyBindForm.accountId) {
        this.$message.warning('请选择销售易账号')
        return
      }

      bindXsyAccount({
        companyId: this.xsyBindForm.companyId,
        accountId: this.xsyBindForm.accountId
      }).then(res => {
        if (res.code === 200) {
          this.msgSuccess('绑定成功')
          this.xsyBindDialog.open = false
          this.getList()
        }
      })
    },



    // 解绑销售易账号
    handleUnbindXsy(row) {
      this.$confirm('是否确认解绑当前销售易账号？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return unbindXsyAccount({
          companyId: row.companyId,
          accountId: row.accountId
        })
      }).then(res => {
        if (res.code === 200) {
          this.msgSuccess('解绑成功')
          this.getList()
        }
      }).catch(() => {})
    },

    handleRedPacket(row){
      const companyId=row.companyId;

      getCompanyConfigKey('redPacket:config',companyId).then(res=>{
        if(res.data.configValue!=null){
          this.redPacketConfig=JSON.parse(res.data.configValue);
        }
        this.redPacketConfigForm.configId=res.data.configId;
        this.redPacketConfigOpen.open=true;
      })
    },

    handleAppRedPacket(row){
      const companyId=row.companyId;

      getCompanyConfigKey('his:AppRedPacket',companyId).then(res=>{
        if(res.data.configValue!=null){
          this.hisAppRedPacket=JSON.parse(res.data.configValue);
        }
        this.hisAppRedPacketForm.configId=res.data.configId;
        this.hisAppRedPacketOpen.open=true;
      })
    },

    handleSidebarChange(row){
      const companyId=row.companyId;
      getSidebarCompanyImage(companyId).then(res=>{
          this.sidebarFrom.imageUrl=res.imageUrl;
          this.sidebarFrom.companyId=companyId;
          this.sidebarFrom.open=true;
      })
    },

    handSaveSidebarCompanyImage(){

      const param={
        companyId:this.sidebarFrom.companyId,
        imageUrl:this.sidebarFrom.imageUrl
      }

      saveSidebarCompanyImage(param).then(res=>{
        this.sidebarFrom.open=false;
        this.$message.success("保存成功");
      })
    },
    /** 获取SIP分机号显示文本 */
    getSipExtNumDisplay() {
      if (!this.form.sipExtNumIds || this.form.sipExtNumIds === '') {
        return '';
      }
      const exts = this.form.sipExtNumIds.split(',');
      if (exts.length <= 5) {
        return exts.join(', ');
      }
      return exts.slice(0, 5).join(', ') + `...等${exts.length}个`;
    },
    /** 添加SIP分机号 */
    handleAddSipExtNum() {
      this.sipExtDialog.selectedExts = [];
      this.sipExtDialog.queryParams = {
        pageNum: 1,
        pageSize: 10,
        startExtNum: null,
        endExtNum: null
      };
      this.sipExtDialog.open = true;
      this.getSipExtList();
    },
    /** 查看已选SIP分机号 */
    handleViewSipExtNum() {
      if (!this.form.sipExtNumIds || this.form.sipExtNumIds === '') {
        this.$message.warning('暂无已选分机号');
        return;
      }
      const extIds = this.form.sipExtNumIds.split(',').filter(id => id);
      // 保存所有分机号ID
      this.sipExtViewDialog.extList = extIds;
      // 设置总数
      this.sipExtViewDialog.total = extIds.length;
      // 重置页码
      this.sipExtViewDialog.pageNum = 1;
      this.sipExtViewDialog.open = true;
      // 加载第一页数据
      this.loadSipExtDetailPage();
    },
    /** 追加SIP分机号 */
    handleAppendSipExt() {
      this.sipExtViewDialog.open = false;
      this.handleAddSipExtNum();
    },
    /** 获取SIP分机号列表 */
    getSipExtList() {
      this.sipExtDialog.loading = true;
      getUnBindExtnumPage(this.sipExtDialog.queryParams).then(response => {
        this.sipExtDialog.extList = response.rows || [];
        this.sipExtDialog.total = response.total || 0;
        this.sipExtDialog.loading = false;
      }).catch(() => {
        this.sipExtDialog.loading = false;
      });
    },
    /** 重置SIP分机号查询 */
    resetSipExtQuery() {
      this.sipExtDialog.queryParams = {
        pageNum: 1,
        pageSize: 10,
        startExtNum: null,
        endExtNum: null
      };
      this.getSipExtList();
    },
    /** SIP分机号选择变化 */
    handleSipExtSelectionChange(selection) {
      this.sipExtDialog.selectedExts = selection.map(item => item.extNum);
    },
    /** 确认选择SIP分机号 */
    confirmSipExtSelection() {
      if (this.sipExtDialog.selectedExts.length === 0) {
        this.$message.warning('请至少选择一个分机号');
        return;
      }

      // 如果是从查看对话框过来的，需要追加
      if (this.form.sipExtNumIds && this.form.sipExtNumIds !== '') {
        const existingExts = this.form.sipExtNumIds.split(',').filter(id => id);
        const newExts = [...new Set([...existingExts, ...this.sipExtDialog.selectedExts])];
        this.form.sipExtNumIds = newExts.join(',');
      } else {
        this.form.sipExtNumIds = this.sipExtDialog.selectedExts.join(',');
      }

      this.sipExtDialog.open = false;
      this.$message.success(`已选择${this.sipExtDialog.selectedExts.length}个分机号`);
    },
    /** 加载当前页的分机号详细信息 */
    loadSipExtDetailPage() {
      if (!this.sipExtViewDialog.extList || this.sipExtViewDialog.extList.length === 0) {
        this.sipExtViewDialog.pagedExtList = [];
        return;
      }

      this.sipExtViewDialog.loading = true;

      // 如果userName有值，则传入所有分机号；否则只传入当前页的分机号
      let extNumIds;
      if (this.sipExtViewDialog.queryParams.userName) {
        // 将所有分机号字符串数组转换为Long数组
        extNumIds = this.sipExtViewDialog.extList.map(extNum => Number(extNum));
      } else {
        // 计算当前页的分机号
        const start = (this.sipExtViewDialog.pageNum - 1) * this.sipExtViewDialog.pageSize;
        const end = start + this.sipExtViewDialog.pageSize;
        const currentPageExts = this.sipExtViewDialog.extList.slice(start, end);
        // 将分机号字符串数组转换为Long数组
        extNumIds = currentPageExts.map(extNum => Number(extNum));
      }

      // 构建请求参数对象
      const params = {
        pageNum: 1,
        pageSize: 100,
        sipExtNumList: extNumIds,
        userCode:this.sipExtViewDialog.queryParams.userName,
        extNum: this.sipExtViewDialog.queryParams.extNum
      };

      // 调用后端接口获取详细信息
      getSipExtDetail(params).then(response => {
        if (response.code === 0) {
          this.sipExtViewDialog.pagedExtList = response.rows || [];
        } else {
          this.$message.error(response.msg || '获取分机号详细信息失败');
          this.sipExtViewDialog.pagedExtList = [];
        }
        this.sipExtViewDialog.loading = false;
      }).catch(error => {
        console.error('获取分机号详细信息失败:', error);
        this.$message.error('获取分机号详细信息失败');
        this.sipExtViewDialog.pagedExtList = [];
        this.sipExtViewDialog.loading = false;
      });
    },
    /** 处理分机号查看对话框分页变化 */
    handleSipExtViewPageChange() {
      // 分页变化时，重新加载当前页数据
      this.loadSipExtDetailPage();
    },
    /** 切换密码显示/隐藏 */
    togglePasswordVisibility(index) {
      if (this.sipExtViewDialog.pagedExtList[index]) {
        this.$set(this.sipExtViewDialog.pagedExtList[index], 'showPassword',
          !this.sipExtViewDialog.pagedExtList[index].showPassword);
      }
    },
    /** 搜索已选分机号 */
    handleSipExtViewSearch() {
      // 重置页码
      this.sipExtViewDialog.pageNum = 1;
      // 重新加载数据
      this.loadSipExtDetailPage();
    },
    /** 重置已选分机号查询 */
    resetSipExtViewQuery() {
      this.sipExtViewDialog.queryParams = {
        extNum: null,
        userName: null
      };
      this.sipExtViewDialog.pageNum = 1;
      this.loadSipExtDetailPage();
    },
    /** SIP分机号查看对话框选择变化 */
    handleSipExtViewSelectionChange(selection) {
      this.sipExtViewDialog.selectedExts = selection.map(item => item);
    },
    /** 格式化分机号显示（最多显示3个，超过用...标识） */
    formatExtNumsDisplay(extList) {
      if (!extList || extList.length === 0) {
        return '';
      }
      const extNums = extList.map(item => item.extNum || item);
      if (extNums.length <= 3) {
        return extNums.join(', ');
      }
      return `${extNums.slice(0, 3).join(', ')}...等${extNums.length}个`;
    },
    /** 执行批量解绑操作（统一入口） */
    executeBatchUnbind(extList) {
      if (!extList || extList.length === 0) {
        this.$message.warning('请至少选择一个分机号');
        return;
      }

      // 格式化显示的分机号
      const displayText = this.formatExtNumsDisplay(extList);
      const totalCount = extList.length;

      this.$confirm(`是否确认解绑以下分机号？\n${displayText}\n共 ${totalCount} 个分机需解绑`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        // 获取当前公司的ID
        const companyId = this.form.companyId;

        if (!companyId) {
          this.$message.error('无法获取公司ID，请刷新页面后重试');
          return;
        }

        // 构建包含extNum、userCode和companyId的对象数组
        const extListParams = extList.map(item => {
          return {
            extNum: item.extNum,
            userCode: item.userCode || ''
          };
        });

        companyBatchUnbindSipExt(companyId,extListParams).then(response => {
          if (response.code === 200) {
            this.msgSuccess("解绑成功");

            // 清空选中项
            this.sipExtViewDialog.selectedExts = [];

            // 重新从后端获取公司最新信息，确保数据实时同步
            getCompany(companyId).then(companyResponse => {
              if (companyResponse.code === 200 && companyResponse.data) {
                // 更新公司的分机号列表
                const newSipExtNumIds = companyResponse.data.sipExtNumIds || '';
                this.form.sipExtNumIds = newSipExtNumIds;

                // 重新初始化extList
                if (newSipExtNumIds && newSipExtNumIds !== '') {
                  const extIds = newSipExtNumIds.split(',').filter(id => id);
                  this.sipExtViewDialog.extList = extIds;
                  this.sipExtViewDialog.total = extIds.length;
                } else {
                  this.sipExtViewDialog.extList = [];
                  this.sipExtViewDialog.total = 0;
                }

                // 调整页码
                const totalPages = Math.ceil(this.sipExtViewDialog.total / this.sipExtViewDialog.pageSize);
                if (this.sipExtViewDialog.pageNum > totalPages && totalPages > 0) {
                  this.sipExtViewDialog.pageNum = totalPages;
                } else if (totalPages === 0) {
                  this.sipExtViewDialog.pageNum = 1;
                }

                // 刷新当前页数据
                this.loadSipExtDetailPage();
              } else {
                this.$message.error('获取公司信息失败');
              }
            }).catch(error => {
              console.error('获取公司信息失败:', error);
              this.$message.error('获取公司信息失败');
            });
          } else {
            this.$message.error(response.msg || '解绑失败');
          }
        }).catch(error => {
          this.$message.error('解绑失败：'+ error);
        });

      }).catch(() => {});
    },
    /** 单个解绑SIP分机号 */
    handleUnbindSipExt(row) {
      // 将单个分机号包装成数组，调用统一的批量解绑方法
      this.executeBatchUnbind([row]);
    },
    /** 批量解绑SIP分机号 */
    handleBatchUnbindSipExt() {
      if (this.sipExtViewDialog.selectedExts.length === 0) {
        this.$message.warning('请至少选择一个分机号');
        return;
      }
      // 调用统一的批量解绑方法
      this.executeBatchUnbind(this.sipExtViewDialog.selectedExts);
    }

  }
}
</script>
<style scoped>
.pad-tips {
  color: #999;
  font-size: 12px;
  height: 50px;
}
</style>
