<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item :label="$t('年份')" prop="year">
        <el-date-picker clearable size="small" style="width: 200px" @change="handleQuery"
                        v-model="queryParams.year"
                        type="year"
                        value-format="yyyy"
                        :placeholder="$t('请选择')+$t('年份')">
        </el-date-picker>
      </el-form-item>
      <el-form-item :label="$t('员工号')" prop="employeeid">
        <el-select v-model="queryParams.employeeid" filterable :placeholder="$t('请选择')+$t('人员')" clearable @change="handleQuery">
          <el-option
            v-for="dict in employeeOptions"
            :key="dict.staffid"
            :label="dict.name"
            :value="dict.staffid">
            <span style="float: left">{{ dict.name }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ dict.staffid }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t('搜索') }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('重置') }}</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="['plant:targetagreement:add']"
        >{{ $t('新增') }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          @click="generateManager"
          v-hasPermi="['plant:targetagreement:edit']"
        >{{ $t('生成经理目标协议') }}</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="['plant:targetagreement:remove']"
        >删除</el-button>
      </el-col>-->
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="targetagreementList" :height="clientHeight" border>
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-table
            :data="props.row.tTargetyardsticks"
            border
            :row-class-name="tableRowClassName"
            :header-cell-style="headerCellStyle">
            <el-table-column :label="$t('目标')" align="center" prop="target" :show-overflow-tooltip="true" />
            <el-table-column :label="$t('完成时间')" align="center" prop="achieveDate" width="100">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.achieveDate, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column :label="$t('判定标准')" align="left" header-align="center" prop="yardstick">
              <template slot-scope="scope">
                <span>{{ scope.row.yardstick }}</span>
              </template>
            </el-table-column>
            <el-table-column :label="$t('合作者')" align="center" prop="partners" width="200" />
            <el-table-column :label="$t('权重比例')" align="center" prop="weighing" width="80" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span v-if="scope.row.weighing !== null">{{ scope.row.weighing }}%</span>
              </template>
            </el-table-column>/
            <el-table-column :label="$t('评估')" align="center" prop="assessment" :show-overflow-tooltip="true" />
            <el-table-column :label="$t('类别')" align="center" prop="category" :show-overflow-tooltip="true" />
          </el-table>
        </template>
      </el-table-column>
      <el-table-column :label="$t('年份')" align="center" prop="year" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('员工姓名')" align="center" prop="employeeName" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('考核人')" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span v-if="scope.row.actualpost === '24'">{{ scope.row.appraiser }}</span>
          <span v-else>{{ scope.row.appraiserName }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('总体考核')" align="center" prop="overall" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('备注')" align="center" prop="remarks" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('操作')" align="center" fixed="right" width="330" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['plant:targetagreement:edit']"
          >{{ $t('修改') }}</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="handleYardstick(scope.row),selectFocus(year)"
            v-hasPermi="['plant:targetyardstick:edit']"
          >{{ $t('判定标准') }}</el-button>
          <el-button
            type="text"
            size="small"
            icon="el-icon-download"
            @click="downloadHandle(scope.row)"
          >{{ $t('下载报告') }}</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="handleDoc(scope.row)"
          >{{ $t('签字版') }}</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['plant:targetagreement:remove']"
          >{{ $t('删除') }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <form ref="downloadForm" :action="downloadAction" target="FORMSUBMIT">
      <input name="id" v-model="downloadForm.id"  hidden  />
    </form>

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

    <!-- 添加或修改目标协议对话框 -->
    <el-dialog  :close-on-click-modal="false" :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="$t('年份')" prop="year">
          <el-date-picker clearable size="small" style="width: 200px" @change="handleStaff"
                          v-model="form.year"
                          type="year"
                          value-format="yyyy"
                          :disabled="isDisabled"
                          :placeholder="$t('请选择')+$t('年份')">
          </el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('姓名')" prop="employeeid">
          <el-select v-model="form.employeeid" filterable :placeholder="$t('请选择')+$t('人员')" :disabled="isDisabled" >
            <el-option
              v-for="dict in employeeOptions"
              :key="dict.staffid"
              :label="dict.name"
              :value="dict.staffid">
              <span style="float: left">{{ dict.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ dict.staffid }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('考核人')" prop="appraiser">
          <el-input v-if="form.actualpost === '24'" v-model="form.appraiser" :placeholder="$t('请输入')+$t('考核人')" />
          <el-select v-model="form.appraiser" filterable :placeholder="$t('请选择')+$t('考核人')" v-else>
            <el-option
              v-for="dict in appraiserOptions"
              :key="dict.staffid"
              :label="dict.name"
              :value="dict.staffid">
              <span style="float: left">{{ dict.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ dict.staffid }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('总体考核')" prop="overall">
          <el-input type="textarea" :rows="4" v-model="form.overall" :placeholder="$t('请输入') + $t('总体考核')" />
        </el-form-item>
        <el-form-item :label="$t('备注')" prop="remarks">
          <el-input v-model="form.remarks" :placeholder="$t('请输入') + $t('备注')" />
        </el-form-item>
          <el-form-item :label="$t('归属部门')" prop="deptId">
              <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true" :placeholder="$t('请选择') + $t('归属部门')" />
          </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ $t('确 定') }}</el-button>
        <el-button @click="cancel">{{ $t('取 消') }}</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog  :close-on-click-modal="false" :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"
                :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress"
                :on-success="handleFileSuccess"
                :auto-upload="false"
                drag
        >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              {{ $t('将文件拖到此处，或') }}
              <em>{{ $t('点击上传') }}</em>
            </div>
            <div class="el-upload__tip" slot="tip">
                <el-checkbox v-model="upload.updateSupport" />{{ $t('是否更新已经存在的用户数据') }}
                <el-link type="info" style="font-size:12px" @click="importTemplate">{{ $t('下载模板') }}</el-link>
            </div>
            <div class="el-upload__tip" style="color:red" slot="tip">{{ $t('提示：仅允许导入“xls”或“xlsx”格式文件！') }}</div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitFileForm">{{ $t('确 定') }}</el-button>
            <el-button @click="upload.open = false">{{ $t('取 消') }}</el-button>
        </div>
    </el-dialog>

    <!-- 判定标准对话框 -->
    <el-dialog  :close-on-click-modal="false" v-dialogDrag :title="yardstickTitle" :visible.sync="yardstickOpen" width="1800px" append-to-body @close='closeDialog'>
      <el-form :inline="true" :model="yardstickQueryParams">
        <el-form-item>
          <el-button v-hasPermi="['plant:targetaction:add']" type="primary" @click="addYardstick()">{{ $t('新增') }}</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="yardstickLoading" :data="targetyardstickList" border>
        <el-table-column :label="$t('目标')" align="center" header-align="center" prop="target">
          <template slot-scope="scope">
<!--              <el-select-->
<!--                v-if="scope.row.isEdit"-->
<!--                v-model="scope.row.target"-->
<!--                placeholder="请输入或选择"-->
<!--                clearable-->
<!--                filterable-->
<!--                allow-create-->
<!--              >-->
<!--                <el-option-->
<!--                  v-for="item in contentList"-->
<!--                  :key="item.description"-->
<!--                  :label="item.description"-->
<!--                  :value="item.description">-->
<!--                </el-option>-->
<!--              </el-select>-->
            <el-autocomplete
              style="width:100%"
              v-if="scope.row.isEdit"
              class="inline-input"
              v-model="scope.row.target"
              :fetch-suggestions="querySearch"
              placeholder="请输入目标"
              @select="handleSelect"
            ></el-autocomplete>
            <span v-else>{{ scope.row.target }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('完成时间')" align="center" header-align="center" prop="achieveDate" width="100" >
          <template slot-scope="scope">
            <el-date-picker
              v-if="scope.row.isEdit"
              v-model="scope.row.achieveDate"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('请选择')+$t('完成时间')">
            </el-date-picker>
            <span v-else>{{ parseTime(scope.row.achieveDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('判定标准')" align="left" header-align="center" prop="yardstick" width="500" >
          <template slot-scope="scope">
            <el-select style="width:100%"
              v-if="scope.row.isEdit"
              v-model="scope.row.yardstick"
              placeholder="请输入或选择"
              clearable
              multiple
              filterable
              allow-create
              @focus="selectChange(scope.row.target)"
            >
              <el-option
                v-for="item in measuresList"
                :key="item.measures"
                :label="item.measures"
                :value="item.measures">
              </el-option>
            </el-select>
            <span v-else>{{ scope.row.yardstick }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('合作者')" align="center" header-align="center" prop="partners">
          <template slot-scope="scope">
            <span v-if="scope.row.isEdit">
              <el-input v-if="rowActualpost === '24'" type="textarea" :rows="4" v-model="scope.row.partners" :placeholder="$t('请输入') + $t('合作者')" />
              <el-select v-model="scope.row.partners" :placeholder="$t('请选择')+$t('合作者')" multiple v-else>
                <el-option
                  v-for="dict in partnersOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </span>
            <span v-else>
              <span v-if="rowActualpost === '24'">{{ scope.row.partners }}</span>
              <span v-else>{{ scope.row.partnersName }}</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('权重比例')" align="center" header-align="center" prop="weighing" width="100">
          <template slot-scope="scope">
            <el-input v-if="scope.row.isEdit" v-model="scope.row.weighing" :placeholder="$t('请输入')+$t('权重比例')" />
            <span  v-if="!scope.row.isEdit && scope.row.weighing !== null">{{ scope.row.weighing }}%</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('评估')" align="center" header-align="center" prop="assessment">
          <template slot-scope="scope">
            <el-input v-if="scope.row.isEdit" type="textarea" v-model="scope.row.assessment" :placeholder="$t('请输入')+$t('评估')" />
            <span v-else>{{ scope.row.assessment }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('类别')" align="center" header-align="center" prop="category">
          <template slot-scope="scope">
            <el-input v-if="scope.row.isEdit" type="textarea" v-model="scope.row.category" :placeholder="$t('请输入')+$t('类别')" />
            <span v-else>{{ scope.row.category }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('操作')" align="center" fixed="right" width="120" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button v-hasPermi="['plant:targetaction:edit']" type="text" size="small" v-if="scope.row.isEdit" @click="saveYardstick(scope.row)">{{ $t('保存') }}</el-button>
            <el-button type="text" size="small" v-if="scope.row.isEdit" @click="cancelYardstick(scope.row, scope.$index)">{{ $t('取消') }}</el-button>
            <el-button v-hasPermi="['plant:targetaction:edit']" v-if="!scope.row.isEdit" @click="editYardstick(scope.row)" type="text" size="mini">{{ $t('编辑') }}</el-button>
            <el-button v-hasPermi="['plant:targetaction:edit']" v-if="!scope.row.isEdit" type="text" size="small" @click="deleteYardstick(scope.row)">{{ $t('删除') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 生成经理对话框 -->
    <el-dialog  :close-on-click-modal="false" v-dialogDrag :title="generate.title" :visible.sync="generate.open" width="400px" append-to-body>
      <el-form :model="form" ref="queryForm" label-width="68px">
        <el-form-item :label="$t('年份')" prop="year">
          <el-date-picker clearable size="small" style="width: 200px"
                          v-model="form.year"
                          type="year"
                          value-format="yyyy"
                          :placeholder="$t('请选择') + $t('年份')">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="cyan" icon="el-icon-refresh" size="mini" @click="generateYear">{{$t('生成')}}</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 报告附件对话框 -->
    <el-dialog  :close-on-click-modal="false" v-dialogDrag :title="doc.title" :visible.sync="doc.open" width="700px" append-to-body>
      <el-upload
        ref="doc"
        :limit="50"
        :headers="doc.headers"
        :action="doc.url + '?pType=' + doc.pType + '&pId=' + doc.pId"
        :disabled="doc.isUploading"
        :on-progress="handleFileDocProgress"
        :on-success="handleFileDocSuccess"
        :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="doc.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')"
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleSee(scope.row)"
            >{{ $t('预览') }}</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>
      <el-dialog  :close-on-click-modal="false" v-dialogDrag :title="pdf.title" :visible.sync="pdf.open" width="1300px" 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 :src="pdf.pdfUrl" frameborder="0" width="100%" height="700px"></iframe>
        </div>
      </el-dialog>
      <div slot="footer" class="dialog-footer">
        <!--        <el-button type="primary" @click="submitFileForm">{{ $t('确 定') }}</el-button>-->
        <el-button @click="doc.open = false">{{ $t('返 回') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTargetagreement, getTargetagreement, delTargetagreement, addTargetagreement, updateTargetagreement, generateTargetagreement, exportTargetagreement, importTemplate} from "@/api/plant/targetagreement";
import { listTargetyardstick, getTargetyardstick, delTargetyardstick, addTargetyardstick, updateTargetyardstick } from "@/api/plant/targetyardstick";
import {listAllStaffmgr, listStaffmgr} from "@/api/plant/staffmgr";
import { treeselect } from "@/api/system/dept";
import { getToken } from "@/utils/auth";
import {allFileList, delCommonfile ,updateCommonfile ,addCommonfile} from "@/api/common/commonfile";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {getAllContent, getAllMeasures} from "@/api/plant/targetlist";


export default {
  name: "Targetagreement",
  components: { Treeselect },
  data() {
    return {
      year: new Date().getFullYear(),
      contentList: [],
      measuresList: [],
      // 遮罩层
      loading: true,
      yardstickLoading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      //是否禁用修改操作
      isDisabled: false,
      // 目标协议表格数据
      targetagreementList: [],
      // 目标完成判定标准表格数据
      targetyardstickList: [],
      //选择查看人员判定标准的人员岗位
      rowActualpost: "",
      // 弹出层标题
      title: "",
      yardstickTitle: "",
      // 部门树选项
      deptOptions: undefined,
      // 人员字典
      employeeOptions: [],
      appraiserOptions: [],
      // 合作者字典
      partnersOptions: [],
      clientHeight:300,
      // 是否显示弹出层
      open: false,
      yardstickOpen: false,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/plant/targetagreement/importData"
      },
      // 报告附件参数
      doc: {
        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: 'targetAgreement'
        },
        pType: 'targetAgreement',
        pId: null
      },
      pdf : {
        title: '',
        pdfUrl: '',
        numPages: null,
        open: false,
        pageNum: 1,
        pageTotalNum: 1,
        loadedRatio: 0,
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        year: null,
        employeeid: null,
        appraiser: null,
      },
      yardstickQueryParams: {
        agreementId: null,
      },
      //下载参数
      downloadForm: {
        id: '',
        key: ''
      },
      downloadAction: process.env.VUE_APP_BASE_API +'/plant/targetagreement/exportPDF',
      //下载按钮参数
      generate: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        //年份
        year: null
      },
      //人员表查询参数
      staffmgrQueryParams: {
        actualposts: null,
        leftYear: null
      },
      // 表单参数
      form: {},
      //部门ID
      deptId: null,
      // 表单校验
      rules: {
        year: [
          { required: true, message: this.$t('年份') + this.$t('不能为空'), trigger: "blur" }
        ],
        employeeid: [
          { required: true, message: this.$t('员工号') + this.$t('不能为空'), trigger: "blur" }
        ],
        deptId: [
          { required: true, message: this.$t('部门编号') + this.$t('不能为空'), trigger: "blur" }
        ],
      }
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
        this.$refs.tree.filter(val);
    }
   },
  created() {
    //设置表格高度对应屏幕高度
    this.$nextTick(() => {
        this.clientHeight = document.body.clientHeight -250
    })
    this.getList();
    this.getEmployee();
    this.getAppraiser();
    this.getTreeselect();
    this.getDicts("PARTNERS").then(response => {
      this.partnersOptions = response.data;
    });
  },
  methods: {
    selectFocus(year){
      this.queryParams.year=year;
      getAllContent(this.queryParams).then(response => {
        console.log(response)
        this.contentList = response.data;
        for (let i = 0; i <this.contentList.length ; i++) {
          this.contentList[i].value =  this.contentList[i].description +  this.contentList[i].targets
        }
        console.log(this.contentList)
      });
    },
    selectChange(content){
      this.queryParams.description=content;
      getAllMeasures(this.queryParams).then(response => {
        this.measuresList = response.data;
      });
      this.queryParams.description=null;
    },
    /** 查询目标协议列表 */
    getList() {
      this.loading = true;
      listTargetagreement(this.queryParams).then(response => {
        this.targetagreementList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.deptId = response.rows[0].deptId;
      });
    },
     /** 查询部门下拉树结构 */
     getTreeselect() {
        treeselect().then(response => {
            this.deptOptions = response.data;
        });
     },
    getEmployee(year) {
      this.staffmgrQueryParams.leftYear = year
      listAllStaffmgr(this.staffmgrQueryParams).then(response => {
        this.employeeOptions = response.rows;
      });
    },
    getAppraiser(year) {
      this.staffmgrQueryParams.leftYear = year
      listAllStaffmgr(this.staffmgrQueryParams).then(response => {
        this.appraiserOptions = response.rows;
      });
    },
    //年份选择change事件
    handleStaff(val){
      this.getAppraiser(val)
      this.getEmployee(val)
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        year: null,
        employeeid: null,
        appraiser: null,
        overall: null,
        remarks: null,
        deptId: null,
        delFlag: null,
        createrCode: null,
        createdate: null,
        updaterCode: null,
        updatedate: null,
        tTargetyardsticks: null
      };
      this.resetForm("form");
    },
    yardstickReset() {
      this.yardstickForm = {
        id: null,
        agreementId: null,
        target: null,
        achieveDate: null,
        yardstick: null,
        partners: null,
        weighing: null,
        assessment: null,
        category: null,
        delFlag: null,
        createrCode: null,
        createdate: null,
        updaterCode: null,
        updatedate: null
      };
      this.resetForm("yardstickForm");
    },
    /** 搜索按钮操作 */
    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
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.isDisabled = false;
      this.open = true;
      this.title = this.$t('添加')+this.$t('目标协议');
    },
    /** 生成经理按钮操作 */
    generateManager() {
      this.reset();
      this.generate.open = true;
      this.generate.title = this.$t('生成经理目标协议');
    },
    generateYear() {
      this.form.deptId = this.deptId;
      generateTargetagreement(this.form).then(response => {
        if (response === 1) {
          this.msgSuccess(this.$t('修改成功'));
          this.generate.open = false;
          this.getList();
        }else if (response === 2) {
          this.msgError(this.$t('次年份经理目标协议数据已存在'))
        }
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.isDisabled = true;
      const id = row.id || this.ids
      getTargetagreement(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = this.$t('修改')+this.$t('目标协议');
        this.getAppraiser(response.data.year)
        this.getEmployee(response.data.year)
      });
    },
    /** 判断标准按钮操作 */
    handleYardstick(row) {
      this.rowActualpost = row.actualpost
      let _this = this
      this.yardstickReset();
      this.yardstickLoading = true;
      this.yardstickQueryParams.agreementId = row.id
      const id = row.id
      let employeeName = "";
      let year = "";
      getTargetagreement(id).then(response => {
        employeeName = response.data.employeeName;
        year = response.data.year;
      });
      listTargetyardstick(this.yardstickQueryParams).then(response => {
        response.rows.forEach(element => {
          element["isEdit"] = false
        });
        response.rows.forEach(element => {
          element["isAdd"] = false
        });
        this.targetyardstickList = response.rows;
        console.info("actualpost:" + row.actualpost)
        if (row.actualpost !== "24") {
          this.targetyardstickList.forEach(function (value,key,arr) {
            var partnersName = null;
            let partners = null;
            if (value.partners != null) {
              partners = value.partners.split(",");
              partners.forEach(function (value, key, arr) {
                if (key != 0) {
                  partnersName = partnersName + "," + _this.selectDictLabel(_this.partnersOptions, value);
                }else if (key == 0) {
                  partnersName = _this.selectDictLabel(_this.partnersOptions, value);
                }
              });
            }
            if (value.yardstick!=null){
              let yardstick=value.yardstick.replaceAll(",","");
              _this.targetyardstickList[key].yardstick=yardstick;
            }
            _this.targetyardstickList[key].partners = partners;
            _this.targetyardstickList[key].partnersName = partnersName;
          })
        }
        this.yardstickLoading = false;
        this.yardstickOpen = true;
        this.year=row.year;
        this.yardstickTitle = employeeName + year + this.$t('年') + this.$t('判断标准');
      });
    },
    /** 新增判断标准按钮操作 */
    addYardstick() {
      this.targetyardstickList.push({
        agreementId: this.yardstickQueryParams.agreementId,
        target: '',
        achieveDate: '',
        yardstick: '',
        partners: '',
        partnersName: '',
        weighing: '',
        assessment: '',
        category: '',
        isEdit: true,
        isAdd: true
      });
      this.partners = ''
    },
    querySearch(queryString, cb) {
      var contentList = this.contentList;
      var results = queryString ? contentList.filter(this.createFilter(queryString)) : contentList;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (target) => {
        return (target.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    handleSelect(item) {
      // this.selectChange(item.description)
    },
    /** 保存判断标准按钮操作 */
    saveYardstick(row) {
      row.isEdit = false;
      var that = this;
      that.yardstickLoading = true;
      this.yardstickForm = row;
      this.yardstickForm.agreementId = this.yardstickQueryParams.agreementId;
      let newYardstick="";
      row.yardstick.forEach(
        item=>{
          newYardstick+=item+",";
        }
      )
      row.yardstick = newYardstick.substring(0,newYardstick.length-1)
      if (this.rowActualpost !== "24") {
        var partner = null;
        this.yardstickForm.partners.forEach(function (value,key,arr) {
          if (key != 0) {
            partner = partner + "," + value;
          }else if (key == 0) {
            partner = value;
          }
        })
        this.yardstickForm.partners = partner;
      }else {
        this.form.actualpost = "24"
      }
      this.form.id = row.agreementId
      if (row.isAdd == true) {
        addTargetyardstick(this.yardstickForm).then(response => {
          this.msgSuccess(this.$t('新增成功'));
          this.handleYardstick(this.form);
        });
      }else {
        updateTargetyardstick(this.yardstickForm).then(response => {
          this.msgSuccess(this.$t('修改成功'));
          this.handleYardstick(this.form);
        });
      }
    },
    /** 取消判断标准按钮操作 */
    cancelYardstick(row, index) {
      // 如果是新增的数据
      if (row.isAdd) {
        this.targetyardstickList.splice(index, 1)
      } else {
        // 不是新增的数据  还原数据
        for (const i in row.oldRow) {
          row[i] = row.oldRow[i]
        }
        row.isEdit = false
      }
    },
    /** 修改判断标准按钮操作 */
    editYardstick(row) {
      // 备份原始数据
      row['oldRow'] = JSON.parse(JSON.stringify(row));
      this.$nextTick(() => {
        var yardstick = row.yardstick;
        row.yardstick=yardstick.split(",");
        row.isEdit = true;
      })
    },
    /** 删除判断标准按钮操作 */
    deleteYardstick(row) {
      const ids = row.id || this.ids;
      this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: "warning"
      }).then(function() {
        return delTargetyardstick(ids);
      }).then(() => {
        this.getList();
        this.yardstickQueryParams.id = row.agreementId
        this.handleYardstick(this.yardstickQueryParams);
        this.msgSuccess(this.$t('删除成功'));
      })
    },
    closeDialog () {
      this.reset();
      this.getList();
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTargetagreement(this.form).then(response => {
              this.msgSuccess(this.$t('修改成功'));
              this.open = false;
              this.getList();
            });
          } else {
            addTargetagreement(this.form).then(response => {
              this.msgSuccess(this.$t('新增成功'));
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
          type: "warning"
        }).then(function() {
          return delTargetagreement(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess(this.$t('删除成功'));
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm(this.$t('是否确认导出所有目标协议数据项?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: "warning"
        }).then(function() {
          return exportTargetagreement(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
    /** 导入按钮操作 */
    handleImport() {
        this.upload.title = this.$t('用户导入');
        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, this.$t('导入结果'), { dangerouslyUseHTMLString: true });
        this.getList();
    },
    // 提交上传文件
    submitFileForm() {
        this.$refs.upload.submit();
    },
    //下载报告
    downloadHandle (row) {
      if (row.appraiser == null) {
        this.msgError(this.$t('请选择')+this.$t('考核人'));
      }else {
        this.downloadForm.id = row.id;
        this.$nextTick(() => {
          this.$refs['downloadForm'].submit()
        })
      }
    },
    tableRowClassName({row, rowIndex}) {
      if(rowIndex % 2 === 0){
        return 'warning-row';
      } else {
        return 'success-row';
      }
      return '';
    },
    headerCellStyle({ row, rowIndex }) {
      return 'background-color: #e2efe8; border: none'
    },
    /** 报告附件按钮操作 */
    handleDoc(row) {
      this.doc.id = row.id;
      this.doc.title = row.employeeName + row.year + this.$t('年') + this.$t('签字版');
      this.doc.open = true;
      this.doc.queryParams.pId = row.id
      this.doc.pId = row.id
      this.getFileList()
      this.$nextTick(() => {
        this.$refs.doc.clearFiles()
      })
    },
    getFileList (){
      allFileList(this.doc.queryParams).then(response => {
        response.forEach(element => {
          element["isEdit"] = false
        });
        response.forEach(element => {
          element["isAdd"] = false
        });
        this.doc.commonfileList = response;
      });
    },
    //附件上传中处理
    handleFileDocProgress(event, file, fileList) {
      this.doc.file = file;
      this.doc.isUploading = true;
    },
    //附件上传成功处理
    handleFileDocSuccess(response, file, fileList) {
      this.doc.isUploading = false;
      this.$alert(response.msg, this.$t('导入结果'), { dangerouslyUseHTMLString: true });
      this.getFileList()
    },
    //pdf预览
    openPdf(){
        window.open(this.pdf.pdfUrl);//path是文件的全路径地址
      },
      handleSee (row){
        this.pdf.open =true
        this.pdf.title = row.fileName
        this.pdf.pdfUrl = process.env.VUE_APP_BASE_API +'/pdf/web/viewer.html?file=' + process.env.VUE_APP_BASE_API + row.fileUrl
      },
    /** 删除按钮操作 */
    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('删除成功'));
      })
    },
    // 文件下载处理
    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()
    },
  }
};
</script>

<style scoped>
  /deep/.el-table .warning-row {
    background: #edf0ff;
  }

  /deep/.el-table .success-row {
    background: #e2efe8;
  }

  .el-table::before {
    height: 0px;
  }

  /deep/.el-table .cell {
    white-space: pre-line;
  }
</style>
