<template>
  <div>
    <avue-crud
      :data="tableData"
      :option="optionData"
      :page.sync="page"
      :table-loading="tableLoading"
      @on-load="getList"
      @size-change="sizeChange"
      @search-change="searchVal"
      @current-change="currentChange"
      @search-reset="searchReset"
    >
      <template slot="publishDateSearch">
        <el-date-picker
          v-model="publishDateTime"
          type="monthrange"
          range-separator="至"
          start-placeholder="开始月份"
          end-placeholder="结束月份"
          value-format="yyyy-MM"
          @change="publishDateTimeChange"
        >
        </el-date-picker>
      </template>
      <template slot="menuLeft">
        <el-button type="primary" icon="el-icon-plus" size="small" @click.stop="addData()">
          新增
        </el-button>
        <!-- <el-button type="primary" icon="el-icon-upload2" size="small" @click.stop="importPakageFn">
          导入积分包
        </el-button> -->
      </template>
      <template slot="menuRight">
        <el-checkbox v-model="toApproval" @change="toApprovalClick" class="checkbox">只看待审核</el-checkbox>
        <el-button type="primary" :loading="exportFnLoading" icon="el-icon-download" size="small" @click.stop="exportFn">
          导出数据
        </el-button>
      </template>

      <template slot="scorePackageName1" slot-scope="scope">
        <el-tooltip class="item" effect="dark" :content="'执行包编号：' + scope.row.packageSn" placement="top-start">
          <span>{{ scope.row.scorePackageName }}</span>
        </el-tooltip>
      </template>
      <template slot="taskTypes" slot-scope="scope">
        <el-button type="text" size="small" icon="el-icon-view" @click="viewDetail(scope.row, scope.index)">查看 </el-button>
      </template>

      <template slot="menu" slot-scope="scope">
        <template v-if="showRestart(scope.row)">
          <el-button type="text" size="small" icon="el-icon-view" @click="restartFn(scope.row, scope.index)">重启 </el-button>
        </template>
        <template v-else>
          <template v-if="scope.row.enableType == '0' || scope.row.enableType == '2'">
            <el-button
              type="text"
              size="small"
              icon="el-icon-tickets"
              v-show="scope.row.enableFlag != '1' && scope.row.typeid == '4' && scope.row.yjddsh != null && scope.row.yjddsh > 0"
              @click="receiveApproval(scope.row, scope.index)"
              >接单审批
            </el-button>
            <el-button
              style="color: #56b088"
              type="text"
              size="small"
              icon="el-icon-document-checked"
              v-show="scope.row.dsh != null && scope.row.dsh != '0'"
              @click="taskReview(scope.row, scope.index)"
              >任务审核
            </el-button>
            <el-button
              type="text"
              size="small"
              icon="el-icon-setting"
              v-show="scope.row.scorePackageStatus == null || scope.row.scorePackageStatus <= 2"
              @click="editBtn(scope.row, scope.index)"
              >编辑
            </el-button>
            <el-button
              type="text"
              size="small"
              icon="el-icon-folder-delete"
              @click="suspendBtn(scope.row, scope.index)"
              v-show="scope.row.scorePackageStatus !== '4' && scope.row.scorePackageStatus !== '5' && scope.row.scorePackageStatus !== '6' && scope.row.scorePackageStatus != '9'"
              >终止
            </el-button>
            <!-- <el-button
              type="text"
              size="small"
              icon="el-icon-finished"
              v-show="
                scope.row.settleFlag == '0' &&
                  scope.row.scorePackageStatus != '9' &&
                  scope.row.scorePackageStatus == '4' &&
                  ['4', '5'].includes(scope.row.typeid)
              "
              @click="settleById(scope.row)"
              >结算
            </el-button> -->
            <el-button type="text" size="small" icon="el-icon-folder-checked" @click="exportBtn(scope.row, scope.index)">导出 </el-button>
            <el-button
              type="text"
              size="small"
              icon="el-icon-folder-checked"
              v-show="scope.row.scorePackageStatus == '4' && scope.row.scorePackageStatus != '9'"
              @click="splitBtn(scope.row, scope.index)"
              >拆包
            </el-button>
          </template>
          <el-button type="text" size="small" icon="el-icon-view" @click="toView(scope.row, scope.index)">查看 </el-button>
          <el-button type="text" size="small" icon="el-icon-view" @click="detailFn(scope.row, scope.index)">详情 </el-button>
        </template>
      </template>
    </avue-crud>
    <!-- 新增弹窗 -->
    <el-dialog :title="showTit" :visible.sync="showDialog" width="80%" @close="handleClose" center>
      <el-form :model="pointsForm" :rules="rules" ref="pointsForm" label-width="138px" class="demo-ruleForm">
        <el-row>
          <el-col :span="12">
            <el-form-item label="执行包名称" prop="scorePackageName">
              <el-input v-model="pointsForm.scorePackageName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行包编号" prop="packageSn">
              <el-input v-model="pointsForm.packageSn" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="承接对象类型" prop="typeid">
              <el-select style="width: 100%" v-model="pointsForm.typeid" placeholder="请选择" disabled @change="typeidChange">
                <el-option v-for="item in typeidList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="承接对象" prop="userList">
              <el-select style="width: 100%" multiple :multiple-limit="1" v-model="pointsForm.userList" placeholder="请选择">
                <el-option v-for="item in receivingObject" :key="item.value" :label="item.label" :value="item.value"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="关联服务企业" prop="relatedService">
              <el-select style="width: 100%" v-model="pointsForm.relatedService" placeholder="请选择" @change="allEnterpriseBtn">
                <el-option v-for="item in sendPackageDeptList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="关联执行包" prop="relationScoreId">
              <el-select style="width: 100%" v-model="pointsForm.relationScoreId" placeholder="请选择" @change="relationScorechange" :disabled="packageDisabled">
                <el-option v-for="item in getRelationScoreData" :key="item.id" :label="item.scorePackageName" :value="item.id"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="生效日期" prop="startTime">
              <el-date-picker
                class="w100"
                v-model="pointsForm.startTime"
                @input="$forceUpdate()"
                disabled
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="选择日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="截止日期" prop="endTimeValue">
              <el-date-picker
                class="w100"
                disabled
                :picker-options="pickerOptions"
                v-model="pointsForm.endTimeValue"
                @input="$forceUpdate()"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="选择日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="可分配服务值" prop="kfpjf">
              <el-input v-model="pointsForm.kfpjf" :disabled="kfpjfNot"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="服务总值" prop="score">
              <el-input v-model="pointsForm.score" onkeyup="value=value.replace(/[^\d]/g,'')" disabled @input="getScoreval(pointsForm.score)"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="接单对象范围" prop="packageUserScope">
              <el-select style="width: 100%" v-model="pointsForm.packageUserScope" placeholder="请选择" :disabled="userScopeAble" @change="$forceUpdate()">
                <el-option v-for="item in objectScopelist" :key="item.value" :label="item.label" :value="item.value"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="推广产品" prop="drugtable">
              <el-select v-model="pointsForm.drugtable" @change="$forceUpdate()" placeholder="默认全选" style="width: 100%" multiple :disabled="idVal !== '-1'">
                <el-option v-for="(item, index) in drugList" :key="index" :label="item.drug_name" :value="item.drug_id"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="测试试卷">
              <el-select
                v-model="pointsForm.quizIds"
                placeholder="选择试卷，支持多选"
                style="width: 100%"
                multiple
                :disabled="dialogType === 'edit' && pointsForm.relationScoreId !== '-1'"
                @change="$forceUpdate()"
              >
                <el-option v-for="item in quizList" :key="item.quizId" :label="item.title" :value="item.quizId"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="有效服务类型" required>
              <dismantleTable
                ref="dismantleTableRef"
                :propsTableData="pkgTaskTypeQtyList"
                @updateScope="
                  val => {
                    pointsForm.score = val;
                  }
                "
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="描述：" prop="description">
              <el-input type="textarea" placeholder="请描述推广的产品品种" v-model="pointsForm.description"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" :loading="buttonLoading" @click="sureBtn('pointsForm')">确 定</el-button>
        <el-tooltip class="item" effect="dark" content="连续下发积分包" placement="top">
          <!-- <el-button type="success" :loading="buttonLoading" @click="sureBtn1('pointsForm')">确定并继续</el-button> -->
        </el-tooltip>
        <!--          <el-badge is-dot class="item">-->
        <!--          <el-button class="share-button" icon="el-icon-share" type="primary"></el-button>-->
        <!--          </el-badge>-->
      </span>
    </el-dialog>

    <!-- 核对积分包信息 -->
    <el-dialog title="核对积分包信息" :visible.sync="reviewPakageDialog" top="30vh" width="440px" @close="reviewPakageClose" center>
      <div class="attention">
        较上次填写信息变化字段：“接单对象类型”,“结算渠道”,“XXX”。请确认无误后点击“确定”
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="reviewPakageClose">取 消</el-button>
        <el-button type="primary" :loading="buttonLoading" @click="importPakageSubmitBtn('importPakageForm')">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :title="showTit" :visible.sync="showDialog1" width="65%" @close="handleClose" center>
      <el-button size="small" @click="exportExcel()" type="success" style="margin-right: 20px">模板下载</el-button>
      <!--        <el-button size="small" @click="importExcel" type="success" style="margin-right: 20px">文件上传</el-button>-->
      <div><br /></div>
      <div>填表说明：</div>
      <div>1、执行包名称不能重复</div>
      <div>
        2、接单对象类型为“兼职”时接单对象不必填写，“全职”时请填写全职人员姓名
      </div>
      <div>
        3、“关联服务企业”与“关联任务积分包”所填内容必须是系统中已存在的名称，每次批量时需要保持这两个字段唯一，不能出现多个“关联服务企业”或“关联任务积分包”的情况。
      </div>
      <div>
        4、“关联任务积分包”如果有值时，“有效服务类型”无需填写。“关联任务积分包”为'无'时，有效服务类型必须填写，如未填写，默认全部任务类型
      </div>
      <div>
        "有效服务类型"填写举例：1、全部。2、指定某些任务类型。每个任务类型之间用&分隔
      </div>
      <div><br /></div>
      <el-upload
        ref="upload"
        :headers="headers"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        limit="1"
        :auto-upload="false"
        :on-error="uploadError"
        :on-success="uploadSuccess"
        :action="uploadPath()"
        accept=".xls,.xlsx"
        class="upload-demo"
      >
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <span style="margin-right: 1080px">上传文件错误项：</span>
        <el-table v-loading="listLoading" :data="tableLists" :model="userInfo" border element-loading-text="加载中" size="small" style="width: 100%" fit>
          <el-table-column prop="index" label="序号" align="center" width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="行序号" prop="rowNum " align="center">
            <template slot-scope="scope">
              <span :title="scope.row.rowNum">{{ scope.row.rowNum }}</span>
            </template>
          </el-table-column>
          <el-table-column label="列序号" prop="columnNum" align="center">
            <template slot-scope="scope">
              <span :title="scope.row.columnNum">{{ scope.row.columnNum }}</span>
            </template>
          </el-table-column>
          <el-table-column label="列名称" prop="columnName" align="center">
            <template slot-scope="scope">
              <span :title="scope.row.columnName">{{ scope.row.columnName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="所填内容" prop="content" align="center">
            <template slot-scope="scope">
              <span :title="scope.row.content">{{ scope.row.content }}</span>
            </template>
          </el-table-column>
          <el-table-column label="错误原因" prop="reason" align="center">
            <template slot-scope="scope">
              <span :title="scope.row.reason">{{ scope.row.reason }}</span>
            </template>
          </el-table-column>
        </el-table>
        <div><br /></div>
        <el-button @click="cancelBtn" type="primary">取 消</el-button>
        <el-button @click="cancelBtn" type="primary">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 导出弹窗 -->
    <el-dialog title="导出" :visible.sync="exportDig" width="40%" :close-on-click-modal="false" center>
      <template>
        <div class="down-item">
          <div class="btn">
            <span>word格式：</span>
            <template v-if="checkRow && checkRow.reportOpt.status === 'NOT_GENERATE'">
              <el-button class="first" @click="taskExport('word')" :loading="wordLoading">生成报告</el-button>
            </template>
            <template v-else-if="checkRow && checkRow.reportOpt.status === 'GENERATING'">
              <el-button class="first" :loading="true">报告生成中...</el-button>
            </template>
            <template v-else-if="checkRow && (checkRow.reportOpt.status === 'GENERATED' || checkRow.reportOpt.status === 'ERROR')">
              <el-button @click="taskExport('word')">重新导出</el-button>
              <el-button @click="downloadTask('word')" v-if="checkRow.reportOpt.status === 'GENERATED'">下载报告</el-button>
              <el-button disabled :title="checkRow.reportOpt.errorMsg" v-else-if="checkRow.reportOpt.status === 'ERROR'">导出失败</el-button>
            </template>
          </div>
          <div class="title-msg">
            <p v-if="checkRow && checkRow.reportOpt.status === 'GENERATED'">下载截止日期：{{ checkRow.reportOpt.ttl }}</p>
            <p v-if="checkRow && checkRow.reportOpt.status === 'ERROR'">本次导出失败：{{ checkRow.reportOpt.errorMsg }}</p>
          </div>
        </div>
        <div class="down-item">
          <div class="btn">
            <span>excel格式：</span>
            <template v-if="checkRow && checkRow.excelReportOpt.status === 'NOT_GENERATE'">
              <el-button class="first" @click="taskExport('excel')" :loading="excelLoading">生成报告</el-button>
            </template>
            <template v-if="checkRow && checkRow.excelReportOpt.status === 'GENERATING'">
              <el-button class="first" :loading="true">报告生成中...</el-button>
            </template>
            <template v-else-if="checkRow && (checkRow.excelReportOpt.status === 'GENERATED' || checkRow.excelReportOpt.status === 'ERROR')">
              <el-button @click="taskExport('excel')">重新导出</el-button>
              <el-button @click="downloadTask('excel')" v-if="checkRow.excelReportOpt.status === 'GENERATED'">下载报告</el-button>
              <el-button disabled :title="checkRow.excelReportOpt.errorMsg" v-else-if="checkRow.excelReportOpt.status === 'ERROR'">导出失败</el-button>
            </template>
          </div>

          <div class="title-msg">
            <p v-if="checkRow && checkRow.excelReportOpt.status === 'GENERATED'">下载截止日期：{{ checkRow.excelReportOpt.ttl }}</p>
            <p v-if="checkRow && checkRow.excelReportOpt.status === 'ERROR'">本次导出失败：{{ checkRow.excelReportOpt.errorMsg }}</p>
          </div>
        </div>
      </template>
      <el-divider></el-divider>
      <!-- 新版导出 -->
      <template v-if="false">
        <div class="down-item">
          <div class="btn">
            <span>word格式（新版）：</span>
            <template v-if="checkRow && checkRow.newReportOpt.status === 'NOT_GENERATE'">
              <el-button class="first" @click="taskNewExport('word')" :loading="newWordLoading">生成报告</el-button>
            </template>
            <template v-else-if="checkRow && checkRow.newReportOpt.status === 'GENERATING'">
              <el-button class="first" :loading="true">报告生成中...</el-button>
            </template>
            <template v-else-if="checkRow && (checkRow.newReportOpt.status === 'GENERATED' || checkRow.newReportOpt.status === 'ERROR')">
              <el-button @click="taskNewExport('word')">重新导出</el-button>
              <el-button @click="downloadNewTask('word')" v-if="checkRow.newReportOpt.status === 'GENERATED'">下载报告</el-button>
              <el-button disabled :title="checkRow.newReportOpt.errorMsg" v-else-if="checkRow.newReportOpt.status === 'ERROR'">导出失败</el-button>
            </template>
          </div>
          <div class="title-msg">
            <p v-if="checkRow && checkRow.newReportOpt.status === 'GENERATED'">下载截止日期：{{ checkRow.newReportOpt.ttl }}</p>
            <p v-if="checkRow && checkRow.newReportOpt.status === 'ERROR'">本次导出失败：{{ checkRow.newReportOpt.errorMsg }}</p>
          </div>
        </div>
        <div class="down-item">
          <div class="btn">
            <span>excel格式（新版）：</span>
            <template v-if="checkRow && checkRow.newExcelReportOpt.status === 'NOT_GENERATE'">
              <el-button class="first" @click="taskNewExport('excel')" :loading="newExcelLoading">生成报告</el-button>
            </template>
            <template v-if="checkRow && checkRow.newExcelReportOpt.status === 'GENERATING'">
              <el-button class="first" :loading="true">报告生成中...</el-button>
            </template>
            <template v-else-if="checkRow && (checkRow.newExcelReportOpt.status === 'GENERATED' || checkRow.newExcelReportOpt.status === 'ERROR')">
              <el-button @click="taskNewExport('excel')">重新导出</el-button>
              <el-button @click="downloadNewTask('excel')" v-if="checkRow.newExcelReportOpt.status === 'GENERATED'">下载报告</el-button>
              <el-button disabled :title="checkRow.newExcelReportOpt.errorMsg" v-else-if="checkRow.newExcelReportOpt.status === 'ERROR'">导出失败</el-button>
            </template>
          </div>
          <div class="title-msg">
            <p v-if="checkRow && checkRow.newExcelReportOpt.status === 'GENERATED'">下载截止日期：{{ checkRow.newExcelReportOpt.ttl }}</p>
            <p v-if="checkRow && checkRow.newExcelReportOpt.status === 'ERROR'">本次导出失败：{{ checkRow.newExcelReportOpt.errorMsg }}</p>
          </div>
        </div>
      </template>
      <span slot="footer" class="dialog-footer">
        注意： 1.报告将于24小时之内生成完毕，请注意下载。<br />
        <i style="margin-left:62px"></i>2.报告汇总为封面+任务数据汇总+任务列表明细。
        <br />
        <i style="margin-left:10px"></i>3.报告详情为每条任务的任务详情+图片。
      </span>
    </el-dialog>
    <!-- 中止任务 -->
    <el-dialog title="终止任务" :visible.sync="enableFlagDig" width="50%" center>
      <el-form :model="enableForm" :rules="enableRule" ref="enableForm" label-width="150px" class="demo-ruleForm">
        <el-row v-if="suspendData.stopStatus !== 'NOTHING'">
          <el-col :span="24">
            <el-form-item label="请选择积分收回方式" prop="enableFlag">
              <el-radio-group v-model="enableForm.enableFlag">
                <el-radio label="1">全部收回</el-radio>
                <!-- <el-radio label="2">剩余收回</el-radio> -->
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <p class="tc" v-if="suspendData.stopStatus === 'NOTHING'" style="color: red;">
          该积分包中存在本企业或上级企业还未审核的任务，请审核后再进行该操作
        </p>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button :type="suspendData.stopStatus === 'NOTHING' ? 'primary' : ''" @click="stopcancelBtn()">
          {{ suspendData.stopStatus === 'NOTHING' ? '确 定' : '取 消' }}
        </el-button>
        <el-button v-if="suspendData.stopStatus !== 'NOTHING'" type="primary" @click="enableFlagBtn('enableForm')">
          确 定
        </el-button>
      </span>
    </el-dialog>
    <!-- 表单-查看有效服务类型 -->
    <el-dialog title="有效服务类型" :visible.sync="taskTypedialog" width="50%" center :before-close="handleClose">
      <div>
        <ul>
          <li v-for="(item, index) in taskTypes" :key="index">{{ item.code }}：{{ item.label }}</li>
        </ul>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="taskTypedialog = false">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 模板上传失败 -->
    <el-dialog title="模板上传失败！" width="600px" :close-on-click-modal="false" @close="importErrorDialogClose" :visible.sync="importErrorDialogShow" center>
      <avue-crud style="width: 100%;" :data="importErrorTableData" :option="errorOption"> </avue-crud>
    </el-dialog>
    <!-- 批量下发积分包提交前确认弹窗 -->
    <el-dialog title="核对积分包信息" width="600px" top="14vh" @close="importConfirmDialog = false" :visible.sync="importConfirmDialog" center>
      <div>
        上传文件名称：
        {{ importPakageFileList.length && importPakageFileList[0]['name'] }}
      </div>
      <div v-html="differenceInfo"></div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="importConfirmDialog = false">取 消</el-button>
        <el-button type="primary" :loading="buttonLoading" @click="importPakageConfirmBtn">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="重启积分包" :visible.sync="restartVisible" center width="45%" :before-close="restartVisibleClose">
      <el-form :model="restartForm" :rules="restartFormRef" ref="restartForm">
        <el-form-item label="截止日期" prop="endTimeValue">
          <el-date-picker
            style="width:500px"
            :picker-options="pickerOptions"
            v-model="restartForm.endTimeValue"
            @input="$forceUpdate()"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="restartVisible = false">取 消</el-button>
        <el-button type="primary" @click="restartSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 展示当前任务拆分详情 -->
    <el-dialog title="任务完成详情" :visible.sync="taskListDialog" width="60%" center>
      <el-table :data="taskListArr" border style="width: 100%">
        <el-table-column prop="baseId" label="任务大类"> </el-table-column>
        <el-table-column prop="taskTypeName" label="任务类型"> </el-table-column>
        <el-table-column prop="price" label="积分值"> </el-table-column>
        <el-table-column prop="qty" label="拆解个数" width="180"> </el-table-column>
        <el-table-column prop="count" label="完成个数" width="180"> </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="taskListDialog = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import dismantleTable from './components/dismantleTable.vue';
import {allotPointsData, importErrorTableOption} from '@/const/crud/assignPoints/quota/index';
import fileDownload from 'js-file-download';
import {tree1, tree2, tree3, tree4, tree5, tree7, plist, pFlist} from '@/const/crud/taskTypeTree/index';
import {getToken} from '@/util/auth';
import {wmscorepackage} from '@/api/wmscorepackage';
import {
  getScorePackagePage,
  getRelationScoreList,
  objectScope1,
  objectScope2,
  showDescription,
  addWmScorePackage,
  packageUserScope,
  packageUserScopeByOpt,
  exportZbReport,
  exportZbReportExcel,
  updateEnable,
  updateWmScorePackage,
  getScorePackagePageById,
  getAllParentDept,
  getTaskTypeTree,
  editData,
  getDrugProducerList,
  getListDrugApi,
  typeidPersonal,
  taskNewExportNbqybg,
  taskExportNewExcelNbqybg,
  exportInfoApi,
  restartApi,
  getListAncestorApi,
  getPkgTaskDetailsApi
} from '@/api/assignPoints/currency/index';

import {fetchList} from '@/api/wmdeptbudget/plan.js';
import {settleById, geSubmitToken, settleSave, settleIssue, settleReIssue, settleSubmit} from '@/api/settle/settle';
import {selectByScorePackageId} from '@/api/task/taskType';
import {getSubSelect, getSettleSubSelect} from '@/api/admin/deptSub';
import {getBatchHistory, batchGeneratePakage, getPackageSn} from '@/api/assignPoints/quota';
import store from '@/store';
import {templateDownload} from '@/api/assignPoints/currency/manList';
import {getDictType} from '@/api/common';
import {SUBJECT_TYPE_MAP} from '@/const/auth';
import {getAvailQuizList} from '@/api/test';
import BigNumber from 'bignumber.js';

// BigNumber.config({ ROUNDING_MODE: BigNumber.ROUND_HALF_UP })
export default {
  name: 'allotPoints',
  components: {dismantleTable},
  data() {
    return {
      taskListArr: [],
      taskListDialog: false,
      toApproval: false,
      tree1: tree1,
      tree2: tree2,
      tree3: tree3,
      tree4: tree4,
      tree5: tree5,
      tree7: tree7,
      optionData: allotPointsData,
      tableData: [],
      tableLists: [],
      showTit: '',
      listLoading: true,
      showDialog: false,
      showDialog1: false,
      userScopeAble: false,
      headers: {
        Authorization: 'Bearer ' + store.getters.access_token
      },
      userInfo: {
        rowNum: '', //行序号
        columnNum: '', //列序号
        columnName: '', //列名称
        content: '', //所填内容
        reason: '' //错误原因
      },
      pkgTaskTypeQtyList: [],
      pointsForm: {
        subjectLocation: '',
        packageUserScope: '1',
        scorePackageName: '',
        relationScoreId: '',
        kfpjf: '',
        relatedService: '',
        typeid: '3',
        taskTypeList: [],
        userList: [],
        score: '',
        drugtable: [],
        quizIds: [],
        startTime: '',
        endTimeValue: '',
        packageSn: null
      },
      pickerOptions: {
        disabledDate(time) {
          // 禁用当前日期之前和一年后的日期
          const currentDate = new Date();
          return time.getTime() < currentDate.getTime();
        }
      },
      rules: {
        scorePackageName: [{required: true, message: '请输入执行包名称', trigger: 'blur'}],
        score: [{required: true, message: '请输入服务总值', trigger: 'blur'}],
        relationScoreId: [{required: true, message: '请选择关联任务积分包', trigger: 'change'}],
        userList: [{required: true, message: '请选择承接对象', trigger: 'change'}],
        taskTypeList: [{required: true, message: '请选择有效服务类型', trigger: 'input'}],
        packageUserScope: [{required: true, message: '请选择接单对象范围', trigger: 'change'}],
        relatedService: [{message: '请选择关联服务企业', trigger: 'change'}],
        typeid: [{required: true, message: '请选择接单对象类型', trigger: 'change'}]
      },
      restartVisible: false,
      currentRow: {},
      restartForm: {
        endTimeValue: ''
      },
      restartFormRef: {
        endTimeValue: [
          {
            type: 'date',
            required: true,
            message: '请选择日期',
            trigger: 'blur'
          }
        ]
      },

      importPakageForm: {
        typeid: '3',
        subjectLocation: '', // 结算渠道
        packageUserScope: '1', // 接单对象范围
        relationScoreId: '', // 关联执行包
        kfpjf: '', // 可分配服务值
        taskTypeList: [], // 有效服务类型
        drugtable: [],
        endTimeValue: ''
        // userList: []          // 承接对象
      },
      kfpjfNot: true,
      page: {
        pageSize: 20,
        pagerCount: 5,
        pageSizes: [10, 20, 50, 100, 150, 200]
      },
      exportDig: false,
      wordLoading: false,
      excelLoading: false,
      taskExportInfoLoading: false,
      newWordLoading: false,
      newExcelLoading: false,
      tableLoading: false,
      getRelationScoreData: [],
      showPackage: true,
      objectScopelist: [],
      idVal: '', // 判断tree 是否禁用: 若禁用，传后台返回来的值；若不禁用，传手动选的值
      checkRow: null,
      suspendData: {},
      enableFlagDig: false,
      enableForm: {},
      enableRule: {
        enableFlag: [{required: true, message: '请选择积分回收方式', trigger: 'change'}]
      },
      searchForm: {},
      publishDateTime: '', // 发布时间
      monthStart: '',
      monthEnd: '',
      returnVal: [],
      sendPackageDeptList: [],
      typeidList: [],
      receivingObject: [],
      receivingObject1: [],
      defaultProps: {
        // 有效服务类型展示tree
        children: 'children',
        label: 'taskTypeName',
        disabled: this.disabledFn
      },
      getNodeVal: [],
      kfpjfVal: '',
      checkedDsScope: [],
      checkVal: '',
      taskTypedialog: false, // 有效服务类型弹窗
      taskTypes: [],
      taskTypeList1val: [],
      scoreVal: '',
      getScore: '',
      jddxVal: '',
      keys: [],
      dialogType: 'add',
      settleTableVisible: false,
      buttonLoading: false,
      form: {},
      id: '',
      gridData: [],
      settleButtonShow: false,
      invoiceList: [],

      drugProducerList: [],
      drugProducerListCopy: [],
      drugList: [],
      timeId: null, // 定时器id
      packageDisabled: false,
      isDelay: false,
      importPakageDialog: false,
      // importPakageDialog: true,
      importPakageFileList: [],
      importTemplateDialog: false,
      reviewPakageDialog: false,
      importPakageFile: null,
      errorOption: importErrorTableOption,
      importErrorTableData: [],
      importErrorDialogShow: false,
      importHistory: {}, // 批量下发积分包历史记录
      importConfirmDialog: false, // 批量下发积分包提交前确认弹窗
      differenceInfo: '',
      submitToken: '', // 提交
      availQuizList: [],
      quizList: [], // 测试试卷列表
      exportFnLoading: false
    };
  },
  mounted() {
    // 承接对象类型-展示-默认全职"3""
    this.typeidShow();
    // 获取承接对象 - 全职
    this.showObjectscope(); //承接对象

    this.showTaskType(); // 有效服务类型

    this.getAllParentList(); //关联服务企业

    this.showRelationScore();
    this.getDrugProducerList(); // 推广产品企业
    this.getListDrug();
    this.getAvailQuizListFn();

    this.showUserScope(); // 接单对象范围
  },
  activated() {
    this.getList(this.page, this.searchForm);
  },
  methods: {
    // 获取可用的试卷
    async getAvailQuizListFn() {
      const res = await getAvailQuizList();
      if (res.data.code === 0) {
        this.availQuizList = res.data.data || [];
      }
    },
    toApprovalClick() {
      this.page.currentPage = 1;
      this.getList(this.page);
    },
    // 查询栏-发布时间change
    publishDateTimeChange(val) {
      this.monthStart = val ? val[0] : '';
      this.monthEnd = val ? val[1] : '';
    },
    // 导入积分包错误展示弹窗关闭
    importErrorDialogClose() {
      this.importErrorDialogShow = false;
    },
    // 关闭核对积分包信息弹窗
    reviewPakageClose() {
      this.reviewPakageDialog = false;
    },
    // 关闭导入积分包模板下载弹窗
    importTemplateClose() {
      this.importTemplateDialog = false;
    },
    // 导入模板下载
    handleDown(type) {
      const fileName = type === 'full' ? 'scorepackage_full_import_template.xlsx' : 'scorepackage_part_import_template.xlsx';
      const downloadName = type === 'full' ? '全职人员专用模板.xlsx' : '兼职人员专用模板.xlsx';
      templateDownload({
        fileName
      })
        .then(response => {
          let url = window.URL.createObjectURL(new Blob([response.data]));
          let link = document.createElement('a');
          link.style.display = 'none';
          link.href = url;
          link.setAttribute('download', downloadName);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        })
        .catch(() => {});
    },
    importPakageHandleRemove(file, fileList) {
      this.importPakageFileList = [];
      this.importPakageFile = null;
    },
    importPakageHandleExceed(files, fileList) {
      this.$message.warning('最多上传一个文件！');
    },
    importPakageHandleSuccess(res, file) {
      this.importPakageFileList = [{name: file.name, url: res.data.url}];
    },
    importPakageHandleError() {
      this.importPakageFileList = [];
      this.$message.error('上传失败，请重试！');
    },
    importPakageHandleChange(file, fileList) {
      this.importPakageFile = file.raw;
      this.importPakageFileList = [{name: file.name}];
      let existFile = fileList.slice(0, fileList.length - 1).find(f => f.name === file.name); //如果文件名重复
      if (existFile) {
        this.$message.error('当前文件已经存在!');
        fileList.pop();
      }
    },
    // 获取批量下发积分包弹窗的历史记录
    async getBatchHistory() {
      const {data} = await getBatchHistory();
      if (data.code === 0 && data.data && data.data.history) {
        this.importHistory = Object.assign({}, data.data.history);
        this.importPakageForm = data.data.history;
        this.checkedDsScope = this.importPakageForm.taskTypeList.map(ele => ele.taskTypeId);
        this.setSelectNodes(this.checkedDsScope);
        // 动态展示页面
        if (this.importPakageForm.typeid) this.typeidChange(this.importPakageForm.typeid);
        if (this.importPakageForm.relationScoreId) this.relationScorechange1(this.importPakageForm.relationScoreId, true);
        if (this.importPakageForm.relatedService) this.allEnterpriseBtn(this.importPakageForm.relatedService, true);
      } else {
        this.showTaskType('1');
      }
      // const oneYearLater = new Date();
      // oneYearLater.setFullYear(oneYearLater.getFullYear() + 1);
      // // 获取一年后日期的时间戳
      // this.importPakageForm.endTimeValue = oneYearLater.getTime();
    },
    // 导入积分包
    importPakageFn() {
      this.showPackage = true;
      this.getBatchHistory();
      this.importPakageDialog = true;
      this.importPakageForm.packageUserScope = this.objectScopelist[0].value;
    },
    async exportFn() {
      this.exportFnLoading = true;
      try {
        const obj = Object.assign(
          {
            packageType1: '1', // 必传固定值
            packageType2: '1' // 必传固定值
          },
          this.searchForm
        );
        const res = await exportInfoApi(obj);
        let url = window.URL.createObjectURL(new Blob([res.data]));
        let link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', '导出数据.xlsx');
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      } catch (err) {
        console.log('error', err);
      }
      this.exportFnLoading = false;
    },

    // 关闭导入积分包
    importPakageClose() {
      this.importPakageDialog = false;
      this.importPakageFileList = [];
      this.importPakageFile = null;
      this.importPakageForm = {
        typeid: '3',
        subjectLocation: '', // 结算渠道
        packageUserScope: '1', // 接单对象范围
        relationScoreId: '', // 关联执行包
        kfpjf: '', // 可分配服务值
        taskTypeList: [] // 有效服务类型
        // userList: []          // 承接对象
      };
      this.getList(this.page, this.searchForm);
    },
    // 批量下发积分包提交
    importPakageSubmitBtn(formName) {
      if (this.importPakageFileList.length === 0) {
        return this.$message.warning('请上传模板！');
      }
      this.$refs[formName].validate(valid => {
        if (valid) {
          const date = this.formatDate(this.importPakageForm.endTimeValue);
          this.importPakageForm.endTime = date;
          this.importPakageForm.taskTypeList = this.getAllTaskTypeList(); // 获取所有选择的'有效服务类型'
          // 提交前确认
          this.importConfirmDialog = true;
          this.differenceInfo = '';
          let diffItems = [];
          const diffTaskTypeList = () => {
            if (this.importHistory.taskTypeList.length !== this.importPakageForm.taskTypeList.length) return false;
            const historyIds = this.importHistory.taskTypeList.map(ele => ele.taskTypeId);
            const pakageFormIds = this.importPakageForm.taskTypeList.map(ele => ele.taskTypeId);
            return historyIds.every(ele => pakageFormIds.includes(ele));
          };
          if (Object.keys(this.importHistory).length) {
            if (this.importHistory.typeid !== this.importPakageForm.typeid) {
              diffItems.push('"承接对象类型"');
            }
            if (this.importHistory.subjectLocation !== this.importPakageForm.subjectLocation && this.importPakageForm.typeid === '4') {
              // 当前接单对象类型为'兼职'时, 结算渠道改变, 进行提示.
              diffItems.push('"结算渠道"');
            }
            if (this.importHistory.relatedService !== this.importPakageForm.relatedService) {
              diffItems.push('"关联服务企业"');
            }
            if (this.importHistory.relationScoreId !== this.importPakageForm.relationScoreId) {
              diffItems.push('"关联执行包"');
            }
            if (this.importHistory.packageUserScope !== this.importPakageForm.packageUserScope) {
              diffItems.push('"接单对象范围"');
            }
            if (!diffTaskTypeList()) {
              diffItems.push('"有效服务类型"');
            }
            if (diffItems.length) {
              // differenceInfo将会通过v-html解析, 注意内容安全性
              this.differenceInfo = `较上次填写信息变化字段：<span style="color: red;">${diffItems.join('，')}</span>。请确认无误后点击"确定"`;
            } else {
              this.differenceInfo = '较上次填写信息无变化';
            }
          } else {
            this.differenceInfo = '';
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 批量下发积分包提交前确认
    importPakageConfirmBtn() {
      this.importConfirmDialog = false;
      this.buttonLoading = true;
      this.importPakageForm.packageType1 = '1'; // 必传固定值
      this.importPakageForm.packageType2 = '1'; // 必传固定值
      this.importPakageForm.userNum = '1'; // 必传固定值
      if (this.importPakageForm.taskTypeList.length === 0) {
        this.$message.error('有效服务类型不能为空');
        return false;
      }
      if (this.idVal != '-1') {
        this.importPakageForm.drugProducerList = this.drugProducerList; // 推广产品企业
        if (!this.importPakageForm.drugtable || this.importPakageForm.drugtable.length === 0) {
          this.importPakageForm.drugtable = this.drugList.map(item => item.drug_id); // 推广产品企业
        }
        if (parseInt(this.getScore) > parseInt(this.kfpjfVal)) {
          this.$message.error('服务总值必须小于可分配积分值');
          this.relationScorechange1(this.idVal);
          return false;
        }
      } else {
        if (!this.importPakageForm.drugProducerList || this.importPakageForm.drugProducerList.length === 0) {
          this.importPakageForm.drugProducerList = this.drugProducerList; // 推广产品企业
        }
        if (!this.importPakageForm.drugtable || this.importPakageForm.drugtable.length === 0) {
          this.importPakageForm.drugtable = this.drugList.map(item => item.drug_id); // 推广产品企业
        }
      }
      if (parseInt(this.getScore) == '0') {
        this.$message.error('服务总值必须大于0');
        this.relationScorechange1(this.idVal);
        return false;
      }
      let data = JSON.parse(JSON.stringify(this.importPakageForm));
      delete data.drugProducerList;
      console.log('data', data);
      const importPakageFormData = new FormData();
      importPakageFormData.append('excel', this.importPakageFile);
      importPakageFormData.append(
        'history',
        new Blob([JSON.stringify(data)], {
          type: 'application/json'
        })
      );

      batchGeneratePakage(importPakageFormData)
        .then(res => {
          if (res.data.code === 0) {
            if (res.data.data) {
              this.importErrorTableData = res.data.data;
              this.importErrorDialogShow = true;
            } else {
              this.$message.success('导入积分包成功');
              this.importPakageClose();
            }
          } else {
            this.$message.error(res.data.msg);
          }
          this.buttonLoading = false;
        })
        .catch(() => {
          // this.cancelBtn();
          this.buttonLoading = false;
        });
      setTimeout(() => {
        this.$store.dispatch('SET_INTEGRAL');
      }, 500);
    },
    // 推广产品企业
    getDrugProducerList() {
      getDrugProducerList({deptId: this.$store.getters.userInfo.deptId}).then(res => {
        this.drugProducerListCopy = res.data.data;
      });
    },
    // 获取产品
    async getListDrug() {
      const res = await getListDrugApi();
      console.log('res getListDrug', res);
      this.drugList = res.data.data;
    },
    // 关联执行包-展示
    showRelationScore() {
      getRelationScoreList().then(response => {
        this.getRelationScoreData = response.data.data;
      });
    },
    // 关联服务企业-展示
    getAllParentList() {
      getListAncestorApi().then(response => {
        response.data.data.forEach(item => {
          const addnew = {
            value: item.deptId + '',
            label: item.name
          };
          this.sendPackageDeptList.push(addnew);
        });
      });
    },
    // 承接对象类型-展示
    typeidShow() {
      typeidPersonal().then(response => {
        response.data.data.forEach(item => {
          const addnew = {
            value: item.value,
            label: item.label
          };
          this.typeidList.push(addnew);
        });
      });
    },

    // 全职-接单对象展示
    showObjectscope() {
      this.receivingObject1 = [];
      objectScope1().then(response => {
        response.data.data.forEach(item => {
          const addnew = {
            value: item.id,
            label: item.realname + ' ' + item.username
          };
          this.receivingObject1.push(addnew);
        });
        this.typeidChange('3');
      });
    },

    // 承接对象类型-判断是否显示接单对象
    async typeidChange(id) {
      this.jddxVal = id;
      this.pointsForm.subjectLocation = '';
      if (id == '3') {
        // 全职
        this.receivingObject = this.receivingObject1;
        this.pointsForm.subjectLocation = '';
        this.showPackage = true;
        this.pointsForm.packageUserScope = '1';
        this.userScopeAble = true;
      }
    },
    // 承接对象类型-判断是否显示接单对象
    typeidChange1(id) {
      this.jddxVal = id;
      this.importPakageForm.subjectLocation = '';
      if (id == '3') {
        this.importPakageForm.subjectLocation = '';
        this.showPackage = true;
        this.importPakageForm.packageUserScope = '1';
        this.userScopeAble = true;
      } else if (id === '5') {
        this.importPakageForm.subjectLocation = '';
        this.showPackage = true;
        this.importPakageForm.packageUserScope = '1';
        this.userScopeAble = true;
      } else {
        this.userScopeAble = false;
        this.showPackage = false;
      }
    },
    // 有效服务类型展示
    showTaskType(type) {
      // this.pointsForm.taskTypeList = [];
      let arg = {
        description: '1'
      };
      getTaskTypeTree(arg).then(response => {
        // this.pointsForm.taskTypeList = response.data.data.treeList
        if (type == '1') {
          this.checkedDsScope = response.data.data.keys;
          // this.getNodeVal = response.data.data.treeList
        }
      });
    },
    // 有效服务类型-展示
    filterNode(value, data) {
      if (!value) return true;
      return data.taskTypeName.indexOf(value) !== -1;
    },

    // 获取选中的值
    getNodeData(data, checked) {
      this.getNodeVal = this.$refs.tree1.getCheckedNodes();
    },
    // 关联服务企业获取id-用于请求关联任务积分包
    allEnterpriseBtn(id, isHistory) {
      if (id) {
        this.$set(this.pointsForm, 'relatedService', id);
        console.log('cc');

        this.$refs.pointsForm.validateField('relatedService');
      }

      this.pointsForm.relationScoreId = '';
      if (!isHistory) {
        // 非导入积分包获取历史记录时调用, 清空"关联执行包"
        this.importPakageForm.relationScoreId = '';
      }
      let arg = {relatedService: id};
      // 根据选择的"关联服务企业", 请求"关联执行包"列表
      getRelationScoreList(arg).then(response => {
        this.getRelationScoreData = response.data.data;
        /**
         * 导入积分包获取历史记录时
         * 1.如果"关联执行包"列表不为空, 并且"关联执行包"列表中不存在历史"关联执行包", 清空"关联执行包"
         * 2.如果"关联执行包"列表为空, 清空"关联执行包"
         */
        if (isHistory) {
          if (Array.isArray(this.getRelationScoreData) && this.getRelationScoreData.length) {
            if (!this.getRelationScoreData.some(ele => ele.id === this.importPakageForm.relationScoreId)) {
              this.importPakageForm.relationScoreId = '';
            }
          } else {
            this.importPakageForm.relationScoreId = '';
          }
        }
      });
    },
    // 接单对象范围-默认展示
    showUserScope() {
      packageUserScopeByOpt().then(response => {
        response.data.data.forEach(item => {
          const addnew = {
            value: item.value,
            label: item.label
          };
          this.objectScopelist.push(addnew);
        });
      });
    },

    // 初始化页面
    getList(page, params) {
      this.tableLoading = true;
      getScorePackagePage(
        Object.assign(
          {
            current: page.currentPage,
            size: page.pageSize,
            toApproval: this.toApproval,
            packageType1: '1', // 必传固定值
            packageType2: '1' // 必传固定值
          },
          params,
          this.searchForm
        )
      )
        .then(response => {
          this.tableData = [];
          this.tableData = response.data.data.records;
          this.page.total = response.data.data.total;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },

    // 查询
    searchVal(form, done) {
      this.searchForm = form;
      this.searchForm.monthStart = this.monthStart;
      this.searchForm.monthEnd = this.monthEnd;
      this.page.currentPage = 1;
      this.getList(this.page, form);
      done();
    },

    // 选中关联任务积分包，展示关联的值
    async relationScorechange(id) {
      clearTimeout(this.timeId); // 清空定时器
      this.pointsForm.drugProducerList = null; // 切换'关联执行包', 清空'推广产品企业'
      this.pointsForm.drugtable = []; // 切换'关联执行包', 清空'推广产品企业'
      this.idVal = id;
      this.pointsForm.quizIds = [];

      if (id == '-1') {
        this.pointsForm.kfpjf = '';
        this.checkedDsScope = [];
        this.showTaskType('1');
        this.drugProducerList = [...this.drugProducerListCopy]; // 推广产品企业
        this.quizList = this.availQuizList;
        this.getListDrug();
      } else {
        this.packageDisabled = true;
        this.buttonLoading = true;
        let curr = this.getRelationScoreData.find(item => item.id === id);

        if (curr) {
          if (curr.endTime && curr.startTime) {
            this.$set(this.pointsForm, 'endTimeValue', curr.endTime);
            this.$set(this.pointsForm, 'startTime', curr.startTime);
          }
        }
        if (curr && curr.drugtable) {
          this.pointsForm.drugtable = curr.drugtable;
          const arr = [
            {
              drug_name: curr.drugtableName[0],
              drug_id: curr.drugtable[0]
            }
          ];
          this.drugList = arr;
        }
        this.timeId = setTimeout(() => {
          if (this.buttonLoading === true) {
            // 2.5s后还没加载成功, 进行提示
            this.pointsForm.relationScoreId = ''; // 清空'关联执行包'
            this.packageDisabled = false;
            this.buttonLoading = false;
            this.isDelay = true; // 网络延迟
            this.$message.error('网络延迟，请重新选择“关联任务积分包”！');
          }
        }, 2500);
        let arg = {
          id: id
        };
        const response = await getRelationScoreList(arg);
        clearTimeout(this.timeId);
        if (!this.isDelay) {
          // 没延迟
          this.packageDisabled = false;
          this.buttonLoading = false;
          this.pointsForm.score = 0;
          this.getScore = 0;
          // this.showTaskType();
          this.checkedDsScope = [];
          this.kfpjfVal = response.data.data[0].kfpjf; // 获取值进行判断
          this.pointsForm.kfpjf = response.data.data[0].kfpjf; // 默认展示的值
          this.taskTypeList1val = response.data.data[0].taskTypeList1; // 获取有效服务类型list
          this.checkedDsScope = response.data.data[0].taskTypeSet;
          this.drugProducerList = response.data.data[0].drugProducerList; // 推广产品企业
          this.pkgTaskTypeQtyList = response.data.data[0].pkgTaskTypeQtyList;
          if (this.pkgTaskTypeQtyList) {
            this.$refs.dismantleTableRef.setData(this.pkgTaskTypeQtyList);
          }

          // this.setSelectNodes(this.checkedDsScope);
          const quizRelations = response.data.data[0].quizRelations || [];
          this.quizList = quizRelations.map(ele => ({
            ...ele,
            quizId: ele.relationId
          }));
        } else {
          this.isDelay = false;
        }
      }
    },
    // 选中关联任务积分包，展示关联的值
    async relationScorechange1(id, isHistory) {
      clearTimeout(this.timeId); // 清空定时器
      this.importPakageForm.drugProducerList = null; // 切换'关联执行包', 清空'推广产品企业'
      this.importPakageForm.drugtable = []; // 切换'关联执行包', 清空'推广产品企业'
      this.idVal = id;
      if (id == '-1') {
        this.importPakageForm.kfpjf = '';
        this.checkedDsScope = [];
        this.showTaskType('1');
        this.drugProducerList = [...this.drugProducerListCopy]; // 推广产品企业
        this.getListDrug();
      } else {
        console.log('getRelationScoreData', this.getRelationScoreData);
        let curr = this.getRelationScoreData.find(item => item.id === id);
        if (curr) {
          this.pointsForm.endTimeValue = curr.endTime;
          this.pointsForm.startTime = curr.startTime;
        }
        if (curr && curr.drugtable) {
          this.pointsForm.drugtable = curr.drugtable;
          const arr = [
            {
              drug_name: curr.drugtableName[0],
              drug_id: curr.drugtable[0]
            }
          ];
          this.drugList = arr;
        }
        this.packageDisabled = true;
        this.buttonLoading = true;
        this.timeId = setTimeout(() => {
          if (this.buttonLoading === true) {
            // 2.5s后还没加载成功, 进行提示
            this.importPakageForm.relationScoreId = ''; // 清空'关联执行包'
            this.packageDisabled = false;
            this.buttonLoading = false;
            this.isDelay = true; // 网络延迟
            this.$message.error('网络延迟，请重新选择“关联任务积分包”！');
          }
        }, 2500);
        let arg = {
          id: id
        };
        const response = await getRelationScoreList(arg);
        clearTimeout(this.timeId);
        if (!this.isDelay) {
          // 没延迟
          this.packageDisabled = false;
          this.buttonLoading = false;
          // this.showTaskType();
          this.kfpjfVal = response.data.data[0].kfpjf; // 获取值进行判断
          this.importPakageForm.kfpjf = response.data.data[0].kfpjf; // 默认展示的值
          this.taskTypeList1val = response.data.data[0].taskTypeList1; // 获取有效服务类型list
          if (!isHistory) {
            this.checkedDsScope = [];
            this.checkedDsScope = response.data.data[0].taskTypeSet;
          }
          this.drugProducerList = response.data.data[0].drugProducerList; // 推广产品企业
          this.pkgTaskTypeQtyList = response.data.data[0].pkgTaskTypeQtyList;
          this.$refs.dismantleTableRef.setData(this.pkgTaskTypeQtyList, this.pointsForm.kfpjf);
        } else {
          this.isDelay = false;
        }
      }
    },
    setSelectNodes(arr) {
      this.$refs.tree1.setCheckedKeys(arr);
      this.$refs.tree2.setCheckedKeys(arr);
      this.$refs.tree3.setCheckedKeys(arr);
      // this.$refs.tree7.setCheckedKeys(arr);
    },
    // 新增按钮-展示弹窗
    addData() {
      // 获取执行包编号
      getPackageSn().then(res => {
        if (res.data.code === 0) {
          this.dialogType = 'add';
          this.showTit = '新增';
          this.showDialog = true;
          this.showPackage = true;
          this.pointsForm.packageSn = res.data.data || null;
        }
      });
    },

    // 批量下发按钮-展示弹窗
    addData1() {
      this.dialogType = 'add';
      this.showTit = '批量下发';
      this.showDialog1 = true;
      this.listLoading = false;
      this.showTaskType('1');
    },
    // 编辑
    editBtn(row) {
      this.dialogType = 'edit';
      this.showTit = '编辑';
      this.showDialog = true;
      this.jddxVal = row.typeid;
      if (row.typeid == '4') {
        // 判断接单对象是否展示
        this.showPackage = false;
      } else {
        this.showPackage = true;
      }

      let arg = {
        id: row.id
      };

      getScorePackagePageById(arg).then(response => {
        this.showTaskType();
        this.pointsForm = response.data.data;
        this.idVal = this.pointsForm.relationScoreId;
        this.kfpjfVal = this.pointsForm.kfpjf; // 获取值进行判断-可分配积分
        this.scoreVal = this.pointsForm.score; // 获取值进行判断-服务总值
        // 回显选中的有效服务类型
        this.checkedDsScope = this.pointsForm.taskTypeSet;
        this.showQuizList(this.pointsForm.relationScoreId);
        // if (this.pointsForm.relationScoreId === '-1') {
        //   this.pointsForm.quizIds = [...this.pointsForm.quizRelationIds]
        //   delete this.pointsForm.quizRelationIds
        // }
        // if (row.endTime) {
        //   const timestamp = new Date(row.endTime).getTime();
        //   this.pointsForm.endTimeValue = timestamp;
        // }
      });
    },
    showRestart(row) {
      return false;
      if (row.endTime) {
        let targetDate;
        // 判断 endTime 是否符合 YYYY-MM-DD 格式
        const datePattern = /^\d{4}-\d{2}-\d{2}$/;
        if (datePattern.test(row.endTime)) {
          // 如果是日期格式，则添加 23:59:59
          targetDate = new Date(`${row.endTime} 23:59:59`);
        } else {
          // 否则直接转换为 Date 对象
          targetDate = new Date(row.endTime);
        }
        const currentDate = new Date();
        if (targetDate.getTime() < currentDate.getTime()) {
          return true;
        }
      }
      return false;
    },
    restartFn(row) {
      this.currentRow = row;
      this.restartVisible = true;
    },
    restartVisibleClose() {
      this.$refs.restartForm.resetFields();
      this.restartVisible = false;
    },
    restartSubmit() {
      this.$refs.restartForm.validate(async valid => {
        if (valid) {
          const date = this.formatDate(this.restartForm.endTimeValue);
          const obj = {
            id: this.currentRow.id,
            endTime: date
          };
          const res = await restartApi(obj);
          if (res.data.code === 0) {
            this.$message.success('重启成功');
            this.getList(this.page);
            this.restartVisibleClose();
          }
        }
      });
    },
    // 回显试卷列表
    async showQuizList(id) {
      if (id == '-1') {
        this.quizList = this.availQuizList;
      } else {
        let arg = {
          id
        };
        const response = await getRelationScoreList(arg);
        const quizRelations = response.data.data[0].quizRelations || [];
        this.quizList = quizRelations.map(ele => ({
          ...ele,
          quizId: ele.relationId
        }));
      }
    },
    // 判断是否为-1, 若为-1则选择，不为-1则禁用
    disabledFn() {
      if (this.idVal == '-1') {
        return false;
      } else {
        return true;
      }
    },
    close() {
      this.getList(this.page, this.searchForm);
    },

    // 判断服务总值不能大于可分配积分值
    getScoreval(score) {
      this.getScore = score;
      if (Number(score) <= Number(0)) {
        this.$message.error('服务总值必须大于0');
        return false;
      } else {
        if (this.showTit == '新增') {
          if (parseInt(score) > parseInt(this.kfpjfVal)) {
            this.$message.error('服务总值必须小于可分配积分值');
          }
          return false;
        } else {
          if (parseInt(score) - parseInt(this.scoreVal) > parseInt(this.kfpjfVal)) {
            this.$message.error('服务总值必须小于可分配积分值');
          }
          return false;
        }
      }
    },
    getAllTaskTypeList() {
      let taskTypeList = [];
      taskTypeList = taskTypeList.concat(this.$refs.tree1.getCheckedNodes());
      taskTypeList = taskTypeList.concat(this.$refs.tree2.getCheckedNodes());
      taskTypeList = taskTypeList.concat(this.$refs.tree3.getCheckedNodes());
      return taskTypeList;
    },
    formatDate(inputDate) {
      const date = new Date(inputDate);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    // 弹窗-确定按钮
    sureBtn(formName) {
      this.$refs.pointsForm.validate(valid => {
        if (valid) {
          const date = this.formatDate(this.pointsForm.endTimeValue);
          this.pointsForm.endTime = date;
          this.buttonLoading = true;
          this.pointsForm.packageType1 = '1'; // 必传固定值
          this.pointsForm.packageType2 = '1'; // 必传固定值
          this.pointsForm.userNum = '1'; // 必传固定值
          if (this.dialogType == 'add') {
            if (this.pointsForm.relatedService == 0) {
              this.$message.info('请选择关联服务企业');
              return false;
            }
            // 新增
            if (this.jddxVal == '3') {
              if (this.pointsForm.userList.length == 0) {
                this.$message.error('接单对象不能为空');
                return false;
              }
            }
            if (this.idVal != '-1') {
              if (!this.pointsForm.drugtable || this.pointsForm.drugtable.length === 0) {
                this.pointsForm.drugtable = this.drugList.map(item => item.drug_id);
              }
              this.pointsForm.drugProducerList = this.drugProducerList; // 推广产品企业

              if (parseInt(this.getScore) > parseInt(this.kfpjfVal)) {
                this.$message.error('服务总值必须小于可分配积分值');
                this.relationScorechange(this.idVal);
                return false;
              }
            } else {
              if (!this.pointsForm.drugProducerList || this.pointsForm.drugProducerList.length === 0) {
                this.pointsForm.drugProducerList = this.drugProducerList; // 推广产品企业
              }
              if (!this.pointsForm.drugtable || this.pointsForm.drugtable.length === 0) {
                this.pointsForm.drugtable = this.drugList.map(item => item.drug_id);
              }
            }

            if (parseInt(this.pointsForm.score) == '0') {
              this.$message.error('服务总值必须大于0');
              this.relationScorechange(this.idVal);
              return false;
            }
            const tableData = this.$refs.dismantleTableRef.getDetail();
            let pkgTaskTypeQtyList;
            pkgTaskTypeQtyList = tableData.map(item => {
              return {
                taskTypeName: item.taskTypeName,
                price: item.score,
                taskTypeId: item.taskTypeId,
                qty: item.qty
              };
            });

            let flag = this.pkgTaskTypeQtyList.every(item => item.qty == 0);
            if (flag) {
              this.$message.error('请选择具体任务');
              return false;
            }
            this.pointsForm.pkgTaskTypeQtyList = pkgTaskTypeQtyList;

            delete this.pointsForm.drugProducerList;
            let treeArr = tableData.map(item => {
              return {
                taskTypeName: item.taskTypeName,
                taskTypeId: item.orgTaskTypeId
              };
            });

            let arr1 = [...pFlist];
            tableData.forEach(item => {
              const curr = arr1.find(iten => iten.taskTypeId === item.parent_id);
              if (curr) {
                curr.children.push({
                  taskTypeId: item.orgTaskTypeId,
                  taskTypeName: item.taskTypeName
                });
              }
            });

            let arr3 = arr1.concat(treeArr);
            const arr4 = arr3.filter(item => {
              if (!item.children || item.children.length > 0) {
                return item;
              }
            });
            this.pointsForm.taskTypeList = arr4;

            addWmScorePackage(this.pointsForm)
              .then(response => {
                this.$message.success('新增成功');
                this.cancelBtn();
                this.buttonLoading = false;
              })
              .catch(() => {
                // this.cancelBtn();
                this.buttonLoading = false;
              });
          } else {
            // this.relationScorechange(this.idVal);
            // this.checkedDsScope = this.pointsForm.taskTypeSet;
            // 编辑
            if (this.jddxVal == '3') {
              if (this.pointsForm.userList == null) {
                this.$message.error('接单对象不能为空');
                return false;
              }
            }

            if (parseInt(this.getScore) - parseInt(this.scoreVal) > parseInt(this.kfpjfVal)) {
              this.$message.error('服务总值必须小于可分配积分值');
              // this.relationScorechange(this.idVal);
              return false;
            } else if (parseInt(this.getScore) == '0') {
              this.$message.error('服务总值必须大于0');
              return false;
            } else {
              editData(this.pointsForm)
                .then(response => {
                  this.cancelBtn();
                  this.buttonLoading = false;
                })
                .catch(() => {
                  this.buttonLoading = false;
                  // this.cancelBtn();
                });
            }
          }
          setTimeout(() => {
            this.$store.dispatch('SET_INTEGRAL');
          }, 500);
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 弹窗-确定按钮
    sureBtn1(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const date = this.formatDate(this.pointsForm.endTimeValue);
          this.pointsForm.endTime = date;
          this.buttonLoading = true;
          // if (this.idVal == "-1") {
          //     this.pointsForm.taskTypeList = this.$refs['tree'].getCheckedNodes()
          // } else {
          //     console.log(1)
          //     this.pointsForm.taskTypeList = this.taskTypeList1val;
          // }
          this.pointsForm.taskTypeList = this.getAllTaskTypeList();
          this.pointsForm.packageType1 = '1'; // 必传固定值
          this.pointsForm.packageType2 = '1'; // 必传固定值
          this.pointsForm.userNum = '1'; // 必传固定值
          if (this.pointsForm.relationScoreId !== '-1') {
            this.pointsForm.quizRelationIds = [...this.pointsForm.quizIds];
            delete this.pointsForm.quizIds;
          }

          if (this.pointsForm.taskTypeList.length == 0) {
            this.$message.error('有效服务类型不能为空');
            return false;
          }

          if (this.dialogType == 'add') {
            // 新增
            if (this.jddxVal == '3') {
              if (this.pointsForm.userList.length == 0) {
                this.$message.error('接单对象不能为空');
                return false;
              }
            }
            if (this.idVal != '-1') {
              this.pointsForm.drugProducerList = this.drugProducerList; // 推广产品企业
              this.pointsForm.drugtable = this.drugList.map(item => item.drug_id);
              if (parseInt(this.getScore) > parseInt(this.kfpjfVal)) {
                this.$message.error('服务总值必须小于可分配积分值');
                this.relationScorechange(this.idVal);
                return false;
              }
            } else {
              if (!this.pointsForm.drugProducerList || this.pointsForm.drugProducerList.length === 0) {
                this.pointsForm.drugProducerList = this.drugProducerList; // 推广产品企业
              }
              if (!this.pointsForm.drugList || this.pointsForm.drugList.length === 0) {
                this.pointsForm.drugtable = this.drugList.map(item => item.drug_id);
              }
            }
            if (parseInt(this.getScore) == '0') {
              this.$message.error('服务总值必须大于0');
              this.relationScorechange(this.idVal);
              return false;
            }
            delete this.pointsForm.drugProducerList;
            addWmScorePackage(this.pointsForm)
              .then(async response => {
                this.$message.success('新增成功');
                this.showDialog = true;
                this.pointsForm.scorePackageName = '';
                this.pointsForm.kfpjf = this.pointsForm.kfpjf - this.pointsForm.score;
                this.buttonLoading = false;
                let res = await getPackageSn();
                this.pointsForm.packageSn = res.data.data || null;
              })
              .catch(() => {
                // this.cancelBtn();
                this.buttonLoading = false;
              });
          } else {
            // this.relationScorechange(this.idVal);
            // this.checkedDsScope = this.pointsForm.taskTypeSet;
            // 编辑
            if (this.jddxVal == '3') {
              if (this.pointsForm.userList == null) {
                this.$message.error('接单对象不能为空');
                return false;
              }
            }

            if (parseInt(this.getScore) - parseInt(this.scoreVal) > parseInt(this.kfpjfVal)) {
              this.$message.error('服务总值必须小于可分配积分值');
              // this.relationScorechange(this.idVal);
              return false;
            } else if (parseInt(this.getScore) == '0') {
              this.$message.error('服务总值必须大于0');
              return false;
            } else {
              editData(this.pointsForm)
                .then(response => {
                  this.cancelBtn();
                  this.buttonLoading = false;
                })
                .catch(() => {
                  this.buttonLoading = false;
                  // this.cancelBtn();
                });
            }
          }
          setTimeout(() => {
            this.$store.dispatch('SET_INTEGRAL');
          }, 500);
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 终止
    suspendBtn(row) {
      this.enableFlagDig = true;
      this.suspendData = row;
    },
    // 中止确认按钮
    enableFlagBtn(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let args = {
            enableType: this.enableForm.enableFlag,
            id: this.suspendData.id
          };
          updateEnable(args).then(response => {
            this.$message.success('终止成功');
            this.getList(this.page);
            this.enableFlagDig = false;
            this.enableForm = {};
          });
        } else {
          console.log('error submit!!');
          return false;
        }
        setTimeout(() => {
          this.$store.dispatch('SET_INTEGRAL');
        }, 500);
      });
    },
    // 接单审批
    receiveApproval(row) {
      this.$router.push({
        path: '/admin/assignPoints/quota/approval?id=' + row.id
      });
    },

    // 任务审核
    taskReview(row) {
      this.$router.push({
        path: '/admin/assignPoints/quota/taskAudit?id=' + row.id + '&type=taskAudit' + '&taskStatus=2'
      });
    },

    // 删除
    delBtn(row) {
      this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.tableLoading = true;
          updateWmScorePackage({
            id: row.id,
            delFlag: 1
          })
            .then(() => {
              this.getList(this.page);
              this.tableLoading = false;
            })
            .catch(() => {
              this.tableLoading = false;
            });
        })
        .catch(() => {
          //console.log("请求异常");
        });
    },
    // 查看
    toView(row) {
      this.$router.push({
        path: '/admin/assignPoints/quota/taskAudit?id=' + row.id + '&type=look' + '&scorePackageStatus=' + row.scorePackageStatus
      });
    },

    // 导出
    exportBtn(row) {
      this.exportDig = true;
      this.checkRow = row;
    },
    // 拆包
    splitBtn(row) {
      this.$router.push({
        path: '/admin/assignPoints/quota/split?id=' + row.id + '&score=' + row.score
      });
    },
    // 导出汇总报告
    taskExport(type) {
      let row = this.checkRow;
      var obj = {
        scorePackageDrugId: row.id,
        exportType: 1
      };
      if (type === 'word') {
        this.wordLoading = true;
        exportZbReport(obj)
          .then(response => {
            if (undefined == response.data || undefined == response.data.data) {
              this.$message.error('导出失败');
              return false;
            }
            this.$message.success(response.data.data);
            this.exportDig = false;
            this.getList(this.page);
            this.wordLoading = false;
          })
          .catch(() => {
            this.wordLoading = false;
          });
      } else if (type === 'excel') {
        this.excelLoading = true;
        exportZbReportExcel(obj)
          .then(response => {
            if (undefined == response.data || undefined == response.data.data) {
              this.$message.error('导出失败');
              return false;
            }
            this.$message.success(response.data.data);
            this.exportDig = false;
            this.getList(this.page);
            this.excelLoading = false;
          })
          .catch(() => {
            this.excelLoading = false;
          });
      }
    },
    async taskNewExport(type) {
      try {
        let row = this.checkRow;
        var obj = {
          id: row.id,
          taskStatus: 3
        };
        let res;
        if (type === 'word') {
          this.newWordLoading = true;
          res = await taskNewExportNbqybg(obj);
        } else if (type === 'excel') {
          this.newExcelLoading = true;
          res = await taskExportNewExcelNbqybg(obj);
        }
        if (res.data) {
          this.$message.success(res.data.data);
          this.exportDig = false;
          this.getList(this.page);
        } else {
          this.$message.error('导出失败');
        }
        this.newWordLoading = false;
        this.newExcelLoading = false;
      } catch (err) {
        this.newWordLoading = false;
        this.newExcelLoading = false;
      }
    },
    // 下载报告
    downloadTask(type) {
      let latestUrl;
      if (type === 'word') {
        latestUrl = this.checkRow.reportOpt.latestUrl;
      } else if (type === 'excel') {
        latestUrl = this.checkRow.excelReportOpt.latestUrl;
      }
      let a = document.createElement('a');
      a.href = latestUrl;
      a.click();
      this.$message.success('导出汇总报告成功');
      this.exportDig = false;
    },
    downloadNewTask(type) {
      let latestUrl;
      if (type === 'word') {
        latestUrl = this.checkRow.newReportOpt.latestUrl;
      } else if (type === 'excel') {
        latestUrl = this.checkRow.newExcelReportOpt.latestUrl;
      }
      let a = document.createElement('a');
      a.href = latestUrl;
      a.click();
      this.$message.success('导出汇总报告成功');
      this.exportDig = false;
    },
    // 导出报告详情
    taskExportInfo() {
      this.taskExportInfoLoading = true;
      let row = this.checkRow;
      var obj = {
        scorePackageDrugId: row.id,
        exportType: 2
      };
      exportZbReport(obj)
        .then(response => {
          if (undefined == response.data || undefined == response.data.data) {
            this.$message.error('导出失败');
            return false;
          }
          let obj = response.data.data;
          let a = document.createElement('a');
          a.href = obj.url; // 这里的请求方式为get，如果需要认证，接口上需要带上token
          a.click();
          this.$message.success('导出报告详情成功');
          this.taskExportInfoLoading = false;
        })
        .catch(() => {
          this.taskExportInfoLoading = false;
        });
    },
    // 隐藏弹出窗
    stopcancelBtn() {
      this.enableFlagDig = false;
      this.enableForm = {};
    },
    cancelBtn() {
      this.showDialog = false;
      this.showDialog1 = false;
      this.taskTypedialog = false;
      this.pointsForm = {
        packageUserScope: '1',
        scorePackageName: '',
        relationScoreId: '',
        kfpjf: '',
        taskTypeList: [],
        userList: [],
        score: '',
        subjectLocation: '',
        packageSn: null
      };
      this.$refs.pointsForm.resetFields();
      this.getList(this.page, this.searchForm);
    },

    dateChange() {
      console.log('11');
      this.$forceUpdate();
    },
    handleClose() {
      this.taskTypedialog = false;
      this.showDialog = false;
      this.showDialog1 = false;
      this.enableFlagDig = false;
      this.$refs.pointsForm.resetFields();
      this.$refs.dismantleTableRef.init();
      this.pointsForm.typeid = '3';
      this.getList(this.page, this.searchForm);
    },

    // 表格-查看有效服务类型
    viewDetail(row) {
      // this.taskTypes = row.taskTypes == null ? "无" : row.taskTypes;
      // this.taskTypedialog = true;

      selectByScorePackageId({id: row.id}).then(response => {
        this.taskTypes = response.data.data;
        this.taskTypes.forEach(item => {
          item.code = plist[item.code];
        });
        this.taskTypedialog = true;
      });
    },
    async detailFn(row) {
      const res = await getPkgTaskDetailsApi({
        pkgId: row.id
      });
      if (res.data.code === 0) {
        this.taskListArr = res.data.data;
      }
      this.taskListDialog = true;
    },
    // 分页查询
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    currentChange(current) {
      this.page.currentPage = current;
    },
    searchReset() {
      this.publishDateTime = '';
      this.monthStart = '';
      this.monthEnd = '';
    },
    //以下是结算的方法
    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总价';
          return;
        }
        if (index === 3 || index === 4) {
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            // sums[index] += ' 元';
          } else {
            sums[index] = 'N/A';
          }
        } else {
          sums[index] = '*';
        }
      });
      return sums;
    },
    discountChange(e) {
      let value = e.discount.toString();
      value = value.replace(/[^\d.\-]/g, ''); //清除"数字"和"." "-"负号以外的字符
      value = value.replace(/^\./g, ''); //验证第一个字符是数字
      value = value.replace(/\.{2,}/g, ''); //只保留第一个, 清除多余的
      value = value
        .replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.');
      value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数

      e.discount = value;
      e.settleAmount = (Number(this.score) * Number(value)).toFixed(2);
      let actualAmount = 0;
      if (this.form.serviceCharge !== null && this.form.serviceCharge !== undefined) {
        actualAmount = (value / (this.form.serviceCharge + 1)).toFixed(2);
        e.actualAmount = actualAmount;
        this.calcPayAmount();
      }
    },
    discountInput(e) {
      let value = e.discount;
      // if (value) {
      //
      // } else {
      //     e.discount = 0
      //     e.settleAmount = 0
      // }
      value = value.replace(/[^\d.\-]/g, ''); //清除"数字"和"." "-"负号以外的字符
      value = value.replace(/^\./g, ''); //验证第一个字符是数字
      value = value.replace(/\.{2,}/g, ''); //只保留第一个, 清除多余的
      value = value
        .replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.');
      value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
      // if (Number(value) > 2) {
      //   e.discount = 1
      //   this.$message.warning('折扣不能超过2');
      //   return
      // }
      // e.discount = Number(value)
      e.discount = value;
      e.settleAmount = (Number(this.score) * Number(value)).toFixed(2);
      let actualAmount = 0;
      if (this.form.serviceCharge !== null && this.form.serviceCharge !== undefined) {
        actualAmount = (value / (this.form.serviceCharge + 1)).toFixed(2);
        e.actualAmount = actualAmount;
        this.calcPayAmount();
      }
    },
    settleAmountChange(e) {
      let value = e.settleAmount.toString();
      if (value) {
        value = value.replace(/[^\d.\-]/g, ''); //清除"数字"和"." "-"负号以外的字符
        value = value.replace(/\.{2,}/g, ''); //只保留第一个, 清除多余的
        value = value
          .replace('.', '$#$')
          .replace(/\./g, '')
          .replace('$#$', '.');
        value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数

        let total = Number(this.score) * 1.2;
        let total1 = Number(this.score) * 1.2;
        // if (Number(value) > total) {
        //   e.settleAmount = this.score
        //   e.discount = 1
        //   this.$message.warning('折扣不能超过2');
        //   return
        // }
        // if (Number(value) < total1) {
        //   e.settleAmount = this.score
        //   e.discount = 1
        //   this.$message.warning('折扣不能低于0.5');
        //   return
        // }
        let discount = (Number(value) / Number(this.score)).toFixed(2);
        let actualAmount = (value / (this.form.serviceCharge + 1)).toFixed(2);
        e.settleAmount = value;
        e.discount = discount;
        e.actualAmount = actualAmount;
      } else {
        e.settleAmount = 0;
        e.discount = 0;
        e.actualAmount = 0;
      }
      this.calcPayAmount();
    },
    settleAmountInput(e) {
      let value = e.settleAmount;
      value = value.replace(/[^\d.\-]/g, ''); //清除"数字"和"." "-"负号以外的字符
      value = value.replace(/\.{2,}/g, ''); //只保留第一个, 清除多余的
      value = value
        .replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.');
      value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
      let discount = 0;
      let actualAmount = 0;
      if (value) {
        discount = (Number(value) / Number(this.score)).toFixed(2);
        actualAmount = (value / (this.form.serviceCharge + 1)).toFixed(2);
      }

      e.settleAmount = value;
      e.discount = discount;
      e.actualAmount = actualAmount;
      this.calcPayAmount();
    },
    actualAmountChange(e) {
      let value = e.actualAmount;
      value = value.replace(/[^\d.\-]/g, ''); //清除"数字"和"." "-"负号以外的字符
      value = value.replace(/\.{2,}/g, ''); //只保留第一个, 清除多余的
      value = value
        .replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.');
      value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
      let settleAmount = 0;
      let discount = 0;
      if (this.form.serviceCharge !== undefined && this.form.serviceCharge !== null) {
        settleAmount = (value / (1 + this.form.serviceCharge)).toFixed(2);
        discount = (settleAmount / Number(this.score)).toFixed(2);
        console.log(settleAmount);
      } else {
        console.log('未选择结算渠道');
      }
      e.actualAmount = value;
      e.settleAmount = settleAmount;
      e.discount = discount;
    },
    actualAmountInput(e) {
      let value = e.actualAmount;
      value = value.replace(/[^\d.\-]/g, ''); //清除"数字"和"." "-"负号以外的字符
      value = value.replace(/\.{2,}/g, ''); //只保留第一个, 清除多余的
      value = value
        .replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.');
      value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
      let settleAmount = 0;
      let discount = 0;
      if (this.form.serviceCharge !== undefined && this.form.serviceCharge !== null) {
        settleAmount = (value / (1 + this.form.serviceCharge)).toFixed(2);
        discount = (settleAmount / Number(this.score)).toFixed(2);
      } else {
        console.log('未选择结算渠道');
      }
      e.actualAmount = value;
      e.settleAmount = settleAmount;
      e.discount = discount;
    },
    reIssue(id) {
      this.$confirm('此操作将不可撤回,确认重新结算?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.buttonLoading = true;
        const args = {
          id: id
        };
        settleReIssue(args)
          .then(response => {
            this.$message.warning(response.data.msg);
            this.buttonLoading = false;
          })
          .catch(() => {
            // this.hideDialog();
            this.buttonLoading = false;
          });
      });
    },
    hideDialog() {
      this.settleTableVisible = false;
      this.form = {};
      this.gridData = [];
      this.getList(this.page, this.searchForm);
      // this.$refs.form.resetFields();
    },
    settleSave() {
      if (!this.id) {
        this.$message.error('数据异常');
        return;
      }
      this.$refs['form'].validate(valid => {
        if (valid) {
          for (var i = 0; i < this.gridData.length; i++) {
            const item = this.gridData[i];
            if (Number(item.discount) < Number(0.8) || Number(item.discount) > Number(1.2)) {
              this.$message.error('第' + parseInt(i + 1) + '行，折扣应介于0.8~1.2之间');
              return false;
            }
          }
          const args = {
            id: this.id,
            invoiceCategory: this.form.invoiceCategory,
            categoryName: this.form.categoryName,
            description: this.form.description,
            subjectLocation: this.form.subjectLocation,
            notes: this.gridData,
            mahSettleDeptId: this.form.mahSettleDeptId,
            token: this.submitToken
          };
          if (args.subjectLocation === 'REN_LI_JIA' && args.notes[0].settleAmount > 50000) {
            this.$message.error('人力家单笔结算额不得超过5万元');
            return;
          }
          this.buttonLoading = true;
          settleSave(args)
            .then(response => {
              if (response.data.code === 0) {
                this.$message.success('保存成功');
                //this.$message.success("提交结算申请结算成功");
              }
              this.hideDialog();
              this.buttonLoading = false;
            })
            .catch(() => {
              this.buttonLoading = false;
              // this.hideDialog();
            });
        }
      });
    },
    settleSubmit() {
      if (!this.id) {
        this.$message.error('数据异常');
        return;
      }
      this.$refs['form'].validate(valid => {
        if (valid) {
          for (var i = 0; i < this.gridData.length; i++) {
            const item = this.gridData[i];
            if (Number(item.discount) < Number(0.8) || Number(item.discount) > Number(1.2)) {
              this.$message.error('第' + parseInt(i + 1) + '行，折扣应介于0.8~1.2之间');
              return false;
            }
          }
          const args = {
            id: this.id,
            invoiceCategory: this.form.invoiceCategory,
            categoryName: this.form.categoryName,
            description: this.form.description,
            subjectLocation: this.form.subjectLocation,
            mahSettleDeptId: this.form.mahSettleDeptId,
            notes: this.gridData,
            token: this.submitToken
          };
          if (args.subjectLocation === 'REN_LI_JIA' && args.notes[0].settleAmount > 50000) {
            this.$message.error('人力家单笔结算额不得超过5万元');
            return;
          }
          this.buttonLoading = true;
          settleSubmit(args)
            .then(response => {
              if (response.data.code === 0) {
                this.$message.success('提交成功');
              }
              this.hideDialog();
              this.buttonLoading = false;
            })
            .catch(() => {
              this.buttonLoading = false;
              // this.hideDialog();
            });
        }
      });
    },
    //以上是结算的方法
    // 导入弹窗关闭
    importExcel() {
      // 导入Excel表格
      this.disabled1 = true;
    },
    // 导出Excel表格
    exportExcel(row) {
      //获取并存储服务器返回的AuthorizationToken信息
      // 发送下载报表请求
      console.log('发送下载报表请求');
      let param = {fileName: 'batch_create_score_package_template.xlsx'};
      axios
        .post('/admin/template-file/download', param, {
          responseType: 'arraybuffer'
        })
        .then(res => {
          fileDownload(res.data, '批量创建积分包模板.xlsx');
          this.$message.success('下载模板成功');
        });
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    uploadError(res, file, fileList) {
      // 上传错误
      this.loading = false;
      this.$message({
        message: '未检测到数据，请修改后重新上传',
        type: 'error'
      });
      this.$refs.upload.clearFiles();
    },
    uploadSuccess(res, file, fileList) {
      // 上传成功后的回调
      this.loading = false;
      if (res.msg == null && res.data.length == 0) {
        this.$message.success('文件上传成功');
      } else if ((res.msg = '批量创建积分包失败')) {
        this.$message({
          message: '文件上传失败',
          type: 'error'
        });
      } else if (res.msg == null && res.data.length > 0) {
      }
      this.tableLists = res.data;
      this.listLoading = false;
      this.$refs.upload.clearFiles();
    },
    uploadPath() {
      // 上传地址
      return 'admin/wmscorepackage/batch';
    },

    submitUpload(row) {
      // 开始上传按钮
      this.$refs.upload.submit(row);
    }
  }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.settle-label {
  width: 48%;

  ::v-deep .el-input__inner {
    width: 233px;
  }
}
.settle-desc {
  width: 80%;

  ::v-deep textarea {
    width: 600px;
  }
}

.separator {
  background-color: rgba(242, 242, 242, 1) !important;
  text-align: center;
  width: 96%;
  height: 34px;
  line-height: 34px;
  margin-bottom: 2px;
}

.settle-grid {
  ::v-deep .el-input__inner {
    text-align: center;
    border: none;
  }
}
.template-btn {
  color: #3894ff;
}
.import-pakage-upload {
  ::v-deep.el-upload-list__item {
    margin-top: 0;
  }
}
.template-download-box {
  padding: 20px;
  border: 1px solid #cccccc;
  border-radius: 6px;
}
.attention {
  color: #d9001b;
}
.down-item {
  margin-left: 20px;
  margin-bottom: 15px;
  span {
    width: 160px;
    display: inline-block;
    text-align: right;
  }
  .first {
    width: 240px;
  }
}
.checkbox {
  margin-right: 15px !important;
}
.btn {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>

<style>
/*.treeBox {*/
/*  width: 30%;*/
/*  height: 200px;*/
/*  border: 1px solid #dcdfe6;*/
/*  overflow-y: scroll;*/
/*  overflow-x: hidden;*/
/*  border-radius: 10px;*/
/*}*/
.treeBox {
  float: left;
  width: 30%;
}
.treeBox3 {
  width: 35%;
}

/*滚动条样式*/
.treeBox::-webkit-scrollbar {
  width: 10px;
}

.treeBox::-webkit-scrollbar-thumb {
  border-radius: 10px;
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  background-color: #f90;
}

.treeBox::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  border-radius: 10px;
  background: rgba(0, 0, 0, 0.1);
}

.el-upload-dragger {
  background-color: #fff;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  width: 100px;
  height: 30px;
  text-align: center;
  position: relative;
  overflow: hidden;
}
/*.item {*/
/*  margin-top: 10px;*/
/*  margin-right: 40px;*/
/*}*/
.pings {
  width: 10px;
  height: 30px;
}

.generating {
  color: #1e90ff;
  text-align: center;
  display: block;
}

.btns {
  display: flex;
  justify-content: center;
}
.title-msg {
  text-align: center;
  margin-top: 10px;
}
</style>
