<template>
  <div class="app-container">
    <el-row :gutter="20">
      <div class="mb20" v-if="showAlter">
        <el-alert title="任务被退回，请修改后重新提交" type="error" :closable="false">
          <return-comment :taskForm="taskForm" @isReturn="isReturn"></return-comment>
        </el-alert>
      </div>
      <h2 style="text-align: center;">绩效审批表</h2>
      <el-form ref="form" :model="form" :rules="rules">
        <el-row :gutter="20">
          <el-col :span="7" :xs="24">
            <el-form-item label="上报人：" prop="reporter" label-width="100px">
              {{ getUserName(form.reporter) }}
            </el-form-item>
          </el-col>
          <el-col :span="7" :xs="24">
            <el-form-item label="上报部门：" prop="reportDept" label-width="100px">
              {{ getDeptName(form.reportDept) }}
            </el-form-item>
          </el-col>
          <el-col :span="7" :xs="24">
            <el-form-item label="上报时间：" prop="reportTime" label-width="100px">
              {{ form.reportTime }}
            </el-form-item>
          </el-col>
        </el-row>
        <div v-if="taskName == '绩效上报'">
          <el-button type="primary" size="small" icon="el-icon-upload" @click="upload.open = true">上传绩效表</el-button>
          <div
            style="background-color: #f0f9eb; border: 1px solid #c2e7b0; padding: 10px; border-radius: 5px;margin-top: 10px;">
            <span style="font-size: 14px;font-weight: 700;">Tips：</span>
            <span style="font-size: 14px;">若需要添加人员绩效，可再次上传绩效表，重复上传会更新数据和新增数据。</span>
          </div>
        </div>
        <div class="table-title">内业绩效表</div>
        <el-form :inline="true" size="small" class="table-search-bar" @submit.native.prevent>
          <el-form-item label="姓名">
            <el-select v-model="innerParams.userId" filterable clearable @change="getInnerTableData">
              <el-option v-for="item in $store.state.user.userList" :key="item.userId" :label="item.nickName"
                :value="item.userId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="项目编号">
            <el-select v-model="innerParams.projectId" clearable filterable remote reserve-keyword placeholder="请输入项目编号"
              :remote-method="remoteMethod" style="width: 300px;" @change="getInnerTableData">
              <el-option v-for="project in projectList" :key="project.projectId"
                :label="project.projectNumber + '-' + project.projectName" :value="project.projectId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getInnerTableData">搜索</el-button>
            <el-button @click="resetInnerSearch">重置</el-button>
          </el-form-item>
        </el-form>
        <el-table :data="innerTableData" style="width: 100%">
          <el-table-column type="index" label="序号" width="50" />
          <el-table-column prop="projectNumber" label="项目编号" width="80" />
          <el-table-column prop="project.projectName" label="项目名称" />
          <el-table-column prop="nickName" label="姓名" width="80" />
          <el-table-column prop="content" label="工作内容" />
          <el-table-column prop="scaleGrade" label="比例尺" width="80" />
          <el-table-column prop="workload" label="工作量" width="80" />
          <el-table-column prop="unit" label="单位" width="80" />
          <el-table-column prop="price" label="单价" width="80" />
          <el-table-column prop="coefficient" label="系数" width="80" />
          <el-table-column prop="producePerformance" label="绩效" width="100" />
          <el-table-column prop="performanceMonth" label="统计月份" width="100">
            <template slot-scope="scope">
              {{ parseTime(scope.row.performanceMonth, '{y}-{m}') }}
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" />
          <el-table-column label="操作" width="100" v-if="taskName == '绩效上报'">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="handleEdit(scope.row, 'inner')">修改</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="innerTotal > 0" :total="innerTotal" :page.sync="innerParams.pageNum"
          :limit.sync="innerParams.pageSize" @pagination="getInnerTableData" />
        <div class="table-title">外业绩效表</div>
        <el-form :inline="true" size="small" class="table-search-bar" @submit.native.prevent>
          <el-form-item label="姓名">
            <el-select v-model="outerParams.userId" filterable clearable @change="getOuterTableData">
              <el-option v-for="item in $store.state.user.userList" :key="item.userId" :label="item.nickName"
                :value="item.userId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="项目编号">
            <el-select v-model="outerParams.projectId" clearable filterable remote reserve-keyword placeholder="请输入项目编号"
              :remote-method="remoteMethod" style="width: 300px;" @change="getOuterTableData">
              <el-option v-for="project in projectList" :key="project.projectId"
                :label="project.projectNumber + '-' + project.projectName" :value="project.projectId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getOuterTableData">搜索</el-button>
            <el-button @click="resetOuterSearch">重置</el-button>
          </el-form-item>
        </el-form>
        <el-table :data="outerTableData" style="width: 100%">
          <el-table-column type="index" label="序号" width="50" />
          <el-table-column prop="projectNumber" label="项目编号" width="80" />
          <el-table-column prop="project.projectName" label="项目名称" />
          <el-table-column prop="nickName" label="姓名" width="80" />
          <el-table-column prop="content" label="工作内容" />
          <el-table-column prop="workload" label="工天" width="80" />
          <el-table-column prop="unit" label="单位" width="80" />
          <el-table-column prop="price" label="单价" width="80" />
          <el-table-column prop="coefficient" label="系数" width="80" />
          <el-table-column prop="producePerformance" label="绩效" width="100" />
          <el-table-column prop="performanceMonth" label="统计月份" width="100">
            <template slot-scope="scope">
              {{ parseTime(scope.row.performanceMonth, '{y}-{m}') }}
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" />
          <el-table-column label="操作" width="100" v-if="taskName == '绩效上报'">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="handleEdit(scope.row, 'outer')">修改</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="outerTotal > 0" :total="outerTotal" :page.sync="outerParams.pageNum"
          :limit.sync="outerParams.pageSize" @pagination="getOuterTableData" />
        <div class="table-title">
          绩效统计表
          <el-button type="success" size="small" icon="el-icon-printer" @click="printPerformanceTable"
            style="margin-left: 20px;">
            打印
          </el-button>
        </div>
        <el-table :data="groupedPerformanceData" style="width: 100%" class="mb20" row-class-name="table-row-class">
          <el-table-column type="index" label="序号" width="50">
            <template slot-scope="scope">
              <span v-if="!scope.row.isSummary">{{ scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="nickName" label="姓名">
            <template slot-scope="scope">
              <span v-if="!scope.row.isSummary">{{ scope.row.nickName }}</span>
              <span v-else class="summary-text">{{ scope.row['dept.deptName'] }}部门总计</span>
            </template>
          </el-table-column>
          <el-table-column prop="dept.deptName" label="部门" />
          <el-table-column prop="producePerformance" label="生产绩效" sortable>
            <template slot-scope="scope">
              <span :class="{ 'summary-text': scope.row.isSummary }">
                {{ scope.row.isSummary ? Number(scope.row.producePerformance).toFixed(2) : scope.row.producePerformance }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="managePerformance" label="管理绩效" sortable>
            <template slot-scope="scope">
              <span :class="{ 'summary-text': scope.row.isSummary }">
                {{ scope.row.isSummary ? Number(scope.row.managePerformance).toFixed(2) : scope.row.managePerformance }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="总绩效" width="100" sortable>
            <template slot-scope="scope">
              <span :class="{ 'summary-text': scope.row.isSummary }">
                {{ (Number(scope.row.producePerformance) + Number(scope.row.managePerformance)).toFixed(2) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="performanceMonth" label="统计月份">
            <template slot-scope="scope">
              <span v-if="!scope.row.isSummary">{{ parseTime(scope.row.performanceMonth, '{y}-{m}') }}</span>
            </template>
          </el-table-column>
        </el-table>


        <el-form-item label="附件上传：" prop="document" label-width="130px">
          <FileUpload v-if="taskName == '绩效上报' && !form.document" ref="orz" :limit="1" :isShowTip="false"
            :filePathName="'绩效审批/' + parseTime(new Date(), '{y}-{m}-{d}-{h}-{i}-{s}')"
            :fileType="['doc', 'docx', 'xls', 'xlsx', 'pdf', 'rar', 'zip']" @input="setDocument">
          </FileUpload>
          <div v-if="form.document" class="upload-list">
            <el-link type="primary" @click="reviewWord(`${baseUrl}${'/profile/upload' + form.document}`)">
              {{ getFileName(form.document) }}
            </el-link>
            <el-link class="ml20" type="warning" :href="`${baseUrl}${'/profile/upload' + form.document}`"
              :underline="false" target="_blank">
              <span class="el-icon-download">下载文件</span>
            </el-link>
            <span class="el-icon-delete del-file" @click="deleteDoc" v-if="taskName == '绩效上报'">删除文件</span>
          </div>
          <div v-else>
            暂无附件
          </div>
        </el-form-item>
        <el-form-item label="绩效说明：" prop="remark" label-width="130px">
          <el-input :disabled="taskName != '绩效上报'" type="textarea" v-model="form.remark" :autosize="{ minRows: 4 }" />
        </el-form-item>
        <el-form-item label="分管审核意见：" prop="managerComment" label-width="130px">
          <el-input type="textarea" v-model="form.managerComment" :autosize="{ minRows: 4 }"
            :disabled="taskName != '分管审核'"></el-input>
          <div class="sign mt10" v-if="form.managerUserId">
            <div class="mr20">签名：<span class="auditor">{{ getUserName(form.managerUserId) }}</span>
            </div>
            <div class="ml20"><span>审核时间：{{ form.managerTime }}</span></div>
          </div>
        </el-form-item>
        <el-form-item label="总经理审批意见：" prop="zjlComment" label-width="130px">
          <el-input type="textarea" v-model="form.zjlComment" :autosize="{ minRows: 4 }"
            :disabled="taskName != '总经理审批'"></el-input>
          <div class="sign mt10" v-if="form.zjlUserId">
            <div class="mr20">签名：<span class="auditor">{{ getUserName(form.zjlUserId) }}</span>
            </div>
            <div class="ml20"><span>审核时间：{{ form.zjlTime }}</span></div>
          </div>
        </el-form-item>
        <el-form-item label="人事制单：" label-width="130px" v-if="taskName == '人事制单'">
          <el-button type="success" icon="el-icon-printer" @click="printPerformanceTable">打印</el-button>
        </el-form-item>
      </el-form>
      <el-row style="text-align: center;" v-if="taskName != ''">
        <el-button type="danger" @click="returnOpen = true" v-show="taskName != '绩效上报'">退 回</el-button>
        <el-button type="warning" @click="saves()">保存</el-button>
        <el-button type="primary" @click="completeApply()">{{ taskName == '绩效上报' ? '提交绩效表' : '完成审批' }}</el-button>
      </el-row>
    </el-row>
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url" :data="upload.data"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-change="handleFileUploadChange"
        :on-success="handleFileSuccess" :auto-upload="false" drag v-loading="uploadLoading"
        element-loading-text="正在上传，请稍等">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
              @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitUpload">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :visible.sync="editDialogVisible" title="修改绩效" width="400px">
      <el-form :model="editRow" label-width="80px">
        <el-form-item label="工作量">
          <el-input-number v-model="editRow.workload" :min="0" @change="calcPerformance" />
        </el-form-item>
        <el-form-item label="系数">
          <el-input-number v-model="editRow.coefficient" :min="0" :max="10" :step="0.01" @change="calcPerformance" />
        </el-form-item>
        <el-form-item label="绩效">
          <el-tag type="success" style="font-size: 16px;font-weight: 700;">{{ editRow.producePerformance }}</el-tag>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="打印绩效统计表" :visible.sync="printDialogVisible" width="800px" append-to-body>
      <div class="mb20">
        <el-radio-group v-model="selectedPrintType">
          <el-radio label="all">打印全部部门</el-radio>
          <el-radio label="selected">选择部门打印</el-radio>
        </el-radio-group>
        <div v-if="selectedPrintType === 'selected'" class="mt10">
          <el-select v-model="selectedDepts" multiple placeholder="请选择要打印的部门" style="width: 100%">
            <el-option
              v-for="dept,index in availableDepts"
              :key="index + dept.deptName"
              :label="dept.deptName"
              :value="dept.deptName">
            </el-option>
          </el-select>
        </div>
      </div>
      <performance-print 
        :form="form" 
        :performanceTableData="filteredPerformanceData"
        @cancel="printDialogVisible = false" />
    </el-dialog>
    <el-dialog title="退回" :visible.sync="returnOpen" width="40%" append-to-body>
      <return-btn :taskForm="taskForm" @goBack="$emit('goBack')" @saves="" @cancel="returnOpen = false"></return-btn>
    </el-dialog>
  </div>
</template>

<script>
import { parseTime } from "@/utils/ruoyi";
import { complete, rejectTask, returnList, returnTask, getNextFlowNode, delegate, flowTaskForm, } from "@/api/flowable/todo";
import { listPerformance, getPerformance, addPerformance, updatePerformance, delPerformance } from "@/api/oa/performance/performance"
import { listPerformanceStaff, getPerformanceStaff, updatePerformanceStaff, getMonthPerformanceList } from "@/api/oa/performance/performanceStaff";
import { getUsersDeptLeaderByDept, getUsersManageLeaderByDept, getUserByPost } from '@/api/system/post'
import { listProject } from "@/api/oa/project/project";
import { downloadTemplate } from "@/api/file/project";
import { getUserByRole } from "@/api/system/role";
import { getToken } from "@/utils/auth";
import PerformancePrint from '../components/print/performancePrint.vue';
import returnBtn from '@/views/flowable/form/components/flowBtn/returnBtn.vue';
import ReturnComment from '@/views/flowable/form/components/flowBtn/returnComment.vue';

export default {
  components: {
    PerformancePrint, returnBtn, ReturnComment
  },
  props: {
    taskName: {
      type: String,
      required: true
    },
    taskForm: {
      type: Object,
      required: true
    },
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      flowData: {},
      form: {},
      rules: {
        managerComment: [
          { required: this.taskName == '分管审核', message: '请填写分管领导意见', trigger: 'blur' }
        ],
        zjlComment: [
          { required: this.taskName == '总经理审批', message: '请填写总经理审批意见', trigger: 'blur' }
        ]
      },
      printDialogVisible: false,
      upload: {
        open: false,
        title: "上传绩效表",
        isUploading: false,
        updateSupport: 0,
        headers: { 'Authorization': "Bearer " + getToken() },
        data: { 'performanceId': this.taskForm.formId },
        url: process.env.VUE_APP_BASE_API + "/oa/performanceStaff/uploadSheet"
      },
      uploadLoading: false,
      uploadFormData: undefined,
      innerTableData: [],
      outerTableData: [],
      performanceTableData: [],
      innerTotal: 0,
      outerTotal: 0,
      innerParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        projectId: null
      },
      outerParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        projectId: null
      },
      projectList: [],
      editDialogVisible: false,
      editRow: {},
      editType: '', // 'inner' or 'outer'
      formTotal: 0,
      returnOpen: false,
      showAlter: true,
      groupedPerformanceData: [],
      selectedPrintType: 'all',
      selectedDepts: [],
      availableDepts: [],
    }
  },
  computed: {
    filteredPerformanceData() {
      if (this.selectedPrintType === 'all') {
        return this.performanceTableData;
      }
      return this.performanceTableData.filter(item => 
        this.selectedDepts.includes(item.dept?.deptName)
      );
    }
  },
  created() {
    this.initForm();
  },
  methods: {
    async initForm() {
      const formId = this.taskForm.formId;
      if (this.taskName == '绩效上报') {
        this.form.reporter = this.$store.getters.userId;
        this.form.reportDept = this.$store.getters.deptId;
        this.form.reportTime = parseTime(new Date(), "{y}-{m}-{d}")
      }
      let res = await getPerformance(formId)
      if (res.data) {
        this.formTotal = 1
        this.form = res.data;
      }
      this.getInnerTableData();
      this.getOuterTableData();
      this.getTotalPerformance();
    },
    getInnerTableData() {
      listPerformanceStaff({
        performanceId: this.taskForm.formId,
        workType: '内业',
        pageSize: this.innerParams.pageSize,
        pageNum: this.innerParams.pageNum,
        userId: this.innerParams.userId,
        projectId: this.innerParams.projectId
      }).then(res => {
        this.innerTableData = res.rows || [];
        this.innerTotal = res.total || 0;
      })
    },
    getOuterTableData() {
      listPerformanceStaff({
        performanceId: this.taskForm.formId,
        workType: '外业',
        pageSize: this.outerParams.pageSize,
        pageNum: this.outerParams.pageNum,
        userId: this.outerParams.userId,
        projectId: this.outerParams.projectId
      }).then(res => {
        this.outerTableData = res.rows || [];
        this.outerTotal = res.total || 0;
      })
    },
    getTotalPerformance() {
      let deptId;
      if (this.taskName == '绩效上报') {
        deptId = this.$store.getters.deptId;
      } else {
        deptId = this.form.reportDept;
      }
      getMonthPerformanceList({ performanceId: this.taskForm.formId, deptId: deptId }).then(res => {
        this.performanceTableData = res.data;
        this.processGroupedData();
      })
    },
    processGroupedData() {
      // 按部门分组
      const groupedByDept = {};
      this.performanceTableData.forEach(item => {
        const deptName = item.dept?.deptName || '未分配部门';
        if (!groupedByDept[deptName]) {
          groupedByDept[deptName] = [];
        }
        groupedByDept[deptName].push(item);
      });

      // 转换为数组并添加部门汇总行
      this.groupedPerformanceData = [];
      Object.entries(groupedByDept).forEach(([deptName, items]) => {
        // 添加部门数据行
        this.groupedPerformanceData.push(...items);
        
        // 计算部门汇总
        const deptSummary = {
          isSummary: true,
          'dept.deptName': deptName,
          producePerformance: items.reduce((sum, item) => sum + (Number(item.producePerformance) || 0), 0),
          managePerformance: items.reduce((sum, item) => sum + (Number(item.managePerformance) || 0), 0)
        };
        this.groupedPerformanceData.push(deptSummary);
      });
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计';
          return;
        }
        if (index === 1 || index === 2) {
          sums[index] = '';
          return;
        }
        if (index === 5) { // 总计列
          const produceSum = data.reduce((sum, row) => sum + (Number(row.producePerformance) || 0), 0);
          const manageSum = data.reduce((sum, row) => sum + (Number(row.managePerformance) || 0), 0);
          sums[index] = (produceSum + manageSum).toFixed(2);
          return;
        }
        if (index === 6) { // 统计月份列
          sums[index] = '';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0).toFixed(2);
        } else {
          sums[index] = '';
        }
      });
      return sums;
    },
    remoteMethod(val) {
      let params = {
        pageNum: 1,
        pageSize: 20,
        projectNumber: val
      }
      listProject(params).then(res => {
        this.projectList = res.rows;
      })
    },
    resetInnerSearch() {
      this.innerParams.userId = null;
      this.innerParams.projectId = null;
      this.getInnerTableData();
    },
    resetOuterSearch() {
      this.outerParams.userId = null;
      this.outerParams.projectId = null;
      this.getOuterTableData();
    },
    /**Excel文件上传中处理 */
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
      this.uploadLoading = true;
    },
    /* Excel文件改变时 */
    handleFileUploadChange(file, fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1);
      }
      this.uploadFormData = new FormData();
      this.uploadFormData.append("file", file);
      this.upload.data = { 'performanceId': this.taskForm.formId };
    },
    /** Excel文件上传成功处理 */
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.uploadLoading = false;
      this.fileList = [];
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.$refs["uploadRef"].clearFiles();
      this.getInnerTableData();
      this.getOuterTableData();
      this.getTotalPerformance();
    },
    /* Excel上传提交按钮 */
    submitUpload() {
      const formData = new FormData();
      const file = this.$refs['uploadRef'].uploadFiles[0];
      if (file) {
        formData.append('file', file.raw);
        formData.append('performanceId', this.taskForm.formId);
        this.$refs['uploadRef'].uploadFiles[0].formData = formData;
      }
      this.$refs['uploadRef'].submit();
    },
    /* 下载模板 */
    importTemplate() {
      const path = '/profile/upload/template/performance.xlsx'
      downloadTemplate(path).then(res => {
        const blob = new Blob([res])
        saveAs(blob, '绩效模版.xlsx');
      });
    },
    handleEdit(row, type) {
      this.editRow = { ...row };
      this.editType = type;
      this.editDialogVisible = true;
    },
    calcPerformance() {
      const { workload, price, coefficient } = this.editRow;
      this.editRow.producePerformance = (workload * price * coefficient).toFixed(2);
    },
    submitEdit() {
      updatePerformanceStaff(this.editRow).then(() => {
        this.$message.success('修改成功');
        this.editDialogVisible = false;
        if (this.editType === 'inner') {
          this.getInnerTableData();
        } else {
          this.getOuterTableData();
        }
      });
    },
    async saves() {
      if (this.formTotal != 0) {
        if (this.taskName == '分管审核') {
          this.form.managerUserId = this.$store.getters.userId;
          this.form.managerTime = this.parseTime(new Date(), '{y}-{m}-{d}');
        } else if (this.taskName == '总经理审批') {
          this.form.zjlUserId = this.$store.getters.userId;
          this.form.zjlTime = this.parseTime(new Date(), '{y}-{m}-{d}');
        }
        await updatePerformance(this.form)
      } else {
        this.form.performanceId = this.taskForm.formId;
        await addPerformance(this.form)
        this.initForm();
      }
      this.$message.success('保存成功')
    },
    completeApply() {
      let msg;
      if (this.taskName == '人事制单') {
        msg = '最后一个节点，提交将结束流程，是否提交？'
      } else {
        msg = '是否提交到下一个流程？'
      }
      this.$modal.confirm(msg).then(res => {
        this.$refs['form'].validate(valid => {
          if (valid) {
            this.saves();
            getNextFlowNode({ taskId: this.taskForm.taskId }).then(async () => {
              if (this.taskName == '绩效上报') {
                let result = await getUsersManageLeaderByDept({ deptId: this.form.reportDept });
                const managerList = result.data.map(element => element.userId);
                this.$set(this.taskForm.variables, "approvalList", managerList);
                this.successComplete();
              } else if (this.taskName == '分管审核') {
                let result = await getUserByPost({ postName: '总经理' })
                this.$set(this.taskForm.variables, "approval", result.data[0].userId);
                this.successComplete();
              } else if (this.taskName == '总经理审批') {
                let result = await getUserByRole({ roleId: 3 })
                this.$set(this.taskForm.variables, "approvalList", result.data);
                this.successComplete();
              } else if (this.taskName == '人事制单') {
                this.$modal.confirm('最后一个节点，提交将结束流程，是否提交？').then(res => {
                  this.successComplete();
                })
              }
            })
          } else {
            scrollTo(0, 600)
          }
        })
      })
    },
    successComplete() {
      complete(this.taskForm).then(response => {
        this.$modal.msgSuccess(response.msg);
        this.$emit('goBack')
      })
    },
    setDocument(val) {
      let arr = val.split('/upload')
      this.$set(this.form, 'document', arr[1])
      if (val == "") {
        this.$set(this.form, 'document', "")
      }
    },
    deleteDoc() {
      this.$set(this.form, 'document', '')
    },
    isReturn(val) {
      this.showAlter = val
    },
    printPerformanceTable() {
      // Get unique departments from performance data
      const deptMap = new Map();
      this.performanceTableData.forEach(item => {
        if (item.dept?.deptName) {
          deptMap.set(item.dept.deptName, item.dept);
        }
      });
      console.log(this.performanceTableData);
      this.availableDepts = Array.from(deptMap.values());
      this.selectedDepts = [];
      this.selectedPrintType = 'all';
      this.printDialogVisible = true;
    },
  }
}
</script>

<style lang="scss" scoped>
@import "@/assets/styles/element-reset.scss";

.table-title {
  font-size: 18px;
  font-weight: 700;
  text-align: left;
  margin: 32px 0 16px 0;
  color: #222;
  letter-spacing: 1px;
  background: linear-gradient(90deg, #e3f0ff 0%, #f8fbff 100%);
  padding: 10px 0 10px 16px;
  border-left: 5px solid #409EFF;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.06);
}

.table-search-bar {
  margin-bottom: 10px;
}

.sign {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding-right: 80px;
  line-height: 30px;
  /* 如果需要垂直居中 */
}

:deep(.table-row-class) {
  &.summary-row {
    background-color: #f0f9eb;
    color: #67c23a;
    font-weight: bold;
    
    td {
      background-color: #f0f9eb !important;
      border-bottom: 2px solid #67c23a;
    }
  }
}

:deep(.el-table__row) {
  &.summary-row {
    background-color: #f0f9eb;
    
    td {
      background-color: #f0f9eb !important;
      color: #67c23a;
      font-weight: bold;
      border-bottom: 2px solid #67c23a;
    }
  }
}

.summary-text {
  font-weight: bold;
  font-size: 15px;
}

:deep(.el-table__row.summary-row) {
  background-color: #f0f9eb;
  
  td {
    background-color: #f0f9eb !important;
    border-bottom: 2px solid #67c23a;
  }
}
</style>