<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
  <div>
    <el-row>
      <el-col :span="24">

        <el-form :model="inputForm" ref="inputForm" v-loading="loading" :class="method === 'view' ? 'readonly' : ''"
          :disabled="status === 'audit' || status === 'taskFormDetail'" label-width="110px" @submit.native.prevent>
          <el-row :gutter="15">
            <!--                <el-col :span="12">-->
            <!--                  <el-form-item label="档案名称" prop="name"-->
            <!--                                :rules="[-->
            <!--                                {required: true, message:'档案名称不能为空', trigger:'blur'}-->
            <!--                   ]">-->
            <!--                    <el-input v-model="inputForm.name" placeholder="请填写档案名称" clearable></el-input>-->
            <!--                  </el-form-item>-->
            <!--                </el-col>-->
            <el-col :span="12">
              <el-form-item label="档案号" prop="fileNumber" :rules="[
              ]">
                <el-input :disabled="true" v-model="inputForm.fileNumber" placeholder="请填写档案号" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目名称" prop="cwProjectRecordsDTO.projectName" :rules="[
              ]">
                <el-input :disabled="true" v-model="inputForm.cwProjectRecordsDTO.projectName" placeholder="请填写项目名称"
                  clearable>
                  <!--                      <el-button slot="append" :disabled="status === 'audit' || status === 'taskFormDetail'" @click="openChooseProject" icon="el-icon-search"></el-button>-->
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目编号" prop="cwProjectRecordsDTO.projectNumber" :rules="[
              ]">
                <el-input :disabled="true" v-model="inputForm.cwProjectRecordsDTO.projectNumber" placeholder="请填写项目编号"
                  clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目经理1" prop="cwProjectRecordsDTO.projectMasterName" :rules="[
              ]">
                <el-input :disabled="true" v-model="inputForm.cwProjectRecordsDTO.projectMasterName"
                  placeholder="请填写项目经理1"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目经理2" prop="cwProjectRecordsDTO.realHeaderName" :rules="[
              ]">
                <el-input :disabled="true" v-model="inputForm.cwProjectRecordsDTO.realHeaderName"
                  placeholder="请填写项目经理2"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="被审计单位" prop="auditedUnitsName" :rules="[
                { required: true, message: '被审计单位不能为空', trigger: 'blur' },
                { required: true, message: '被审计单位不能为空', trigger: 'change' }
              ]">
                <el-input :readonly="true" v-model="inputForm.auditedUnitsName" @focus="openChooseClient"
                  placeholder="请填写被审计单位" clearable>
                  <el-button slot="append" :disabled="status === 'audit' || status === 'taskFormDetail'"
                    @click="openChooseClient" icon="el-icon-search"></el-button>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="报告册数" prop="reportNum" :rules="[
                { required: true, message: '报告册数不能为空', trigger: 'blur' }
              ]">
                <el-input-number v-model="inputForm.reportNum" controls-position="right" style="width:100%"
                  :precision="0" :max="9999999999" :step="1" :min="0" placeholder="请填写报告册数" :controls="false" clearable>
                </el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="底稿册数" prop="papersNum" :rules="[
                { required: true, message: '底稿册数不能为空', trigger: 'blur' }
              ]">
                <el-input-number v-model="inputForm.papersNum" controls-position="right" style="width:100%"
                  :precision="0" :max="9999999999" :step="1" :min="0" placeholder="请填写底稿册数" :controls="false" clearable>
                </el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="审计收费(元)" prop="auditMoney" :rules="[
                { required: true, message: '请输入审计收费(元)', trigger: 'blur' }
              ]">
                <el-input v-on:input="inputForm.auditMoney = inputForm.auditMoney.replace(/[^\d.]/g, '')
                  .replace(/^\./g, '')
                  .replace(/\.{2,}/g, '.')
                  .replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
                  .replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^0+/, '0')" v-model="inputForm.auditMoney"
                  controls-position="right" :controls="false" style="width:100%;" placeholder="请输入审计收费(元)"
                  :disabled="this.inputForm.auditMoney == this.accountTotal && this.accountTotal != 0 ? true : false"
                  clearable @keyup="inputMoney">
                  <template #suffix>
                    <el-button style="background-color: white;color: #1b1e25;border-color: white;" type="primary"
                      @click="openInvoice(this.inputForm.id)" icon="el-icon-search"></el-button>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="isShow">
              <el-form-item label="关联报告" prop="connectReport" :rules="[
                { required: true, message: '关联报告不能为空', trigger: 'blur' },
                { required: true, message: '关联报告不能为空', trigger: 'change' }
              ]">
                <el-input :readonly="true" v-model="inputForm.connectReport" @focus="openReport" placeholder="请填写关联报告"
                  clearable>
                  <el-button slot="append" @focus="openReport" icon="el-icon-search"></el-button>
                </el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="档案年度" prop="year" :rules="[
                { required: true, message: '档案年度不能为空', trigger: 'blur' }
              ]">
                <el-date-picker v-model="inputForm.year" type="year" value-format="YYYY" placeholder="选择档案年度"
                  style="width:100%" placement="bottom-start" :clearable="false">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="归档时间" prop="auditDate" :rules="[
              ]">
                <el-input :disabled="true" v-model="inputForm.auditDate" placeholder="请填写归档时间" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col v-if="status !== 'audit'" :span="12">
              <el-form-item label="案卷号" prop="number" :rules="[
              ]">
                <el-input :disabled="true" v-model="inputForm.number" placeholder="请填写案卷号" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col v-if="status !== 'audit'" :span="12">
              <el-form-item label="确认案卷号" prop="isNumber" :rules="[
              ]">
                <el-input :disabled="true" v-model="inputForm.isNumber" placeholder="请填写确认案卷号" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-form v-if="status === 'audit'" style="width: 100%" :model="inputForm" ref="inputForm"
              v-loading="loading" :class="method === 'view' ? 'readonly' : ''" label-width="110px"
              @submit.native.prevent>
              <el-col :span="12">
                <el-form-item label="案卷号" prop="number" :rules="[
                  { required: true, message: '案卷号不能为空', trigger: 'blur' }
                ]">
                  <el-input style="width: 100%" :disabled="false" v-model="inputForm.number" placeholder="请填写案卷号"
                    clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="确认案卷号" prop="isNumber" :rules="[
                  { required: true, message: '确认案卷号不能为空', trigger: 'blur' }
                ]">
                  <el-input :disabled="false" style="width: 100%" v-model="inputForm.isNumber" placeholder="请填写确认案卷号"
                    clearable></el-input>
                </el-form-item>
              </el-col>
            </el-form>

            <el-col :span="24">
              <el-form-item label="备注" prop="remarks" :rules="[
              ]">
                <el-input type="textarea" style="width:100%" maxlength="1000" v-model="inputForm.remarks"
                  placeholder="请填写备注" show-word-limit></el-input>

              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请人" prop="createBy.name" :rules="[
              ]">
                <el-input :disabled="true" v-model="inputForm.createBy.name" placeholder="请填写创建人" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请时间" prop="createDate" :rules="[
              ]">
                <el-input :disabled="true" v-model="inputForm.createDate" placeholder="请填写创建时间" clearable></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-divider content-position="left"><i class="el-icon-document"></i> 审计报告</el-divider>
          <el-row :gutter="15">
            <el-col :span="12">
              <el-form-item label="报告文号" prop="reportNo" :rules="[
              ]">
                <el-input :disabled="true" v-model="inputForm.reportNo" placeholder="请填写报告文号" clearable>
                  <!--                    <el-button slot="append" :disabled="status === 'audit' || status === 'taskFormDetail'" @click="openReportChoose" icon="el-icon-search"></el-button>-->
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="报告日期" prop="reportDate" :rules="[
              ]">
                <el-input :disabled="true" v-model="inputForm.reportDate" placeholder="请填写报告日期" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="签字注师1" prop="signatureAnnotator1Name" :rules="[
              ]">
                <el-input :disabled="true" v-model="inputForm.signatureAnnotator1Name" placeholder="请填写签字注师1"
                  clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="签字注师2" prop="signatureAnnotator2Name" :rules="[
              ]">
                <el-input :disabled="true" v-model="inputForm.signatureAnnotator2Name" placeholder="请填写签字注师2"
                  clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="报告主办人" prop="reportCreateName" :rules="[
              ]">
                <el-input :disabled="true" v-model="inputForm.reportCreateName" placeholder="请填写报告主办人"
                  clearable></el-input>
              </el-form-item>
            </el-col>
            <!--              <el-form :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''" :disabled="status !== 'audit'"-->
            <!--                       label-width="110px" @submit.native.prevent>-->
            <!--              <el-col :span="12">-->
            <!--                <el-form-item label="审计意见" prop="reportRemarks"-->
            <!--                              :rules="[-->
            <!--                   ]">-->
            <!--                  <el-input type="textarea"  style="width:100%" maxlength="225" v-model="inputForm.reportRemarks" placeholder="请填写审计意见" show-word-limit></el-input>-->

            <!--                </el-form-item>-->
            <!--              </el-col>-->
            <!--              </el-form>-->
            <el-col :span="12">
              <el-form-item label="审计意见" prop="reportRemarks" :class="method === 'view' ? 'readonly' : ''" :rules="[
              ]">
                <el-input type="textarea" :disabled="status !== 'audit'" style="width:100%" maxlength="225"
                  v-model="inputForm.reportRemarks" placeholder="请填写审计意见" show-word-limit></el-input>

              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-tabs v-model="activeName" type="border-card" @tab-click="tabHandleClick">
          <el-tab-pane label="附件" name="files">
            <!--        附件-->
            <UpLoadComponent ref="uploadComponent"></UpLoadComponent>
          </el-tab-pane>

        </el-tabs>
      </el-col>
    </el-row>
    <ProjectRecordsChooseCom ref="projectRecordsChooseCom" @getProject="getProject"></ProjectRecordsChooseCom>
    <WorkClientChooseByProjectCom ref="workClientChooseByProjectCom" @getClient="getClient">
    </WorkClientChooseByProjectCom>
    <ReportChooseByProjectCom ref="reportChooseByProjectCom" @getReport="getReport"></ReportChooseByProjectCom>
  </div>

  <el-dialog title="开票信息选择" :close-on-click-modal="false" draggable width="1100px" height="500px" @close="closeTable"
    append-to-body destroy-on-close="true" :visible.sync="dialogTableVisible" v-if="dialogTableVisible"
    v-model="dialogTableVisible">
    <div style="height: calc(100% - 80px);">
      <el-form :inline="true" class="query-form" ref="searchForm" :model="searchForm" @submit.native.prevent>
        <!-- 搜索框-->
        <el-form-item label="发票号" prop="number">
          <el-input v-model="searchForm.number" placeholder="请输入发票号" clearable></el-input>
        </el-form-item>
        <el-form-item label="开票申请编号" prop="no">
          <el-input v-model="searchForm.no" placeholder="请输入开票申请编号" clearable></el-input>
        </el-form-item>
        <el-form-item label="报告号" prop="reportNo">
          <el-input v-model="searchForm.reportNo" placeholder="请输入报告号" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getReport(this.inputForm.id)" icon="el-icon-search">查询</el-button>
          <el-button @click="resetSearch()" icon="el-icon-refresh-right">重置</el-button>
        </el-form-item>
      </el-form>

      <vxe-table border="inner" auto-resize resizable height="400px" :loading="loading" ref="auditData"
        show-header-overflow show-overflow="title" highlight-hover-row @checkbox-change="selectionChangeHandle"
        :menu-config="{}" :print-config="{}" :sort-config="{ remote: true }" :data="dataList"
        :row-config="{ isCurrent: true }" :radio-config="{ trigger: 'row' }">

        <vxe-column type="seq" width="60" title="序号"></vxe-column>
        <vxe-column type="checkbox" width="60px"></vxe-column>
        <vxe-column min-width="230" align="center" title="项目名称" field="projectName"></vxe-column>
        <vxe-column min-width="160" align="center" title="报告号" field="reportNo"></vxe-column>
        <vxe-column min-width="160" align="center" title="开票申请编号" field="no"></vxe-column>
        <vxe-column min-width="160" align="center" title="发票号" field="number"></vxe-column>
        <vxe-column min-width="160" align="center" title="开票金额（元）" field="account"></vxe-column>
        <vxe-column min-width="160" align="center" title="开票申请人" field="billingPeople"></vxe-column>
        <vxe-column min-width="160" align="center" title="开票时间" field="billingDate"></vxe-column>

      </vxe-table>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeReport" icon="el-icon-circle-close">关闭</el-button>
        <el-button type="primary" @click="getData()" icon="el-icon-circle-check"
          :disabled="this.searchForm.totalAudit == 0 ? true : false" v-noMoreClick>({{ this.searchForm.totalAudit
          }})确定</el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog title="关联报告信息" :close-on-click-modal="false" draggable width="1100px" height="500px" @close="close1"
    append-to-body :visible.sync="reportVisible" v-if="reportVisible" v-model="reportVisible">
    <div style="height: calc(100% - 80px);">
      <vxe-table border="inner" auto-resize resizable height="400px" :loading="loading" ref="clientTable"
        show-header-overflow show-overflow highlight-hover-row :menu-config="{}" :print-config="{}"
        :sort-config="{ remote: true }" :data="reportData" :row-config="{ isCurrent: true }"
        :radio-config="{ trigger: 'row' }">
        <vxe-column type="seq" width="60" title="序号"></vxe-column>
        <vxe-column type="radio" width="60px"></vxe-column>
        <vxe-column min-width="230" align="center" title="项目名称" field="projectName"></vxe-column>
        <vxe-column min-width="160" align="center" title="报告号" field="reportNo"></vxe-column>
        <vxe-column min-width="160" align="center" title="审计收费(元)" field="auditFees">
        </vxe-column>
        <vxe-column min-width="160" align="center" title="创建人" field="loginName"></vxe-column>
        <vxe-column min-width="160" align="center" title="创建时间" field="createTime">
        </vxe-column>

      </vxe-table>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close1()" icon="el-icon-circle-close">关闭</el-button>
        <el-button type="primary" v-if="method != 'view'" @click="getClient1()" icon="el-icon-circle-check"
          v-noMoreClick>确定</el-button>
      </span>
    </template>
  </el-dialog>



</template>

<script>
import UpLoadComponent from '@/views/common/UpLoadComponentV3.1'
import ProjectReportArchiveService from '@/api/cw/projectRecords/ProjectReportArchiveService'
import ProjectRecordsChooseCom from '@/views/cw/projectRecords/ProjectRecordsChooseCom'
import WorkClientChooseByProjectCom from '@/views/cw/projectReportArchive/WorkClientChooseByProjectCom'
import ReportChooseByProjectCom from '@/views/cw/projectReportArchive/ReportChooseByProjectCom'
import officeService from '@/api/sys/officeService'
import processService from '@/api/flowable/processService'
import ProjectRecordsService from "../../../api/cw/projectRecords/ProjectRecordsService";
import taskService from "@/api/flowable/taskService.js";
export default {
  props: {
    businessId: {
      type: String,
      default: ''
    },
    formReadOnly: {
      type: Boolean,
      default: false
    },
    status: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      reportVisible: false,
      dialogTableVisible: false,
      title: '',
      method: '',
      loading: false,
      inputForm: {
        id: '',
        createDate: '',
        createBy: {
          id: '',
          name: ''
        },
        remarks: '',
        projectId: '',
        name: '',
        auditedUnits: '',
        reportNum: '',
        papersNum: '',
        auditMoney: '',
        year: '',
        number: '',
        isNumber: '',
        auditDate: '',
        procInsId: '',
        processDefinitionId: '',
        status: '',
        workAttachmentDtoList: [],
        cwProjectReportArchiveReportDTOList: [],
        cwProjectRecordsDTO: {
          remarks: '',
          projectNumber: '',
          projectName: '',
          officeId: '',
          projectMoney: '',
          auditYear: '',
          planStartDate: '',
          planEndDate: '',
          projectMasterId: '',
          projectLeaderId: '',
          procInsId: '',
          processDefinitionId: '',
          status: '',
          contractId: ''
        },
        connectReport: '',
        connectReportId: '',
        auditedUnitsName: '',
        fileNumber: '',
        reportDate: '',
        reportNo: '',
        signatureAnnotator1: '',
        signatureAnnotator1Name: '',
        signatureAnnotator2: '',
        signatureAnnotator2Name: '',
        reportCreateName: '',
        reportId: '',
        reportRemarks: '',
        procDefId: '',
        procDefKey: '',
        formTitle: '',
        title: ''
      },
      keyWatch: '',
      activeName: 'files',
      tableKeyReport: '',
      dataList: [],
      searchForm: {
        projectName: '',
        reportNo: '',
        no: '',
        number: '',
        billingPeople: '',
        account: '',
        billingDate: '',
        totalAudit: ''
      },
      accountTotal: '',
      reportData: [],
      reportInno: {
        projectName: '',
        reportNo: '',
        auditFees: '',
        createTime: '',
        loginName: ''
      },
      selectRecord: [],
      isShow: false,


    }
  },
  projectReportArchiveService: null,
  created() {
    this.projectReportArchiveService = new ProjectReportArchiveService()
  },
  computed: {
    bus: {
      get() {
        this.$refs.uploadComponent.setDividerName('附件', false)
        return this.businessId
      },
      set(val) {
        this.businessId = val
      }
    },

  },
  watch: {
    'keyWatch': {
      handler(newVal) {
        if (this.commonJS.isNotEmpty(this.bus)) {
          this.init('', this.bus)
        } else {
          this.$nextTick(() => {
            this.$refs.inputForm.resetFields()
          })
        }
      }
    },
    'loading': {
      handler(newVal) {
        console.log(newVal)
        this.$emit('changeLoading', newVal)
        this.$refs.uploadComponent.changeLoading(newVal)
      },

    }
  },
  components: {
    UpLoadComponent,
    ProjectRecordsChooseCom,
    WorkClientChooseByProjectCom,
    ReportChooseByProjectCom,
  },
  methods: {
    getKeyWatch(keyWatch) {
      this.keyWatch = keyWatch
    },
    async init(method, id) {
      this.activeName = 'files'
      this.projectReportArchiveService = new ProjectReportArchiveService()
      this.method = method
      this.inputForm = {
        id: '',
        createDate: '',
        createBy: {
          id: '',
          name: this.$store.state.user.name
        },
        remarks: '',
        projectId: '',
        name: '',
        auditedUnits: '',
        reportNum: '',
        papersNum: '',
        auditMoney: '',
        year: '',
        number: '',
        isNumber: '',
        auditDate: '',
        procInsId: '',
        processDefinitionId: '',
        status: '',
        workAttachmentDtoList: [],
        cwProjectReportArchiveReportDTOList: [],
        cwProjectRecordsDTO: {
          remarks: '',
          projectNumber: '',
          projectName: '',
          officeId: '',
          projectMoney: '',
          auditYear: '',
          planStartDate: '',
          planEndDate: '',
          projectMasterId: '',
          projectLeaderId: '',
          procInsId: '',
          processDefinitionId: '',
          status: '',
          contractId: ''
        },
        auditedUnitsName: '',
        connectReport: '',
        fileNumber: '',
        reportDate: '',
        reportNo: '',
        signatureAnnotator1: '',
        signatureAnnotator1Name: '',
        signatureAnnotator2: '',
        signatureAnnotator2Name: '',
        reportCreateName: '',
        reportId: '',
        reportRemarks: '',
        procDefId: '',
        procDefKey: '',
        formTitle: '',
        title: '',
      }
      this.selectRecord = []
      this.inputForm.id = id
      this.loading = false
      this.$nextTick(async () => {
        console.log(this.inputForm.id)
        this.$refs.inputForm.resetFields()
        this.loading = true
        const data = await this.projectReportArchiveService.queryById(this.inputForm.id)
        console.log(data)
        this.$refs.uploadComponent.clearUpload()
        this.inputForm = this.recover(this.inputForm, data)
        this.inputForm = JSON.parse(JSON.stringify(this.inputForm))
        if (this.commonJS.isEmpty(this.inputForm.workAttachmentDtoList)) {
          this.inputForm.workAttachmentDtoList = []
        }
        if (this.commonJS.isEmpty(this.inputForm.createDate)) {
          this.inputForm.createDate = this.moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
        }
        if (this.commonJS.isEmpty(this.inputForm.createBy.name)) {
          this.inputForm.createBy.name = this.$store.state.user.name
        }
        if (this.commonJS.isEmpty(this.inputForm.officeId)) {
          this.inputForm.officeId = this.$store.state.user.office.id
        }
        if (this.commonJS.isEmpty(this.inputForm.papersNum)) {
          this.inputForm.papersNum = 0
        }
        if (this.commonJS.isEmpty(this.inputForm.reportNum)) {
          this.inputForm.reportNum = 0
        }
        if (this.status === 'audit' || this.status === 'taskFormDetail') {
          this.method = 'view'
        }
        if (this.inputForm.auditMoney === '0') {
          this.isShow = true
          console.log('connectReport', this.inputForm.connectReport)
        }

        if (!this.commonJS.isEmpty(data.status) && data.status == 2) {
          //将原有审核时间进行处理并同步
          //通过reportId获取上一次审核通过时间
          const hiData = await this.projectReportArchiveService.getLastAuditDateByReportId(this.inputForm.reportId);
          if (!this.commonJS.isEmpty(hiData.auditDate)) {
            try {
              await this.$confirm('该报告之前已经归档并作废，是否沿用原有归档审核时间？上次归档时间为：' + hiData.auditDate, '确认信息', {
                distinguishCancelAndClose: true,
                confirmButtonText: '是',
                cancelButtonText: '否'
              });
              this.inputForm.auditDate = hiData.auditDate;
            } catch (action) {
              //将当前时间进行放入
              this.inputForm.auditDate = this.moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
            }
            this.inputForm.number = hiData.number
            this.inputForm.isNumber = hiData.isNumber
          } else {
            this.inputForm.auditDate = this.moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
          }
        }

        this.$refs.uploadComponent.newUpload(this.method, this.inputForm.workAttachmentDtoList, 'cw_project_archive', null, null, null, null, false)
        this.loading = false

      })
    },
    saveForm(callback) {
      if (this.commonJS.isNotEmpty(this.inputForm.id)) {
        this.projectReportArchiveService.queryById(this.inputForm.id).then((data) => {
          if (data.status !== '0' && data.status !== '1' && data.status !== '3') { // 审核状态不是“未发起”或“暂存”，就弹出提示
            taskService.getTaskAuditUsersByprocInstId(this.$route.query.procInsId).then(res => {
              let userInfo = this.$TOOL.data.get("USER_INFO");
              // 如果审核人是本人的话，则跳过数据状态的限制
              if (res.includes(userInfo.id)) {
                this.doSubmit('save', callback)
              } else {
                this.loading = false;
                let errMsg = '任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在'
                this.$message.error(errMsg)
                throw new Error(errMsg)
              }
            }).catch(err => {
              this.loading = false;
              this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在');
            });
          } else {
            this.doSubmit('save', callback)
          }
        })
      } else {
        this.doSubmit('save', callback)
      }
    },
    startForm(callback) {
      if (this.commonJS.isNotEmpty(this.inputForm.id)) {
        this.projectReportArchiveService.queryById(this.inputForm.id).then((data) => {
          if (data.status !== '0' && data.status !== '1' && data.status !== '3') { // 审核状态不是“未发起”或“暂存”或“撤回”，就弹出提示
            this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
            throw new Error()
          } else {
            this.doSubmit('start', callback)
          }
        })
      } else {
        this.doSubmit('start', callback)
      }
    },
    async agreeForm(callback) {
      await this.projectReportArchiveService.queryById(this.inputForm.id).then((data) => {
        if (data.status !== '2') { // 审核状态不是“待审核”，就弹出提示
          taskService.getTaskAuditUsersByprocInstId(this.$route.query.procInsId).then(res => {
            let userInfo = this.$TOOL.data.get("USER_INFO");
            // 如果审核人是本人的话，则跳过数据状态的限制
            if (res.includes(userInfo.id)) {
              this.doSubmit('agree', callback)
            } else {
              this.loading = false;
              let errMsg = '任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在'
              this.$message.error(errMsg)
              throw new Error()
            }
          }).catch(err => {
            this.loading = false;
            this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在');
          });
        } else {
          this.doSubmit('agree', callback)
        }
      })
    },
    reapplyForm(callback) {
      this.projectReportArchiveService.queryById(this.inputForm.id).then((data) => {
        if (data.status !== '4') { // 审核状态不是“驳回”，就弹出提示
          taskService.getTaskAuditUsersByprocInstId(this.$route.query.procInsId).then(res => {
            let userInfo = this.$TOOL.data.get("USER_INFO");
            // 如果审核人是本人的话，则跳过数据状态的限制
            if (res.includes(userInfo.id)) {
              this.doSubmit('reapply', callback)
            } else {
              this.loading = false;
              let errMsg = '任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在'
              this.$message.error(errMsg)
              throw new Error(errMsg)
            }
          }).catch(err => {
            this.loading = false;
            this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在');
          });

        } else {
          this.doSubmit('reapply', callback)
        }
      })
    },
    // 表单提交
    doSubmit(status, callback) {
      if (status === 'save') {
        // 暂存
        this.inputForm.status = '1'
        this.loading = true
        if (this.$refs.uploadComponent.checkProgress()) {
          this.loading = false
          return
        }
        this.$refs.uploadComponent.getDataList().then((list) => {
          // list为返回数据
          this.inputForm.workAttachmentDtoList = list
        })
        this.inputForm.createDate = this.moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
        this.projectReportArchiveService.saveForm(this.inputForm).then((data) => {
          this.inputForm.id = data.businessId
          callback(data.businessTable, data.businessId, this.inputForm)
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
        return
      } else if (status === 'start') {
        // 送审  待审核
        this.inputForm.status = '2'
      } else if (status === 'reapply') {
        this.inputForm.status = '2'
      }
      this.$refs['inputForm'].validate((valid) => {
        if (valid) {
          this.loading = true
          if (this.$refs.uploadComponent.checkProgress()) {
            this.loading = false
            throw new Error()
          } else {
            if (status === 'agree') {
              // 审核同意
              this.inputForm.auditDate = this.moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
              // this.inputForm.agreeUserId = this.$store.state.user.id
              this.inputForm.status = '5'
              if (this.inputForm.isNumber !== this.inputForm.number) {
                this.$message.error('“案卷号”与“确认案卷号”不一致，请重新填写')
                this.loading = false
                throw new Error('“案卷号”与“确认案卷号”不一致，请重新填写')
              }
            }
            if (this.commonJS.isEmpty(this.inputForm.createDate)) {
              this.inputForm.createDate = this.moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
            }
            this.$refs.uploadComponent.getDataList().then((list) => {
              // list为返回数据
              this.inputForm.workAttachmentDtoList = list
              list.forEach(item => {
                if (this.commonJS.isEmpty(item.fileType)) {
                  this.$message.error('附件中的文件类型不可以为空')
                  this.loading = false
                  throw new Error('附件中的文件类型不可以为空')
                }
              })
              this.projectReportArchiveService.saveForm(this.inputForm).then((saveDate) => {
                officeService.queryById(this.$store.state.user.office.id).then((byId) => {
                  // 判断当前人的所属部门是否为苏州分部，根据部门的机构编码(szfb)来判断是不是苏州分部
                  if (byId.code === 'szfb') { // 当前人的所属部门为苏州分部
                    processService.getByName('会计-项目报告归档-苏州分部').then((data) => {
                      if (!this.commonJS.isEmpty(data.id)) {
                        if (status === 'start' || status === 'reapply') {
                          if (status === 'start') {
                            this.inputForm.procDefId = data.id
                            this.inputForm.procDefKey = data.key
                          }
                          let processTitle = `${this.$store.state.user.name} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了 ${this.inputForm.reportNo} - ${this.inputForm.cwProjectRecordsDTO.projectName} ` + `[会计-项目报告归档-苏州分部]`
                          this.inputForm.formTitle = `发起流程【会计-项目报告归档-苏州分部】`
                          this.inputForm.title = processTitle
                        }
                        callback(saveDate.businessTable, saveDate.businessId, this.inputForm)
                        this.loading = false
                      }
                    })
                  } else {
                    processService.getByName('会计-项目报告归档').then((data) => {
                      if (!this.commonJS.isEmpty(data.id)) {
                        if (status === 'start' || status === 'reapply') {
                          if (status === 'start') {
                            this.inputForm.procDefId = data.id
                            this.inputForm.procDefKey = data.key
                          }
                          let processTitle = `${this.$store.state.user.name} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了 ${this.inputForm.reportNo} - ${this.inputForm.cwProjectRecordsDTO.projectName} ` + `[会计-项目报告归档]`
                          this.inputForm.formTitle = `发起流程【会计-项目报告归档】`
                          this.inputForm.title = processTitle
                        }
                        callback(saveDate.businessTable, saveDate.businessId, this.inputForm)
                        this.loading = false
                      }
                    })
                  }
                })
              }).catch(() => {
                this.loading = false
                throw new Error()
              })
            })
          }
        }
      })
    },
    async updateStatusById(type, callback) {
      this.loading = true
      if (this.$refs.uploadComponent.checkProgress()) {
        this.loading = false
        throw new Error()
      } else {
        if (type === 'reject' || type === 'reback') {
          await this.projectReportArchiveService.queryById(this.inputForm.id).then((data) => {
            if (data.status !== '2') { // status的值不等于“审核中”就弹出提示
              taskService.getTaskAuditUsersByprocInstId(this.$route.query.procInsId).then(res => {
                let userInfo = this.$TOOL.data.get("USER_INFO");
                // 如果审核人是本人的话，则跳过数据状态的限制
                if (res.includes(userInfo.id)) {
                  if (type === 'reject') {
                    if (this.inputForm.isNumber !== this.inputForm.number) {
                      this.$message.error('“案卷号”与“确认案卷号”不一致，请重新填写')
                      this.loading = false
                      throw new Error('“案卷号”与“确认案卷号”不一致，请重新填写')
                    } else {
                      // 驳回
                      let _this = this
                      const wait = function () {
                        return new Promise(function (resolve, reject) {
                          _this.inputForm.status = '4'
                          _this.loading = true
                          if (_this.$refs.uploadComponent.checkProgress()) {
                            _this.loading = false
                            reject(new Error())
                          }
                          _this.$refs.uploadComponent.getDataList().then((list) => {
                            // list为返回数据
                            _this.inputForm.workAttachmentDtoList = list
                          })
                          resolve()
                        })
                      }
                      wait().then(() => {
                        this.projectReportArchiveService.saveForm(this.inputForm).then((data) => {
                          callback()
                          this.loading = false
                        }).catch(() => {
                          this.loading = false
                        })
                      }).catch(() => {
                        this.loading = false
                      })
                    }
                  }
                  if (type === 'reback') {
                    // 撤回
                    let param = { status: '3', id: this.inputForm.id }
                    this.projectReportArchiveService.updateStatusById(param).then(() => {
                      this.loading = false
                      callback()
                    })
                  }
                } else {
                  this.loading = false
                  this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
                  throw new Error()
                }
              }).catch(err => {
                this.loading = false;
                this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在');
              });
            } else {
              if (type === 'reject') {
                if (this.inputForm.isNumber !== this.inputForm.number) {
                  this.$message.error('“案卷号”与“确认案卷号”不一致，请重新填写')
                  this.loading = false
                  throw new Error('“案卷号”与“确认案卷号”不一致，请重新填写')
                } else {
                  // 驳回
                  let _this = this
                  const wait = function () {
                    return new Promise(function (resolve, reject) {
                      _this.inputForm.status = '4'
                      _this.loading = true
                      if (_this.$refs.uploadComponent.checkProgress()) {
                        _this.loading = false
                        reject(new Error())
                      }
                      _this.$refs.uploadComponent.getDataList().then((list) => {
                        // list为返回数据
                        _this.inputForm.workAttachmentDtoList = list
                      })
                      resolve()
                    })
                  }
                  wait().then(() => {
                    this.projectReportArchiveService.saveForm(this.inputForm).then((data) => {
                      callback()
                      this.loading = false
                    }).catch(() => {
                      this.loading = false
                    })
                  }).catch(() => {
                    this.loading = false
                  })
                }
              }
              if (type === 'reback') {
                // 撤回
                let param = { status: '3', id: this.inputForm.id }
                this.projectReportArchiveService.updateStatusById(param).then(() => {
                  this.loading = false
                  callback()
                })
              }
            }
          })
        } else if (type === 'hold') {
          this.projectReportArchiveService.queryById(this.inputForm.id).then((data) => {
            if (data.status !== '4') { // status的值不等于“驳回”就弹出提示
              this.loading = false
              this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
              throw new Error()
            } else {
              // 终止
              let param = { status: '1', id: this.inputForm.id }
              this.projectReportArchiveService.updateStatusById(param).then(() => {
                this.loading = false
                callback()
              })
            }
          })
        }
      }
    },
    close() {
      this.inputForm = {
        id: '',
        createDate: '',
        createBy: {
          id: '',
          name: ''
        },
        remarks: '',
        projectId: '',
        name: '',
        auditedUnits: '',
        reportNum: '',
        papersNum: '',
        auditMoney: '',
        year: '',
        number: '',
        isNumber: '',
        auditDate: '',
        procInsId: '',
        processDefinitionId: '',
        status: '',
        workAttachmentDtoList: [],
        cwProjectReportArchiveReportDTOList: [],
        cwProjectRecordsDTO: {
          remarks: '',
          projectNumber: '',
          projectName: '',
          officeId: '',
          projectMoney: '',
          auditYear: '',
          planStartDate: '',
          planEndDate: '',
          projectMasterId: '',
          projectLeaderId: '',
          procInsId: '',
          processDefinitionId: '',
          status: '',
          contractId: ''
        },
        auditedUnitsName: '',
        connectReport: '',
        fileNumber: '',
        reportDate: '',
        reportNo: '',
        signatureAnnotator1: '',
        signatureAnnotator1Name: '',
        signatureAnnotator2: '',
        signatureAnnotator2Name: '',
        reportCreateName: '',
        reportId: '',
        reportRemarks: '',
        procDefId: '',
        procDefKey: '',
        formTitle: '',
        title: ''
      }
      this.$refs.uploadComponent.clearUpload()
      this.$refs.inputForm.resetFields()
      this.inputForm.reportId = ''
      this.inputForm.projectId = ''
    },
    tabHandleClick(event) {
      // console.log(event)
    },
    // 新增
    // eslint-disable-next-line no-dupe-keys
    insertEvent(type) {
    },
    // 删除
    removeEvent(row, rowIndex, type) {
      if (type === 'report') {
        this.$refs.reportTable.remove(row)
        this.inputForm.cwProjectReportArchiveReportDTOList.splice(rowIndex, 1)
      }
    },
    // 打开项目选择组件
    openChooseProject(event) {
      if (this.commonJS.isNotEmpty(this.inputForm.auditedUnitsName) || this.commonJS.isNotEmpty(this.inputForm.auditedUnits) || this.commonJS.isNotEmpty(this.inputForm.cwProjectReportArchiveReportDTOList)) {
        this.$confirm(`重新选择项目会清空"被审计单位"以及"审计报告"的数据，是否继续？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$refs.projectRecordsChooseCom.init()
        }).catch(() => {
        })
      } else {
        this.$refs.projectRecordsChooseCom.init()
      }
    },
    // 项目选择结果获取
    getProject(row) {
      this.inputForm.projectId = row.id
      this.inputForm.cwProjectRecordsDTO.projectName = row.projectName
      this.inputForm.cwProjectRecordsDTO.projectNumber = row.projectNumber
      this.inputForm.cwProjectRecordsDTO.projectMasterId = row.projectMasterId
      this.inputForm.auditedUnitsName = ''
      this.inputForm.auditedUnits = ''
      this.inputForm.cwProjectReportArchiveReportDTOList = []
    },
    // 打开被审计单位选择组件
    openChooseClient() {
      this.$refs.workClientChooseByProjectCom.init(this.inputForm.projectId)
    },
    // 被审计单位选择结果获取
    getClient(row) {
      this.inputForm.auditedUnitsName = row.name
      this.inputForm.auditedUnits = row.id
    },
    // 打开审计报告选择组件
    openReportChoose() {
      this.$refs.reportChooseByProjectCom.init(this.inputForm.projectId, this.inputForm.id)
    },
    // 审计报告选择结果获取
    getReport(row) {
      if (this.commonJS.isNotEmpty(row)) {
        if (this.commonJS.isNotEmpty(row.reportId)) {
          this.projectReportArchiveService.findReportUse(row.reportId).then((data) => {
            if (data === false) {
              this.inputForm.reportDate = row.reportDate
              this.inputForm.reportNo = row.reportNo
              this.inputForm.signatureAnnotator1 = row.signatureAnnotator1
              this.inputForm.signatureAnnotator1Name = row.signatureAnnotator1Name
              this.inputForm.signatureAnnotator2 = row.signatureAnnotator2
              this.inputForm.signatureAnnotator2Name = row.signatureAnnotator2Name
              this.inputForm.reportCreateName = row.createName
              this.inputForm.reportId = row.reportId
            } else {
              this.$message.error('此报告正在归档中或已归档，请重新选择')
            }
          })
        }
      }
    },
    openInvoice(id) {
      this.$nextTick(() => {
        this.getReportList(id)
        // this.$refs.searchForm.resetFields()
        this.searchForm.totalAudit = 0
      })
      this.dialogTableVisible = true

    },
    getReportList() {
      console.log(this.inputForm.id)
      ProjectRecordsService.getReportById({
        id: this.inputForm.id,
        cwProjectRecordsDTO: this.searchForm
      }).then((data) => {
        this.dataList = data
      })
    },
    resetSearch() {
      this.dataListAllSelections = []
      this.$refs.searchForm.resetFields()
      this.getReportList(this.inputForm.id)
    },
    getData() {
      this.accountTotal = this.countTotal(this.selectRecord, 'account')
      this.dialogTableVisible = false
      this.inputForm.auditMoney = this.accountTotal
    },
    countTotal: function (arr, keyName) {
      let total1 = 0
      let number = 0;
      for (var i = 0; i < arr.length; i++) {
        number = parseFloat(arr[i].account);
        total1 = number + total1;
      }
      return total1
    },
    closeReport() {
      this.dialogTableVisible = false
      this.inputForm.auditMoney = ''
    },
    selectionChangeHandle() {
      this.selectRecord = this.$refs.auditData.getCheckboxRecords()
      this.searchForm.totalAudit = this.countTotal(this.selectRecord, 'account')
    },
    getReportByProjectId(id, projectId) {
      this.loading = true
      ProjectRecordsService.getReportByProjectId(id, projectId).then(data => {
        console.log(data)
        this.reportData = data
        this.loading = false
      })
    },
    openReport() {
      this.reportVisible = true
      this.$nextTick(() => {
        this.getReportByProjectId(this.inputForm.id, this.inputForm.projectId)
      })
    },

    close1() {
      this.reportVisible = false
    },
    getClient1() {
      let row = this.$refs.clientTable.getRadioRecord()
      console.log(row)
      if (this.commonJS.isEmpty(row)) {
        this.$message.error('请选择一条数据')
        return
      }
      this.reportVisible = false
      this.inputForm.connectReport = row.reportNo
      this.inputForm.connectReportId = row.reportId
    },
    closeTable() {
      this.$refs.searchForm.resetFields()
      this.dialogTableVisible = false
    },
    inputMoney() {
      // if (/^0+$/.test(this.inputForm.auditMoney)) {
      // 	this.inputForm.auditMoney = "0";
      // }
      if (this.inputForm.auditMoney === '0') {
        this.isShow = true
      } else {
        this.isShow = false
      }
    }
  }
}
</script>
<style scoped>
/deep/ .el-input-number .el-input__inner {
  text-align: left;
}
</style>
