<template>
  <basic-container>
    <div class="tabStyle" v-loading="pageLoading">
      <avue-crud
        :data="tableData"
        :option="option"
        :page.sync="page"
        :table-loading="tableLoading"
        @on-load="getList"
        @size-change="sizeChange"
        @current-change="currentChange"
        @search-change="searchVal"
        @search-reset="searchReset"
      >
        <!-- 左侧操作菜单 -->
        <template slot="menuLeft">
          <el-button v-if="addShowFlag" type="primary" icon="el-icon-plus" size="small" @click.stop="addBtn()">新增 </el-button>
          <el-button type="primary" size="small" @click="exportBtnFn">导 出</el-button>
          <el-button v-if="importShowFlag" type="primary" size="small" @click="importBtn">导 入</el-button>
        </template>
        <!-- 分配日期搜索 -->
        <template slot="allocationDateSearch">
          <el-date-picker
            v-model="dateTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            @change="startDateBtn"
          >
          </el-date-picker>
        </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>
            <el-button type="text" size="small" icon="el-icon-view" @click="viewBtn(scope.row, scope.index)">查看 </el-button>
            <el-button
              v-if="addShowFlag"
              type="text"
              size="small"
              icon="el-icon-setting"
              @click="updateBtn(scope.row, scope.index)"
              :disabled="scope.row.packageFinishStatus === '2' || scope.row.packageFinishStatus === '1'"
              >编辑
            </el-button>
            <el-button type="text" v-if="false" size="small" icon="el-icon-close" @click="suspendBtn(scope.row, scope.index)">
              终止
            </el-button>
            <!-- <el-button
              type="text"
              size="small"
              icon="el-icon-document"
              @click="taskStatisticsFn(scope.row, scope.index)"
            >
              服务统计
            </el-button> -->

            <el-button type="text" size="small" icon="el-icon-folder-checked" :disabled="scope.row.ysh == 0 || scope.row.ysh == null" @click="exportBtn(scope.row, scope.index)">
              导出
              <!-- 合同下载 -->
            </el-button>
            <!-- :disabled="scope.row.ysh == 0 || scope.row.ysh == null" -->
            <el-button v-if="scope.row.contract" type="text" size="small" icon="el-icon-folder-checked" @click="exportFile(scope.row, scope.index)">
              合同下载
            </el-button>
          </template>
        </template>
      </avue-crud>
      <!-- 新增 -->
      <el-dialog :title="showTitle" :visible.sync="showDig" center width="80%" :before-close="handleClose">
        <el-form v-if="showDig" :model="distributionForm" :disabled="allNot" :rules="rules" ref="distributionForm" label-width="140px" class="demo-ruleForm">
          <el-row>
            <el-col :span="12">
              <el-form-item label="执行包名称" prop="scorePackageName">
                <el-input v-model="distributionForm.scorePackageName"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="所属月份" prop="belongDate">
                <el-date-picker disabled v-model="distributionForm.belongDate" type="month" placeholder="选择日期" format="yyyy-MM" value-format="yyyy-MM" style="width: 100%">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="关联服务企业" prop="relatedService">
                <el-select
                  v-model="distributionForm.relatedService"
                  placeholder="请选择"
                  @change="RelatedServiceChange"
                  style="width: 100%"
                  :disabled="relatedAble || editDisabled"
                >
                  <el-option v-for="item in fwqyOptions" :key="item.deptId" :label="item.name" :value="item.deptId"> </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="关联执行包名称" prop="relationScoreId">
                <el-select
                  v-model="distributionForm.relationScoreId"
                  placeholder="请选择"
                  @change="scoreNameChange"
                  style="width: 100%"
                  v-bind:disabled="scoreAble || editDisabled"
                >
                  <el-option v-for="item in gljfbOptions" :key="item.id" :label="item.relationScoreName" :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="planId">
                <el-select v-model="distributionForm.planId" style="width: 100%" @change="planIdChange" :disabled="planIdDisabled">
                  <el-option v-for="item in planList" :key="item.planId" :label="item.planName" :value="item.planId"> </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="承接对象" prop="acceptSug">
                <el-select v-model="distributionForm.acceptSug" placeholder="请选择" style="width: 100%" disabled>
                  <el-option v-for="item in jbdxOptions" :key="item.id" disabled :label="item.gsmc" :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
                  disabled
                  class="w100"
                  v-model="distributionForm.startTime"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  type="date"
                  @input="$forceUpdate()"
                  placeholder="选择日期"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="截止日期" prop="endTimeValue">
                <el-date-picker
                  disabled
                  class="w100"
                  v-model="distributionForm.endTimeValue"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  type="date"
                  @input="$forceUpdate()"
                  placeholder="选择日期"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="可分配积分值" prop="kfpjfz">
                <el-input v-model="kfpjfz" :disabled="kfpjfVal"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="执行包总值" prop="score">
                <el-input disabled v-model="distributionForm.score"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="推广产品" prop="drugtable">
                <el-select v-model="distributionForm.drugtable" placeholder="默认全选" style="width: 100%" disabled multiple>
                  <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-col :span="12">
              <el-form-item label="服务区域" prop="provAbbr" v-if="IS_DLS">
                <el-select v-model="distributionForm.provAbbr" placeholder="请选择服务区域" style="width: 100%" :disabled="!distributionForm.acceptSug">
                  <el-option v-for="(item, index) in provAbbrList" :key="index" :label="item" :value="item"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <!-- <el-col :span="12">
              <el-form-item label="B端服务上限(%)" prop="entTaskLimit">
                <el-input-number
                  disabled
                  v-model="distributionForm.entTaskLimit"
                  controls-position="right"
                  :min="0"
                  :max="100"
                  class="input-num-box w100"
                />
              </el-form-item>
            </el-col> -->
            <el-col :span="12">
              <el-form-item label="测试试卷" v-if="false">
                <el-select v-model="distributionForm.quizIds" placeholder="选择试卷，支持多选" style="width: 100%" multiple>
                  <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 v-if="false">
            <el-col :span="12">
              <el-form-item label="审核管理费比例(%)" prop="auditManagementFeeRates">
                <el-input-number v-model="distributionForm.auditManagementFeeRates" controls-position="right" :min="0" :max="100" class="input-num-box w100" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row v-if="!IS_DLS">
            <el-col :span="24">
              <el-form-item label="有效服务类型" required>
                <div>
                  <div class="treeBox">
                    <el-tree
                      disabled
                      ref="tree1"
                      :data="tree1"
                      :filter-node-method="filterNode"
                      :default-checked-keys="checkedDsScope"
                      show-checkbox
                      node-key="taskTypeId"
                      :props="defaultProps"
                      @check-change="getNodeData"
                    >
                    </el-tree>
                  </div>
                  <div class="treeBox">
                    <el-tree
                      disabled
                      ref="tree2"
                      :data="tree2"
                      :filter-node-method="filterNode"
                      :default-checked-keys="checkedDsScope"
                      show-checkbox
                      node-key="taskTypeId"
                      :props="defaultProps"
                      @check-change="getNodeData"
                    >
                    </el-tree>
                  </div>
                  <div class="treeBox treeBox3">
                    <el-tree
                      disabled
                      ref="tree3"
                      :data="tree3"
                      :filter-node-method="filterNode"
                      :default-checked-keys="checkedDsScope"
                      show-checkbox
                      node-key="taskTypeId"
                      :props="defaultProps"
                      @check-change="getNodeData"
                    >
                    </el-tree>
                  </div>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-else>
            <el-col :span="24">
              <el-form-item label="有效服务类型" required>
                <dismantleTable ref="dismantleTableRef" :propsTableData="planItem" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="描述">
                <el-input type="textarea" :rows="3" v-model="distributionForm.description"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose('form')">取 消</el-button>
          <el-button type="primary" @click="submitForm('distributionForm')" :loading="buttonLoading" v-show="addShow">确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog title="导出" :visible.sync="exportDig" width="40%" 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>
          <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="!isShengyu">
            <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' && isShengyu" style="color: red;">
            由于（{{ suspendData.score - suspendData.kfpjf }}）积分已被下级分派，您将回收（{{ suspendData.kfpjf }}）积分，是否继续？
          </p>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="stopcancelBtn()">取 消</el-button>
          <el-button type="primary" @click="enableFlagBtn('enableForm')">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <!-- 任务审核 -->
    <taskStatistics :taskStatisticsShow.sync="taskStatisticsShow" :currentId.sync="currentId" />

    <!-- 重启积分包 -->
    <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" v-model="restartForm.endTimeValue" 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="importDialogVisible" width="60%" :before-close="importClose" center>
      <div class="import-content" v-loading="importLoading">
        <el-upload
          :action="uploadUrl"
          :headers="headers"
          :before-upload="beforeFileUpload"
          :limit="1"
          :on-remove="handleRemove"
          :on-exceed="handleExceed"
          :on-error="handleError"
          accept=".xls,.xlsx"
          :show-file-list="false"
          :on-success="handleSuccess"
          :file-list="fileList"
        >
          <el-button size="small" type="primary">导入执行包（*.xlsx,*.xls）</el-button>
        </el-upload>
        <el-button type="text" @click="dowmTemplateFn">下载模板</el-button>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="importDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 导入存在失败 -->
    <el-dialog title="上传失败" width="60%" :close-on-click-modal="false" @close="importErrorDialogShow = false" :visible.sync="importErrorDialogShow" center>
      <div>
        <el-table :data="importErrorTableData" border style="width: 100%">
          <el-table-column prop="idx" label="行号" width="180" />
          <el-table-column prop="errorMsg" label="错误信息" />
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="importErrorDialogShow = false">关 闭</el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
import dismantleTable from './components/dismantleTable.vue';
import {templateDownload} from '@/api/assignPoints/currency/manList';
import {pointsData} from '@/const/crud/points';
import {tree1, tree2, tree3, tree7, pFlist} from '@/const/crud/taskTypeTree/index';
import store from '@/store';
import {
  selectWmScorePackageLists,
  saves,
  updateByIds,
  updateStatusByIds,
  stopWmScorePackage,
  lists,
  selectKfpjf,
  selectWmScorePackage,
  listCso, // 展示关联积分包
  remote,
  scoreTasktype,
  showTask,
  listCsoById,
  selectRelationScoreId,
  getTaskTree,
  taskExportNbqybg,
  taskExportExcelNbqybg,
  taskNewExportNbqybg,
  taskExportNewExcelNbqybg,
  settleSave,
  getSysFileApi,
  getListAncestorApi,
  pkgInfoExportApi
} from '@/api/taskManagement/points.js';
import {getDrugProducerList, getListDrugApi, getTaskTypeTree, updateEnable, exportInfoApi, restartApi} from '@/api/assignPoints/currency/index';
// import Form from "../../gen/form.vue";
import {mapGetters} from 'vuex';
import {getAvailQuizList} from '@/api/test';
import {getPlanListApi} from '@/api/wmdeptbudget/plan.js';
import taskStatistics from './components/taskStatistics.vue';

export default {
  name: 'points',
  data() {
    return {
      pageLoading: false,
      addShowFlag: true,
      importShowFlag: false,
      IS_DLS: false,
      planItem: [],
      currentSelect: null,
      taskStatisticsShow: false,
      planIdDisabled: true,
      currentId: '',
      loadingTxt: '......',
      taskExportLoading: false,
      wordLoading: false,
      excelLoading: false,
      newWordLoading: false,
      newExcelLoading: false,

      exportDig: false,
      checkRow: '', // 导出选中值
      buttonLoading: false,
      tree1: tree1,
      tree2: tree2,
      tree3: tree3,
      tree7: tree7,
      checkedDsScope: [],
      listQuerys: {
        taskTypeName: undefined
      },
      TreeData: [],
      defaultProps: {
        children: 'children',
        label: 'taskTypeName',
        disabled: this.disabledFn
      },
      getNodeVal: [],
      //承接对象
      isAble: false,
      //关联积分包
      scoreAble: false,
      relatedAble: false,
      kfpjfVal: true,
      kfpjfz: '',
      relationScoreId: '',
      belongDate: '',
      showTitle: '',
      showDig: false,
      allNot: false,
      addShow: false,
      drugList: [],
      provAbbrList: [],
      editDisabled: false,
      distributionForm: {
        provAbbr: '',
        scorePackageName: '',
        score: '',
        relatedService: '',
        relationScoreId: '',
        description: '',
        acceptSug: '',
        packageFinishStatus: '',
        belongDate: '',
        drugtable: [],
        startTime: '',
        endTimeValue: '',
        quizIds: [],
        planId: ''
      },
      pickerOptions: {
        disabledDate(time) {
          // 禁用当前日期之前
          const currentDate = new Date();
          return time.getTime() < currentDate.getTime();
        }
      },
      rules: {
        scorePackageName: [{required: true, message: '请输入执行包名称', trigger: 'blur'}],
        acceptSug: [{required: true, message: '请选择承接对象', trigger: 'blur'}],
        provAbbr: [{required: true, message: '请选择服务区域', trigger: 'blur'}],
        relationScoreId: [
          {
            required: true,
            message: '请选择关联执行包名称',
            trigger: 'change'
          }
        ],
        score: [{required: true, message: '请输入执行包总值', trigger: 'blur'}, {pattern: /^[0-9]*$/, message: '请输入正确的执行包总值'}],
        planId: [{required: true, message: '请选择服务目标', trigger: 'change'}],
        packageType1: [
          {
            required: true,
            message: '请选择积分包任务类型',
            trigger: 'change'
          }
        ],
        wmScoreTaskTypeList: [
          {
            required: true,
            message: '请选择有效服务类型',
            trigger: 'blur'
          }
        ],
        relatedService: [{required: true, message: '请选择关联服务企业', trigger: 'blur'}],
        belongDate: [{required: true, message: '请选择所属月份', trugger: 'blur'}],
        startTime: [
          {
            required: true,
            message: '请选择日期',
            trigger: 'blur'
          }
        ],
        endTimeValue: [
          {
            required: true,
            message: '请选择日期',
            trigger: 'blur'
          }
        ]
      },
      restartVisible: false,
      currentRow: {},
      restartForm: {
        endTimeValue: ''
      },
      restartFormRef: {
        endTimeValue: [
          {
            required: true,
            message: '请选择日期',
            trigger: 'blur'
          }
        ]
      },
      socreYjwc: 0,
      socreShtg: 0,
      socreShtgRate: 0,
      scorePay: 0,
      tableData: [],
      option: pointsData,
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10 // 每页显示多少条
      },
      tableLoading: false,
      searchForm: {},
      gljfbOptions: [
        {
          relationScoreName: '无',
          id: '-1'
        }
      ],
      jbdxOptions: [],
      fwqyOptions: [],
      scoreIdVal: '',
      relatedServiceVal: '',
      idVal: '',
      packageIsConductVal: '',

      packageType1: [],
      dateOptions: [],
      checkedId: '',
      relationScoreIdVal: '',
      validShow: true,
      wmScoreTaskTypeListVal: [],
      taskTypeList1val: [],
      typeList: false,
      packsgeType: false,
      returnVal: [],
      oldStars: [],
      packsgeTypedifference: true,
      packageType1Val: '',
      lookValue: '',
      dialogType: 'add',
      dateTime: '', // 查询时间
      allocationDate: '', // 开始时间
      endLabelDate: '', // 结束时间
      id: '',
      drugProducerList: [],
      drugProducerListCopy: [],
      settleTableVisible: false,
      form: {},
      gridData: [],
      settleButtonShow: false,
      textareaDisabled: false,
      suspendData: {},
      enableFlagDig: false,
      enableForm: {},
      enableRule: {
        enableFlag: [{required: true, message: '请选择积分回收方式', trigger: 'change'}]
      },
      isShengyu: false, // 是否剩余
      quizList: [], // 测试试卷列表
      planList: [],
      importDialogVisible: false,
      importLoading: false,
      uploadUrl: '/admin/wmscorepackage/batch/create',
      headers: {
        Authorization: 'Bearer ' + store.getters.access_token
      },
      importErrorDialogShow: false,
      importErrorTableData: [],
      fileList: [],
      fileTypeLimit: [
        // excel
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      ] // 支持上传的文件类型
    };
  },
  components: {taskStatistics, dismantleTable},
  mounted() {
    if (this.userInfo.roles.includes(39)) {
      this.addShowFlag = false;
    }
    if (this.userInfo.roles.includes(3)) {
      this.planIdDisabled = false;
    }
    if (this.userInfo.roles.includes(4)) {
      this.IS_DLS = true;
    }
    // const oneYearLater = new Date();
    // oneYearLater.setFullYear(oneYearLater.getFullYear() + 1);
    // // 获取一年后日期的时间戳
    // this.distributionForm.endTimeValue = oneYearLater.getTime();

    this.loading();
    // this.acceptSugChoose();
    // this.scoreNameChoose();
    // this.getTaskTree();
    // this.showRemote(); // 积分包任务类型展示
    // this.showTaskType(); // 有效服务类型展示
    // this.showRelatedService(); // 关联服务企业
    this.getDrugProducerList(); // 推广产品企业
    this.getAvailQuizListFn();
    this.getListDrug();
  },
  computed: {
    ...mapGetters(['website', 'keyCollapse', 'userInfo'])
  },

  methods: {
    importBtn() {
      this.importDialogVisible = true;
    },
    async exportBtnFn() {
      this.pageLoading = true;
      const res = await pkgInfoExportApi();
      try {
        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);
        this.pageLoading = false;
      } catch (err) {
        this.pageLoading = false;
      }
    },
    importClose() {
      this.fileList = [];
      this.importDialogVisible = false;
    },
    dowmTemplateFn() {
      this.importLoading = true;
      templateDownload({
        fileName: 'ent_pkg_batch_create_tmpl.xlsx'
      })
        .then(response => {
          this.importLoading = false;
          let url = window.URL.createObjectURL(new Blob([response.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(() => {
          this.importLoading = false;
        });
    },
    beforeFileUpload(file) {
      this.importLoading = true;
      if (!this.fileTypeLimit.includes(file.type)) {
        this.$message.warning('不支持的文件格式');
        return false;
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning('最多上传一个文件');
    },
    handleError(err) {
      this.$message.error('上传失败！');
      this.importLoading = false;
    },
    importClose() {
      this.fileList = [];
      this.importDialogVisible = false;
    },
    handleRemove(file, fileList) {},

    handleSuccess(res, file, fileList) {
      this.fileList = [];
      this.importLoading = false;
      if (res.code == 0) {
        if (res.data.length == 0) {
          this.$message.success('上传成功！');
          this.importClose();
          this.getList(this.page);
        } else {
          this.importErrorTableData = res.data;
          this.importErrorDialogShow = true;
        }
      }
    },
    async getPlanList(pkgId, planId) {
      const res = await getPlanListApi('QRT', pkgId);
      this.planList = res.data.data;
      this.planList.forEach(item => {
        item.planName = item.planName + `(${item.planIssue} ~ ${item.planExpiry})`;
      });
      // 编辑
      if (this.dialogType == 'edit') {
        this.planIdChange(planId);
      }
    },
    // 任务统计
    taskStatisticsFn(row) {
      this.taskStatisticsShow = true;
      this.currentId = row.id;
    },
    // 获取产品
    async getListDrug() {
      const res = await getListDrugApi();
      // this.drugList = res.data.data;
    },

    // 获取可用的试卷
    async getAvailQuizListFn() {
      const res = await getAvailQuizList();
      if (res.data.code === 0) {
        this.quizList = res.data.data || [];
      }
    },
    loading() {
      setInterval(() => {
        if (this.loadingTxt.length == 6) {
          this.loadingTxt = '.';
        }
        if (this.loadingTxt.length < 6) {
          this.loadingTxt += '.';
        }
      }, 300);
    },

    // 推广产品企业
    getDrugProducerList() {
      getDrugProducerList({deptId: this.$store.getters.userInfo.deptId}).then(res => {
        this.drugProducerListCopy = res.data.data;
      });
    },
    gettreenode() {
      //获取选中属性节点
      console.log(this.$refs.tree.getCheckedKeys());
    },
    async taskExport(type) {
      let row = this.checkRow;
      var obj = {
        id: row.id
      };
      let res;
      if (type === 'word') {
        this.wordLoading = true;
        res = await taskExportNbqybg(obj);
      } else if (type === 'excel') {
        this.excelLoading = true;
        res = await taskExportExcelNbqybg(obj);
      }

      if (res.data) {
        this.$message.success(res.data.data);
        this.exportDig = false;
        this.getList(this.page);
        this.wordLoading = false;
        this.excelLoading = false;
      } else {
        this.$message.error('导出失败');
      }
    },
    async taskNewExport(type) {
      try {
        let row = this.checkRow;
        var obj = {
          id: row.id
        };
        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;
      }
    },
    // 导出按钮
    exportBtn(row) {
      this.exportDig = true;
      this.checkRow = row;
    },

    // 报告下载
    async exportFile(row) {
      var timestamp = Date.parse(new Date());
      let filename = `市场服务包合同${timestamp}.pdf`;
      const res = await getSysFileApi(row.contract.fileId);
      let url = window.URL.createObjectURL(new Blob([res.data]));
      let link = document.createElement('a');
      link.style.display = 'none';
      link.href = url;
      link.setAttribute('download', filename);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    // 下载报告
    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;
    },
    rightClick(event, data, node, obj) {
      this.currentId = data.id;
      this.form.deptId = data.id;
      this.form.name = data.name;
      this.form.parentId = data.parentId;
      this.form.sort = data.sort;
      this.levelCheck = node.level;
      this.showRightMenu = false; // 先把模态框关死，目的是：第二次或者第n次右键鼠标的时候 它默认的是true
      this.showRightMenu = true;

      if (!data.isLock) {
        //判断是几级菜单
        //let level=data.
        let menu = document.querySelector('#menu');
        menu.style.left = event.clientX - 200 + 'px';
        menu.style.top = event.clientY - 140 + 'px';
        // 给整个document添加监听鼠标事件，点击任何位置执行closeRightMenu方法，及时将菜单关闭
        document.addEventListener('click', this.closeRightMenu);
      } else {
        this.showRightMenu = false;
        document.removeEventListener('click', this.closeRightMenu);
      }
    },

    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 获取选中的值
    getNodeData(data, checked) {
      this.getNodeVal = this.$refs.tree1.getCheckedNodes();
    },
    getTaskTree() {
      this.distributionForm.wmScoreTaskTypeList = [];
      getTaskTree().then(response => {
        this.distributionForm.wmScoreTaskTypeList = response.data.data;
      });
    },
    getCheckedNodes() {
      console.log(this.$refs.tree1.getCheckedNodes());
    },
    getCheckedKeys() {
      console.log(this.$refs.tree1.getCheckedKeys());
    },
    showRelatedService(type) {
      let obj = {
        onlySelf: ''
      };
      if (this.importShowFlag) {
        obj.onlySelf = true;
      }
      getListAncestorApi(obj)
        .then(response => {
          console.log('response', response);
          // debugger
          this.fwqyOptions = response.data.data;
          // 当发包对象为药企管理员
          let roles = this.userInfo.roles;
          if (roles.includes(3)) {
            this.distributionForm.relatedService = this.fwqyOptions[0].deptId;
            this.distributionForm.relationScoreId = '-1';
            this.scoreNameChange('-1');
            this.scoreAble = true;
            this.relatedAble = true;
          }
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },

    // 有效服务类型展示

    showTaskType(type) {
      // this.distributionForm.wmScoreTaskTypeList = []
      let arg = {
        description: '1'
      };
      getTaskTypeTree(arg).then(response => {
        // this.distributionForm.wmScoreTaskTypeList = response.data.data.treeList
        if (type == '1') {
          this.checkedDsScope = response.data.data.keys;
          // this.getNodeVal = response.data.data.treeList
        }
      });
    },

    // showTaskType() {
    //   scoreTasktype("score_task_type").then((response) => {
    //     response.data.data.forEach((item) => {
    //       const addnew = {
    //         key: item.value,
    //         label: item.label,
    //         value: item.description,
    //       };
    //
    //       this.dateOptions.push(addnew);
    //     });
    //   });
    // },

    // 积分包任务类型展示
    showRemote() {
      remote('packsge_type1').then(response => {
        response.data.data.forEach(item => {
          const addnew = {
            value: item.value,
            label: item.label
          };

          this.packageType1.push(addnew);
        });
      });
    },

    // 初始化页面
    getList(page, params) {
      this.tableLoading = true;
      selectWmScorePackageLists(
        Object.assign(
          {
            current: page.currentPage,
            size: page.pageSize
          },
          params,
          this.searchForm
        )
      )
        .then(response => {
          this.tableData = [];
          this.tableData = response.data.data.records;
          this.page.total = response.data.data.total;
          this.tableLoading = false;
          // let resData = response.data.data.records;
          //
          // var yfp = 0;
          // var ysd = 0;
          // var shtg = 0;
          // var payScoreVal = 0;
          // if (resData.length > 0) {
          //     for (var i = 0; i < resData.length; i++) {
          //         if (undefined != resData[i].ytj) {
          //             ysd += resData[i].ytj;
          //         }
          //
          //         if (undefined != resData[i].ysh) {
          //             shtg += resData[i].ysh;
          //             // if(undefined!=resData[i].score) {
          //             //   var socre = parseFloat(resData[i].ysh * 100 / resData[i].score).toFixed(0);
          //             //   if (socre > 100) {
          //             //     socre = 100;
          //             //   }
          //             //   resData[i].scoreJd=socre;
          //             // }
          //         }
          //
          //         if (undefined != resData[i].kfpjf) {
          //             yfp += resData[i].kfpjf;
          //         }
          //         if (undefined != resData[i].payScore) {
          //             payScoreVal += resData[i].payScore;
          //         }
          //     }
          //     this.scorePay = payScoreVal;
          //     this.socreShtg = shtg;
          //     this.socreYjwc = yfp;
          //
          //     if (yfp > 0) {
          //         var socre = parseFloat((shtg * 100) / yfp).toFixed(2);
          //         if (socre > 100) {
          //             socre = 100;
          //         }
          //         this.socreShtgRate = parseInt(socre);
          //     }
          // }
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },

    // 查看按钮
    viewBtn(row) {
      this.currentSelect = row;
      // debugger
      this.showRelatedService();
      this.distributionForm.belongDate = row.belongDate;
      this.addShow = false;
      this.allNot = true;
      this.showTitle = 'view';
      this.showTitle = '查看';
      this.showDig = true;
      this.lookValue = row.packageType1;
      this.lookDetail(row.id);
    },

    // 回显数据
    lookDetail(id) {
      // debugger
      let args = {
        scoreId: id
      };
      selectWmScorePackage(args).then(response => {
        // this.packsgeTypebtn(this.packageType1Val);
        this.returnVal = [];
        // this.returnVal = response.data.data.wmScoreTaskTypeList;
        this.returnVal = response.data.data.taskTypeSet;

        let showVal = [];
        for (let i = 0; i < this.returnVal.length; i++) {
          showVal.push(this.returnVal[i].type);
        }
        const data = response.data.data;

        data.relatedService = data.relatedService ? Number(data.relatedService) : '';
        data.planId = data.planId ? Number(data.planId) : '';
        data.acceptSug = data.acceptSug ? Number(data.acceptSug) : '';
        if (this.IS_DLS) {
          this.getPlanList(data.relationScoreId, data.planId);
        }
        this.distributionForm = data; // 查看和编辑的回显
        const timestamp = new Date(this.distributionForm.endTime).getTime();
        this.distributionForm.endTimeValue = this.distributionForm.endTime;
        // this.belongDate = this.distributionForm.belongDate;
        // this.distributionForm.wmScoreTaskTypeList = this.taskTypeSet; // 回显复选框
        // this.getKfpVal(response.data.data.relationScoreId);

        const list = [
          {
            relationScoreName: data.relationScoreName,
            id: data.relationScoreId
          }
        ];
        this.gljfbOptions = list;
        // this.getRelatedVal(response.data.data.relatedService);
        // this.distributionForm.relationScoreId = response.data.data.relationScoreId; // 查看和编辑的回显
        // if (this.distributionForm.wmScoreTaskTypeList == null) {
        //     this.showTaskType()
        // }
        this.showTaskType();
        // 回显选中的有效服务类型
        this.checkedDsScope = this.distributionForm.taskTypeSet;
        this.showDig = true;
        this.tableLoading = false;
      });
    },

    // 获取可分配积分
    getKfpVal(id) {
      this.jbdxOptions = [];
      let args = {
        // scoreId: scoreName,
        id: id
      };
      selectKfpjf(args).then(response => {
        // debugger
        this.kfpjfz = response.data.data[0].kfpjf == null ? 0 : response.data.data[0].kfpjf;
        this.jbdxOptions = response.data.data[0].acceptSug;
        // response.data.data[0].acceptSug.forEach((item) => {
        //     const addnew = {
        //         gsmc: item.gsmc,
        //         id: item.id
        //     };
        //
        //     this.jbdxOptions.push(addnew)
        // })
      });
    },

    getRelatedVal(relatedService) {
      // debugger
      this.gljfbOptions = [];
      let args = {
        relatedService: relatedService
      };
      selectRelationScoreId(args).then(response => {
        // debugger
        this.gljfbOptions = response.data.data;
        //关联服务企业展示关联积分包
        // response.data.data.forEach((item) => {
        //     const addnew = {
        //         id: item.id,
        //         relationScoreName: item.relationScoreName
        //     };
        //     this.gljfbOptions.push(addnew)
        // })
      });
    },

    // 根据积分包任务类型 展示 可选的有效服务类型
    // packsgeTypebtn(id) {
    //
    //   this.dateOptions = []
    //   // this.distributionForm.wmScoreTaskTypeList = []
    //   showTask(id == "" ? this.lookValue : id).then((response) => {
    //     response.data.data.forEach((item) => {
    //       const addnew = {
    //         key: item.value,
    //         label: item.label,
    //       };
    //
    //       this.dateOptions.push(addnew);
    //     });
    //
    //   });
    // },
    dateFormat: function(time) {
      var date = new Date(time);
      var year = date.getFullYear();
      /* 在日期格式中，月份是从0开始的，因此要加0
       * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
       * */
      var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
      // 拼接
      return year + '-' + month;
    },
    // 新增按钮-弹窗
    addBtn() {
      if (this.userInfo.roles.includes(3)) {
        this.importShowFlag = true;
        this.getPlanList('-1');
        // 获取计划
      }
      this.dialogType = 'add';
      this.showDig = true;
      this.showTitle = '新增';
      this.allNot = false;
      this.addShow = true;
      this.showTaskType('1');
      this.showRelatedService();
      this.checkedDsScope = [];
      // debugger
      // this.disabledFn();
      var vm = this;
      //默认显示当前时间
      const myDate = new Date();
      const year = myDate.getFullYear(); // 获取当前年份
      const month = myDate.getMonth() + 1; // 获取当前月份(0-11,0代表1月所以要加1);
      vm.distributionForm.belongDate = month > 9 ? `${year}-${month}` : `${year}-0${month}`;
    },

    //关联执行包名称-选中的值
    scoreNameChange(id) {
      this.scoreIdVal = id;
      this.distributionForm.acceptSug = '';
      this.distributionForm.wmScoreTaskTypeList = [];
      if (id == '-1') {
        this.typeList = false;
        this.packsgeType = false;
        this.kfpjfz = '';
        // this.belongDate = "";
        this.checkedDsScope = [];
        this.showTaskType('1');
        this.drugProducerList = [...this.drugProducerListCopy]; // 推广产品企业
        this.getListDrug();
      } else {
        let curr = this.gljfbOptions.find(item => item.id === id);
        this.distributionForm.wmScoreTaskTypeList = this.wmScoreTaskTypeList;
        this.typeList = true;
        this.packsgeType = true;
        this.distributionForm.planId = '';
        this.getPlanList(id);
      }
      let arg = {
        id: id
      };
      selectKfpjf(arg)
        .then(response => {
          // debugger
          if (response.data.code == '0') {
            this.jbdxOptions = [];
            response.data.data[0].acceptSug.forEach(item => {
              const addnew = {
                gsmc: item.gsmc,
                deptId: item.deptId,
                id: item.id,
                provAbbr: item.provAbbr
              };

              this.jbdxOptions.push(addnew);
            });
            if (this.currentSelect && this.currentSelect.planId) {
              this.distributionForm.planId = this.currentSelect.planId;
              this.planIdChange(this.currentSelect.planId);
            }

            this.showTaskType();
            this.taskTypeList1val = response.data.data[1].wmScoreTaskTypeList1;
            // console.log("334434343",this.taskTypeList1val)
            this.wmScoreTaskTypeListVal = [];
            // this.taskTypeList1val = [];
            this.distributionForm.wmScoreTaskTypeList = [];
            this.kfpjfz = response.data.data[1].kfpjf;
            this.distributionForm.belongDate = response.data.data[1].belongDate;
            this.distributionForm.packageType1 = response.data.data[1].packageType1;
            this.distributionForm.wmScoreTaskTypeList = response.data.data[1].wmScoreTaskTypeList;
            if (this.distributionForm.wmScoreTaskTypeList == '') {
              this.showTaskType();
            }
            this.checkedDsScope = response.data.data[1].wmScoreTaskTypeList;
            if (!this.IS_DLS) {
              this.setSelectNodes(this.checkedDsScope);
            }
            this.planIdDisabled = false;
          }
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    setSelectNodes(arr) {
      this.$refs.tree1.setCheckedKeys(arr);
      this.$refs.tree2.setCheckedKeys(arr);
      this.$refs.tree3.setCheckedKeys(arr);
      // this.$refs.tree7.setCheckedKeys(arr);
    },

    getAllTaskTypeList() {
      let taskTypeList = [];
      taskTypeList = taskTypeList.concat(this.$refs.tree1.getCheckedNodes());
      taskTypeList = taskTypeList.concat(this.$refs.tree2.getCheckedNodes());
      taskTypeList = taskTypeList.concat(this.$refs.tree3.getCheckedNodes());
      // taskTypeList = taskTypeList.concat(this.$refs.tree7.getCheckedNodes());
      // taskTypeList = taskTypeList.concat(this.$refs.tree4.getCheckedNodes())
      // taskTypeList = taskTypeList.concat(this.$refs.tree5.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}`;
    },
    // 新增按钮-提交
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          // const date = this.formatDate(this.distributionForm.endTimeValue);
          const date = this.distributionForm.endTimeValue;
          // debugger

          // this.showTaskType()
          let wmScoreTaskTypeList;
          if (!this.IS_DLS) {
            wmScoreTaskTypeList = this.getAllTaskTypeList();
            console.log('wmScoreTaskTypeList', wmScoreTaskTypeList);
          }
          let pkgTaskTypeQtyList;

          // 代理商发包
          if (this.IS_DLS) {
            const tableData = this.$refs.dismantleTableRef.getDetail();
            pkgTaskTypeQtyList = tableData.map(item => {
              return {
                taskTypeName: item.taskTypeName,
                price: item.score,
                taskTypeId: item.taskTypeId,
                qty: item.qty
              };
            });

            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;
              }
            });
            wmScoreTaskTypeList = arr4;
          }

          if (wmScoreTaskTypeList.length == 0) {
            this.$message.error('有效服务类型不能为空');
            return false;
          }
          let args = {
            pkgTaskTypeQtyList: pkgTaskTypeQtyList,
            id: this.idVal == '' ? '' : this.idVal,
            agentTypeId: this.distributionForm.relationScoreId == '-1' ? '1' : '2',
            scoreId: this.distributionForm.scoreId,
            scorePackageName: this.distributionForm.scorePackageName,
            score: this.distributionForm.score,
            acceptSug: this.distributionForm.acceptSug,
            relationScoreId: this.distributionForm.relationScoreId == '-1' ? '' : this.distributionForm.relationScoreId,
            kfpjf: this.kfpjfz == '' ? 0 : this.kfpjfz,
            belongDate: this.distributionForm.belongDate,

            // wmScoreTaskTypeList: "-1" != this.distributionForm.relationScoreId ? this.taskTypeList1val : "" == this.relationScoreId ? this.wmScoreTaskTypeListVal : "",//自己选的
            wmScoreTaskTypeList: wmScoreTaskTypeList,
            description: this.distributionForm.description,
            packageType1: this.distributionForm.packageType1,
            level1Id: this.distributionForm.level1Id,
            level2Id: this.distributionForm.level2Id,
            relatedService: this.distributionForm.relatedService,
            entTaskLimit: this.distributionForm.entTaskLimit || 0,
            auditManagementFeeRates: this.distributionForm.auditManagementFeeRates || 0,
            quizIds: this.distributionForm.quizIds,
            drugtable: this.distributionForm.drugtable,
            startTime: this.distributionForm.startTime,
            endTime: date,
            planId: this.distributionForm.planId,
            provAbbr: this.distributionForm.provAbbr
          };

          // 推广产品企业
          if (this.distributionForm && this.distributionForm.relationScoreId && this.distributionForm.relationScoreId == '-1') {
            if (!this.distributionForm.drugProducerList || this.distributionForm.drugProducerList.length === 0) {
              args.drugProducerList = this.drugProducerList; // 推广产品企业
            } else {
              args.drugProducerList = this.distributionForm.drugProducerList;
            }
            if (!this.distributionForm.drugtable || this.distributionForm.drugtable.length === 0) {
              args.drugtable = this.drugList.map(item => item.drug_id);
            }
          } else {
            this.distributionForm.drugProducerList = this.drugProducerList; // 推广产品企业
            args.drugtable = this.drugList.map(item => item.drug_id);
          }

          if (this.dialogType == 'add') {
            // this.distributionForm.wmScoreTaskTypeList = this.getNodeVal
            // this.distributionForm.wmScoreTaskTypeList = [];
            // this.distributionForm.wmScoreTaskTypeList = this.wmScoreTaskTypeList;
            if (Number(this.distributionForm.score) > this.kfpjfz && this.distributionForm.relationScoreId != '-1') {
              this.$message.error('可分配积分不足');
              return false;
            }
            delete args.drugProducerList;
            this.buttonLoading = true;
            saves(args)
              // saves(this.distributionForm)
              .then(response => {
                // debugger
                this.planList = [];
                this.buttonLoading = false;
                this.getList(this.page);
                this.cancelBtn();
              })
              .catch(() => {
                this.buttonLoading = false;
              });
          } else {
            if (this.showTitle == 'edit') {
              this.distributionForm.wmScoreTaskTypeList = this.getNodeVal;
              if (Number(this.distributionForm.score) > this.kfpjfz + this.scoreIdVal && this.distributionForm.relationScoreId != '-1') {
                this.$message.error('可分配积分不足');
                return false;
              }
            }
            this.buttonLoading = true;
            updateByIds(args)
              .then(response => {
                // updateByIds(this.distributionForm).then((response) => {
                // debugger
                this.planList = [];
                this.getList(this.page);
                this.showDig = false;
                this.tableLoading = false;
                this.buttonLoading = false;
                this.kfpjfz = '';
                this.distributionForm.belongDate = '';
                this.relationScoreId = '';
                this.distributionForm = {
                  wmScoreTaskTypeList: []
                };
              })
              .catch(() => {
                this.buttonLoading = false;
              });
          }
          setTimeout(() => {
            this.$store.dispatch('SET_INTEGRAL');
          }, 600);
        } else {
          console.log('error submit!!');
          return false;
        }
        this.buttonLoading = false;
      });
    },
    // 编辑回显
    async updateBtn(row) {
      // debugger
      //积分包如果被分派，承接对象不可以修改
      this.showRelatedService();
      this.packageIsConduct = row.packageIsConduct;
      if (row.packageIsConduct == '0') {
        this.isAble = false;
      } else {
        this.isAble = true;
      }
      //积分包如果已结算，关联积分包不可以修改
      this.settleStatus = row.settleStatus;
      if (row.settleStatus == '1') {
        this.scoreAble = true;
      } else {
        this.scoreAble = false;
      }
      //无 可以编辑任务类型，其他不可以编辑
      if (row.relationScoreId == '') {
        this.typeList = false;
        this.packsgeType = false;
        this.kfpjfz = '';
        this.distributionForm.belongDate = '';
      } else {
        this.typeList = true;
        this.packsgeType = true;
      }
      // debugger
      this.showDig = true;
      this.dialogType = 'edit';
      this.showTitle = '编辑';
      this.editDisabled = true;
      this.allNot = false;
      this.addShow = true;
      this.idVal = row.id;
      this.packageIsConductVal = row.packageIsConduct;
      this.relationScoreIdVal = row.relationScoreId;
      await this.lookDetail(row.id);
      if (row.endTime) {
        const timestamp = new Date(row.endTime).getTime();
        // this.distributionForm.endTimeValue = timestamp;
        this.distributionForm.endTimeValue = row.endTime;
      }
    },
    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 date = 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();
          }
        }
      });
    },
    // 承接对象
    acceptSugChange(id) {
      this.$forceUpdate(); // 强制刷新
    },

    // 计划包id
    planIdChange(e) {
      const curr = this.planList.find(item => item.planId === e);
      if (this.IS_DLS) {
        if (!curr.planDetails) {
          this.$refs.dismantleTableRef.setData([]);
          return this.$message.error(`服务目标【${curr.planName}】不存在可用的拆解详情，请核实！`);
        }
        this.planItem = curr.planDetails;
        this.$refs.dismantleTableRef.setData(curr.planItems, curr.planScore);
        this.distributionForm.score = curr.planDetails.total;
      }
      if (curr) {
        this.distributionForm.startTime = curr.planIssue;
        this.distributionForm.endTimeValue = curr.planExpiry;
        this.distributionForm.score = curr.planScore;
      }
      const currA = this.jbdxOptions.find(item => item.deptId == curr.consigneeId);
      if (currA) {
        this.distributionForm.acceptSug = currA.id;
        if (currA.provAbbr) {
          this.provAbbrList = currA.provAbbr.split(',');
        }
      }

      this.distributionForm.drugtable = [curr.skuInfo.skuId];
      const arr = [
        {
          drug_name: curr.skuInfo.skuName,
          drug_id: curr.skuInfo.skuId
        }
      ];

      this.drugList = arr;
    },

    // 有效服务类型选中值-添加  新
    chooseItems(data, checked) {
      this.wmScoreTaskTypeListVal = this.$refs.tree.getCheckedNodes();
    },
    //关联服务企业-选中的值
    RelatedServiceChange(relatedService) {
      // debugger
      this.distributionForm.relationScoreId = '';
      // this.distributionForm.wmScoreTaskTypeList = [];
      this.relatedServiceVal = relatedService;
      let arg = {
        relatedService: relatedService
      };
      selectRelationScoreId(arg)
        .then(response => {
          this.gljfbOptions = response.data.data;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },

    // 判断是否为-1, 若为-1则禁用，不为-1则可以选择
    disabledFn() {
      return true;
      // debugger
      if (this.dialogType == 'add' && this.distributionForm.relationScoreId == '-1') {
        return false;
      } else if (this.dialogType == 'edit' && this.packageIsConductVal == '1') {
        return true;
      } else if (this.dialogType == 'edit' && this.packageIsConductVal == '0' && '-1' == this.distributionForm.relationScoreId) {
        return false;
      } else if (this.dialogType == 'edit' && '' != this.distributionForm.relationScoreId) {
        return true;
      } else if (this.dialogType == 'edit' && this.packageIsConductVal == '0' && '' == this.relationScoreIdVal) {
        return false;
      } else if (this.distributionForm.relationScoreId == '-1' && this.packageIsConductVal == '') {
        return false;
      } else {
        return true;
      }
    },
    // 提交时间获取值
    startDateBtn(date, done) {
      (this.allocationDate = date[0]), (this.endLabelDate = date[1]);
    },
    // 搜索按钮
    searchVal(form, done) {
      this.searchForm = form;
      this.searchForm.allocationDate = this.allocationDate;
      this.searchForm.endLabelDate = this.endLabelDate;
      this.page.currentPage = 1;
      this.getList(this.page, form);
      done();
    },
    // 终止
    suspendBtn(row) {
      this.enableFlagDig = true;
      this.suspendData = row;
    },
    // 中止确认按钮
    enableFlagBtn(formName) {
      if (this.enableForm.enableFlag === '2' && this.suspendData.stopStatus === 'NOTHING' && !this.isShengyu) {
        // 剩余收回
        this.isShengyu = true;
        return;
      }
      this.$refs[formName].validate(valid => {
        if (valid) {
          let args = {
            enableType: this.enableForm.enableFlag,
            id: this.suspendData.id
          };
          stopWmScorePackage(args).then(response => {
            this.$message.success('终止成功');
            this.getList(this.page);
            this.stopcancelBtn();
          });
        } else {
          console.log('error submit!!');
          return false;
        }
        setTimeout(() => {
          this.$store.dispatch('SET_INTEGRAL');
        }, 500);
      });
    },
    // 隐藏弹出窗
    stopcancelBtn() {
      this.enableFlagDig = false;
      this.enableForm = {};
      this.isShengyu = false;
    },
    // 终止按钮
    // stopBtn(row, index, done, loading) {
    //   this.$confirm("是否确认终止", "警告", {
    //     confirmButtonText: "是",
    //     cancelButtonText: "否",
    //     type: "warning"
    //   })
    //     .then(() => {
    //       // updateStatusByIds(row)
    //       stopWmScorePackage(row)
    //         .then(data => {
    //           this.$message.success("任务终止成功");
    //           this.getList(this.page);
    //         })
    //         .catch(() => {});
    //       // this.$message.success("任务终止成功");
    //       // this.getList(this.page);
    //     })
    //     .catch(() => {});
    // },

    // 分页查询
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },

    currentChange(current) {
      this.page.currentPage = current;
    },
    handleClose(done) {
      this.planList = [];
      this.resetInfo();
      this.getList(this.page);
      // done();
    },
    resetInfo() {
      this.$refs.distributionForm.resetFields();
      if (this.$refs.dismantleTableRef) {
        this.$refs.dismantleTableRef.setData([]);
      }
      this.distributionForm.planId = '';
      this.distributionForm.drugProducerList = null;
      this.distributionForm.drugtable = [];
      this.kfpjfz = '';
      this.editDisabled = false;
      this.isAble = false;
      console.log('      this.editDisabled = false;', this.editDisabled);
      this.scoreAble = false;
      this.relatedAble = false;
      this.showDig = false;
      this.typeList = false;
      this.packsgeType = false;
      this.showDig = false;
    },
    // 取消弹出窗, 并清空表单
    cancelBtn(formName) {
      this.resetInfo();
      this.getList(this.page);
    },
    // 搜索清空按钮
    searchReset() {
      this.dateTime = '';
      this.allocationDate = '';
      this.endLabelDate = '';
      this.searchForm = {};
    },
    // 结算
    async settleById(row) {
      this.id = row.id;
      this.settleButtonShow = true;
      let {scorePackageName, score, ysh: finishScore, description} = row;
      this.form = {
        scorePackageName,
        score,
        finishScore,
        description
      };
      this.textareaDisabled = !row.p2pDraft;
      let discount;
      if (row.p2pAmount) {
        discount = (Number(row.p2pAmount) / Number(row.score)).toFixed(2);
      } else {
        discount = 1;
      }
      let obj = {
        realName: row.$acceptSug,
        discount: discount,
        settleAmount: row.p2pAmount || row.score,
        allScore: row.score,
        settleNoteStatus: row.packageFinishStatus,
        p2pServiceAmount: row.p2pServiceAmount,
        p2pDraft: row.p2pDraft
      };
      this.gridData.push(obj);
      this.settleTableVisible = true;
    },
    hideDialog() {
      this.settleTableVisible = false;
      this.form = {};
      this.gridData = [];
      this.getList(this.page);
    },
    async settleSave(p2pDraft) {
      if (!this.id) {
        this.$message.error('数据异常');
        return;
      }
      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;
        }
      }
      let data = {
        id: this.id,
        p2pAmount: this.gridData[0].settleAmount,
        p2pServiceAmount: this.gridData[0].p2pServiceAmount,
        description: this.form.description,
        p2pDraft
      };
      const res = await settleSave(data);
      if (res.data.code === 0) {
        let message = p2pDraft ? '保存成功' : '提交成功';
        this.$message.success(message);
        this.hideDialog();
      }
    },
    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总价';
          return;
        }
        if (index === 4) {
          let isNumber = num => num === +num;
          let a = data[0] ? data[0].settleAmount : 0;
          let b = data[0] ? data[0].p2pServiceAmount : 0;
          let pre;
          let numA = isNumber(Number(a)) ? Number(a) : 0;
          let numB = isNumber(Number(b)) ? Number(b) : 0;
          pre = numA + numB;
          sums[index] = pre + ' 元';
        } 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(e.allScore) * Number(value)).toFixed(2);
    },
    discountInput(e) {
      let value = e.discount;
      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(e.allScore) * Number(value)).toFixed(2);
    },

    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 discount = (Number(value) / Number(e.allScore)).toFixed(2);
        e.settleAmount = value;
        e.discount = discount;
      } else {
        e.settleAmount = 0;
        e.discount = 0;
      }
    },
    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;
      if (value) {
        discount = (Number(value) / Number(e.allScore)).toFixed(2);
      }
      e.settleAmount = value;
      e.discount = discount;
    }
  }
};
</script>

<style lang="scss" scoped>
.tabStyle {
  width: 100%;
  margin-top: 10px;
}

.el-input__inner {
  border: 1px solid #dcdfe6 !important;
}

.el-date-editor .el-range-separator {
  padding: 0 0 !important;
}
.treeBox {
  float: left;
  width: 25%;
}
.treeBox3 {
  width: 50%;
}

/*.treeBox {*/
/*  width: 100%;*/
/*  height: 200px;*/
/*  border: 1px solid #DCDFE6;*/
/*  overflow-y: scroll;*/
/*  overflow-x: hidden;*/
/*  border-radius: 10px;*/
/*}*/

/*滚动条样式*/
.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);
}

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

.btns {
  display: flex;
  justify-content: center;
}

.title-msg {
  text-align: center;
  margin-top: 10px;
}

.separator {
  background-color: rgba(242, 242, 242, 1) !important;
  text-align: center;
  width: 96%;
  height: 34px;
  line-height: 34px;
  margin-bottom: 2px;
}
.settle-desc {
  width: 100%;
  ::v-deep .el-form-item__content {
    width: 80%;
  }
}
.down-item {
  margin-left: 20px;
  margin-bottom: 15px;
  span {
    /* width: 160px; */
    display: inline-block;
    text-align: right;
  }
  .btn {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .first {
    width: 240px;
  }
}

.input-num-box {
  ::v-deep .el-input__inner {
    text-align: left;
  }
}
.import-content {
  text-align: center;
}
</style>
