<template>
  <div class="app-container barchart">
    <!-- 搜索栏 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="课程内容" prop="plantName">
        <el-input
          v-model="queryParams.plantName"
          placeholder="请输入课程内容"
          clearable
          size="small"
          @input="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始日期" prop="startDate">
        <el-date-picker clearable size="small" style="width: 200px"
          v-model="queryParams.startDate"
          @change="handleQuery"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择开始日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束日期" prop="endDate">
        <el-date-picker clearable size="small" style="width: 200px"
          v-model="queryParams.endDate"
          @change="handleQuery"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item :label="$t('申请状态')" prop="approveStatus">
        <el-select v-model="queryParams.approveStatus" @change="handleQuery"    :placeholder="$t('请选择') + $t('申请状态')" clearable size="small">
          <el-option
            v-for="dict in approveStatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 顶部工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['spec:plan:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['spec:plan:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['spec:plan:remove']"
        >删除</el-button>
      </el-col> -->
        <el-col :span="1.5">
            <el-button
                    type="info"
                    icon="el-icon-upload2"
                    size="mini"
                    @click="handleImport"
                    v-hasPermi="['spec:plan:edit']"
            >导入</el-button>
        </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['spec:plan:export']"
        >导出</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!-- 表格 -->
    <el-table v-loading="loading" ref="planTable" :data="planList" @selection-change="handleSelectionChange" :height="clientHeight" border :cell-style="tableCellStyle">
      <el-table-column type="selection" width="55"   align="center" />
      <el-table-column label="员工" fixed="left" align="center"   prop="staffName" :show-overflow-tooltip="true"/>
      <el-table-column label="课程内容" fixed="left" align="center" width="150"   prop="plantName" :show-overflow-tooltip="true"/>
      <el-table-column label="开始日期" width="90" fixed="left" align="center"   prop="startDate">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束日期" width="90" fixed="left" align="center"   prop="endDate">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实际完成日期" width="105" align="center"   prop="dateOfCompletion">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dateOfCompletion, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="具体内容" align="center" width="200"   prop="classContent" :show-overflow-tooltip="true"/>
      <el-table-column label="学习状态" align="center"   prop="studyState" :formatter="studyStateFormat"/>
      <el-table-column :label="$t('申请状态')" align="center"   prop="approveStatus"
                        :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-tag
            :type="approveStatusType(scope.row.approveStatus)"
            disable-transitions>{{approveStatusFormat(scope.row)}}</el-tag>
        </template>
      </el-table-column>
       <el-table-column label="创建人"   align="center" prop="createBy" :show-overflow-tooltip="true"/>
      <el-table-column label="创建时间"   align="center" prop="createdate" width="130">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdate, '{y}-{m}-{d}  {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改人"   align="center" prop="updateBy" :show-overflow-tooltip="true"/>
      <el-table-column label="修改时间"   align="center" prop="updatedate" width="130">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedate, '{y}-{m}-{d}  {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <!-- 渲染时间(年|月) -->
      <el-table-column
        v-if="IsShowyear"
        v-for="(item, index) in showMonths"
        :label="item.year"
        prop="showMonths"
        align="center"
        :key="index"
      >
        <el-table-column
          v-for="(it, index1) in item.months"
          :label="it.str"
          prop="str"
          min-width="50"
          style="padding: 0; margin: 0;"
          align="center"
          :key="index1"
        >
          <template slot-scope="scope" class="progressCon">
            <div v-if="getCellDateWidth > 0">
              <div
                v-if="index === 0 && index1 === 0 && scope.$index % 2 === 0"
                class="progressUpon"
                :style="{width:optimizeCalcWidth(scope.row),left:optimizeCalcLeft(scope.row)}"
              ></div>
              <div
                v-else-if="index === 0 && index1 === 0 && scope.$index % 2 !== 0"
                class="progressDownon"
                :style="{width:optimizeCalcWidth(scope.row),left:optimizeCalcLeft(scope.row)}"
              ></div>
            </div>
            <div v-else>
              <div
                v-if="scope.$index % 2 === 0"
                :class="scope.row.beginTimeStamp <= it.endTimeStamp && scope.row.endTimeStamp >= it.beginTimeStamp ? 'progressUpon' : '' "
                :style="{width:scope.row.beginTimeStamp <= it.endTimeStamp && scope.row.endTimeStamp >= it.beginTimeStamp ? calcwidth(scope.row,it) : '0px',left:scope.row.beginTimeStamp <= it.endTimeStamp && scope.row.endTimeStamp >= it.beginTimeStamp ? calcLeft(scope.row,it) : '0px'}"
              ></div>
              <div v-else
                   :class="scope.row.beginTimeStamp <= it.endTimeStamp && scope.row.endTimeStamp >= it.beginTimeStamp  ? 'progressDownon' : '' "
                   :style="{width:scope.row.beginTimeStamp <= it.endTimeStamp && scope.row.endTimeStamp >= it.beginTimeStamp ? calcwidth(scope.row,it) : '0px',left:scope.row.beginTimeStamp <= it.endTimeStamp && scope.row.endTimeStamp >= it.beginTimeStamp ? calcLeft(scope.row,it) : '0px'}"
              ></div>
            </div>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width" width="400">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-chat-dot-round"
            @click="handleFeedback(scope.row)"
            v-hasPermi="['spec:plan:edit']"
          >反馈</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="handleDocSuccessor(scope.row)"
            v-hasPermi="['spec:plan:edit']"
          >学员附件</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="handleDocMentor(scope.row)"
            v-hasPermi="['spec:plan:edit']"
          >学习资料</el-button>
          <el-button
            v-if="scope.row.editFlag != 0"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['spec:plan:edit']"
          >修改</el-button>
          <el-button
            v-if="scope.row.editFlag != 0"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['spec:plan:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改培训计划对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="员工" prop="staffId" >
          <el-select v-model="form.staffId" placeholder="请选择学员" disabled>
            <el-option
              v-for="successor in successorOptions"
              :key="successor.key"
              :label="successor.value"
              :value="successor.key"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程内容" prop="plantName">
          <el-input v-model="form.plantName" placeholder="请输入课程内容" />
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker clearable size="small" style="width: 220px"
            v-model="form.startDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择开始日期"
            :picker-options="pickerOptionsStartDate">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker clearable size="small" style="width: 220px"
            v-model="form.endDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择结束日期"
            :picker-options="pickerOptionsEndDate">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="具体内容">
          <el-input
            type="textarea"
            :rows="6"
            placeholder="请输入内容"
            v-model="form.classContent">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
        <el-upload
                ref="upload"
                :limit="1"
                accept=".xlsx, .xls"
                :headers="upload.headers"
                :action="upload.url + '?updateSupport=' + upload.updateSupport + '&yearPlanId=' + queryParams.yearPlanId"
                :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress"
                :on-success="handleFileSuccess"
                :auto-upload="false"
                drag
        >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
                将文件拖到此处，或
                <em>点击上传</em>
            </div>
            <div class="el-upload__tip" slot="tip">
                <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
                <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
            </div>
            <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitFileForm">确 定</el-button>
            <el-button @click="upload.open = false">取 消</el-button>
        </div>
    </el-dialog>
    <!-- 学习资料对话框 -->
    <el-dialog v-dialogDrag :title="docMentor.title" :visible.sync="docMentor.open" width="700px" append-to-body>
      <el-upload
        ref="docMentor"
        :limit="50"
        :headers="docMentor.headers"
        :action="docMentor.url + '?pType=' + docMentor.pType + '&pId=' + docMentor.pId"
        :disabled="docMentor.isUploading"
        :on-progress="handleFileDocProgressMentor"
        :on-success="handleFileDocSuccessMentor"
        :auto-upload="true"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          {{ $t('将文件拖到此处，或') }}
          <em>{{ $t('点击上传') }}</em>
        </div>
      </el-upload>
      <el-table :data="docMentor.commonfileList" border>
        <el-table-column :label="$t('文件名')" align="center" prop="fileName" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <a  class="link-type"  @click="handleDownload(scope.row)">
              <span>{{ scope.row.fileName }}</span>
            </a>
          </template>
        </el-table-column>
        <el-table-column :label="$t('大小(Kb)')" align="center" prop="fileSize" :show-overflow-tooltip="true" width="80" />
        <el-table-column :label="$t('上传人')" align="center" prop="creator" :show-overflow-tooltip="true" width="120"/>
        <el-table-column :label="$t('操作')" align="center" width="120" class-name="small-padding fixed-width">
          <template slot-scope="scope">
          <el-button
              v-if="scope.row.fileName.endsWith('pdf')||scope.row.fileName.endsWith('xlsx')||scope.row.fileName.endsWith('md')
                 ||scope.row.fileName.endsWith('docx')||scope.row.fileName.endsWith('doc')||scope.row.fileName.endsWith('txt')
                 ||scope.row.fileName.endsWith('jpg')||scope.row.fileName.endsWith('png')||scope.row.fileName.endsWith('csv')
                 ||scope.row.fileName.endsWith('mp4')||scope.row.fileName.endsWith('svg')||scope.row.fileName.endsWith('dwg')
                 ||scope.row.fileName.endsWith('flv')||scope.row.fileName.endsWith('swf')||scope.row.fileName.endsWith('gif')
                 ||scope.row.fileName.endsWith('3gp')||scope.row.fileName.endsWith('mkv')||scope.row.fileName.endsWith('tif')"
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleSee(scope.row)"
            > {{ $t('预览') }}</el-button>
            <el-button
              v-if="scope.row.fileName.endsWith('ppt')||scope.row.fileName.endsWith('pptx') "
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleSeePPT(scope.row)"
            > {{ $t('ppt预览') }}</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-download"
              @click="handleDownload(scope.row)"
            >{{ $t('下载') }}</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDeleteDoc(scope.row)"
            >{{ $t('删除') }}</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="docMentor.open = false">{{ $t('返 回') }}</el-button>
      </div>
    </el-dialog>
    <!-- 学员附件对话框 -->
    <el-dialog v-dialogDrag :title="docSuccessor.title" :visible.sync="docSuccessor.open" width="700px" append-to-body>
      <el-table :data="docSuccessor.commonfileList" border>
        <el-table-column :label="$t('文件名')" align="center" prop="fileName" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <a  class="link-type"  @click="handleDownload(scope.row)">
              <span>{{ scope.row.fileName }}</span>
            </a>
          </template>
        </el-table-column>
        <el-table-column :label="$t('大小(Kb)')" align="center" prop="fileSize" :show-overflow-tooltip="true" width="80" />
        <el-table-column :label="$t('上传人')" align="center" prop="creator" :show-overflow-tooltip="true" width="120"/>
        <el-table-column :label="$t('操作')" align="center" width="120" class-name="small-padding fixed-width">
          <template slot-scope="scope">
             <el-button
              v-if="scope.row.fileName.endsWith('pdf')||scope.row.fileName.endsWith('xlsx')||scope.row.fileName.endsWith('md')
                 ||scope.row.fileName.endsWith('docx')||scope.row.fileName.endsWith('doc')||scope.row.fileName.endsWith('txt')
                 ||scope.row.fileName.endsWith('jpg')||scope.row.fileName.endsWith('png')||scope.row.fileName.endsWith('csv')
                 ||scope.row.fileName.endsWith('mp4')||scope.row.fileName.endsWith('svg')||scope.row.fileName.endsWith('dwg')
                 ||scope.row.fileName.endsWith('flv')||scope.row.fileName.endsWith('swf')||scope.row.fileName.endsWith('gif')
                 ||scope.row.fileName.endsWith('3gp')||scope.row.fileName.endsWith('mkv')||scope.row.fileName.endsWith('tif')"
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleSee(scope.row)"
            > {{ $t('预览') }}</el-button>
            <el-button
              v-if="scope.row.fileName.endsWith('ppt')||scope.row.fileName.endsWith('pptx') "
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleSeePPT(scope.row)"
            > {{ $t('ppt预览') }}</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-download"
              @click="handleDownload(scope.row)"
            >{{ $t('下载') }}</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDeleteDoc(scope.row)"
            >{{ $t('删除') }}</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="docSuccessor.open = false">{{ $t('返 回') }}</el-button>
      </div>
    </el-dialog>
    <!-- 反馈对话框 -->
    <el-dialog v-dialogDrag :title="feedbackDialog.title" :visible.sync="feedbackDialog.open" width="800px" append-to-body>
      <div style="width:700px; margin:0px auto;">
        <div v-if="feedbackDialog.studyState != 0">
          <h3 style="margin-bottom:20px;">学员心得</h3>
          <el-table :data="tableData" border style="width: 100%">
            <el-table-column prop="id" label="编号" width="50"></el-table-column>
            <el-table-column prop="question" label="问题" width="250"></el-table-column>
            <el-table-column prop="answer" label="答案"></el-table-column>
          </el-table>
          <el-table :data="docFeedback.commonfileList" border>
            <el-table-column :label="$t('文件名')" align="center" prop="fileName" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <a  class="link-type"  @click="handleDownload(scope.row)">
                  <span>{{ scope.row.fileName }}</span>
                </a>
              </template>
            </el-table-column>
            <el-table-column :label="$t('大小(Kb)')" align="center" prop="fileSize" :show-overflow-tooltip="true" width="80" />
            <el-table-column :label="$t('上传人')" align="center" prop="creator" :show-overflow-tooltip="true" width="120"/>
            <el-table-column :label="$t('操作')" align="center" width="120" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                 <el-button
              v-if="scope.row.fileName.endsWith('pdf')||scope.row.fileName.endsWith('xlsx')||scope.row.fileName.endsWith('md')
                 ||scope.row.fileName.endsWith('docx')||scope.row.fileName.endsWith('doc')||scope.row.fileName.endsWith('txt')
                 ||scope.row.fileName.endsWith('jpg')||scope.row.fileName.endsWith('png')||scope.row.fileName.endsWith('csv')
                 ||scope.row.fileName.endsWith('mp4')||scope.row.fileName.endsWith('svg')||scope.row.fileName.endsWith('dwg')
                 ||scope.row.fileName.endsWith('flv')||scope.row.fileName.endsWith('swf')||scope.row.fileName.endsWith('gif')
                 ||scope.row.fileName.endsWith('3gp')||scope.row.fileName.endsWith('mkv')||scope.row.fileName.endsWith('tif')"
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleSee(scope.row)"
            > {{ $t('预览') }}</el-button>
            <el-button
              v-if="scope.row.fileName.endsWith('ppt')||scope.row.fileName.endsWith('pptx') "
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleSeePPT(scope.row)"
            > {{ $t('ppt预览') }}</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-download"
              @click="handleDownload(scope.row)"
            >{{ $t('下载') }}</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDeleteDoc(scope.row)"
            >{{ $t('删除') }}</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-form v-if="feedbackDialog.studyState == 2">
          <h3 style="margin-top:30px;margin-bottom:20px;">导师反馈</h3>
          <el-form-item>
            <editor v-model="feedbackParams.mentorFeedback" :min-height="192"/>
          </el-form-item>
        </el-form>
        <el-form v-if="mentorFeedback != null && feedbackDialog.studyState != 2">
          <h3 style="margin-top:30px;margin-bottom:20px;">导师反馈</h3>
        <el-form-item>
          <p v-html="mentorFeedback" style="border:1px solid #DFE6EC; overflow:scroll; height:200px;" />
        </el-form-item>
        </el-form>
        <div style="text-align:center;">
          <el-button
            @click="handleApprove()"
            type="success"
            size="medium"
            style="margin-right:25px;"
            v-if="feedbackDialog.studyState == 2"
          >
            {{ $t('通 过') }}
          </el-button>
          <el-button
            @click="handleReject()"
            type="danger"
            size="medium"
            v-if="feedbackDialog.studyState == 2"
          >
          {{ $t('驳 回') }}
          </el-button>
        </div>
      </div>
    </el-dialog>
      <!-- 预览对话框 -->
        <el-dialog  v-loading="loadingFlash"     element-loading-background="rgba(0,0,0,0.2)"                 v-dialogDrag :title="pdf.title" :visible.sync="pdf.open"  width="1300px" :center="true" append-to-body>
      <div style="margin-top: -60px;float: right;margin-right: 40px;">
        <el-button size="mini" type="text" @click="openPdf">{{$t('新页面打开PDF')}}</el-button></div>
      <div style="margin-top: -30px" >
        <iframe id="iFrame" class="iframe-html" :src="pdf.pdfUrl" frameborder="0" width="100%" height="700px" v-if="ppt"></iframe>
      </div>
      <div style="padding: 30px; width: 100%; height: 100%;" >
        <el-carousel class="" ref="carousel"  arrow="always"  v-if="pptView"
                   height="700px"  trigger="click" :autoplay="false" indicator-position="outside">
          <el-carousel-item class="lun_img" v-for="item in imgs" v-bind:key="item" >
            <img :src="item" width="100%" height="100%" object-fit="cover" />
          </el-carousel-item>
        </el-carousel>

      </div>
    </el-dialog>
    <plan-approve v-if="planApproveVisible" ref="planApprove" @refreshDataList="getList"></plan-approve>
  </div>
</template>

<script>
import { getFeedbackByPlanId } from "@/api/training/spec/feedback";
import { addFeedback, updateFeedback } from "@/api/training/spec/feedback";
import { getAnswer } from "@/api/training/spec/answer";
import { getPlan, listPlanByYearId, delPlan, addPlan, updatePlan, updatePlan2, exportPlan, importTemplate } from "@/api/training/spec/plan";
import { allFileList, delCommonfile } from "@/api/common/commonfile";
import { treeselect } from "@/api/system/dept";
import { getToken } from "@/utils/auth";
import PlanApprove from "./plan-approve"
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {getYearplan} from "@/api/training/spec/yearplan";
import Editor from '@/components/Editor';

export default {
  name: "Plan",
  components: { Treeselect, PlanApprove, Editor },
  data() {
    return {
       //图片集合   打开关闭按钮 等等
      imgs:[],
      jpgList:[],
      ppt:false,
      pptView:false,
      loadingFlash:false,
      // 报告附件参数
      docFeedback: {  // 反馈附件
        file: "",
        // 是否显示弹出层（报告附件）
        open: false,
        // 弹出层标题（报告附件）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 报告附件上传位置编号
        ids: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/commonfile/uploadFile",
        commonfileList: null,
        queryParams: {
          pId: null,
          pType: 'docFeedback'
        },
        pType: 'docFeedback',
        pId: null
      },
      docMentor: {  // 学习资料
        file: "",
        // 是否显示弹出层（报告附件）
        open: false,
        // 弹出层标题（报告附件）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 报告附件上传位置编号
        ids: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/commonfile/uploadFile",
        commonfileList: null,
        queryParams: {
          pId: null,
          pType: 'docMentor'
        },
        pType: 'docMentor',
        pId: null
      },
      docSuccessor: { // 学员附件
        file: "",
        // 是否显示弹出层（报告附件）
        open: false,
        // 弹出层标题（报告附件）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 报告附件上传位置编号
        ids: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/commonfile/uploadFile",
        commonfileList: null,
        queryParams: {
          pId: null,
          pType: 'docSuccessor'
        },
        pType: 'docSuccessor',
        pId: null
      },
      // 导师反馈内容
      mentorFeedback: null,
      // 开始日期不能跨年
      pickerOptionsStartDate: {
        disabledDate(time) {
          return time.getYear() != new Date().getYear();
        }
      },
      // 结束日期不能跨年
      pickerOptionsEndDate: {
        disabledDate(time) {
          return time.getYear() != new Date().getYear();
        }
      },
      // 反馈参数
      feedbackParams: {
        id: null,
        mentorFeedback: null
      },
      showMonths:[],
      minDay:"", // 最小日期
      maxDay:"", // 最大日期
      IsShowyear:true, // 显示年|月 、 月|日
      // 查看培养详情参数
      detail: {
        // 是否显示弹出层（报告附件）
        open: false,
        // 弹出层标题（报告附件）
        title: ""
      },
      // 反馈对话框参数
      feedbackDialog: {
        id: 0,
        // 是否显示弹出层（报告附件）
        open: false,
        // 弹出层标题（报告附件）
        title: "",
        // 学习状态
        studyState: null,
        // 计划id
        planId: null,
      },
      // 遮罩层
      loading: true,
      planApproveVisible: false,
      // 选中数组
      ids: [],
      dataListSelections: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 培养计划表格数据
      planList: [],
      // 弹出层标题
      title: "",
      // 操作
      operation: "",
      // 部门树选项
      deptOptions: undefined,
      clientHeight:300,
      // 是否显示弹出层
      open: false,
      // 学习状态字典
      studyStateOptions: [],
      approveStatusOptions: [],
      // 学员列表
      successorOptions: [],
      // 包含导师ID的查询对象
      queryObject: {
        mentorStaffId: ""
      },
      // 用户导入参数
      upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/spec/plan/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        staffId: null,
        plantName: null,
        startDate: null,
        endDate: null,
        classHour: null,
        studyState: null,
        yearPlanId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      // pdf文件参数
      pdf : {
          title: '',
          pdfUrl: '',
          numPages: null,
          open: false,
          pageNum: 1,
          pageTotalNum: 1,
          loadedRatio: 0,
      },
      // 表格参数
      tableData: [],
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
        this.$refs.tree.filter(val);
    }
   },
  computed:{
    // 获取最小日期-月开始时间戳
    minDayTimeStamp() {
      if(this.IsShowyear){
        return this.showMonths[0].months[0].beginTimeStamp
      }else{
        return this.showMonths[0].days[0].daysArr[0].timestamp
      }
    },
    // 获取最大日期时间戳
    maxDayTimeStamp() {
      let Length = this.showMonths.length // 年有多少个
      // 如果显示年|月 与 月|日 是不同的
      if(this.IsShowyear){
        let monthsLength = this.showMonths[Length - 1].months.length  //月有多少个
        return this.showMonths[Length - 1].months[monthsLength - 1].endTimeStamp
      }else{
        let daysLength = this.showMonths[Length - 1].days.length
        let daysarrLength = this.showMonths[Length - 1].days[daysLength - 1].daysArr.length  //天有多少个
        return this.showMonths[Length - 1].days[daysLength - 1].daysArr[daysarrLength - 1].timestamp + 86400000  //+86400000 是因为时间戳都是0点这样+1天的时间戳，就表示最晚一天的最后的时间
      }
    },
    // 最大日期与最小日期的时间戳差
    maxAndminDayTimeStamp() {
      return this.maxDayTimeStamp - this.minDayTimeStamp
    },
    // 获取日期单元格宽度 => 如果返回0则只用之前第一版的计算方法
    getCellDateWidth() {
      let num = 0 // 获取日期单元格数量
      if(this.IsShowyear){
        // 月数量
        for(let i = 0;i < this.showMonths.length;i++){
          num += this.showMonths[i].months.length
        }
      }else{
        // 天数量
        for(let i = 0;i < this.showMonths.length;i++){
          for(let j = 0;j < this.showMonths[i].days.length;j++){
            num += this.showMonths[i].days[j].daysArr.length
          }
        }
      }
      // 每个单元格最小30宽度
      let MaxWidth = window.screen.width
      let CellNum = MaxWidth / 30 > 0 ? MaxWidth / 30  : 0
      if(num >= CellNum){ // 页面宽 / 单元格最小宽度 = 最多放下的值
        return num * 30
      }else{
        // 单元格的值，就不能是最小值30了
        // 需要获取dom的宽度，在进行计算，但是dom还未渲染完成，因此这里就不考虑了，直接只用第一版的方法动态计算
        // TODO
        return 0
      }

    }
  },
  created() {
    //设置表格高度对应屏幕高度
    this.$nextTick(() => {
        this.clientHeight = document.body.clientHeight -250
    })
    const yearId = this.$route.params && this.$route.params.yearId;
    // 设置查询参数年度计划编号
    this.queryParams.yearPlanId = yearId;
    this.getList();
    this.getTreeselect();
    this.getDicts("st_study_state").then(response => {
      this.studyStateOptions = response.data;
    });
    this.getDicts("spec_training_approve_status").then(response => {
      this.approveStatusOptions = response.data;
    });
  },
  methods: {
    /** 单元格样式 */
    tableCellStyle (row, column, rowIndex, columnIndex) {
      // 超时学习突出显示
      if (row.column.label === "实际完成日期" && row.row.dateOfCompletion > row.row.endDate) {
        return "background: #FFEEEE"
      }
      // 修改过的计划突出显示
      if (row.column.label === "修改人" && row.row.updateBy!=null) {
        return "background: #FFFFDB"
      }
      if (row.column.label === "修改时间" && row.row.updatedate!=null) {
        return "background: #FFFFDB"
      }
    },
    /** 通过处理 */
    handleApprove() {
      this.feedbackParams.planId = this.feedbackDialog.planId;
      // 导师反馈内容，有则修改，无则新增
      if (this.mentorFeedback == null) {
        addFeedback(this.feedbackParams).then(response => {
          // 发邮件通知学员

          this.feedbackDialog.open = false;
          // 修改学习状态为1已完成
          let plan = {};
          plan.id = this.feedbackDialog.planId;
          plan.studyState = 1;
          plan.dateOfCompletion = new Date();
          updatePlan2(plan).then(response => {
            this.feedbackDialog.open = false;
            this.msgSuccess("已通过");
            this.getList();
          });
        });
      } else {
        updateFeedback(this.feedbackParams).then(response => {
          // 发邮件通知学员

          this.feedbackDialog.open = false;
          // 修改学习状态为1已完成
          let plan = {};
          // 获取计划id(修改条件)
          plan.id = this.feedbackDialog.planId;
          plan.studyState = 1;
          plan.dateOfCompletion = new Date();
          updatePlan2(plan).then(response => {
            this.feedbackDialog.open = false;
            this.msgSuccess("已通过");
            this.getList();
          });
        });
      }
    },
    /** 驳回处理 */
    handleReject() {
      this.feedbackParams.planId = this.feedbackDialog.planId;
      // 导师反馈内容：有则修改，无则新增
      if (this.mentorFeedback == null) {
        addFeedback(this.feedbackParams).then(response => {
          // 发邮件通知学员

          this.feedbackDialog.open = false;
        // 修改学习状态为3导师已反馈
          let plan = {};
          // 获取计划id(修改条件)
          plan.id = this.feedbackDialog.planId;
          plan.studyState = 3;
          updatePlan2(plan).then(response => {
            this.feedbackDialog.open = false;
            this.msgSuccess("已驳回");
            this.getList();
          });
        });
      } else {
        updateFeedback(this.feedbackParams).then(response => {
          // 发邮件通知学员

          this.feedbackDialog.open = false;
        // 修改学习状态为3导师已反馈
          let plan = {};
          plan.id = this.feedbackDialog.planId;
          plan.studyState = 3;
          plan.dateOfCompletion = new Date();
          updatePlan2(plan).then(response => {
            this.feedbackDialog.open = false;
            this.msgSuccess("已驳回");
            this.getList();
          });
        });
      }
    },
    /** 反馈处理 */
    handleFeedback(row) {
      // 加载反馈附件
      this.docFeedback.id = row.id;
      this.docFeedback.queryParams.pId = row.id
      this.docFeedback.pId = row.id
      this.getFileListFeedback()
      this.$nextTick(() => {
        this.$refs.docFeedback.clearFiles()
      })
      // 清空导师反馈内容
      this.feedbackParams.mentorFeedback = null;
      // 清空表格数据
      this.tableData = [];
      let feedback1 = {};
      feedback1.planId = row.id;
      feedback1.questionId = 1;
      let feedback2 = {};
      feedback2.planId = row.id;
      feedback2.questionId = 2;
      let feedback3 = {};
      feedback3.planId = row.id;
      feedback3.questionId = 3;
      let answerObj1 = {};
      let answerObj2 = {};
      let answerObj3 = {};
      // 获取问题和答案
      getAnswer(feedback1).then(response => {
        let data = response.data;
        if (data != null) {
          answerObj1 = { id: 1, question: data.question, answer: data.answer};
        }
        return getAnswer(feedback2);
      }).then(response => {
        let data = response.data;
        if (data != null) {
          answerObj2 = { id: 2, question: data.question, answer: data.answer};
        }
        return getAnswer(feedback3);
      }).then(response => {
        let data = response.data;
        if (data != null) {
          answerObj3 = { id: 3, question: data.question, answer: data.answer};
          this.tableData.push(answerObj1);
          this.tableData.push(answerObj2);
          this.tableData.push(answerObj3);
        }
        // 获取导师反馈内容
        return getFeedbackByPlanId(row.id);
      }).then(response => {
        if (response.data != null) {
          let data = response.data;
          this.mentorFeedback = data.mentorFeedback;
          this.feedbackParams.id = data.id;
        }
        this.feedbackDialog.title = row.staffName + row.plantName + "学习情况反馈";
        this.feedbackDialog.planId = row.id;
        this.feedbackDialog.studyState = row.studyState;
        this.feedbackDialog.open = true;
      });
    },
    /** 文件下载处理 */
    handleDownload(row) {
      var name = row.fileName;
      var url = row.fileUrl;
      var suffix = url.substring(url.lastIndexOf("."), url.length);
      const a = document.createElement('a')
      a.setAttribute('download', name)
      a.setAttribute('target', '_blank')
      a.setAttribute('href', process.env.VUE_APP_BASE_API + url)
      a.click()
    },

    /** 报告附件按钮操作 */
    handleDocMentor(row) {
      this.docMentor.id = row.id;
      this.docMentor.title = row.plantName + this.$t('学习资料');
      this.docMentor.open = true;
      this.docMentor.queryParams.pId = row.id
      this.docMentor.pId = row.id
      this.getFileListMentor()
      this.$nextTick(() => {
        this.$refs.docMentor.clearFiles()
      })
    },
    handleDocSuccessor(row) {
      this.docSuccessor.id = row.id;
      this.docSuccessor.title = row.plantName + this.$t('学员附件');
      this.docSuccessor.open = true;
      this.docSuccessor.queryParams.pId = row.id
      this.docSuccessor.pId = row.id
      this.getFileListSuccessor()
      this.$nextTick(() => {
        this.$refs.docSuccessor.clearFiles()
      })
    },
    getFileListMentor() {
      allFileList(this.docMentor.queryParams).then(response => {
        this.docMentor.commonfileList = response;
      });
    },
    getFileListSuccessor() {
      allFileList(this.docSuccessor.queryParams).then(response => {
        this.docSuccessor.commonfileList = response;
      });
    },
    getFileListFeedback() {
      allFileList(this.docFeedback.queryParams).then(response => {
        this.docFeedback.commonfileList = response;
      });
    },
    /** 附件上传中处理 */
    handleFileDocProgressFeedback(event, file, fileList) {
      this.docFeedback.file = file;
      this.docFeedback.isUploading = true;
    },
    handleFileDocProgressMentor(event, file, fileList) {
      this.docMentor.file = file;
      this.docMentor.isUploading = true;
    },
    handleFileDocProgressSuccessor(event, file, fileList) {
      this.docSuccessor.file = file;
      this.docSuccessor.isUploading = true;
    },
    /** 附件上传成功处理 */
    handleFileDocSuccessFeedback(response, file, fileList) {
      this.docMentorFeedback.isUploading = false;
      this.$alert(response.msg, this.$t('导入结果'), { dangerouslyUseHTMLString: true });
      this.getFileListFeedback()
    },
    handleFileDocSuccessMentor(response, file, fileList) {
      this.docMentor.isUploading = false;
      this.$alert(response.msg, this.$t('导入结果'), { dangerouslyUseHTMLString: true });
      this.getFileListMentor()
    },
    handleFileDocSuccessSuccessor(response, file, fileList) {
      this.docSuccessor.isUploading = false;
      this.$alert(response.msg, this.$t('导入结果'), { dangerouslyUseHTMLString: true });
      this.getFileListSuccessor()
    },
    /** 删除按钮操作 */
    handleDeleteDoc(row) {
      const ids = row.id || this.ids;
      this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: "warning"
      }).then(function() {
        return delCommonfile(ids);
      }).then(() => {
        this.getFileList()
        this.msgSuccess(this.$t('删除成功'));
      })
    },
    /** 查询培训计划列表 */
    getList() {
      this.loading = true;
      listPlanByYearId(this.queryParams).then(response => {
        this.planList = response.rows;
        this.total = response.total;
        this.setrowspans() // 设置合并
        this.getChartTitle() // 渲染的信息
        this.$nextTick(() => {
          this.$refs.planTable.doLayout(); // 解决表格错位
        });
        this.loading = false;
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
        treeselect().then(response => {
            this.deptOptions = response.data;
        });
    },
    /** 学习状态字典翻译 */
    studyStateFormat(row, column) {
      return this.selectDictLabel(this.studyStateOptions, row.studyState);
    },
    // 申请状态字典翻译
    approveStatusFormat(row, column) {
      return this.selectDictLabel(this.approveStatusOptions, row.approveStatus);
    },
    approveStatusType (type) {
      if (type == 0) {
        return 'danger'
      }else if (type == 1) {
        return 'success'
      }else if (type == 2) {
        return 'danger'
      }else {
        return 'info'
      }
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: null,
        staffId: null,
        plantName: null,
        delFlag: null,
        createrCode: null,
        createdate: null,
        updaterCode: null,
        updatedate: null,
        deptId: null,
        startDate: null,
        endDate: null,
        classHour: null,
        classContent: null,
        studyState: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
      this.dataListSelections = selection
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      getYearplan(this.queryParams.yearPlanId).then(response => {
        this.form.staffId = response.data.staffId.toString();
        this.open = true;
        this.title = "添加培养计划";
        this.operation = "modify";
      });
      this.open = true;
      this.title = "添加培养计划";
      this.operation = "add";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPlan(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改培养计划";
        this.operation = "modify";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePlan(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            // 设置表单参数年度计划编号
            this.form.yearPlanId = this.queryParams.yearPlanId;
            addPlan(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delPlan(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有培养计划数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportPlan(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
    /** 导入按钮操作 */
    handleImport() {
        this.upload.title = "导入培养计划数据";
        this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
        importTemplate().then(response => {
            this.download(response.msg);
        });
    },
    /** 文件上传中处理 */
    handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
    },
    /** 文件上传成功处理 */
    handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
        this.getList();
    },
    /** 提交上传文件 */
    submitFileForm() {
        this.$refs.upload.submit();
    },
    addAprrove (row, type) {
      var rows = row ? [row] : this.dataListSelections.map(item => {
        return item
      })
      this.planApproveVisible = true
      console.log(rows)
      console.log(type)
      this.$nextTick(() => {
        this.$refs.planApprove.init(rows, type)
      })
    },
    optimizeCalcWidth(val) {
      let SumNum = this.maxAndminDayTimeStamp
      let diffNum = this.IsShowyear ? val.endTimeStamp - val.beginTimeStamp : val.endTimeStamp + 84600000 - val.beginTimeStamp  // 结束日期 - 开始日期
      let rate = Math.round(diffNum / SumNum * 10000) / 100.00 //得到百分比
      let widthPx = this.getCellDateWidth * rate / 100.00
      return widthPx + 'px'
    },
    optimizeCalcLeft(val) {
      let SumNum = this.maxAndminDayTimeStamp
      let diffNum = val.beginTimeStamp - this.minDayTimeStamp // 开始日期 - 整个月开始日期
      let rate = Math.round(diffNum / SumNum * 10000) / 100.00 //得到百分比
      let leftPx = this.getCellDateWidth * rate / 100.00
      return leftPx + 'px'
    },
    // 计算图表的Left
    calcLeft(val,date) {
      // 如果本月的最大时间戳都没有结束时间长，那么就可判断
      if(val.endTimeStamp > date.endTimeStamp){
        // 如果本月开始日期小于开始日期
        if(val.beginTimeStamp > date.beginTimeStamp){
          // 进行判断
          let diffNum = date.endTimeStamp - val.beginTimeStamp
          let SumNum = date.endTimeStamp - date.beginTimeStamp
          let rate =  100 - Math.round(diffNum / SumNum * 10000) / 100.00
          // 位置判断
          return rate+"%"
        }
      }else if(val.endTimeStamp > date.beginTimeStamp && val.endTimeStamp < date.endTimeStamp){
        // 进行判断
        if(val.beginTimeStamp > date.beginTimeStamp){
          // 都在一个单元格中
          let diffNum = val.beginTimeStamp - date.beginTimeStamp
          let SumNum = date.endTimeStamp - date.beginTimeStamp
          let rate =  Math.round(diffNum / SumNum * 10000) / 100.00
          // 位置判断
          return rate+"%"
        }
      }
      return '0px'
    },
    // 计算图表的Width
    calcwidth(val,date) {

      if(this.IsShowyear){
        // 如果是 年|月
        // 1. 如果本月的最大时间戳都没有结束时间长，那么就可设置100%
        // 2. 如果本月的最小时间戳比结束时间长，那么设置0
        // 3. 如果本月的最小时间戳没有结束时间长，那么进行判断
        if(val.endTimeStamp > date.endTimeStamp){
          // 如果本月开始日期小于开始日期
          if(val.beginTimeStamp > date.beginTimeStamp){
            // 进行判断
            let diffNum = date.endTimeStamp - val.beginTimeStamp
            let SumNum = date.endTimeStamp - date.beginTimeStamp
            let rate = Math.round(diffNum / SumNum * 10000) / 100.00
            return 'calc('+ rate +'% + 2px)' // 结束时间超过本月最大时间戳直接+2px
          }
          return 'calc(100% + 2px)'
        }else if(val.endTimeStamp < date.beginTimeStamp){
          return '0px'
        }else if(val.endTimeStamp > date.beginTimeStamp && val.endTimeStamp <= date.endTimeStamp){
          // 进行判断
          if(val.beginTimeStamp > date.beginTimeStamp){
            // 都在一个单元格中
            let SumNum = date.endTimeStamp - date.beginTimeStamp // 全月多少数
            let diffNum = val.endTimeStamp - val.beginTimeStamp // 过程多少数
            diffNum = diffNum === 0 ?  86400000 : diffNum
            let rate = Math.round(diffNum / SumNum * 10000) / 100.00
            return 'calc('+ rate +'%)'
          }else{
            // 不在一个单元格中，则不需要判断任何信息
            let diffNum = val.endTimeStamp - date.beginTimeStamp
            let SumNum = date.endTimeStamp - date.beginTimeStamp
            let rate = Math.round(diffNum / SumNum * 10000) / 100.00
            return 'calc('+ rate +'%)'
          }
        }
      }
      return '0px'
    },
    //获得数据相同的行数(网络复制)
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        return {
          rowspan: row.rowspan,
          colspan: 1
        };
      }
    },
    // 根据id去分组(网络复制)
    setrowspans() {
      // 先给所有的数据都加一个v.rowspan = 1
      this.planList.forEach(v => {
        v.rowspan = 1;
      });
      // 双层循环
      for (let i = 0; i < this.planList.length; i++) {
        // 内层循环，上面已经给所有的行都加了v.rowspan = 1
        // 这里进行判断
        // 如果当前行的id和下一行的id相等
        // 就把当前v.rowspan + 1
        // 下一行的v.rowspan - 1
        for (let j = i + 1; j < this.planList.length; j++) {
          //此处可根据相同字段进行合并，此处是根据的id
          if (this.planList[i].id === this.planList[j].id) {
            this.planList[i].rowspan++;
            this.planList[j].rowspan--;
          }
        }
        // 这里跳过已经重复的数据
        i = i + this.planList[i].rowspan - 1;
      }
    },
    // 渲染表格头，首先是年月，如2018年11月
    getChartTitle(startDate, endDate){
      var chartTable = this.planList;
      // 准备日期，为了防止多次赋值属性，导致计算属性重新计算，决定只赋值一次
      let maxDayParams = "",minDayParams = ""

      for(var i = 0; i < chartTable.length; i++){

        var StartDate = chartTable[i].startDate;
        var EndDate = chartTable[i].endDate;
        var mainObj = chartTable[i];

        // 计划日期
        maxDayParams === "" ? maxDayParams = EndDate : ''
        minDayParams === "" ? minDayParams = StartDate : ""
        maxDayParams = this.compareDate(EndDate,maxDayParams,true)
        minDayParams = this.compareDate(StartDate,minDayParams,false)
        var days = this.GetNumberOfDays(StartDate,EndDate) // 计算工期
        this.planList[i].days = days + 1 // 加一是因为没算结算当天
        // 记录时间戳
        this.planList[i].beginTimeStamp = this.getTimeStamp(StartDate)
        this.planList[i].endTimeStamp = this.getTimeStamp(EndDate)
      }
      this.minDay = minDayParams
      this.maxDay = maxDayParams
      console.log("小："+this.minDay)
      console.log("大："+this.maxDay)

      this.getYearArr()
      console.log(this.showMonths)

    },

    // 获取需要的格式的年月日信息
    getYearArr(){
      // 如果有一个日期相差超过366天，按照年，不超过则按天
      var days = this.GetNumberOfDays(this.minDay,this.maxDay)
      if(days >= 365){
        //需要记录月份
        this.IsShowyear = true
      }else{
        //需要记录天数
        this.IsShowyear = true
      }
      // 获取需要格式的年月信息
      let yearArr = []; // 存年

      let minYear = new Date(this.minDay).getFullYear();
      let maxYear = new Date(this.maxDay).getFullYear();
      // 保存年
      if(minYear === maxYear){
        yearArr.push({
          year: minYear+"",
          months: [],        // 放月的数组
          days: []
        })
      }else{
        for(let i = minYear;i <= maxYear;i++){
          yearArr.push({
            year: i+"",
            months: [],        // 放月的数组
            days: []
          })
        }
      }
      // 保存月
      for(let i = 0;i < yearArr.length;i++){
        let minMonth = 1
        if(i === 0){
          minMonth = new Date(this.minDay).getMonth() + 1;
        }
        // 1.eg：2016年9月 至 2019年01月
        // 2.如果只有一个年，那么月份就是最小月到最大月
        if(yearArr.length > 1){
          // 如果是最后一年，那么就要判断是否到最后一个月
          if(yearArr.length - 1 === i){
            let maxMonth = new Date(this.maxDay).getMonth() + 1;
            let _maxDay = new Date(this.maxDay).getDate() // 最大日期 天数
            let j = 1
            while(j <= maxMonth){
              let monthsDays = this.getLastDay(yearArr[i].year, j); // 获取月份一共有多少天
              let timestampstr = this.getTimeStamp(yearArr[i].year +"-"+  (j > 9 ? j : '0'+j) + "-" + monthsDays)
              let timestampstr1 = this.getTimeStamp(yearArr[i].year +"-"+  (j > 9 ? j : '0'+j) + "-01")
              yearArr[i].months.push({str:j+"月",num:j,endTimeStamp:timestampstr,beginTimeStamp:timestampstr1});// 记录最大最小的时间戳
              // 如果显示月|天 才用记录天
              if(!this.IsShowyear){
                yearArr[i].days[yearArr[i].days.length] = {year: "",month: "",daysArr: {}}
                yearArr[i].days[yearArr[i].days.length - 1].year = yearArr[i].year    // 赋值年
                yearArr[i].days[yearArr[i].days.length - 1].month = j;    // 赋值月
                yearArr[i].days[yearArr[i].days.length - 1].daysArr = []
                // 如果结束月，不是到本月最后一天，而是截止到最
                if(j === maxMonth){
                  monthsDays = _maxDay
                }
                for(let k = 1; k <= monthsDays; k++){
                  timestampstr = this.getTimeStamp(yearArr[i].year +"-"+  (j > 9 ? j : '0'+j) + "-" + (k > 9 ? k : '0'+k))
                  yearArr[i].days[yearArr[i].days.length - 1].daysArr.push({day: k+"",timestamp:timestampstr});// 赋值天
                }
              }
              j++
            }
          }else{
            if(i === 0){
              let j = minMonth
              let _minDay = new Date(this.minDay).getDate() // 最小日期 天数

              while(j <= 12){
                let monthsDays = this.getLastDay(yearArr[i].year, j); // 获取月份一共有多少天
                let timestampstr = this.getTimeStamp(yearArr[i].year +"-"+  (j > 9 ? j : '0'+j) + "-" + monthsDays)
                let timestampstr1 = this.getTimeStamp(yearArr[i].year +"-"+  (j > 9 ? j : '0'+j) + "-01")
                yearArr[i].months.push({str:j+"月",num:j,endTimeStamp:timestampstr,beginTimeStamp:timestampstr1});// 记录最大最小的时间戳
                // 如果显示月|天 才用记录天
                if(!this.IsShowyear){
                  yearArr[i].days[yearArr[i].days.length] = {year: "",month: "",daysArr: {}}
                  yearArr[i].days[yearArr[i].days.length - 1].year = yearArr[i].year    // 赋值月
                  yearArr[i].days[yearArr[i].days.length - 1].month = j     // 赋值月
                  yearArr[i].days[yearArr[i].days.length - 1].daysArr = []
                  for(let k = 1; k <= monthsDays; k++){
                    // 如果开始月，就不从1日开始，而是从最开始的日期那天开始算起
                    if(k === 1 && j === minMonth){
                      k = _minDay
                    }
                    timestampstr = this.getTimeStamp(yearArr[i].year +"-"+  (j > 9 ? j : '0'+j) + "-" + (k > 9 ? k : '0'+k))
                    yearArr[i].days[yearArr[i].days.length - 1].daysArr.push({day: k+"",timestamp:timestampstr});// 赋值天
                  }
                }
                j++
              }
            }else{
              let j = 1
              while(j <= 12){
                let monthsDays = this.getLastDay(yearArr[i].year, j); // 获取月份一共有多少天
                let timestampstr = this.getTimeStamp(yearArr[i].year +"-"+  (j > 9 ? j : '0'+j) + "-" + monthsDays)
                let timestampstr1 = this.getTimeStamp(yearArr[i].year +"-"+  (j > 9 ? j : '0'+j) + "-01")
                yearArr[i].months.push({str:j+"月",num:j,endTimeStamp:timestampstr,beginTimeStamp:timestampstr1});// 记录最大最小的时间戳
                // 如果显示月|天 才用记录天
                if(!this.IsShowyear){
                  yearArr[i].days[yearArr[i].days.length] = {year: "",month: "",daysArr: {}}
                  yearArr[i].days[yearArr[i].days.length - 1].year = yearArr[i].year    // 赋值年
                  yearArr[i].days[yearArr[i].days.length - 1].month = j // 赋值月
                  yearArr[i].days[yearArr[i].days.length - 1].daysArr = []
                  for(let k = 1; k <= monthsDays; k++){
                    timestampstr = this.getTimeStamp(yearArr[i].year +"-"+  (j > 9 ? j : '0'+j) + "-" + (k > 9 ? k : '0'+k))
                    yearArr[i].days[yearArr[i].days.length - 1].daysArr.push({day: k+"",timestamp:timestampstr});// 赋值天
                  }
                }
                j++
              }
            }

          }
        }else{
          // 如果只有一年那么没有必要判断是否记录天
          let maxMonth = new Date(this.maxDay).getMonth() + 1;
          let _minMonth = minMonth
          let _minDay = new Date(this.minDay).getDate() // 最小日期 天数
          let _maxDay = new Date(this.maxDay).getDate() // 最大日期 天数
          while(_minMonth <= maxMonth){
            let monthsDays = this.getLastDay(yearArr[i].year, _minMonth); // 获取月份一共有多少天
            let timestampstr = this.getTimeStamp(yearArr[i].year +"-"+  (_minMonth > 9 ? _minMonth : '0'+_minMonth) + "-" + monthsDays)
            let timestampstr1 = this.getTimeStamp(yearArr[i].year +"-"+  (_minMonth > 9 ? _minMonth : '0'+_minMonth) + "-01")
            yearArr[i].months.push({str:_minMonth+"月",num:_minMonth,endTimeStamp:timestampstr,beginTimeStamp:timestampstr1});// 记录最大最小的时间戳
            yearArr[i].days[yearArr[i].days.length] = {year: "",month: "",daysArr: {}}
            yearArr[i].days[yearArr[i].days.length - 1].year = yearArr[i].year     // 赋值月
            yearArr[i].days[yearArr[i].days.length - 1].month = _minMonth    // 赋值月
            yearArr[i].days[yearArr[i].days.length - 1].daysArr = []
            // 如果结束月，不是到本月最后一天，而是截止到最
            if(_minMonth === maxMonth){
              monthsDays = _maxDay
            }
            for(let k = 1; k <= monthsDays; k++){
              // 如果开始月，就不从1日开始，而是从最开始的日期那天开始算起
              if(k === 1 && _minMonth === minMonth){
                k = _minDay
              }
              timestampstr = this.getTimeStamp(yearArr[i].year +"-"+  (_minMonth > 9 ? _minMonth : '0'+_minMonth) + "-" + (k > 9 ? k : '0'+k))
              yearArr[i].days[yearArr[i].days.length - 1].daysArr.push({day: k+"",timestamp:timestampstr});// 赋值天
            }
            _minMonth++
          }
        }
      }
      this.showMonths = yearArr
    },

    // 获取月的最后一天
    getLastDay(myyear, mymonth){
      var new_date = new Date(myyear, mymonth, 0);
      return new_date.getDate();
    },

    // 获得天数
    GetNumberOfDays(date1,date2){
      //date1：开始日期，date2结束日期
      var a1 = Date.parse(new Date(date1));
      var a2 = Date.parse(new Date(date2));
      var day = parseInt((a2-a1)/ 86400000);//核心：时间戳相减，然后除以天数
      return day
    },
    // 时间比较 true 比大
    compareDate(dateTime1,dateTime2,condition = true)
    {
      var formatDate1 = new Date(dateTime1)
      var formatDate2 = new Date(dateTime2)
      if(formatDate1 >= formatDate2)
      {
        return condition ? dateTime1 : dateTime2
      }
      else
      {
        return condition ? dateTime2 : dateTime1
      }
    },
    // 获取时间戳
    getTimeStamp(val){
      return new Date(val).getTime()
    },
      //文件预览
    openPdf(){
      //ppt就跳路由预览，office就直接打开文件新页面
      const didi={ imgs:this.imgs}
      if( this.pptView==true&&this.ppt==false){
        let routeUrl = this.$router.resolve({
          path: "/cpms/index.html#/pptyulan",
          query:didi
        });
        window.open("/cpms/index.html#/pptyulan?id=" + this.pdf.pdfUrl, '_blank')
        console.log(this.imgs)
      }else {
        window.open(this.pdf.pdfUrl)
      }
    },
    handleSeePPT (row){
      //ppt预览
      this.loadingFlash=true
      this.pdf.open =true
      this.pdf.title = row.fileName
      this.pdf.pdfUrl = row.fileUrl
      this.pptView=true
      this.ppt=false
      const formatDate =new FormData();
      formatDate.append("filepath",row.fileUrl)

      //调用文件预览api
      let res= this.officeConvert.pptConvertCommon(formatDate)

      //查看接受的全局方法的返回结果 console.log(res)
      //利用.then方法接受Promise对象

      res.then((result)=>{
        //关闭加载中
        this.loadingFlash=false

        //成功时直接给地址
        this.videoList = result.data.imagePathList
        //将返回的地址集合遍历添加到绑定的数组中
        this.imgs=[]
        for (var key=0;key<this.videoList.length;key++) {
          this.imgs.push( process.env.VUE_APP_BASE_API+  this.videoList[key]  );
        }
      }).catch(result => {

        //请求失败，关闭loading，pdf地址直接为为空，不显示
        this.pdf.pdfUrl =""
        this.loadingFlash = false;
      })
    },
    handleSee (row){
      //office预览
      this.loadingFlash=true
      this.pdf.open =true
      this.pdf.title = row.fileName
      this.pdf.pdfUrl =""

      this.pptView=false
      this.ppt=true

      const formatDate =new FormData();
      formatDate.append("filepath",row.fileUrl)

      //调用文件预览api
      let res= this.officeConvert.officeConvertCommon(formatDate)


      //查看接受的全局方法的返回结果 console.log(res)
      //利用.then方法接受Promise对象
      res.then((result)=>{
        //关闭加载中
        this.loadingFlash=false

        if(result.msg.includes("csv")){
          this.pdf.pdfUrl =process.env.VUE_APP_BASE_API+ result.data
          this.$alert(result.msg, this.$t('检查乱码'), { dangerouslyUseHTMLString: true });
          //    this.$message({message: result.msg, center: true,type:'warning',  offset:400, });

        }else if(result.msg.includes("不存在")){
          //文件不存在时提示
          this.pdf.pdfUrl =""
          this.$alert(result.msg, this.$t('预览失败'), { dangerouslyUseHTMLString: true });
          //    this.$message({message: result.msg, center: true,type:'warning',  offset:400, });
          this.pdf.open =false
        }else if(result.msg.includes("不支持此格式")){

          this.pdf.pdfUrl =""
          this.$alert(result.msg, this.$t('预览失败'), { dangerouslyUseHTMLString: true });
          //    this.$message({message: result.msg, center: true,type:'warning',  offset:400, });
          this.pdf.open =false
        } else{
          //成功时直接给地址
          this.pdf.pdfUrl =process.env.VUE_APP_BASE_API+ result.data
        }
        // this.$nextTick(() => {
        //   const iframe = window.frames['iFrame']
        //   const handleLoad = () => {
        //     setTimeout(() => {
        //       const Do = (iframe.contentWindow || iframe.contentDocument)
        //       console.log(Do.document.getElementsByTagName('table')[0])
        //       Do.document.getElementsByTagName('table')[0].style.width = "100%"
        //       Do.document.getElementsByTagName('table')[0].setAttribute("class","table")
        //     }, 500)
        //   }
        //   iframe.addEventListener('load', handleLoad, true)
        // })
      }).catch(result => {

        //请求失败，关闭loading，pdf地址直接为为空，不显示
        this.pdf.pdfUrl =""
        this.loadingFlash = false;

      })



    },
  }
};
</script>
<style>

/* 单元格padding */
.barchart .el-table--border th:first-child .cell, .el-table--border td:first-child .cell{
  padding: 0px;
}
.barchart .el-table th > .cell{
  padding: 0px;
}
/* 单元格高度 */
.barchart .el-table--medium th,.barchart  .el-table--medium td {
  padding: 0px 0px !important;
  height: 25px !important;
}
.barchart .progressCon{
  padding: 0;
  margin: 0;
  position: relative;
}
.barchart .progressUpon{
  background: rgb(38, 84, 124);
  height: 1.5em;
  /* width: calc(100% + 2px); // +2是因为边框线为2px*/
  z-index: 2;
  position: absolute;
  top: 25%;
  left:0px
}
.barchart .progressDownon{
  background: rgb(255,209,102);
  height: 1.5em;
  /* width: calc(100% + 2px); // +2是因为边框线为2px*/
  z-index: 2;
  position: absolute;
  top: 25%;
  left:0px
}
</style>
