<template>
  <div class="app-container">
    <!-- 员工账户统计 -->
    <el-row :gutter="16" class="account-stats-row" v-if="accountStats">
      <el-col :span="8">
        <el-card shadow="never" class="stats-card">
          <div class="stats-card-label">已购员工账户</div>
          <div class="stats-card-number">{{ accountStats.purchasedCount }}</div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="never" class="stats-card">
          <div class="stats-card-label">已使用账号数</div>
          <div class="stats-card-number">{{ accountStats.usedCount }}</div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="never" class="stats-card">
          <div class="stats-card-label">剩余可用账号</div>
          <div class="stats-card-bottom">
            <span class="stats-card-number" :class="{ 'text-danger': accountStats.remainingCount === 0 }">{{ accountStats.remainingCount }}</span>
            <el-button type="primary" size="mini">购买</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
      <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
            v-if="showRedPacket"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleRedRecharge(scope.row)"
            v-hasPermi="['his:company:redRecharge']"
          >红包充值
          </el-button>
          <el-button
            v-if="showRedPacket"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleRedDeduct(scope.row)"
            v-hasPermi="['his:company:redDeduct']"
          >红包扣款
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleRevenue(scope.row)"
            v-hasPermi="['company:company:revenue']"
          >分账配置</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="管理员帐号" 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>


      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</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: 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>

  </div>
</template>

<script>
import {
  listCompany,
  getCompany,
  delCompany,
  addCompany,
  updateCompany,
  recharge,
  redRecharge,
  deduct,
  redDeduct,
  exportCompany,
  resetPwd,
  getDivConfig,
  setDiv, exitMiniProgram,
  getGatewayCompanyList,
  getAccountStats
} from '@/api/his/company'
import { getFollowDoctorList } from '@/api/his/doctor'
import { docList } from '@/api/his/doctor'
import { getVoiceApiList } from '@/api/company/companyVoiceApi'
import { getCitysArea } 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'
export default {
  name: 'Company',
  data() {
    return {
      gatewayList:[],
      // 员工账户使用统计
      accountStats: null,
      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: '批量修改小程序'
      },
    }
  },
  created() {

    getGatewayCompanyList().then(res=>{
        this.gatewayList = res.data;
        console.log(this.gatewayList);
    }).catch(res=>{});
    getSignProjectName()
    .then(res=>{
      this.signProjectName = res.signProjectName;
    })
    .catch(res=>{console.log("getSignProjectName Err")})
    this.getAccountStats()
    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() {
      console.log("-----------------",this.revenueForm)
      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;
      console.log("--------------",param)
      if(param.companyId && param.divFlag){
        setDiv(param).then(response => {
            if (response.code === 200) {
              this.msgSuccess(response.msg)
              this.revenue.open = false
              this.getList()
            }
          })
        console.log("--------------",param)
      }
    },
    /** 提交按钮 */
    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()
            }
          })
        }
      })
    },

    getList() {
      this.loading = true
      listCompany(this.queryParams).then(response => {
        this.companyList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    getAccountStats() {
      getAccountStats().then(response => {
        this.accountStats = response.data
      })
    },
    // 取消按钮
    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(() => {
        console.log('ok')
        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(response => {
        this.form = response.data
        this.form.usedNum = row.usedNum
        this.open = true
        this.title = '修改公司'
        if (this.form.status != null) {
          this.form.status = String(this.form.status)
        }
        if (this.form.doctorIds != null) {
          this.doctorIds = ((this.form.doctorIds).split(',')).map(Number)
        }
        if (this.form.followDoctorIds != null) {
          this.form.followDoctorIds = JSON.parse(this.form.followDoctorIds)
        }
        if (this.form.packageCateIds != null) {
          this.form.packageCateIds = JSON.parse(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) {

          if (this.form.followDoctorIds == null || this.form.followDoctorIds.length == 0) {
            this.form.followDoctorIds = null
          }

          if (this.form.followDoctorIds != null && this.form.followDoctorIds.length > 0) {
            this.form.followDoctorIds = JSON.stringify(this.form.followDoctorIds)
          }

          if (this.form.packageCateIds != null) {
            this.form.packageCateIds = JSON.stringify(this.form.packageCateIds)
          }
          if (this.doctorIds != null) {
            this.form.doctorIds = (this.doctorIds).toString()
          }
          if (this.doctorIds != null) {
            this.form.doctorIds = (this.doctorIds).toString()
          }
          // if (this.form.miniAppMaster==null || this.form.miniAppMaster.length ===0 ){
          //   return this.$message.error("请选择主小程序")
          // }

          // if (this.form.miniAppServer==null || this.form.miniAppServer.length ===0 ){
          //   return this.$message.error("请选择备小程序")
          // }

          if (this.form.companyId != null) {
            /* if(this.form.maxPadNum < this.form.usedNum && this.form.maxPadNum !== -1){
              this.msgError("最大Pad数不能小于已使用Pad数,当前已使用"+this.form.usedNum)
               return;
            } */
            updateCompany(this.form).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addCompany(this.form).then(response => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    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()
        }
      });
    },
  }
}
</script>
<style scoped>
.pad-tips {
  color: #999;
  font-size: 12px;
  height: 50px;
}

.account-stats-row {
  margin-bottom: 16px;
}

.stats-card {
  text-align: center;
}

.stats-card >>> .el-card__body {
  padding: 20px 16px;
}

.stats-card-label {
  font-size: 13px;
  color: #909399;
  margin-bottom: 8px;
}

.stats-card-number {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  line-height: 1;
}

.stats-card-number.text-danger {
  color: #F56C6C;
}

.stats-card-bottom {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

</style>
