<template>
  <section>
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item :label="$t('he-tong-lie-biao')" class="toolbar_formitem_n1"></el-form-item>
        <!-- 合同编号/名称 -->
        <el-form-item>
          <div style="display: flex;align-items: center;height: 40px;">
            <el-input v-model="keyword" class="input-with-select" @keyup.enter.native="searchFilter" :placeholder="searchField == 1 ? $t('qing-shu-ru-he-tong-bian-hao') : $t('qing-shu-ru-he-tong-ming-cheng')" clearable size="small">
              <el-select slot="prepend" v-model="searchField" :placeholder="$t('defaultText.pleaseChoose')" style="width:120px">
                <el-option :label="$t('he-tong-ming-cheng')" :value="0"></el-option>
                <el-option :label="$t('contractno')" :value="1"></el-option>
              </el-select>
              <el-button slot="append" @click="searchFilter" icon="el-icon-search"></el-button>
            </el-input>
          </div>
        </el-form-item>
        <!-- 合同类型 -->
        <el-form-item>
          <span style="margin-left:5px;margin-right:5px;color:#606266;">{{ $t('he-tong-lei-xing') }}</span>
          <el-select v-model="typeName" style="width:120px;" :placeholder="$t('defaultText.pleaseChoose')" @change="searchFilter" size="small" clearable>
            <el-option v-for="item in typeList" :key="item.id" :label="item.typeName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- 状态 -->
        <el-form-item>
          <span style="margin-left:5px;margin-right:5px;color:#606266;">{{$t('state.states')}}</span>
          <el-select v-model="status" style="width:120px;" :placeholder="$t('defaultText.pleaseChoose')" @change="searchFilter" size="small" clearable>
            <el-option v-for="item,index in statusList" :key="item.label" :label="item.label" :value="index"></el-option>
          </el-select>
        </el-form-item>
        <!-- 创建时间 -->
        <!-- <el-form-item>
          <span style="margin-left:5px;margin-right:5px;color:#606266;">{{$t('creationtime')}}</span>
          <el-date-picker
            style="width:240px;"
            v-model="dateArray"
            type="daterange"
            size="small"
            range-separator="-"
            :start-placeholder="$t('interval')"
            :end-placeholder="$t('interval')"
            value-format="yyyy-MM-dd"
            clearable
            @change="searchFilter"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <span style="margin-left:5px;margin-right:5px;color:#606266;">{{ $t('xia-bi-hui-kuan-ri-qi') }}</span>
          <el-date-picker
            style="width:240px;"
            v-model="paymentDate"
            type="daterange"
            size="small"
            :start-placeholder="$t('interval')"
            :end-placeholder="$t('interval')"
            value-format="yyyy-MM-dd"
            clearable
            @change="searchFilter"
          ></el-date-picker>
        </el-form-item> -->
        <el-form-item>
          <span style="margin-left:5px;margin-right:5px;color:#606266;">对方单位</span>
          <el-input v-model.trim="customerOrgs" placeholder="请输入" size="small" style="width: 150px" clearable @input="onCustomerOrgsInput"></el-input>
        </el-form-item>
        <el-form-item>
          <span style="margin-left:5px;margin-right:5px;color:#606266;">合同状态</span>
          <el-select v-model="finishStatuss" placeholder="请选择" style="width:120px" size="small" clearable @change="searchFilter">
            <el-option label="履约中" :value="1"></el-option>
            <el-option label="履约完成" :value="2"></el-option>
          </el-select>
        </el-form-item>
        


        <el-form-item style="float:right;">
          <el-dropdown>
            <el-link type="primary" :underline="false">{{$t('viewmore')}}<i class="el-icon-arrow-down el-icon--right"></i></el-link>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-if="permissions.contractType" @click.native="typeEdit()"><el-link type="primary" :underline="false" >{{$t('bian-ji') + $t('types')}}</el-link></el-dropdown-item>
              <el-dropdown-item v-if="permissions.contractType" @click.native="typeEditTwo()"><el-link type="primary" :underline="false" >二级分类</el-link></el-dropdown-item>
              <el-dropdown-item v-if="permissions.contractImport" @click.native="importDialog = true"><el-link type="primary" :underline="false" >{{$t('dao-ru')}}</el-link></el-dropdown-item>
              <el-dropdown-item v-if="permissions.contractExport" @click.native="exportContract()"><el-link type="primary" :underline="false" >{{$t('export.export')}}</el-link></el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-form-item>
        <el-form-item style="float:right;" v-if="permissions.contractNew">
          <el-link type="primary" :underline="false" @click="newlyAdd()">{{ $t('xin-zeng-he-tong') }}</el-link>
        </el-form-item>
      </el-form>
    </el-col>

    <el-table :data="contractList" v-loading="listLoading" :height="tableHeight" border highlight-current-row>
      <el-table-column type="index" width="50"></el-table-column>
      <el-table-column prop="name" :label="$t('he-tong-ming-cheng')" min-width="190"></el-table-column>
      <el-table-column prop="number" :label="$t('contractno')" min-width="190"></el-table-column>
      <el-table-column prop="typeName" label="合同类型" min-width="190"></el-table-column>
      <el-table-column prop="secTypeName" label="二级分类" min-width="190"></el-table-column>
      <el-table-column prop="customerOrg" label="对方单位" min-width="190"></el-table-column>
      <el-table-column prop="status" :label="$t('state.states')" min-width="120" align="center">
        <template slot-scope="scope">
          <span :style="statusList[scope.row.status].color">{{statusList[scope.row.status].label}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="customerContact" label="对方联系人" min-width="190"></el-table-column>
      <el-table-column prop="customerPhone" label="对方联系电话" min-width="190"></el-table-column>
      <el-table-column prop="useDepartment" label="使用部门" min-width="190"></el-table-column>
      <el-table-column prop="fundsSource" label="经费来源" min-width="190">
        <template slot-scope="scope">
          <span v-if="scope.row.fundsSource == 1">科研</span>
          <span v-if="scope.row.fundsSource == 2">其他（专项等）</span>
        </template>
      </el-table-column>
      <el-table-column prop="undertaker" label="合同承办人" min-width="190"></el-table-column>
      <el-table-column prop="agent" label="委托代理人" min-width="190"></el-table-column>
      <el-table-column prop="signDate" label="签订日期" min-width="190"></el-table-column>
      <el-table-column prop="startDate" label="合同生效日期" min-width="190"></el-table-column>
      <el-table-column prop="endDate" label="合同终止日期" min-width="190"></el-table-column>
      <el-table-column prop="filingsDate" label="备案日期" min-width="190"></el-table-column>
      <el-table-column prop="amounts" label="合同金额(元)/含税价" min-width="190"></el-table-column>
      <el-table-column prop="taxRate" label="增值税税率" min-width="190">
        <template slot-scope="scope">
          <span v-if="scope.row.taxRate">{{ scope.row.taxRate || 0 }} %</span>
        </template>
      </el-table-column>
      <el-table-column prop="amountsNoTax" label="合同金额(元)/不含税价" min-width="190"></el-table-column>
      <el-table-column prop="isAmountFixed" label="是否固定金额" min-width="190">
        <template slot-scope="scope">
          <span>{{scope.row.isAmountFixed?'是':'否'}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="currency" label="币种" min-width="190"></el-table-column>
      <el-table-column prop="finishStatus" label="合同状态(是否结清)" min-width="190">
        <template slot-scope="scope">
          <span v-if="scope.row.finishStatus == 1">履约中</span>
          <span v-if="scope.row.finishStatus == 2">履约完成</span>
        </template>
      </el-table-column>
      <el-table-column prop="remarks" label="备注" min-width="190"></el-table-column>
      <el-table-column prop="stampDutyItems" label="印花税税目" min-width="190"></el-table-column>
      <el-table-column prop="indate" :label="$t('creationtime')" min-width="130" align="center"></el-table-column>
      <el-table-column width="340" :label="$t('operation')" align="left" fixed="right">
        <template slot-scope="scope">
          <el-button v-if="permissions.contractView || permissions.contractManagement" size="mini" @click="lookover(scope.row)">{{$t('cha-kan')}}</el-button>
          <el-button v-if="permissions.contractManagement" size="mini" @click="editContract(scope.row)" type="primary">{{$t('bian-ji')}}</el-button>
          <el-button v-if="permissions.contractAudit && (scope.row.status == 1 || scope.row.status == 3)" size="mini" @click="process(scope.row,0)" type="success">{{$t('btn.through')}}</el-button>
          <el-button v-if="permissions.contractAudit && (scope.row.status == 1 || scope.row.status == 3)" size="mini" @click="processR(scope.row,2)" type="danger">{{$t('btn.rejected')}}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-col :span="24" class="toolbar">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[20 , 50 , 80 , 100]"
        :page-size="size"
        layout="total, sizes, prev, pager, next"
        :total="total"
        style="float:right;"
      ></el-pagination>
    </el-col>

    <el-dialog :title="dialogTitle + $t('he-tong')" :visible.sync="addDialog" v-if="addDialog" :close-on-click-modal="false" customClass="customWidth" width="1200px" :top="'7.8vh'">
      <div style="height: 72vh;overflow-y: auto;overflow-x: hidden;">
        <el-form ref="contractForm" :model="contractForm" label-width="160px" :rules="rules" class="contractForm">
          <el-form-item :label="$t('contractno')">
            <el-input v-model="contractForm.number" :disabled="contractForm.status == 0" :maxlength="50" style="width:260px;" show-word-limit :placeholder="$t('peaseenterthe')" clearable @input="searchProject"></el-input>
            <span style="margin-left:20px;">{{ $t('rselatedprojects') }}</span>
            <el-select v-model="contractForm.projectId" filterable clearable style="width:260px;" :disabled="contractForm.status == 0">
              <el-option v-for="item in projectList" :key="item.id" :label="item.projectName  + '\u3000' + (item.projectCode == null?'':item.projectCode)" :value="item.id" >
                    <span style="float: left; color: #8492a6; font-size: 13px;">{{ item.projectCode }}</span>
                    <span style="float: right;">{{ item.projectName }}</span>
                </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('he-tong-ming-cheng')" prop='name'>
            <el-input v-model="contractForm.name" :disabled="contractForm.status == 0" :maxlength="100" show-word-limit :placeholder="$t('peaseenterthe')" clearable></el-input>
          </el-form-item>
          <el-form-item :label="$t('he-tong-lei-xing')">
            <el-select v-model="contractForm.typeId" :disabled="contractForm.status == 0" :placeholder="$t('defaultText.pleaseChoose')" style="width:100%" @change="selectSecTypeId()">
              <el-option v-for="item in typeList" :key="item.id" :label="item.typeName" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="二级分类">
            <el-select v-model="contractForm.secTypeId" :disabled="contractForm.status == 0 || !contractForm.typeId":placeholder="$t('defaultText.pleaseChoose')" style="width:100%" @change="refreshDatas()">
              <el-option v-for="item in secondaryficationList" :key="item.id" :label="item.secTypeName" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item :label="$t('schedulestarttime')">
            <el-date-picker
            :disabled="contractForm.status == 0"
              v-model="contractForm.startDate"
              value-format="yyyy-MM-dd"
              type="date"
              :picker-options="{disabledDate: disabledStart}"
              :placeholder="$t('optiondate')">
            </el-date-picker>
            <span style="float:right;">{{$t('scheduleendtime')}}
            <el-date-picker
            :disabled="contractForm.status == 0"
              style="margin-left: 15px;"
              v-model="contractForm.endDate"
              value-format="yyyy-MM-dd"
              type="date"
              :picker-options="{disabledDate: disabledEnd}"
              :placeholder="$t('optiondate')">
            </el-date-picker>
            </span>
          </el-form-item> -->

          <el-form-item label="对方单位">
            <el-input v-model="contractForm.customerOrg" :disabled="contractForm.status == 0" :placeholder="$t('peaseenterthe')" clearable></el-input>
          </el-form-item>
          <el-form-item label="对方联系人">
            <el-input v-model="contractForm.customerContact" :disabled="contractForm.status == 0" :placeholder="$t('peaseenterthe')" clearable></el-input>
          </el-form-item>
          <el-form-item label="对方联系电话">
            <el-input v-model="contractForm.customerPhone" :disabled="contractForm.status == 0" :placeholder="$t('peaseenterthe')" clearable></el-input>
          </el-form-item>
          <el-form-item label="使用部门">
            <el-input v-model="contractForm.useDepartment" :disabled="contractForm.status == 0" :placeholder="$t('peaseenterthe')" clearable></el-input>
          </el-form-item>
          <el-form-item label="经费来源">
            <el-select v-model="contractForm.fundsSource" :disabled="contractForm.status == 0" placeholder="请选择">
              <el-option label="科研" value="1"></el-option>
              <el-option label="其他（专项等）" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="合同承办人">
            <el-input v-model="contractForm.undertaker" :disabled="contractForm.status == 0" :placeholder="$t('peaseenterthe')" clearable></el-input>
          </el-form-item>
          <el-form-item label="委托代理人">
            <el-input v-model="contractForm.agent" :disabled="contractForm.status == 0" :placeholder="$t('peaseenterthe')" clearable></el-input>
          </el-form-item>
          <el-form-item label="签订日期">
            <el-date-picker v-model="contractForm.signDate" :disabled="contractForm.status == 0" value-format="yyyy-MM-dd" type="date" :placeholder="$t('optiondate')"></el-date-picker>
          </el-form-item>
          <el-form-item label="合同生效日期">
            <el-date-picker v-model="contractForm.startDate" :disabled="contractForm.status == 0" value-format="yyyy-MM-dd" type="date" :placeholder="$t('optiondate')"></el-date-picker>
          </el-form-item>
          <el-form-item label="合同终止日期">
            <el-date-picker v-model="contractForm.endDate" :disabled="contractForm.status == 0" value-format="yyyy-MM-dd" type="date" :placeholder="$t('optiondate')"></el-date-picker>
          </el-form-item>
          <el-form-item label="备案日期">
            <el-date-picker v-model="contractForm.filingsDate" :disabled="contractForm.status == 0" value-format="yyyy-MM-dd" type="date" :placeholder="$t('optiondate')"></el-date-picker>
          </el-form-item>
          <el-form-item label="合同金额(元)/含税价">
            <el-input v-model="contractForm.amounts" :disabled="contractForm.status == 0 || !contractForm.isAmountFixed" :placeholder="$t('peaseenterthe')" @change="chgPayedAmount()" clearable>
              <span slot="prefix">￥</span>
            </el-input>
          </el-form-item>
          <el-form-item label="增值税税率">
            <el-input v-model="contractForm.taxRate" :disabled="contractForm.status == 0" :placeholder="$t('peaseenterthe')" clearable>
              <span slot="prefix">%</span>
            </el-input>
          </el-form-item>
          <el-form-item label="合同金额(元)/不含税价">
            <el-input v-model="contractForm.amountsNoTax" :disabled="contractForm.status == 0" :placeholder="$t('peaseenterthe')" clearable>
              <span slot="prefix">￥</span>
            </el-input>
          </el-form-item>
          <el-form-item label="是否固定金额">
            <el-select v-model="contractForm.isAmountFixed" :disabled="contractForm.status == 0" placeholder="请选择" @change="processingContractAmount()">
              <el-option label="是" :value="true"></el-option>
              <el-option label="否" :value="false"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="币种">
            <el-input v-model="contractForm.currency" :disabled="contractForm.status == 0" :placeholder="$t('peaseenterthe')" clearable></el-input>
          </el-form-item>
          <el-form-item label="合同状态(是否结清)">
            <el-select v-model="contractForm.finishStatus" :disabled="contractForm.status == 0" placeholder="请选择">
              <el-option label="履约中" :value="1"></el-option>
              <el-option label="履约完成" :value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="印花税税目">
            <el-input v-model="contractForm.stampDutyItems" :disabled="contractForm.status == 0" :placeholder="$t('peaseenterthe')" clearable></el-input>
          </el-form-item>
          <el-form-item :label="$t('bei-zhu')">
            <el-input v-model="contractForm.remarks" :disabled="contractForm.status == 0" :placeholder="$t('peaseenterthe')" type="textarea" :rows="3" clearable></el-input>
          </el-form-item>

          <el-form-item label="付款计划">
            <el-table :data="contractPaymentList" size="small" :key="Math.random()" :height="'300px'" show-header="false" style="margin-top:10px;">
              <el-table-column prop="isPayed" width="120">
                  <template slot-scope="scope">
                      <el-checkbox v-model="scope.row.isPayed" >已付款</el-checkbox>
                  </template>
                  <template slot="header" >
                      <span style="font-size:14px;font-weight:normal;">是否已付款</span>
                  </template>
              </el-table-column>
                <!-- <el-table-column prop="payDate" label="付款日期" width="150">
                  <template slot-scope="scope">
                      <div><el-date-picker type="date" v-model="scope.row.payDate" style="width:140px;" :placeholder="$t('optiondate')" value-format="yyyy-MM-dd" size="small"></el-date-picker></div>
                  </template>
                </el-table-column> -->
                <el-table-column prop="payedAmount" label="已付款金额（元）" width="160">
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.payedAmount" controls-position="right" @change="chgPayedAmount()" :min="0" size="small" :precision="2" :controls="false"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column prop="payType" label="付款类型" width="140">
                  <template slot-scope="scope">
                    <el-select v-model="scope.row.payType" placeholder="请选择" size="small">
                      <el-option label="预付" :value="1"></el-option>
                      <el-option label="报账" :value="0"></el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column prop="billNumber" label="凭证号" width="210">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.billNumber" :placeholder="$t('peaseenterthe')" clearable  size="small"></el-input>
                  </template>
                </el-table-column>
                <el-table-column v-if="contractForm.isAmountFixed" prop="pendingAmounts" label="待付款金额（元）" width="210">
                  <template slot-scope="scope">
                    {{ scope.row.pendingAmounts }}
                  </template>
                </el-table-column>
                <el-table-column width="80" fixed="right">
                    <template slot-scope="scope">
                        <el-button icon="el-icon-delete" size="mini" style="margin-left:10px;" @click.stop.native="deleteItem(scope.$index)"></el-button>
                    </template>
                    <template slot="header" >
                        <el-link type="primary" :underline="false" @click="addItem">{{ $t('addTian') }}</el-link>
                    </template>
                </el-table-column>
                  <!-- <el-table-column prop="isPayed" >
                      <template slot-scope="scope">
                          <el-checkbox v-model="scope.row.isPayed" >{{ $t('yi-hui-kuan') }}</el-checkbox>
                      </template>
                      <template slot="header" >
                          <span style="font-size:14px;font-weight:normal;">{{ $t('shi-fou-yi-hui-kuan') }}</span>
                      </template>
                  </el-table-column>
                  <el-table-column prop="payDate"  :label="$t('hui-kuan-ri-qi')" width="210">
                      <template slot-scope="scope">
                          <div><el-date-picker type="date" v-model="scope.row.payDate" style="width:200px;" :placeholder="$t('optiondate')" value-format="yyyy-MM-dd"></el-date-picker></div>
                      </template>
                  </el-table-column>
                  
                  <el-table-column prop="amount" :label="$t('hui-kuan-jin-e')">
                      <template slot-scope="scope">
                        <el-input v-model="scope.row.amount" :id="'payment_amount'+scope.$index" :placeholder="$t('peaseenterthe')" maxlength="10" clearable>
                          <span slot="prefix">￥</span>
                        </el-input>
                      </template>
                  </el-table-column>
                  <el-table-column  width="80">
                      <template slot-scope="scope">
                          <el-button icon="el-icon-delete" size="mini" style="margin-left:10px;" @click.stop.native="deleteItem(scope.$index)"></el-button>
                      </template>
                      <template slot="header" >
                          <el-link type="primary" :underline="false" @click="addItem">{{ $t('addTian') }}</el-link>
                      </template>
                  </el-table-column> -->
              </el-table>
          </el-form-item>
          
          <el-form-item label-width="0" class="contractFiles">
            <div class="contractFiles_title">{{ $t('fu-jian') }}
              <el-upload style="float:right;margin-right:5%;" ref="uploadFile" action="#" :http-request="httpRequest" :on-change="fileChange" :auto-upload="false" :show-file-list="false">
                <el-link type="primary">{{ $t('xin-zeng-fu-jian') }}</el-link>
              </el-upload>
            </div>
            
            <el-table :data="fileList" :header-cell-style="{'font-weight':'normal'}" highlight-current-row
              max-height="240" style="width: 100%;margin-top:10px;margin-bottom:15px">
              <el-table-column :label="$t('headerTop.serialNumber')" min-width="40" align="center">
                <template slot-scope="scope">
                  <div>{{scope.$index + 1}}</div>
                </template>
              </el-table-column>
              <el-table-column :label="$t('filenames')" prop="name" min-width="140"></el-table-column>
              <!-- <el-table-column label="文件大小" min-width="60">
                <template slot-scope="scope">
                  <div>{{scope.$index + 1}}</div>
                </template>
              </el-table-column> -->
              <el-table-column :label="$t('operation')" min-width="40">
                <template slot-scope="scope">
                  <el-link @click="fileDelete(scope.row)" type="primary">{{$t('btn.delete')}}</el-link>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer;">
        <el-button @click.native="deleteContract()" style="float:left" v-if="dialogTitle == $t('bian-ji')">{{$t('btn.delete')}}</el-button>
        <el-button @click.native="addDialog = false">{{$t('btn.cancel')}}</el-button>
        <el-button type="primary" @click="submitInsert()" :loading="submitLoading">{{$t('btn.submit')}}</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="$t('cha-kan-he-tong')" :visible.sync="lookoverDialog" v-if="lookoverDialog" :close-on-click-modal="false" customClass="customWidth" width="1200px" top="7.5vh">
      <div style="height: 72vh;overflow-y: auto;overflow-x: hidden;">
        <el-form label-width="160px" class="lookoverContract clearfix">
          <el-form-item :label="$t('contractno')">
            {{contractForm.number}}
          </el-form-item>
          <el-form-item :label="$t('he-tong-ming-cheng')">
            {{contractForm.name}}
          </el-form-item>
          <el-form-item :label="$t('he-tong-lei-xing')">
            {{contractForm.typeName}}
          </el-form-item>
          <el-form-item label="二级分类">
            {{contractForm.secTypeName}}
          </el-form-item>
          <el-form-item :label="$t('state.states')">
            {{statusList[contractForm.status].label}}
          </el-form-item>
          <el-form-item :label="$t('dismissreason')" v-if="contractForm.status == 2">
            <span v-if="user.userNameNeedTranslate == 1">
              <span><TranslationOpenDataText type='userName' :openid='contractForm.msg.name'></TranslationOpenDataText></span>
              <span>{{contractForm.msg.text}}</span>
            </span>
            <span v-else>
              {{contractForm.msg ? contractForm.msg : ''}}
            </span>
          </el-form-item>
          <el-form-item :label="$t('founder')">
            <span v-if="user.userNameNeedTranslate == 1"><TranslationOpenDataText type='userName' :openid='contractForm.creatorName'></TranslationOpenDataText></span>
            <span v-else>{{contractForm.creatorName}}</span>
          </el-form-item>
          <el-form-item :label="$t('creationtime')">
            {{contractForm.indate}}
          </el-form-item>
          <el-form-item label="对方单位">
            {{contractForm.customerOrg}}
          </el-form-item>
          <el-form-item label="对方联系人">
            {{contractForm.customerContact}}
          </el-form-item>
          <el-form-item label="对方联系电话">
            {{contractForm.customerPhone}}
          </el-form-item>
          <el-form-item label="使用部门">
            {{contractForm.useDepartment}}
          </el-form-item>
          <el-form-item label="经费来源">
            <span v-if="contractForm.fundsSource">科研</span>
            <span v-if="contractForm.fundsSource">其他（专项等）</span>
          </el-form-item>
          <el-form-item label="合同承办人">
            {{contractForm.undertaker}}
          </el-form-item>
          <el-form-item label="委托代理人">
            {{contractForm.signDate}}
          </el-form-item>
          <el-form-item label="签订日期">
            {{contractForm.signDate}}
          </el-form-item>
          <el-form-item label="合同生效日期">
            {{contractForm.startDate}}
          </el-form-item>
          <el-form-item label="合同终止日期">
            {{contractForm.endDate}}
          </el-form-item>
          <el-form-item label="备案日期">
            {{contractForm.filingsDate}}
          </el-form-item>
          <el-form-item label="合同金额(元)/含税价">
            ￥ {{contractForm.amounts}}
          </el-form-item>
          <el-form-item label="增值税税率">
            {{contractForm.taxRate || 0}} %
          </el-form-item>
          <el-form-item label="合同金额(元)/不含税价">
            ￥ {{contractForm.amountsNoTax}}
          </el-form-item>
          <el-form-item label="是否固定金额">
            {{contractForm.isAmountFixed?'是':'否'}}
          </el-form-item>
          <el-form-item label="币种">
            {{contractForm.currency}}
          </el-form-item>
          <el-form-item label="合同状态(是否结清)">
            <span v-if="contractForm.finishStatus == 1">履约中</span>
            <span v-else>履约完成</span>
          </el-form-item>
          <el-form-item label="印花税税目">
            {{contractForm.stampDutyItems}}
          </el-form-item>

          <el-form-item style="width:100%" :label="$t('bei-zhu')">
            {{contractForm.remarks}}
          </el-form-item>
          <el-form-item style="width:100%" label="付款计划">
            <el-table :data="contractPaymentList" size="small" :key="Math.random()" :height="'300px'" show-header="false" style="margin-top:10px;">
                  <el-table-column prop="isPayed" >
                      <template slot-scope="scope">
                        {{ scope.row.isPayed?'已付款':'未付款' }}
                      </template>
                      <template slot="header" >
                          <span style="font-size:14px;font-weight:normal;">是否已付款</span>
                      </template>
                  </el-table-column>
                  <!-- <el-table-column prop="payDate" label="付款日期" width="150"></el-table-column> -->
                  <el-table-column prop="payedAmount" label="已付款金额（元）" width="160"></el-table-column>
                  <el-table-column prop="payType" label="付款类型" width="140">
                    <template slot-scope="scope">
                      {{scope.row.payType?'预付':'报账'}}
                    </template>
                  </el-table-column>
                  <el-table-column prop="billNumber" label="凭证号" width="210"></el-table-column>
                  <el-table-column prop="pendingAmounts" v-if="contractForm.isAmountFixed" label="待付款金额（元" width="180"></el-table-column>
              </el-table>
          </el-form-item>
          
          <el-form-item label-width="0" class="contractFiles">
            <div class="contractFiles_title">{{ $t('fu-jian') }}</div>
            <el-table :data="fileList" :header-cell-style="{'font-weight':'normal'}" highlight-current-row
              max-height="240" style="width: 100%;margin-top:10px;margin-bottom:30px">
              <el-table-column :label="$t('headerTop.serialNumber')" min-width="40" align="center">
                <template slot-scope="scope">
                  <div>{{scope.$index + 1}}</div>
                </template>
              </el-table-column>
              <el-table-column :label="$t('filenames')" prop="name" min-width="140"></el-table-column>
              <!-- <el-table-column label="文件大小" min-width="60">
                <template slot-scope="scope">
                  <div>{{scope.$index + 1}}</div>
                </template>
              </el-table-column> -->
              <el-table-column :label="$t('operation')" min-width="40">
                <template slot-scope="scope">
                  <el-link @click="fileDownload(scope.row)" type="primary">{{$t('other.download')}}</el-link>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>

    <el-dialog :title="$t('he-tong-lei-xing-guan-li')" :visible.sync="typeDialog" v-if="typeDialog" customClass="customWidth" width="500px">
      <el-table :data="typeList" highlight-current-row  height="400" style="width: 100%;">
        <el-table-column type="index" width="60" :label="$t('headerTop.serialNumber')">
          <template slot-scope="scope">{{ scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column prop="typeName"></el-table-column>
        <el-table-column :label="$t('operation')" width="150">
          <template slot-scope="scope">
            <el-button size="small" type="primary" @click="typeItemEdit(scope.row)">{{$t('bian-ji')}}</el-button>
            <el-button size="small" type="danger" @click="typeItemDelete(scope.row)">{{$t('btn.delete')}}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer;">
        <el-button type="primary" @click="typeDialog = false">{{$t('Shutdown')}}</el-button>
        <el-button type="primary" @click="typeItemAdd()">{{ $t('xin-zeng-he-tong-lei-xing') }}</el-button>
      </div>
      <el-dialog :title="typeTitle == this.$t('add') ? $t('xin-zeng-he-tong-lei-xing') : $t('bian-ji-he-tong-lei-xing')" :visible.sync="typeItemDialog" v-if="typeItemDialog" append-to-body width="400px">
        <div style="height: 12vh;overflow-y: auto;overflow-x: hidden;">
          <el-input v-model="typeItemForm.typeName" :maxlength="200"></el-input>
        </div>
        <div slot="footer" class="dialog-footer;">
          <el-button type="primary" @click="typeItemDialog = false">{{$t('btn.cancel')}}</el-button>
          <el-button type="primary" @click="typeItemSubmit()">{{$t('btn.determine')}}</el-button>
        </div>
      </el-dialog>
    </el-dialog>

    <el-dialog :title="$t('dao-ru-he-tong')" :visible.sync="importDialog" v-if="importDialog" width="30%">
      <!-- 模板？ -->
      <p>1. {{$t('other.download')}}
        <el-link type="primary" style="margin-left:5px;" :underline="false" :href="'./upload/上海民航合同模板.xlsx'" download="上海民航合同模板.xlsx">上海民航合同模板.xlsx</el-link>
      </p>
      <div slot="footer" class="dialog-footer" style="text-align:center;">
        <el-upload ref="upload" action="#" :limit="1" :http-request="importContract" :show-file-list="false">
          <el-button type="primary" :loading="importLoading">{{ $t('dao-ru-he-tong') }}</el-button>
        </el-upload>
      </div>
    </el-dialog>
    
    <el-dialog :title="$t('defaultText.pleaseEnterTheReason')"  v-if="denyReasonDialog" :visible.sync="denyReasonDialog" :close-on-click-modal="false" customClass="customWidth" width="500px">
            <div>
                <el-input type="textarea" v-model="denyReason" rows="2" :placeholder="$t('reasonforyourdecisiontoreject')" />
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button  @click="denyReasonDialog = false" >{{$t('btn.cancel')}}</el-button>
                <el-button type="primary" @click="process(null,2)" >{{$t('btn.submit')}}</el-button>
            </div>
    </el-dialog>

    <el-dialog title="二级分类" :visible.sync="typeDialogTwo" width="800px" top="7.8vh">
      <div class="secondaryClassification">
        <el-tabs v-model="tabsName" tab-position="left" style="height: 100%;" @tab-click="tabClick">
          <el-tab-pane v-for="(item, index) in typeList" :key="index" :label="item.typeName" :name="item.typeName">
            <div class="secondaryClassification_content">
              <el-table :data="secondaryficationList" highlight-current-row v-loading="secondaryLoading" height="50vh" style="width: 100%;flex: 1">
                <el-table-column type="index" width="60" :label="$t('headerTop.serialNumber')">
                  <template slot-scope="scope">{{ scope.$index + 1 }}</template>
                </el-table-column>
                <el-table-column prop="secTypeName" label="名称"></el-table-column>
                <el-table-column :label="$t('operation')" width="150">
                  <template slot-scope="scope">
                    <el-button size="small" type="primary" @click="editTypeTwoItem(scope.row)">{{$t('bian-ji')}}</el-button>
                    <el-button size="small" type="danger" @click="typeItemDeleteTwo(scope.row)">{{$t('btn.delete')}}</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div slot="footer" class="dialog-footer dibucLas">
                <el-button type="primary" @click="typeDialogTwo = false">{{$t('Shutdown')}}</el-button>
                <el-button type="primary" @click="editTypeTwoItem()">新增二级分类</el-button>
              </div>
              <el-dialog title="新增/编辑分类" :visible.sync="typeTwoItemVisable" append-to-body width="400px">
                <div style="height: 12vh;overflow-y: auto;overflow-x: hidden;">
                  <el-input v-model.trim="typeItemForm.typeName" :maxlength="200"></el-input>
                </div>
                <div slot="footer" class="dialog-footer;">
                  <el-button type="primary" @click="typeTwoItemVisable = false">{{$t('btn.cancel')}}</el-button>
                  <el-button type="primary" @click="typeItemTwoSubmit()">{{$t('btn.determine')}}</el-button>
                </div>
              </el-dialog>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import { debounce } from 'lodash';
export default {
  data() {
    return {
      paymentDate: null,
      contractPaymentList: [],
      user: JSON.parse(sessionStorage.getItem("user")),
      permissions: JSON.parse(sessionStorage.getItem("permissions")),
      searchField: 0,
      keyword: '',
      typeName: '',
      status: '',
      dateArray: [],
      customerOrgs: '',
      finishStatuss: '',

      typeList: [],
      contractList: [],
      listLoading: false,
      statusList: [
        {label:this.$t('state.approved'),color: 'color:#67c23a;'},
        {label:this.$t('state.WaitingAudit'),color: 'color:#e6a23c;'},
        {label:this.$t('state.rejected'),color: 'color:#f56c6c;'},
        // {label:this.$t('other.importWaitingForReview'),color: 'color:#e6a23c;'},
      ],
      typeDialog: false,
      typeTitle: this.$t('add'),
      typeItemDialog: false,
      typeItemForm: {typeName: ''},

      denyReasonDialog: false,
      denyReason: '',
      denyrow: null,

      dialogTitle: this.$t('add'),
      addDialog: false,
      lookoverDialog: false,
      submitLoading: false,
      contractForm: {
        number: '',
        name: '',
        amounts: '',
        typeId: null,
        remarks: '',
        startDate: '',
        endDate: '',
        secTypeId: ''
      },
      rules:{
        name: [{ required: true, message: this.$t('pleaseentername'), trigger: "blur" }],
      },

      fileList: [],

      importDialog: false,
      importLoading: false,
      typeDialogTwo: false,
      projectList:[],
      page: 1,
      size: 20,
      total: 0,
      tableHeight: 0,
      typeTwoItemVisable: false,
      typeItemTwoForm: {
        typeName: ''
      },
      secondaryficationList: [],
      secondaryficationListTwo: [],
      secondLevelItem: {},
      secondaryLoading: false,
      tabsName: ''
    }
  },
  created() {
    let height = window.innerHeight;
    this.tableHeight = height - 180;
    const that = this;
    window.onresize = function temp() {
      that.tableHeight = window.innerHeight - 185;
    };
  },
  mounted() {
    this.getProjectList();
    this.getContractList();
    this.getContractType();
    this.getSecondLevelList()
  },
  methods: {
    // test(row){
    //   console.log('test',row);
    //   // this.$refs.uploadFile.submit()
    // },
    onCustomerOrgsInput: debounce(function() {
      this.searchFilter();
    }, 500),
    processingContractAmount() {
      if(this.contractForm.isAmountFixed) {
        return
      }
      const list = this.contractPaymentList || []
      const totalNum = list.reduce((sum, item) => sum + (item.payedAmount || 0), 0);
      console.log(list, '<====== 开始执行')
      console.log(totalNum, '<====== 开始执行')
      this.contractForm.amounts = totalNum
    },
    chgPayedAmount() {
      const { amounts } = this.contractForm
      const list = this.contractPaymentList || []
      let totalNum = +amounts || 0
      if(amounts <= 0 || list.length <= 0) {
        this.processingContractAmount()
        return
      } else {
        this.processingContractAmount()
      }
      
      for(let i in list) {
        if(list[i].payedAmount) {
          totalNum = totalNum - list[i].payedAmount
          list[i].pendingAmounts = totalNum
        }
      }

      this.contractPaymentList = list
    },
    restrictNumber(targetId) {
                let inpu = document.getElementById(targetId);
                inpu.value = inpu.value.replace(/[^\d.]/g, "");  //仅保留数字和"."
                inpu.value = inpu.value.replace(/\.{2,}/g, "."); //两个连续的"."仅保留第一个"."
                inpu.value = inpu.value.replace(".", "$#*").replace(/\./g,'').replace('$#*','.');//去除其他"."
                inpu.value = inpu.value.replace(/^(\d+)\.(\d\d).*$/, '$1.$2');;//限制只能输入两个小数
                if (inpu.value.indexOf(".") < 0 && inpu.value != "") { //首位是0的话去掉
                  inpu.value = parseFloat(inpu.value);
                  
                }
                if(inpu.value.split('.')[0].length > 9){
                    inpu.value = inpu.value.split('.')[0].substring(0,9) + (inpu.value.split('.')[1] ? '.' + inpu.value.split('.')[1] : '')
                    
                    this.contractForm.amounts = inpu.value
                  }
                
            },
        searchProject() {
          console.log(this.contractForm.number);
          //按合同编号去匹配项目编号，自动加载关联项目
          if (this.contractForm.number) {
              var matchItem = this.projectList.filter(p=>p.projectCode == this.contractForm.number);
              if (matchItem.length > 0) {
                   this.contractForm.projectId = matchItem[0].id;
                   this.contractForm.name = matchItem[0].projectName;
                   this.contractForm.amount = matchItem[0].contractAmount;
              }
          }
        },
        //删除合同回款情况
        deleteItem(index) {
            this.contractPaymentList.splice(index,1);
        },
        //添加合同回款情况
        addItem() {
            // let p = 0;
            // this.contractPaymentList.push( { contractId:this.contractForm.id, isPayed:false,payDate: null, amount:0.0});
            
            let val = {
              contractId:this.contractForm.id, 
              isPayed:false,
              payDate: null,
              payedAmount: 0,
              payType: 1,
              billNumber: '',
              pendingAmounts: 0,
            }

            this.contractPaymentList.push(val)
        },
        
        getProjectList() {
          this.http.post('/contract/getProjectList',{},
            res => {
              if(res.code == 'ok'){
                  this.projectList = res.data;
              }else{
                this.$message({
                  message: res.msg,
                  type: 'error'
                })
              }
            },err => {
              this.$message({
                message: err,
                type: 'error'
              })
            })
        },  
    disabledStart(date){
      if(this.contractForm.endDate){
        if(date > new Date(this.contractForm.endDate)){
          return true
        }else{
          return false
        }
      }else{
        return false
      }
    },
    disabledEnd(date){
      if(this.contractForm.startDate){
        if(date < new Date(this.contractForm.startDate)){
          return true
        }else{
          return false
        }
      }else{
        return false
      }
    },
    searchFilter(){
      this.page = 1
      this.getContractList()
    },
    handleSizeChange(val){
      this.size = val
      this.page = 1
      this.getContractList()
    },
    handleCurrentChange(val){
      this.page = val;
      this.getContractList()
    },

    importContract(item){
      let str = item.file.name.split('.')
      let format = str[str.length - 1];
      if(format != "xls" && format != "xlsx"){
        this.$message({
          message: this.$t('other.PleaseselecttheXLSorXLSXfile'),
          type: 'error'
        })
      }else{
        this.importLoading = true
        let formData = new FormData();
        formData.append("file", item.file);
        formData.append("userId", this.user.id);
        this.http.uploadFile('/contract/importContract',formData,
        res => {
          this.$refs.upload.clearFiles();
          this.importLoading = false;
          if(res.code == 'ok'){
            this.importDialog = false
            this.$message({
              message: this.$t('other.importSuccess'),
              type: 'success'
            })
            this.getContractList()
          }else{
            this.$message({
              message: res.msg,
              type: 'error'
            })
          }
        },err => {
          this.importLoading = false;
          this.$message({
            message: err,
            type: 'error'
          })
        })
      }
    },
    exportContract(){
      let parameter = {}
      if(this.typeName){
        parameter.typeName = this.typeName
      }
      if(this.keyword){
        if(this.searchField){
          parameter.number = this.keyword
        }else{
          parameter.name = this.keyword
        }
      }
      if(this.status !== ''){
        parameter.status = this.status
      }
      if(this.dateArray && this.dateArray.length == 2){
        parameter.startDate = this.dateArray[0]
        parameter.endDate = this.dateArray[1]
      }

      if(this.customerOrgs) {
        parameter.customerOrg = this.customerOrgs
      }

      if(this.finishStatuss) {
        parameter.finishStatus = this.finishStatuss
      }
      
      this.http.post('/contract/exportContractOneToMany',parameter,
      res => {
        if(res.code == 'ok'){
          let filePath = res.data;
          const a = document.createElement('a'); // 创建a标签
          a.setAttribute('download', this.$t('he-tong-dao-chu') + '.xlsx');// download属性
          a.setAttribute('href', filePath);// href链接
          a.click(); //自执行点击事件
          a.remove();
        }else{
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      },err => {
        this.$message({
          message: err,
          type: 'error'
        })
      })
    },

    typeEdit(){
      this.typeDialog = true
    },
    typeEditTwo() {
      console.log(this.typeList)
      console.log(this.secondaryficationList)
      console.log(this.tabsName)
      this.secondLevelItem = this.typeList[0] || {}
      this.tabsName = this.typeList[0] && (this.typeList[0].mainTypeName || this.typeList[0].typeName)
      const id = this.secondLevelItem.id
      this.secondaryficationList = this.secondaryficationListTwo.filter(item => item.mainTypeId == id)
      this.$forceUpdate()
      this.typeDialogTwo = true
    },
    typeItemAdd(){
      if(this.typeList.length == 20){
        this.$message({
          message: this.$t('he-tong-lei-xing-zui-duo-zhi-neng-chuang-jian-20-ge'),
          type: 'error'
        })
        return
      }
      this.typeTitle = this.$t('add')
      this.typeItemForm = {typeName: ''}
      this.typeItemDialog = true
    },
    typeItemEdit(row){
      this.typeTitle = this.$t('bian-ji')
      this.typeItemForm = JSON.parse(JSON.stringify(row))
      this.typeItemDialog = true
    },
    typeItemDelete(row){
      this.$confirm(this.$t('que-ding-yao-shan-chu-ci-tiao-he-tong-lei-xing-ma'), this.$t('other.prompts'), {
        confirmButtonText: this.$t('btn.determine'),
        cancelButtonText: this.$t('btn.cancel'),
        type: 'warning'
      }).then(() => {
        this.http.post('/contractType/deleteContractType',{
          deleteId: row.id
        },res => {
          if(res.code == 'ok'){
            this.getContractType()
            this.$message({
              type: 'success',
              message: this.$t('message.successfullyDeleted') + '!'
            });
          }else{
            this.$message({
              type: 'error',
              message: res.msg
            });
          }
        },err => {
          this.$message({
            type: 'error',
            message: err
          });
        })
        
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$t('thedeletionhasbeencancelled')
        });          
      });
    },
    typeItemSubmit(){
      this.http.post('/contractType/changeContractType',this.typeItemForm,
      res => {
        if(res.code == 'ok'){
          this.typeItemDialog = false
          this.getContractType()
          this.$message({
            message: this.typeTitle == this.$t('add') ? this.$t('newsuccess') : this.$t('editsuccess'),
            type: 'success'
          })
        }else{
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      },err => {
        this.$message({
          message: err,
          type: 'error'
        })
      })
    },


    newlyAdd(){
      this.dialogTitle = this.$t('add')
      this.contractForm = {
        number: '',
        name: '',
        amounts: '',
        typeId: null,
        remarks: '',
        startDate: '',
        endDate: '',
        isAmountFixed: true,
      }
      this.contractPaymentList = [];
      this.fileList = []
      this.addDialog = true
    },
    editContract(row){
      delete row.customData
      this.dialogTitle = this.$t('bian-ji')
      this.contractForm = JSON.parse(JSON.stringify(row))
      console.log('开始执行', '<================')
      if(row.typeId) {
        const id = row.typeId
        this.secondaryficationList = this.secondaryficationListTwo.filter(item => item.mainTypeId == id)
      }
      this.fileList = this.contractForm.files ? this.contractForm.files : []
      for(let i in this.fileList){
        this.fileList[i].name = this.fileList[i].documentName
      }
      this.addDialog = true;
      this.getContractPaymentList();
    },
    getContractPaymentList() {
      this.contractPaymentList = [];
      this.http.post('/contract-payment/getList',{contractId: this.contractForm.id},
      res => {
        if(res.code == 'ok'){
          res.data = res.data.map(item => ({
            ...item,
            payType: item.payType ? 1 : 0
          }));
          console.log(res.data, '<==== 数据')
          this.contractPaymentList = res.data;
        }else{
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      },err => {
        this.$message({
          message: err,
          type: 'error'
        })
      })
    },
    deleteContract(){
      this.$confirm(this.$t('que-ding-yao-shan-chu-gai-he-tong-ma'), this.$t('other.prompts'), {
        confirmButtonText: this.$t('btn.determine'),
        cancelButtonText: this.$t('btn.cancel'),
        type: 'warning'
      }).then(() => {
        this.http.post('/contract/deleteContract',{
          id: this.contractForm.id
        },res => {
          if(res.code == 'ok'){
            this.addDialog = false
            this.getContractList()
            this.$message({
              type: 'success',
              message: this.$t('message.successfullyDeleted') + '!'
            });
          }else{
            this.$message({
              type: 'error',
              message: res.msg
            });
          }
        },err => {
          this.$message({
            type: 'error',
            message: err
          });
        })
        
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$t('thedeletionhasbeencancelled')
        });          
      });
    },
    processR(row,status){
      this.denyReasonDialog = true
      this.denyrowId = row.id
      this.denyReason = ''
    },
    process(row,status){
      let parameter
      if(status == 2){
        parameter = {
          id: this.denyrowId,
          status: status,
          msg: this.denyReason
        }
      }else{
        parameter = {
          id: row.id,
          status: status
        }
      }
      this.$confirm(this.$t('que-ren-shen-he-tong-guo-ma-tong-guo-hou-he-tong-ji-ben-xin-xi-wu-fa-xiu-gai'), this.$t('other.prompts'), {
        confirmButtonText: this.$t('btn.determine'),
        cancelButtonText: this.$t('btn.cancel'),
        type: 'warning'
      }).then(() => {
        this.http.post('/contract/processContract',parameter,
        res => {
          if(res.code == 'ok'){
            this.getContractList()
            this.denyReasonDialog = false
            this.$message({
              message: status == 0 ? this.$t('state.alreadyPassed') : this.$t('state.rejected'),
              type: 'success'
            })
          }else{
            this.$message({
              message: res.msg,
              type: 'error'
            })
          }
        },err => {
          this.$message({
            message: err,
            type: 'error'
          })
        })
      }); 
    },
    lookover(row){
      console.log('lookover',row);
      const newRow = JSON.parse(JSON.stringify(row))
      if(this.user.userNameNeedTranslate == 1) {
        let obj = {name: '',text: ''}

        if (newRow.msg) {
          let match = newRow.msg.match(/\$userName=(.*?)\$(.*)/);
          if (match) {
            obj.name = match[1];
            obj.text = match[2];
          } else {
            obj.text = newRow.msg;
          }
        }
        // if(newRow.msg.indexOf('$userName=') != '-1') {
        //   let str = newRow.msg.split('$userName=')[1]
        //   let arr = str.split('$')
        //   obj.name = arr[0]
        //   obj.text = arr[1]
        // } else {
        //   obj.text = newRow.msg
        // }
        newRow.msg = obj
        this.contractForm = newRow
      } else {
        this.contractForm = newRow
      }
      this.fileList = this.contractForm.files ? this.contractForm.files : []
      for(let i in this.fileList){
        this.fileList[i].name = this.fileList[i].documentName
      }
      this.lookoverDialog = true;
      this.getContractPaymentList();
    },
    submitInsert(){
      this.$refs.contractForm.validate(valid => {
        if (valid) {
          //校验回款日期和金额
          var totalPayment = 0.0;
          for (var i = 0; i < this.contractPaymentList.length; i++) {
            // if (!this.contractPaymentList[i].payDate) {
            //   this.$message({
            //     message: this.$t('hui-kuan-ri-qi-bu-neng-wei-kong'),
            //     type: 'error'
            //   })
            //   return;
            // }
            if (!this.contractPaymentList[i].payedAmount) {
              this.$message({
                message: this.$t('hui-kuan-jinebu-neng-wei-0'),
                type: 'error'
              })
              return;
            }
            totalPayment += parseFloat(this.contractPaymentList[i].payedAmount);
          }
          if (totalPayment > parseFloat(this.contractForm.amounts)) {
            this.$message({
                message: this.$t('zong-hui-kuan-jinebu-de-da-yu-he-tong-jin-e'),
                type: 'error'
              })
              return;
          }
          this.submitLoading = true
          delete this.contractForm.files
          this.contractForm.paymentListStr = JSON.stringify(this.contractPaymentList);
          delete this.contractForm.msg
          delete this.contractForm.nextPaymentDate
          delete this.contractForm.nextPaymentAmount
          delete this.contractForm.payCustomizedData
          delete this.contractForm.checkerId
          this.http.post(this.dialogTitle == this.$t('add') ? '/contract/addContract' : '/contract/editContract',this.contractForm,
          res => {
            this.submitLoading = false
            if(res.code == 'ok'){
              this.addDialog = false
              this.$message({
                message: res.msg,
                type: 'success'
              })
              if(this.dialogTitle == this.$t('add')){
                this.contractForm.id = res.data
              }
              this.submitFile()
              
            }else{
              this.$message({
                message: res.msg,
                type: 'error'
              })
            }
          },err => {
            this.submitLoading = false
            this.$message({
              message: err,
              type: 'error'
            })
          })
        }
      })
    },

    fileChange(file,fileList){
      // console.log('fileChange',file,fileList);
      file.needUpload = true
      this.fileList.push(file)
    },
    fileDelete(row){
      // console.log(row,this.fileList);
      this.$confirm(this.$t('que-ding-yao-shan-chu-gai-wen-jian-ma'), this.$t('other.prompts'), {
        confirmButtonText: this.$t('btn.determine'),
        cancelButtonText: this.$t('btn.cancel'),
        type: 'warning'
      }).then(() => {
        if(row.uid){
          for(let i in this.fileList){
            if(this.fileList[i].uid && this.fileList[i].uid == row.uid){
              this.fileList.splice(i,1)
            }
          }
        }else{
          this.http.post('/contract-document/fileDelete',{
            contractId: this.contractForm.id,
            fileIds: [row.id]
          },res => {
            if(res.code == 'ok'){
              this.getContractList()
              this.fileList.filter(item => !item.id || item.id != row.id)
              this.$message({
                type: 'success',
                message: this.$t('message.successfullyDeleted') + '!'
              });
            }else{
              this.$message({
                type: 'error',
                message: res.msg
              });
            }
          },err => {
            this.$message({
              type: 'error',
              message: err
            });
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$t('thedeletionhasbeencancelled')
        });          
      });
    },
    fileDownload(row){
      this.http.downloadFile('/contract-document/fileDown',{
        contractId: this.contractForm.id,
        fileId: row.id
      },row.name,err=>{
        this.$message({
          message: err,
          type: 'error'
        })
      })
    },
    submitFile(){
      // console.log('submitFile',this.fileList);
      let formData = new FormData();
      for(let i in this.fileList){
        if(this.fileList[i].needUpload){
          formData.append("file", this.fileList[i].raw);
        }
      }
      formData.append("ContractId", this.contractForm.id);
      this.http.uploadFile('/contract-document/fileUpload',formData,
      res => {
        if(res.code == 'ok'){
          this.getContractList()
        }else{
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      },err => {
        this.$message({
          message: err,
          type: 'error'
        })
      })
    },


    getContractType(){
      this.http.post('/contractType/getContractType',{},
      res=>{
        if(res.code=='ok'){
          this.typeList = res.data
        }else{
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      },err=>{
        this.$message({
          message: err,
          type: 'error'
        })
      })
    },
    getContractList(){
      
      // pageIndex，pageSize，number，name，typeName，status，startDate，endDate
      let parameter = {
        pageIndex: this.page,
        pageSize: this.size,
      }
      if(this.typeName){
        parameter.typeName = this.typeName
      }
      if(this.keyword){
        if(this.searchField){
          parameter.number = this.keyword
        }else{
          parameter.name = this.keyword
        }
      }
      if(this.status !== ''){
        parameter.status = this.status
      }
      if(this.dateArray && this.dateArray.length == 2){
        parameter.startDate = this.dateArray[0]
        parameter.endDate = this.dateArray[1]
      }
      if(this.paymentDate && this.paymentDate.length == 2){
        parameter.paymentStartDate = this.paymentDate[0]
        parameter.paymentEndDate = this.paymentDate[1]
      }

      if(this.customerOrgs) {
        parameter.customerOrg = this.customerOrgs
      }

      if(this.finishStatuss) {
        parameter.finishStatus = this.finishStatuss
      }
      
      this.listLoading = true
      this.http.post('/contract/getContractPage',parameter,
      res => {
        this.listLoading = false
        if(res.code == 'ok'){
          const newData = res.data.data.map(item => {
            return {
              ...item,
              ...item.customData
            }
          })
          this.contractList = newData
          this.total = res.data.total
        }else{
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      },err => {
        this.listLoading = false
        this.$message({
          message: err,
          type: 'error'
        })
      })
    },

    tabClick(e) {
      const item = this.typeList[e.index]
      const { id } = item
      this.secondLevelItem = item
      this.secondaryficationList = this.secondaryficationListTwo.filter(item => item.mainTypeId == id)
    },
    selectSecTypeId() {
      this.contractForm.secTypeId = ''
      const id = this.contractForm.typeId
      this.secondaryficationList = this.secondaryficationListTwo.filter(item => item.mainTypeId == id)
    },
    refreshDatas() {
      this.$forceUpdate()
    },
    editTypeTwoItem(row) {
      const { id, secTypeName } = row || {};
      
      this.typeItemForm = {
        id: id || undefined,
        typeName: secTypeName || ''
      };

      this.typeTwoItemVisable = true;
    },
    typeItemDeleteTwo(row) {
      const { id, secTypeName } = row
      this.$confirm(`此操作将永久删除【${secTypeName}】, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.postData(`/contract-type-sec/deleteContractType`, {
            deleteId: id
          }).then(() => {
            this.getSecondLevelList()
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          })
        }).catch(() => {});
    },
    getSecondLevelList() {
      this.secondaryLoading = true
      this.postData(`/contract-type-sec/getContractType `, {

      }).then(res => {
        const { id } = this.secondLevelItem
        this.secondaryficationList = res.data.filter(item => item.mainTypeId == id)
        this.secondaryficationListTwo = res.data || []
      }).finally(() => {
        this.secondaryLoading = false
      })
    },
    typeItemTwoSubmit() {
      console.log(this.typeItemForm, '<=== 要提交的数据')
      const mainTypeId = this.secondLevelItem.id
      const secTypeName = this.typeItemForm.typeName
      const formVal = {
        mainTypeId,
        secTypeName
      }
      if(this.typeItemForm.id) {
        formVal.id = this.typeItemForm.id
      }
      this.postData(`/contract-type-sec/changeContractType`, {
        ...formVal
      }).then(() => {
        this.getSecondLevelList()
        this.typeTwoItemVisable = false
      })
    },
    async postData(urls, param) {
      return new Promise((resolve, reject) => {
        this.http.post(urls, { ...param },
          res => {
            if(res.code == 'ok') {
              resolve(res)
            } else {
              this.$message({
                message: res.msg,
                type: 'error'
              })
              reject(res)
            }
            resolve(res)
          },
          error => {
            this.$message({
              message: error,
              type: "error"
            });
            reject(error)
          }
        )
      });
    },
  },
}
</script>

<style>
.lookoverContract{
  margin-top: 30px;
}
.lookoverContract .el-form-item{
  width: 50%;
  float: left;
}
.lookoverContract .el-form-item__label{
  font-weight: 600;
}
.lookoverContract .contractFiles{
  width: 100%;
}
.lookoverContract .contractFiles_title{
  margin-left: 5%;
  font-size: 16px;
  line-height: 20px;
  margin-top: 16px;
}
.contractForm{
  margin-top: 30px;
}
.contractForm .el-form-item{
  width: 90%;
}
.contractForm .contractFiles{
  width: 100%;
}
.contractForm .contractFiles_title{
  margin-left: 5%;
  font-size: 16px;
  line-height: 20px;
  margin-top: 16px;
}

.secondaryClassification {
  width: 100%;
  height: 60vh;
  overflow: auto;
}
.secondaryClassification_content {
  padding: 10px 20px;
  display: flex;
  flex-direction: column;
  height: 58vh;
}
.dibucLas {
  padding-top: 10px;
  display: flex;
  justify-content: flex-end;
}
</style>