<template>
  <div class="main"   v-loading.fullscreen.lock="fullscreenLoading">
    <div class="title">
      <span>工单申请</span>
    </div>
    <div class="module1">
      <el-form
        label-position="right"
        :model="form1"
        :rules="rules1"
        class="formStyle1"
      > 
        <el-col :span="9"> 
          <el-form-item label="工单标题" prop="orderTitle" label-width="80px">
            <el-input
              placeholder="请输入工单标题"
              v-model="form1.orderTitle"
              :disabled="active == 1||(workOrderDetail.applyStatus != 4 || form1.applyStatus!= 4) "
            />
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="工单类型" prop="orderClassId" label-width="80px">
            <el-select
              v-model="form1.orderClassId"
              placeholder="请选择工单类型"
               :disabled="active == 1||(workOrderDetail.applyStatus != 4 || form1.applyStatus!= 4) "
            >
              <el-option
                v-for="item in resourceClassList"
                :key="item.classId"
                :label="item.className"
                :value="item.classId"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="联系人" prop="name" label-width="80px">
            <el-input
              placeholder="请输入联系人"
              v-model="form1.name"
                :disabled="active == 1||(workOrderDetail.applyStatus != 4 || form1.applyStatus!= 4) "
            />
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="单位名称" prop="companyName" label-width="80px">
            <el-input
              placeholder="请输入单位名称"
              v-model="form1.companyName"
               :disabled="active == 1||(workOrderDetail.applyStatus != 4 || form1.applyStatus!= 4) "
            />
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="联系电话" prop="phone" label-width="80px">
            <el-input
              placeholder="请输入联系电话"
              v-model="form1.phone"
                :disabled="active == 1||(workOrderDetail.applyStatus != 4 || form1.applyStatus!= 4) "
            />
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="联系邮箱" prop="email" label-width="80px">
            <el-input
              placeholder="请输入联系邮箱"
              v-model="form1.email"
               :disabled="active == 1||(workOrderDetail.applyStatus != 4 || form1.applyStatus!= 4) "
            />
          </el-form-item>
        </el-col>
        <el-col :span="22">
          <el-form-item
            label="问题描述"
            prop="problemDescribe"
            label-width="80px"
          >
            <el-input
              type="textarea"
              v-model="form1.problemDescribe"
              placeholder="请输入问题描述"
              style="width: 99.3%"
              :disabled="active == 1||(workOrderDetail.applyStatus != 4 || form1.applyStatus!= 4) "
            />
          </el-form-item>
        </el-col>
        <el-col :span="22">
          <el-form-item label="驳回原因" prop="refuseReason" label-width="80px">
            <el-input
              type="textarea"
              v-model="form1.refuseReason"
              style="width: 99.3%"
              :disabled="active != 1"
            />
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="附件" prop="g" label-width="80px">
            <el-upload
              class="upload-demo"
              :show-file-list="false"
              :action="$baseUrl + '/api/common/uploadFileLocal'"
              :on-change="handleChange" 
              :on-remove="handleRemove" 
               :disabled="active == 1||(workOrderDetail.applyStatus != 4 || form1.applyStatus!= 4) "
            >
              <el-button
                size="small"
                type="primary"
                icon="el-icon-upload2"
                  :disabled="active == 1||(workOrderDetail.applyStatus != 4 || form1.applyStatus!= 4) "
                >点击上传</el-button
              >
            </el-upload>
           <el-link
                  v-if="form1.fileList.length > 0"
                  type="primary"
                  :underline="false"
                >
                  <span v-for="item in form1.fileList" @click="downloads(item.url)">
                    {{ item.name }}</span
                  >
                </el-link>
          </el-form-item>
        </el-col>
      </el-form>
      <div class="addAchievement" v-if="form1.orderClassId == 34">
        <el-button type="primary" @click="uploadAchievement"
          >查看资源使用情况调研表</el-button
        >
        <el-button type="primary" @click="accountExtension"
          >查看账户延期人员信息统计表</el-button
        >
      </div>
      <el-table
        :data="form1.csAnnexList.filter((v) => v.delFlag != '1')"
        :border="true"
        header-cell-class-name="headerClassName"
      >
        <el-table-column prop="sort" label="序号" width="90" align="center" />
        <el-table-column prop="annexName" label="附件名称" />
        <el-table-column prop="annexFormat" label="格式" />
        <el-table-column prop="annexSize" label="大小" />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="handleRemove(scope.row)"
              >删除</el-button
            >
            <el-button type="text" @click="viewFile(scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div
        class="dialog_footer1" 
      >  
        <el-button
          @click="
            $store.getters.workOrderId.type = 1;
            active = 0;
          "
          v-if="active == 1  && (workOrderDetail.applyStatus != 5 || form1.applyStatus!= 5) && (workOrderDetail.applyStatus != 8 || form1.applyStatus!= 8) "
          >编辑</el-button
        >
        <el-button type="primary" @click="submitForm" v-if="active == 0"
          >提交</el-button
        >
        <el-button @click="cancelSubmit" v-if="active == 0 ">取消</el-button>
        <el-button type="primary" @click="auditing(1)" v-if="active == 1 && (workOrderDetail.applyStatus == 4 || form1.applyStatus == 4)"
          >驳 回</el-button
        >
        <el-button type="primary" @click="auditing(0)" v-if="active == 1&& (workOrderDetail.applyStatus == 4 || form1.applyStatus == 4)"
          >审核通过</el-button
        >
      </div>
    </div>
    <div class="approval" v-if="showFlow">
      <div class="stepList">
        <el-steps direction="vertical" :active="currentActive" :space="70">
          <el-step title="发起申请">
            <template slot="description">
              <!--<div ><span>{{ launchInfo.nickName }}<span
                    style="color: red;">（{{launchInfo.nickName}}）</span>{{launchInfo.roles[0].roleName}}</span>
                    </div>-->
              <div
                v-if="
                  workOrderDetail.applyStatus > 6 ||
                  workOrderDetail.applyStatus == 4
                "
              >
                <span
                  >{{
                    flowListObj && flowListObj.user
                      ? flowListObj.user.nickName
                      : ""
                  }}
                  <!-- 
                  {{ (flowListObj && flowListObj.user && flowListObj.user.dept) ? flowListObj.user.dept.deptName : flowListObj.user.roles.length>0 ? flowListObj.user.roles[0].roleName:''
                  }}</span> -->

                  {{
                    flowListObj.user.roles.length > 0
                      ? flowListObj.user.roles[0].roleName
                      : ""
                  }}</span
                >
              </div>
              <div
                v-if="
                  (flowListObj.nodeList[0] &&
                    flowListObj.nodeList[0].approverResult != '0') ||
                  (flowListObj.nodeList[0] &&
                    flowListObj.nodeList[0].approverResult != null)
                "
              >
                <span>{{
                  flowListObj.nodeList[0] &&
                  flowListObj.nodeList[0].approverTime
                }}</span>
                <span
                  style="color: green; padding-left: 5px"
                  v-if="
                    flowListObj.nodeList[0] &&
                    flowListObj.nodeList[0].approverResult == '1'
                  "
                  >审核通过</span
                >
                <span
                  style="color: red; padding-left: 5px"
                  v-if="
                    flowListObj.nodeList[0] &&
                    flowListObj.nodeList[0].approverResult == '2'
                  "
                  >审核驳回</span
                >
                <span
                  style="color: red; padding-left: 5px"
                  v-if="
                    flowListObj.nodeList[0] &&
                    flowListObj.nodeList[0].approverResult == '3'
                  "
                  >已转交</span
                >
              </div>
            </template>
          </el-step>
          <template>
            <div
              v-for="(item, index) in departmentList"
              :key="index"
              style="height: auto"
            >
              <el-step title="受理部门" style="height: 70px">
                <template slot="title">
                  <span>受理部门</span>
                  <span
                    style="
                      padding-left: 20px;
                      color: #e81a1d;
                      font-size: 14px;
                      cursor: pointer;
                    "
                    @click="delDepart(index)"
                    v-if="index != 0 && workOrderDetail.applyStatus == 6"
                    >删除受理部门</span
                  >
                  <span
                    style="
                      padding-left: 20px;
                      color: #0051aa;
                      font-size: 14px;
                      cursor: pointer;
                    "
                    @click="addDepart"
                    v-if="index == 0 && workOrderDetail.applyStatus == 6"
                    >添加受理部门</span
                  >
                </template>
                <template slot="description">
                  <el-select
                    v-model="item.roleId"
                    placeholder="请选择受理部门"
                    @change="departRoleId(index, $event)"
                    v-if="workOrderDetail.applyStatus == 6"
                  >
                    <el-option
                      v-for="item1 in roleList"
                      :key="item1.roleId"
                      :label="item1.roleName"
                      :value="item1.roleId"
                    >
                    </el-option>
                  </el-select>
                  <div
                    v-if="
                      workOrderDetail.applyStatus > 6 ||
                      workOrderDetail.applyStatus == 4
                    "
                  >
                    <span>{{ item.roleName }}</span>
                  </div>
                </template>
              </el-step>
              <el-step title="受理人员" style="height: 70px">
                <template slot="description">
                  <el-select
                    v-model="item.currentNodeApprover"
                    placeholder="请选择受理人员"
                    @change="departCurrentNodeApprover(index, $event)"
                    v-if="workOrderDetail.applyStatus == 6"
                  >
                    <el-option
                      v-for="item1 in departTotalList"
                      :key="item1.userId"
                      :label="item1.name"
                      :value="item1.userId"
                    >
                    </el-option>
                  </el-select>
                  <div
                    v-if="
                      workOrderDetail.applyStatus > 6 ||
                      workOrderDetail.applyStatus == 4
                    "
                  >
                    <span>{{ item.userName }}</span>
                  </div>
                </template>
              </el-step>
            </div>
          </template>
          <div
            style="
              text-align: center;
              padding-top: 10px;
              padding-bottom: 10px;
              background-color: #ffffff;
            "
            v-if="workOrderDetail.applyStatus == 6"
          >
            <el-button type="primary" @click="submitFlow">提交</el-button>
          </div>
        </el-steps>
      </div>

      <div class="approvalMiddle" v-if="flowListObj">
        <div v-if="flowListObj.user && flowListObj.checkInfo">
          <div class="approvalTitle">
            {{ flowListObj.user.nickName }}({{
              flowListObj.user.roles[0].roleName
            }})，已处理
          </div>
          <div class="approvalMiddleContent">
            <div class="approvalContent2">
              <div>处理结果</div>
              <div>已处理</div>
            </div>
            <div class="approvalContent2">
              <div>处理时间</div>
              <div>
                {{ flowListObj.checkInfo.launchTime }}
              </div>
            </div>
            <div class="approvalContent2">
              <div>反馈结果</div>
              <div>
                <!-- {{ item.approverOpinions }} -->
              </div>
            </div>
            <div class="approvalContent2">
              <div>附件</div>
              <div>
                <el-upload
                  class="upload-demo"
                  :action="$baseUrl + '/api/common/uploadFileLocal'"
                  :limit="1"
                  :on-change="attachmentChange"
                  :file-list="[]" 
                  :disabled="true"
                >
                  <el-button
                    size="small"
                    type="primary"
                    icon="el-icon-upload2"
                    :disabled="true"
                    >点击上传</el-button
                  >
                  <div slot="tip" class="el-upload__tip">
                    支持扩展名：excle.pdf.xlsx…
                  </div>
                </el-upload>
                   
              </div>
            </div>
          </div>
        </div>
        <!-- 循环受理人员 -->
        <div v-for="(item, index) in flowListObj.checkList" :key="index">
          <div class="approvalTitle">
            {{ item.userName }}({{ item.roleName }})，
            <span v-if="item.nodeType == '0'">
              {{
                item.approverResult == 0 || item.approverResult == null
                  ? "未审批"
                  : item.approverResult == 1 && workOrderDetail.applyStatus != 9
                  ? "已审批"
                  : item.approverResult == 1 && workOrderDetail.applyStatus == 9
                  ? "已完成"
                  : ""
              }}</span
            >
            <span v-if="item.nodeType == '2'">
              {{
                item.approverResult == 0 || item.approverResult == null
                  ? "未受理"
                  : item.approverResult == 1 && workOrderDetail.applyStatus != 9
                  ? "已受理"
                  : item.approverResult == 1 && workOrderDetail.applyStatus == 9
                  ? "已完成"
                  : ""
              }}</span
            >

            <span v-if="item.nodeType == '3'">已转交</span>
          </div>
          <div class="approvalMiddleContent" v-if="item.approverResult != 0">
            <div class="approvalContent2">
              <div>处理结果</div>
              <div>
                {{
                  item.approverResult == 1
                    ? "已处理"
                    : item.approverResult == 2
                    ? "驳回"
                    : item.approverResult == 3
                    ? "转交"
                    : ""
                }}
              </div>
            </div>
            <div class="approvalContent2">
              <div>处理时间</div>
              <div>
                {{ item.approverTime }}
              </div>
            </div>
            <div class="approvalContent2">
              <div>反馈结果</div>
              <div>
                {{ item.approverOpinions }}
              </div>
            </div>
            <div class="approvalContent2">
              <div>附件</div>
              <div>
                <el-upload
                  class="upload-demo"
                  :action="$baseUrl + '/api/common/uploadFileLocal'"
                  :limit="1"
                  :on-change="attachmentChange" 
                  :disabled="true"
                >
                  <el-button
                    size="small"
                    type="primary"
                    icon="el-icon-upload2"
                    :disabled="true"
                    >点击上传</el-button
                  >
                  <div slot="tip" class="el-upload__tip">
                    支持扩展名：excle.pdf.xlsx…
                  </div>
                </el-upload>
                    <el-link
                  v-if="item.accessoryUrl.length > 0"
                  type="primary"
                  :underline="false"
                >
                  <span v-for="ittm in item.accessoryUrl" @click="downloads(ittm.url)">
                    {{ ittm.name }}</span
                  >
                </el-link>
              </div>
            </div>
            <div class="approvalContent2" v-if="item.transfereeText">
              <div>转交备注</div>
              <div>
                {{ item.transfereeText }}
              </div>
            </div>
            <div class="approvalContent2" v-if="item.nodeType == '2'">
              <div>部门转交</div>
              <div>
                <el-button type="primary" plain :disabled="true"
                  >部门转交</el-button
                >
              </div>
            </div>
            <div
              class="dialog_footer"
             
            >
              <el-button type="primary" @click="withdrawSubmitType(item)"  v-if="
                item.isLastNode==0 &&
                item.nodeType == '0' &&
                item.approverUserId == $store.getters.roleId_userId.userId &&
                workOrderDetail.applyStatus != 9
              "
                >撤 回</el-button
              >
                <el-button type="primary" @click="withdrawSubmit(item)"  v-if="
                item.isLastNode==0 &&
                (item.nodeType == '2' || item.nodeType == '3') &&
                workOrderDetail.applyStatus != 9 &&
                item.approverUserId == $store.getters.roleId_userId.userId
              "
                >撤 回</el-button
              >
               <el-button type="primary" @click="withdrawSubmit(item)"
                  v-if="
               item.isLastNode==1 &&
                item.closeApply == 0 &&
                (workOrderDetail.applyStatus == '7' ||
                  workOrderDetail.applyStatus == '9') &&
                item.approverUserId == String($store.getters.roleId_userId.userId)   
              "
                >撤 回</el-button
              >
               <el-button type="primary" @click="closeProcessforms(item)"
                 v-if="
                item.isLastNode==1 &&
                item.closeApply == 0 &&
                (workOrderDetail.applyStatus == '7' ||
                  workOrderDetail.applyStatus == '9') &&
                item.approverUserId == String($store.getters.roleId_userId.userId)   
              "
                >关闭工单</el-button
              >
            </div> 
       
          </div>

          <div class="approvalMiddleContent" v-if="item.approverResult == 0">
            <div class="approvalContent2">
              <div>处理结果</div>
              <div>
                <el-select
                  v-model="tempForms[index].approverResult"
                  placeholder="请选择处理结果"
                >
                  <el-option label="已处理" :value="1" />
                  <el-option label="驳回" :value="2" />
                  <el-option label="转交" :value="3" />
                </el-select>
              </div>
            </div>
            <div class="approvalContent2">
              <div>处理时间</div>
              <div>
                <el-date-picker
                  v-model="tempForms[index].approverTime"
                  type="date"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  disabled
                  style="width: 100%"
                >
                </el-date-picker>
              </div>
            </div>
            <div class="approvalContent2">
              <div>反馈结果</div>
              <div>
                <el-input
                  type="textarea"
                  placeholder="请输入反馈结果"
                  v-model="tempForms[index].approverOpinions"
                />
              </div>
            </div>
            <div class="approvalContent2">
              <div>附件</div>
              <div>
                <el-upload
                  class="upload-demo"
                  :action="$baseUrl + '/api/common/uploadFileLocal'"
                  :limit="1"
                  :on-change="attachmentChange" 
                >
                  <el-button size="small" type="primary" icon="el-icon-upload2"
                    >点击上传</el-button
                  >
                  <div slot="tip" class="el-upload__tip">
                    支持扩展名：excle.pdf.xlsx…
                  </div>
                </el-upload>
                  <el-link
                  v-if="tempForms[index].accessoryUrl.length > 0"
                  type="primary"
                  :underline="false"
                >
                  <span v-for="ittm in tempForms[index].accessoryUrl" @click="downloads(ittm.url)">
                    {{ ittm.name }}</span
                  >
                </el-link>
              </div>
            </div>
            <div class="approvalContent2">
              <div>部门转交</div>
              <div>
                <el-button type="primary" plain @click="departmentalTransfer"
                  >部门转交</el-button
                >
              </div>
            </div>
            <div class="approvalContent2" v-if="item.isLastNode != 0">
              <div>是否关闭工单</div>
              <div>
                <el-radio-group v-model="tempForms[index].toCloseApply">
                  <el-radio :label="0">否</el-radio>
                  <el-radio :label="1">是</el-radio>
                </el-radio-group>
              </div>
            </div>
            <div class="approvalContent2" v-if="item.transfereeText != null">
              <div>转交备注</div>
              <div>
                {{ item.transfereeText }}
              </div>
            </div>
            <div class="dialog_footer">
              {{  }}
              <el-button
                type="primary"
                @click="submitWithdraw(index)"
                v-if="userInfo.userId==flowListObj.user.userId|| userInfo.userId==1"
                :disabled="item.applyStatus == 0"
                >撤 回</el-button
              > 
              <el-button type="primary" @click="submitProcessforms(index)"
                >提 交</el-button
              >
            </div>
          </div>
        </div>
      </div>
      <div class="approvalRight">
        <div class="approvalTitle">用户资料</div>
        <div class="approvalContent2">
          <div>单位名称</div>
          <div>{{ form1.companyName }}</div>
        </div>
        <div class="approvalContent2">
          <div>项目负责人</div>
          <div>{{ form1.name }}</div>
        </div>
        <div class="approvalContent2">
          <div>手机号</div>
          <div>{{ form1.phone }}</div>
        </div>
        <div class="approvalContent2">
          <div>单位类别</div>
          <div>{{ form1.companyClassName }}</div>
        </div>
        <div class="approvalContent2">
          <div>职称</div>
          <div>{{ form1.professionalTitle }}</div>
        </div>
        <div class="approvalContent2">
          <div>E-mall</div>
          <div>{{ form1.email }}</div>
        </div>
      </div>
    </div>
    <el-dialog title="驳回原因" :visible.sync="showReason" width="30%">
      <div>
        <el-input
          v-model="refuseReason"
          type="textarea"
          placeholder="请输入驳回原因"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showReason = false">取 消</el-button>
        <el-button type="primary" @click="auditing(2)">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="部门转交" :visible.sync="showTransfer" width="60%">
      <div
        style="
          display: flex;
          align-items: center;
          justify-content: space-between;
        "
      >
        <div class="approvalContent3">
          <div>原受理部门</div>
          <div>
            <el-select
              v-model="originalDepartment"
              placeholder="原受理部门"
              :disabled="true"
            >
            </el-select>
          </div>
        </div>
        <div class="approvalContent3">
          <div style="padding-right: 10px">转交部门</div>
          <div>
            <el-select
              v-model="transferRoleId"
              placeholder="请选择转交部门"
              @change="getDepartTotal"
            >
              <el-option
                v-for="item1 in roleList"
                :key="item1.roleId"
                :label="item1.roleName"
                :value="item1.roleId"
              >
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="approvalContent3">
          <div style="padding-right: 10px">受理人员</div>
          <div>
            <el-select v-model="transferee" placeholder="请选择受理人员">
              <el-option
                v-for="item1 in departTotalList"
                :key="item1.userId"
                :label="item1.name"
                :value="item1.userId"
              >
              </el-option>
            </el-select>
          </div>
        </div>
      </div>
      <div class="approvalContent4">
        <div>转交备注</div>
        <div>
          <el-input
            type="textarea"
            v-model="processforms.transfereeText1"
            placeholder="转交备注"
            maxlength="50"
            show-word-limit
          />
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showTransfer = false">取 消</el-button>
        <el-button type="primary" @click="submitTransfer">提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { settings } from "nprogress";
import {
  getClassListByMark,
  handleOrderApply,
  getOrderDetail,
  editOrderApply,
  getUserSelectListByRoleId,
  updateCsResourceOrderApply,
  getFlowList,
  addConfigs,
  checkConfigs,
  closeApply,
  withdrawDelegation,
  leaderTransferOther,
  withdrawTransfer,
  refuseTransfer,
  approvalRollback,
  getLaunchInfoApi,
} from "@/api/cs/csResourceOrderApply";

import { getUserProfile } from "@/api/system/user";
import { listRole } from "@/api/system/role";
import { active } from "sortablejs";
export default {
  data() {
    return {
      form1: {
        applyType: "1",
        applyStatus: "",
        orderTitle: "",
        orderClassId: "",
        name: "",
        companyName: "",
        phone: "",
        email: "",
        problemDescribe: "",
        fileList: [],
        csAnnexList: [],
      },
      rules1: {
        companyName: [
          { required: true, message: "请输入单位名称", trigger: "blur" },
        ],
        orderTitle: [
          { required: true, message: "请输入工单标题", trigger: "blur" },
        ],
        name: [{ required: true, message: "请输入联系人", trigger: "blur" }],
        orderClassId: [
          { required: true, message: "请选择工单类型", trigger: "change" },
        ],
        problemDescribe: [
          { required: true, message: "请输入问题描述", trigger: "blur" },
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          // { min: 11, max: 11, message: "手机号长度为11位", trigger: "blur" },
          // { pattern: /^1[3456789]\d{9}$/, message: "请输入正确的手机号", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          // { pattern: /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/, message: "邮箱格式有误", trigger: "blur" },
        ],
      },
      resourceClassList: [],
      accountExtensionObj: [],
      achievementObj: null,
      active: 0, //是否可编辑
      applyId: sessionStorage.getItem("applyId") || "",
      workOrderDetail: {
        applyId: sessionStorage.getItem("applyId") || "",
      },
      showReason: false,
      refuseReason: "",
      showFlow: false,
      roleList: [],
      departTotalList: [],
      flowListObj: {
        nodeList: [],
        checkList: [],
      },
      processforms: {
        toCloseApply: 0,
        lastNode: 0,
        // closeApply: 0,
        // approvalConfigId: '',
        // approvalInfoId: '',
        // formId: '',
        // formType: '',
        // approverUserId: '',
        // approverTime: '',
        // approverExplain: '',
        // approverOpinions: '',
        // approverResult: 0,
        // transferee: '',
        // transfereeText: '',
        // accessoryUrl: [],
        // approverNode: 0
      },
      showTransfer: false,
      originalDepartment: "",
      transferRoleId: "",
      transferee: "",
      currentActive: null,
      launchInfo: "",
      tempForms: [],
      fullscreenLoading:false,
      
      userInfo: {},
    };
  },
  mounted() {  
     this.getOrderDetail();
      this.getUser();
    this.getCompanyClassList(); 
    this.achievementObj = sessionStorage.getItem("achievement")
      ? JSON.parse(sessionStorage.getItem("achievement"))
      : "";
    this.accountExtensionObj = sessionStorage.getItem("accountExtension")
      ? JSON.parse(sessionStorage.getItem("accountExtension"))
      : "";

    if (this.$route.params.applyId) {
      this.applyId = this.$route.params.applyId;
      sessionStorage.setItem("applyId", this.applyId);
      if (!this.$store.getters.workOrder) {
        this.getOrderDetail();
      }
      if (this.$route.params.applyId.type == 0) {
        this.active = 0;
      } else {
        this.active = 1;
      }
    }
   let activeInfo=  localStorage.getItem('activeInfo')
     localStorage.removeItem('activeInfo')
   if (activeInfo) {
    this.active=activeInfo
   }
  //  console.log( this.active);  
    if (this.$store.getters.workOrder) {
      if (this.applyId == this.$store.getters.workOrder.applyId) {
        this.form1 = this.$store.getters.workOrder;
      } else {
        this.getOrderDetail();
      }
    }
    this.achievementObj = this.$store.getters.achievementObj;

    listRole().then((res) => {
      this.roleList = res.rows;
    });
    this.getLaunchInfo();

    // 初始化 tempForms
    this.tempForms = this.flowListObj.checkList.map((item) => ({
      approverResult: item.approverResult || null,
      approverTime: item.approverTime || this.getCurrentTime(),
      approverOpinions: item.approverOpinions || "",
      accessoryUrl: item.accessoryUrl || [],
      toCloseApply: item.toCloseApply || 0,
      transfereeText: item.transfereeText || "",
      isLastNode: item.isLastNode || false,
      approvalInfoId: item.approvalInfoId || null,
      lastNode: 0,
      closeApply: 0,
      nodeType: item.nodeType || "",
      approvalNode: item.approvalNode || 0,
      userName: item.userName || "",
      roleName: item.roleName || "",
      approvalRecordId: item.approvalRecordId || "",
      approvalConfigId: item.approvalConfigId || "",
      formId: item.formId || this.applyId,
      formType: item.formType || "1",
      approverUserId: item.approverUserId || "",
      roleId: item.roleId || "",
      acceptId: item.acceptId || null,
      acceptName: item.acceptName || "",
      acceptStatus: item.acceptStatus || null,
      isLeader: item.isLeader || "0",
      isLower: item.isLower || "0",
      createTime: item.createTime || this.getCurrentTime().split(" ")[0],
    }));
  }, 
  methods: {
      getUser() {
      getUserProfile().then((response) => {
        this.userInfo = response.data;
        console.log( this.userInfo,111);
        
      });
    },
    getLaunchInfo() {
      getLaunchInfoApi().then((res) => {
        this.launchInfo = res.data; 
      });
    },

    back() { 
      
      this.$store.commit("SET_achievement", null);
      this.$store.commit("SET_workOrder", null);
      this.$store.commit("SET_workOrderId", null);
      this.$router.go(-1);
    },

    withdrawSubmit(item) {
      withdrawTransfer({
        approvalConfigId: item.approvalConfigId,
      }).then((res) => {
        if (res.code == 200) {
          this.$message({
            message: "操作已撤回",
            type: "success",
          });
          this.getFlow();
        }
      });
    },
    withdrawSubmitType(item) {
      approvalRollback({
        approvalConfigId: item.approvalConfigId,
      }).then((res) => {
        if (res.code == 200) {
          this.$message({
            message: "操作已撤回",
            type: "success",
          });
          this.getFlow();
        }
      });
    },
    workOrderIssuance(index, value) {
      this.flowListObj.checkList[index].acceptId = value;
    },
    departmentalTransfer() {
      this.showTransfer = true;
      // this.originalDepartment = this.processforms.acceptName.split(' ')[0]
      if (this.flowListObj.checkList.length > 0) {
        this.originalDepartment = this.flowListObj.checkList[0].roleName;
      }
    },
    submitTransfer() {
      this.processforms.transfereeText = this.processforms.transfereeText1;
      leaderTransferOther({
        approvalConfigId: this.processforms.approvalConfigId,
        approverUserId: this.processforms.approverUserId,
        transferee: this.transferee,
        roleId: this.transferRoleId,
        transfereeText: this.processforms.transfereeText,
        formId: this.processforms.formId,
        approverOpinions: this.processforms.approverOpinions,
        approvalInfoId: this.processforms.approvalInfoId,
      }).then((res) => {
        this.$message({
          message: "转交成功",
          type: "success",
        });
        this.showTransfer = false;
        this.getFlow();
      });
    },
    getDepartTotal(value) {
      this.transferee = "";
      getUserSelectListByRoleId({ roleId: value }).then((res) => {
        if (res.code == 200) {
          this.departTotalList = res.data;
        }
      });
    },
    getFlow() {
      getFlowList({ formId: this.applyId, formType: "1" }).then((res) => {
        this.flowListObj = res.data;
        if (res.data.nodeList.length != 0 && res.data.nodeList) {
          this.showFlow = true;
        }
        if (res.data.nodeList.length > 0) {
          this.personList = [];
          this.departmentList = [];
          this.carbonCopyRecipients = [];
          res.data.nodeList.forEach((v, k) => {
            if (k == 1) {
              this.wxCurrentNodeApprover = v.currentNodeApprover;
              this.wxRoleId = v.roleId;
            }
            if (v.nodeType == "0" && k > 1) {
              this.personList.push(v);
            }
            if (v.nodeType == "1") {
              this.carbonCopyRecipients.push(v);
            }
            if (v.nodeType == "2" || v.nodeType == "3") {
              this.departmentList.push(v);
            }
          });

          // 初始化 tempForms
          this.tempForms = this.flowListObj.checkList.map((item) => ({
            approverResult: item.approverResult || null,
            approverTime: item.approverTime || this.getCurrentTime(),
            approverOpinions: item.approverOpinions || "",
            accessoryUrl: item.accessoryUrl || [],
            toCloseApply: item.toCloseApply || 0,
            transfereeText: item.transfereeText || "",
            isLastNode: item.isLastNode || false,
            approvalInfoId: item.approvalInfoId || null,
            lastNode: 0,
            closeApply: 0,
            nodeType: item.nodeType || "",
            approvalNode: item.approvalNode || 0,
            userName: item.userName || "",
            roleName: item.roleName || "",
            approvalRecordId: item.approvalRecordId || "",
            approvalConfigId: item.approvalConfigId || "",
            formId: item.formId || this.applyId,
            formType: item.formType || "1",
            approverUserId: item.approverUserId || "",
            roleId: item.roleId || "",
            acceptId: item.acceptId || null,
            acceptName: item.acceptName || "",
            acceptStatus: item.acceptStatus || null,
            isLeader: item.isLeader || "0",
            isLower: item.isLower || "0",
            createTime: item.createTime || this.getCurrentTime().split(" ")[0],
          }));

          let nodeTypeTotal = 1;
          try {
            res.data.nodeList.forEach((v, k) => {
              if (v.approverResult == null && v.nodeType == "0") {
                this.currentActive = k;
                throw "中断";
              }
              if (v.nodeType == "2") {
                nodeTypeTotal += 1;
                if (v.approverResult == null && v.nodeType == "2") {
                  this.currentActive =
                    k + nodeTypeTotal - this.carbonCopyRecipients.length;
                  throw "中断";
                }
              }
            });
          } catch (e) {
            if (e != "中断") throw e;
          }

          res.data.checkList.forEach((v, k) => {
            this.$set(this.processforms, "approvalInfoId", v.approvalInfoId);
            if (v.approverResult == 0) {
              this.processforms = JSON.parse(JSON.stringify(v));
              this.processforms.approverResult = null;
              this.processforms.accessoryUrl = [];
              let time = new Date();
              let y = time.getFullYear().toString().padStart(2, "0");
              let m = (time.getMonth() + 1).toString().padStart(2, "0");
              let d = time.getDate().toString().padStart(2, "0");
              let h = time.getHours().toString().padStart(2, "0");
              let min = time.getMinutes().toString().padStart(2, "0");
              let s = time.getSeconds().toString().padStart(2, "0");
              this.processforms.approverTime =
                y + "-" + m + "-" + d + "  " + h + ":" + min + ":" + s;
              if (!this.processforms.toCloseApply) {
                this.processforms.toCloseApply = 0;
              }
            }
          });
        }
      });
    },
    closeProcessforms(item) {
      closeApply({
        approvalConfigId: item.approvalConfigId,
        approvalInfoId: item.approvalInfoId,
        approvalRecordId: item.approvalRecordId,
        lastNode: 1,
        closeApply: 1,
      }).then((res) => {
        if (res.code == 200) {
          this.$message({
            message: "工单已关闭",
            type: "success",
          });
          this.$router.go(-1);
        }
      });
    },

    async submitWithdraw(index) {
      const formData = { ...this.tempForms[index] };
      withdrawDelegation({
        formId: formData.formId,
        formType: formData.formType,
        approvalConfigId:formData.approvalConfigId,
      })
        .then((res) => {
          if (res.code == 200) {
            this.$message({
              message: "处理成功",
              type: "success",
            });
            this.getOrderDetail();
            this.getFlow();
              //  this.$router.push({
              //   path: "/workOrderManagement/WorkOrderManagement",
              // });
                  // this.$tab.closeOtherPage()
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    async submitProcessforms(index) {
      const formData = { ...this.tempForms[index] };

      formData.closeApply = formData.toCloseApply ? formData.toCloseApply : 0;
      if (!formData.approverResult) {
        this.$message({
          message: "请选择处理结果",
          type: "error",
        });
        return;
      }

      if (!formData.approvalInfoId) {
        await this.getFlow();
      }

      checkConfigs(formData).then((res) => {
        if (res.code == 200) {
          if (formData.approverResult == "2") {
            this.getOrderDetail();
          }
          this.$message({
            message: "处理成功",
            type: "success",
          });
          this.getFlow();
        }
      });
    },
    submitFlow() {
      // 校验受理部门和受理人员是否已选择
      for (let department of this.departmentList) {
        if (!department.roleId || !department.currentNodeApprover) {
          this.$message({
            message: "受理部门和受理人员不能为空",
            type: "error",
          });
          return;
        }
      }

      let confirmForm = {};
      confirmForm.formId = this.applyId;
      confirmForm.formType = "1";
      let nodeList = [
        {
          nodeType: "0",
          sort: 0,
          currentNodeApproverType: 3,
          currentNodeApprover: this.$store.state.user.roleId_userId.userId,
          roleId: this.$store.state.user.roleId_userId.roleId,
        },
      ];
      nodeList = nodeList.concat(this.departmentList);
      confirmForm.nodeList = nodeList; 
      addConfigs({ ...confirmForm }).then((res) => {
        if (res.code == 200) {
          this.$message({
            message: "分配成功",
            type: "success",
          });
          this.$router.push({
            path: "/workOrderManagement/WorkOrderManagement",
            query: {
              refresh: 1,
            },
          });
        }
      });
    },

    getOrderDetail() {
      this.fullscreenLoading=true
      getOrderDetail(this.applyId).then((res) => {
      this.fullscreenLoading = false;
        if (res.code == 200) {
          this.workOrderDetail = res.data;
          this.processforms.toCloseApply = 0;
          this.form1 = { ...this.workOrderDetail };
          this.form1.applyType = res.data.applyType;
          this.form1.applyStatus = res.data.applyStatus;
          this.form1.orderTitle = res.data.orderTitle;
          this.form1.orderClassId = res.data.orderClassId;
          this.form1.name = res.data.name;
          this.form1.companyName = res.data.companyName;
          this.form1.phone = res.data.phone;
          this.form1.email = res.data.email;
          this.form1.problemDescribe = res.data.problemDescribe;
          this.form1.refuseReason = res.data.refuseReason;

          this.form1.fileList = [];
         
          res.data.csAnnexList.forEach((v) => {
            this.form1.fileList.push({
              name: v.annexName,
              fileSize: v.annexSize,
              url: v.annexUrl,
              delFlag: v.delFlag,
            });
          });
          this.form1.csAnnexList = res.data.csAnnexList;
         
          let obj = {
            paperAchievementList: res.data.paperAchievementList,
            patentAchievementList: res.data.patentAchievementList ,
            prizeAchievementList: res.data.prizeAchievementList,
            otherAchievementList:  res.data.otherAchievementList,
            reservationAchievementList:res.data.reservationAchievementList,
            applicationArea: res.data.applicationArea,
            platformSoftware: res.data.platformSoftware,
            softwareName:  res.data.softwareName,
            isPublicize:res.data.isPublicize,
          }; 

          this.achievementObj = obj;
          sessionStorage.setItem(
            "achievement",
            JSON.stringify(this.achievementObj)
          );
          if (sessionStorage.getItem("isbao") == 1) {
            sessionStorage.setItem("isbao", 0);
          } else {
            this.accountExtensionObj = res.data.accountExtensionInfoList
              ? res.data.accountExtensionInfoList.length
                ? res.data.accountExtensionInfoList
                : []
              : [];
          }

          if (this.workOrderDetail.applyStatus == 4) {
            this.getFlow();
          } else if (this.workOrderDetail.applyStatus == 6) {
            this.showFlow = true;
            this.departmentList = [
              {
                nodeType: "2",
                sort: 1,
                currentNodeApproverType: 3,
                currentNodeApprover: "",
                roleId: "",
              },
            ];
          } else if (
            this.workOrderDetail.applyStatus == 7 ||
            this.workOrderDetail.applyStatus == 9
          ) {
            this.getFlow();
          }
          this.$store.commit("SET_achievement", obj);
        }
      }).catch(error=>{
           this.fullscreenLoading = false;
      });
    },
    addDepart() {
      let arr = {
        nodeType: "2",
        sort: this.departmentList.length + 1,
        currentNodeApproverType: 3,
        currentNodeApprover: "",
        roleId: "",
      };
      this.departmentList.push(arr);
      // this.departmentList = JSON.parse(JSON.stringify(this.departmentList.concat(arr)))
      this.$forceUpdate();
      // console.log(this.departmentList)
    },
    departRoleId(index, value) {
      this.departmentList[index].roleId = value;
      this.departmentList[index].currentNodeApprover = "";
      getUserSelectListByRoleId({ roleId: value }).then((res) => {
        if (res.code == 200) {
          this.departTotalList = res.data;
        }
      });
    },
    departCurrentNodeApprover(index, value) {
      this.$forceUpdate();
      // this.departmentList[index].currentNodeApprover = value
    },
    delDepart(index) {
      this.departmentList.splice(index, 1);
      this.$forceUpdate();
    },
    getCompanyClassList() {
      getClassListByMark({ classMark: "orderClass" }).then((response) => {
        this.resourceClassList = response.data;
      });
    },

    auditing(type) {
      let that = this;
      // console.log(that.workOrderDetail.applyId)
      if (type != 2) {
        if (type == 0) {
          that.$modal
            .confirm("是否确认审核通过该申请工单")
            .then(function () {
              let params = {
                applyId: that.workOrderDetail.applyId,
                applyStatus: "6",
                // refuseReason: this.form1.refuseReason
              };
              return handleOrderApply(params);
            })
            .then((res) => {
              if (res.code == 200) {
                that.$message({
                  message: "审核通过",
                  type: "success",
                });
                this.getOrderDetail();
              }
            })
            .catch((err) => {
              console.log(err);
            });
        } else if (type == 1) {
          // that.showReason = true
          handleOrderApply({
            applyId: that.workOrderDetail.applyId,
            applyStatus: "5",
            refuseReason: this.form1.refuseReason,
          }).then((res) => {
            if (res.code == 200) {
              this.$message({
                message: "工单已驳回",
                type: "success",
              });
              this.$router.push({
                path: "/workOrderManagement/WorkOrderManagement",
              });
              // that.showReason = false
            }
          });
        }
      } else {
      }
    },
    cancelSubmit() {
      this.getOrderDetail();
      this.active = 1;
    },
    submitForm() {
      if (this.applyId) {
        let accountExtension = sessionStorage.getItem("accountExtension")
          ? JSON.parse(sessionStorage.getItem("accountExtension"))
          : this.accountExtensionObj;

        // console.log({ ...this.workOrderDetail, ...this.form1, ...this.achievementObj, })
        editOrderApply({
          ...this.workOrderDetail,
          ...this.form1,
          ...this.achievementObj,
          accountExtensionInfoList: accountExtension ? accountExtension : [],
        }).then((res) => {
          if (res.code == 200) {
            this.$message({
              message: "编辑成功",
              type: "success",
            });
   this.active = 1;
            // this.back()
            this.getOrderDetail();
             
          }
        });
      } else {
        // console.log({ ...this.form1, ...this.achievementObj })
        // this.$post('/api/cs/csOrderApply/addOrderApply', { ...this.form1, ...this.achievementObj }).then(res => {
        //   if (res.code == 200) {
        //     this.$message({
        //       message: '申请成功',
        //       type: 'success'
        //     })
        //     this.back()
        //   }
        // })
      }
    },
    handleChange(file, fileList) {
      if (file.status == "success") {
        // console.log(file, fileList)
        this.form1.fileList = fileList;
        let small = {
          sort: fileList.length,
          annexName: file.name,
          annexFormat: file.name.split(".")[1],
          annexSize: (file.size / 1000 / 1024).toFixed(2) + "M",
          annexUrl: file.response.url,
        };
        this.form1.csAnnexList.push(small);
      }
    },
    viewFile(e) {
      // console.log(e);
      window.open(e.annexUrl, "_blank");
    },

    handleRemove({ annexUrl, sort }) {
      if (this.applyId) {
        this.form1.csAnnexList = this.form1.csAnnexList.map((v) => {
          if (v.annexUrl == annexUrl) {
            v.delFlag = "1";
          }
          return v;
        });
      } else {
        this.form1.csAnnexList.splice(sort - 1, 1);
      }
      this.form1.fileList = this.form1.fileList.filter((v) => {
        if (v.response) {
          return v.response.url != annexUrl;
        } else {
          return v.url != annexUrl;
        }
      });
    },
    attachmentChange(file, fileList) {
      if (file.status == "success") {
        // console.log(file)
        fileList.forEach((v) => {
          this.tempForms[index].accessoryUrl.push({
            newFileName: v.response.newFileName,
            url: v.response.url,
            originalFilename: v.response.originalFilename,
            name: v.name,
          });
        });
      }
    },
        downloads(item) {
      const url = window.URL.createObjectURL(new Blob([item]));
      let name = item.split("/");

      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", `${name[name.length - 1]}`); // 设置下载时的默认文件名
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    },
    handlePreview(val) {
      let file = val.url;
      let lastIndex = file.lastIndexOf(".");
      let suffix = file.substring(lastIndex + 1);
      //文件格式是word文档、ppt、excel文件文件时
      if (
        suffix == "doc" ||
        suffix == "ppt" ||
        suffix == "xls" ||
        suffix == "xlsx"
      ) {
        let fileUrl = encodeURIComponent(file);
        //使用Office Web查看器
        let officeUrl =
          "http://view.officeapps.live.com/op/view.aspx?src=" + fileUrl;
        window.open(officeUrl, "_target");
      } else if (suffix == "docx") {
        window.open(file, "_self");
      } else {
        //其他文件格式比如pdf、图片、html
        window.open(file);
      }
    },

    accountExtension() {
      this.$cookie.set("accountExtensionActive", this.active);
      sessionStorage.setItem("workOrder", JSON.stringify(this.form1));
      sessionStorage.setItem(
        "accountExtension",
        JSON.stringify(this.accountExtensionObj)
      );
      this.$cookie.set("workOrder", this.form1);
      this.$router.push("/workOrderListManagement/accountExtension");
    },

    uploadAchievement() {
      this.$cookie.set("adminAchievementActive", 0);
      sessionStorage.setItem("workOrder", JSON.stringify(this.form1));
      this.$store.commit("SET_workOrder", this.form1);
      // this.$router.push('/workOrderListManagement/uploadAchievement',)
      this.$router.push({
        path: "/workOrderListManagement/uploadAchievement",
        query: {
          active: this.active,
        },
      });
    },
    getCurrentTime() {
      const time = new Date();
      const y = time.getFullYear().toString().padStart(2, "0");
      const m = (time.getMonth() + 1).toString().padStart(2, "0");
      const d = time.getDate().toString().padStart(2, "0");
      const h = time.getHours().toString().padStart(2, "0");
      const min = time.getMinutes().toString().padStart(2, "0");
      const s = time.getSeconds().toString().padStart(2, "0");
      return `${y}-${m}-${d} ${h}:${min}:${s}`;
    },
  },
};
</script>

<style scoped>
.main {
  padding: 20px;
}

.title {
  height: 56px;
  padding-left: 20px;
  background: #ffffff;
  border-radius: 4px;
  display: flex;
  align-items: center;
}

.title > img {
  width: 14px;
  height: 19px;
  margin-right: 10px;
  cursor: pointer;
}

.title > span {
  font-weight: bold;
  font-size: 20px;
  color: #000000;
  text-align: left;
}

.module1 {
  height: auto;
  margin-top: 10px;
  margin-bottom: 10px;
  padding: 16px 16px 20px 16px;
  background: #ffffff;
  border-radius: 4px;
}

.formStyle1 {
  display: flex;
  flex-wrap: wrap;
}

::v-deep .el-form-item {
  width: 100%;
}

::v-deep .el-form-item__content {
  width: 70%;
}

::v-deep .el-select {
  width: 100%;
}

.addAchievement {
  margin-left: 106px;
  margin-bottom: 10px;
}

.dialog_footer1 {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  background-color: #ffffff;
  border-top: 1px solid #ebebeb;
  padding: 20px 20px 0 20px;
}

.approval {
  display: flex;
}

/* .approval>div {
  flex: 1;
} */
.stepList {
  width: 26%;
  padding: 40px 0 0 20px;
  min-height: 300px;
  background-color: #ffffff;
}

::v-deep .el-step:last-of-type .el-step__main,
.el-step:last-of-type .el-step__description {
  padding-right: 10%;
}

.approvalMiddle {
  width: 48%;
  min-height: 600px;
  background-color: #ffffff;
}

.approvalTitle {
  height: 46px;
  padding: 14px 0 14px 20px;
  font-weight: bold;
  font-size: 16px;
  color: #333333;
  line-height: 22px;
  text-align: left;
  font-style: normal;
  text-transform: none;
  border-bottom: 1px solid #ebebeb;
}

.approvalMiddleContent {
  padding: 20px;
}

.approvalContent1 {
  display: flex;
  align-items: center;
}

.approvalContent1Item {
  display: flex;
  align-items: center;
}

.approvalContent1Item > div:nth-of-type(1) {
  width: 100px;
  text-align: right;
  margin-right: 10px;
  font-size: 14px;
}

.approvalContent1Item1 {
  margin-left: 20px;
  display: flex;
  align-items: center;
}

.approvalContent1Item1 > div:nth-of-type(1) {
  margin-right: 10px;
  font-size: 14px;
}

.approvalContent2 {
  margin-top: 10px;
  display: flex;
  align-items: center;
}

.approvalContent2 > div:nth-of-type(1) {
  width: 100px;
  text-align: right;
  margin-right: 10px;
  font-size: 14px;
}

.approvalContent2 > div:nth-of-type(2) {
  width: 70%;
}

.approvalRight {
  width: 26%;
  min-height: 400px;
  background: #ffffff;
  border-radius: 4px;
}

.dialog_footer {
  background-color: #ffffff;
  padding: 20px 50px 30px 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
