<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
  <div>
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      v-dialogDrag
      :append-to-body="true"
      width="1200px"
      height="500px"
      @close="close"
      @keyup.enter.native=""
      :visible.sync="visible">
      <el-tabs v-model="activeNameTop" type="border-card" @tab-click="tabHandleClickTop">
        <el-tab-pane label="合同信息" name="contract">
          <el-form size="middle" :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"  :disabled="method==='view'"
                   label-width="150px">
            <el-divider v-if="method==='view' && commonJS.isNotEmpty(inputForm.customerId)" content-position="left">
              <el-link  type="primary" :underline="false" icon="el-icon-document" @click="viewClient(inputForm.customerId)"><b>查看客户详情</b></el-link>
            </el-divider>
            <el-divider v-else content-position="left"><i class="el-icon-document"></i> 客户信息</el-divider>
            <el-row  :gutter="0">
              <el-col :span="12">
                <el-form-item label="委托方" prop="clientContacts"
                              :rules="[{required: true, message: '委托方', trigger: 'blur'}
                       ]">
                  <el-input maxlength="100" @focus="openWorkClient2()" v-model="inputForm.clientContacts" placeholder="请选择委托方">
                    <el-button slot="append" icon="el-icon-search" @click="openWorkClient2()"></el-button>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="客户编号" prop="customerNo"
                              :rules="[
                         ]">
                  <el-input :disabled="true" v-model="inputForm.customerNo" placeholder="请填写客户编号" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="统一社会信用代码" prop="uscCode"
                              :rules="[
                         ]">
                  <el-input :disabled="true" v-model="inputForm.uscCode" placeholder="请填写统一社会信用代码" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="委托方电话" prop="clientContactsPhone"
                              :rules="[
                       ]">
                  <el-input maxlength="15" :disabled="true" v-model="inputForm.clientContactsPhone" placeholder="请输入委托方电话"
                            @keyup.native="inputForm.clientContactsPhone = twoDecimalPlaces(inputForm.clientContactsPhone)"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="地址" prop="address"
                              :rules="[
                         ]">
                  <el-input :disabled="true" v-model="inputForm.address" 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="0">
              <el-col :span="12">
                <el-form-item label="合同名称" prop="contractName"
                              :rules="[{required: true, message: '合同名称不能为空', trigger: 'blur'}
                       ]">
                  <el-input v-model="inputForm.contractName" placeholder="请输入合同名称"     clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="合同编号" prop="contractNo">
                  <el-input maxlength="64" :disabled="true" v-model="inputForm.contractNo" placeholder="自动生成"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="合同类型" prop="contractType"
                              :rules="[
                 ]">
                  <el-select :disabled="true" v-model="inputForm.contractType" placeholder="请选择合同类型" style="width:100%;">
                    <el-option
                      v-for="item in $dictUtils.getDictList('cw_contract_type')"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="合同流水号" prop="contractSerialNumber">
                  <el-input maxlength="64" :disabled="true" v-model="inputForm.contractSerialNumber" placeholder="自动生成"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="付款主体" prop="payerSubject"
                              :rules="[{required: true, message: '付款主体不能为空', trigger: 'blur'}
                       ]">
                  <el-select v-model="inputForm.payerSubject" placeholder="请选择付款主体" style="width:100%;">
                    <el-option
                      v-for="item in $dictUtils.getDictList('cw_payment_subject')"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="付款方式" prop="paymentMethod"
                              :rules="[
                                {required: true, message: '付款方式不能为空', trigger: 'change'}
                       ]">
                  <el-select v-model="inputForm.paymentMethod" placeholder="请选择付款方式" style="width:100%;">
                    <el-option
                      v-for="item in $dictUtils.getDictList('cw_payment_method')"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="付款描述" prop="paymentDescribe"
                              :rules="[
               ]">
                  <el-input type="textarea" v-model="inputForm.paymentDescribe" placeholder="请输入付款描述"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="签约日期" prop="signingDate"
                              :rules="[
                      {required: true, message:'请输入签约日期', trigger:'blur'}
                     ]">
                  <el-date-picker
                    placement="bottom-start"
                    value-format="yyyy-MM-dd"
                    v-model="inputForm.signingDate"
                    style="width: 100%"
                    placeholder="选择日期">
                  </el-date-picker>
                </el-form-item>
              </el-col>

        <el-col :span="12">
          <el-form-item label="合同份数" prop="contractNum"
                        :rules="[{required: true, message: '合同份数', trigger: 'blur'}
                 ]">
            <el-input maxlength="64" v-model="inputForm.contractNum" placeholder="请输入合同份数"></el-input>
          </el-form-item>
        </el-col>

<!--        <el-col :span="12">-->
<!--          <el-form-item label="修改次数" prop="changeNum"-->
<!--                        :rules="[{required: true, message: '修改次数', trigger: 'blur'}-->
<!--                 ]">-->
<!--            <el-input maxlength="64" :disabled="true" v-model="inputForm.changeNum" placeholder="请输入修改次数"></el-input>-->
<!--          </el-form-item>-->
<!--        </el-col>-->

        <el-col :span="12">
          <el-form-item  prop="department" label="所属部门">
            <SelectTree
              ref="officeTree"
              :props="{
                  value: 'id',             // ID字段名
                  label: 'name',         // 显示名称
                  children: 'children'    // 子级字段名
                }"

              :url="`/sys/office/treeData?type=1`"
              :value="inputForm.department"
              :accordion="true"
              size="medium"
              @getValue="(value) => {inputForm.department=value}"/>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="创建人" prop="createBy"
                        :rules="[{required: true, message: '创建人', trigger: 'blur'}
                 ]">
            <el-input maxlength="64" :disabled="true" v-model="inputForm.createBy" placeholder="请输入创建人"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="创建时间" prop="createDate">
            <el-date-picker
              placement="bottom-start"
              value-format="yyyy-MM-dd"
              v-model="inputForm.createDate"
              style="width: 100%"
              :disabled="true"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>

        <el-col>
          <el-form-item label="合同金额类别" prop="contractAmountType"
                        :rules="[
                  {required: true, message:'请选择合同金额类别', trigger:'blur'}
               ]">
            <el-radio-group v-model="inputForm.contractAmountType">
              <el-radio v-for="item in $dictUtils.getDictList('contract_amount_type')" :label="item.value" >{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

              <el-col :span="12">
                <el-form-item label="合同金额(元)" prop="contractAmount" v-if="inputForm.contractAmountType === '1'"
                              :rules="[
                        {required: true, message:'请输入合同金额(元)', trigger:'blur'}
                     ]">
                  <el-input maxlength="15" v-model="inputForm.contractAmount" placeholder="请输入合同金额(元)"
                            @keyup.native="inputForm.contractAmount = twoDecimalPlaces(inputForm.contractAmount)"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="预计金额(元)" prop="predictAmount" v-if="inputForm.contractAmountType === '2'"
                              :rules="[
                  /*{required: true, message:'请输入预计金额(元)', trigger:'blur'}*/
               ]">
                  <el-input maxlength="15" v-model="inputForm.predictAmount" placeholder="请输入预计金额(元)"
                            @keyup.native="inputForm.predictAmount = twoDecimalPlaces(inputForm.predictAmount)"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="合同实际金额" prop="actualContractAmount">
                  <el-input maxlength="64" :disabled="true" v-model="inputForm.actualContractAmount" ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="对方合同编号" prop="contractOpposite">
                  <el-input maxlength="64" v-model="inputForm.contractOpposite" placeholder="请填写对方合同编号"></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item label="收费标准" prop="contractFees">
                  <el-checkbox-group v-model="inputForm.contractFees">
                    <el-checkbox @change="changeContractFee" v-for="item in $dictUtils.getDictList('contract_fee')" :label="item.value">
                      {{item.label}}
                    </el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item prop="contractFee">
                  <el-input style="width: 100%" placeholder="请选择收费标准" v-model="inputForm.contractFee"></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item label="付款约定" prop="paymentAgreement">
                  <el-input maxlength="1000" type="textarea" v-model="inputForm.paymentAgreement" placeholder="请输入付款约定"></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="案卷号" prop="filedNo" v-if="this.inputForm.filedPaperType === '2' & this.inputForm.filedPaperType === '5'"
                              :rules="[{required: true, message: '请输入案卷号', trigger: 'blur'}
                       ]">
                  <el-input maxlength="15" v-model="inputForm.filedNo" placeholder="请输入案卷号"
                  ></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="uploadFile">
              <!--        合同文件-->
              <UpLoadComponent ref="uploadFile"></UpLoadComponent>
            </el-tab-pane>
            <el-tab-pane label="参与签约方" name="contactParty">
              <el-row :gutter="15">
                <el-button type="primary" :disabled="method === 'view'" style="margin-bottom: 15px" size="mini"  @click="openWorkClient">
                  新增参与签约方
                </el-button>
              </el-row>
              <el-row  :gutter="15">
                <el-form :disabled="method === 'view'">
                  <vxe-table
                    border
                    show-overflow
                    show-footer
                    :column-config="{resizable: true}"
                    ref="contactTable"
                    :key="tableKeyClient"
                    class="vxe-table-element"
                    :data="inputForm.cwWorkClientContactDTOList"
                    style=""
                    @cell-click=""
                    @edit-closed=""
                    highlight-current-row
                    :edit-config="{trigger: 'click', mode: 'row', showStatus: false, autoClear: false}"
                  >
                    <vxe-table-column align="center" field="no" title="客户编号" :edit-render="{}">
                      <template v-slot:edit="scope">
                        <el-input :readonly="true" v-model="scope.row.no" placeholder="客户编号" clearable></el-input>
                      </template>
                    </vxe-table-column>
                    <vxe-table-column align="center" field="name" title="客户名称" :edit-render="{}">
                      <template v-slot:edit="scope">
                        <el-input :readonly="true" v-model="scope.row.name" placeholder="客户名称" clearable></el-input>
                      </template>
                    </vxe-table-column>
                    <vxe-table-column align="center" title="操作" width="100">
                      <template v-slot="scope">
                        <el-button size="mini" type="danger" @click="removeEvent(scope.row,scope.$rowIndex,'client')">删除</el-button>
                      </template>
                    </vxe-table-column>
                  </vxe-table>
                </el-form>
              </el-row>
            </el-tab-pane>
<!--            <el-tab-pane label="合同归档文件" name="archiveFile">-->
<!--              &lt;!&ndash;        合同归档文件&ndash;&gt;-->
<!--              <UpLoadComponent ref="archiveFile"></UpLoadComponent>-->
<!--            </el-tab-pane>-->

          </el-tabs>
        </el-tab-pane>
        <el-tab-pane label="关联项目" name="project">
          <el-form size="small" :inline="true" class="query-form" style="margin-bottom: 0;padding-top: 2px;padding-left: 0" ref="projectForm" :model="projectForm" @keyup.enter.native="searchProject()" @submit.native.prevent>
            <!-- 搜索框-->
            <el-form-item label="项目名称" prop="projectName">
              <el-input size="small" v-model="projectForm.projectName" placeholder="请输入项目名称" clearable></el-input>
            </el-form-item>
            <el-form-item label="项目编号" prop="projectNumber">
              <el-input size="small" v-model="projectForm.projectNumber" placeholder="请输入项目编号" clearable></el-input>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="searchProject()" size="small" icon="el-icon-search">查询</el-button>
              <el-button @click="refreshProjectForm()" size="small" icon="el-icon-refresh-right">重置</el-button>
            </el-form-item>
          </el-form>
          <vxe-table
            max-height="500"
            border="inner"
            auto-resize
            resizable
            height="auto"
            :loading="loading"
            size="medium"
            ref="projectTable"
            show-header-overflow
            show-overflow
            highlight-hover-row
            :menu-config="{}"
            @sort-change=""
            :sort-config="{remote:true}"
            :data="projectList"
            :checkbox-config="{}">
            <vxe-column type="seq" width="60" title="序号"></vxe-column>
            <vxe-column min-width="230" align="center" title="项目名称" field="projectName">
              <template slot-scope="scope">
                <el-link  type="primary" :underline="false" v-if="hasPermission('cwProjectRecords:view')" @click="viewProject(scope.row.id)">{{scope.row.projectName}}</el-link>
                <span v-else>{{scope.row.projectName}}</span>
              </template>
            </vxe-column>
            <vxe-column min-width="160" align="center" title="项目编号" field="projectNumber"></vxe-column>
            <vxe-column min-width="160" align="center" title="项目经理" field="projectMasterName"></vxe-column>
            <vxe-column min-width="160" align="center" title="创建人" field="createName"></vxe-column>
            <vxe-column min-width="160" align="center" title="创建时间" field="createDate"></vxe-column>
          </vxe-table>
        </el-tab-pane>
        <el-tab-pane label="关联报告" name="report">
          <el-form size="small" :inline="true" class="query-form" style="margin-bottom: 0;padding-top: 2px;padding-left: 0" ref="reportForm" :model="reportForm" @keyup.enter.native="searchReport()" @submit.native.prevent>
            <!-- 搜索框-->
            <el-form-item label="报告文号" prop="reportNo">
              <el-input size="small" v-model="reportForm.reportNo" placeholder="请输入报告文号" clearable></el-input>
            </el-form-item>
            <el-form-item label="项目名称" prop="projectName">
              <el-input size="small" v-model="reportForm.projectName" placeholder="请输入项目名称" clearable></el-input>
            </el-form-item>
            <el-form-item label="项目编号" prop="projectNumber">
              <el-input size="small" v-model="reportForm.projectNumber" placeholder="请输入项目编号" clearable></el-input>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="searchReport()" size="small" icon="el-icon-search">查询</el-button>
              <el-button @click="refreshReportForm()" size="small" icon="el-icon-refresh-right">重置</el-button>
            </el-form-item>
          </el-form>
          <vxe-table
            max-height="500"
            border="inner"
            auto-resize
            resizable
            height="auto"
            :loading="loading"
            size="medium"
            ref="reportTable"
            show-header-overflow
            show-overflow
            highlight-hover-row
            :menu-config="{}"
            @sort-change=""
            :sort-config="{remote:true}"
            :data="reportList"
            :checkbox-config="{}">
            <vxe-column type="seq" width="60" title="序号"></vxe-column>
            <vxe-column min-width="200" title="报告文号"align="center" field="reportNo">
              <template slot-scope="scope">
                <el-link  type="primary" :underline="false" @click="viewReport(scope.row.id)">{{scope.row.reportNo}}</el-link>
              </template>
            </vxe-column>
            <vxe-column min-width="200" title="项目名称"align="center" field="projectName">
              <template slot-scope="scope">
                <el-link  type="primary" :underline="false" @click="viewProject(scope.row.projectId)">{{scope.row.projectName}}</el-link>
              </template>
            </vxe-column>
            <vxe-column min-width="200" title="项目编号"align="center" field="projectNumber"></vxe-column>
            <vxe-column min-width="150" title="所属部门"align="center" field="officeName"></vxe-column>
            <vxe-column min-width="150" title="项目经理"align="center" field="projectMasterName"></vxe-column>
            <vxe-column min-width="120" title="报告创建人"align="center" field="createName"></vxe-column>
            <vxe-column min-width="180" title="报告创建时间"align="center" field="createDate"></vxe-column>
          </vxe-table>
        </el-tab-pane>
        <el-tab-pane label="关联发票" name="invoice">
          <el-form size="small" :inline="true" class="query-form" style="margin-bottom: 0;padding-top: 2px;padding-left: 0" ref="invoiceForm" :model="invoiceForm" @keyup.enter.native="searchInvoice()" @submit.native.prevent>
            <!-- 搜索框-->
            <el-form-item label="发票申请编号" prop="no">
              <el-input size="small" v-model="invoiceForm.no" placeholder="请输入发票申请编号" clearable></el-input>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="searchInvoice()" size="small" icon="el-icon-search">查询</el-button>
              <el-button @click="refreshInvoiceForm()" size="small" icon="el-icon-refresh-right">重置</el-button>
            </el-form-item>
          </el-form>
          <vxe-table
            max-height="500"
            border="inner"
            auto-resize
            resizable
            height="auto"
            :loading="loading"
            size="medium"
            ref="invoiceTable"
            show-header-overflow
            show-overflow
            highlight-hover-row
            :menu-config="{}"
            @sort-change=""
            :sort-config="{remote:true}"
            :data="invoiceList"
            :checkbox-config="{}">
            <vxe-column type="seq" width="60" title="序号"></vxe-column>
            <vxe-column min-width="150" title="发票申请编号"align="center" field="no">
              <template slot-scope="scope">
                <el-link  type="primary" :underline="false" @click="viewInvoice(false, scope.row.id)">{{scope.row.no}}</el-link>
              </template>
            </vxe-column>
            <vxe-column min-width="150" title="发票号"align="center" field="number"></vxe-column>
            <vxe-column min-width="150" title="实际开票单位"align="center" field="billingWorkplaceReal"></vxe-column>
            <vxe-column min-width="150" title="开票金额（元）"align="center" field="accountDetail"></vxe-column>
            <vxe-column min-width="150" title="开票总金额（元）"align="center" field="account"></vxe-column>
            <vxe-column min-width="120" title="开票内容"align="center" field="billingContent">
              <template slot-scope="scope">
                {{$dictUtils.getDictLabel('invoice_billing_content', scope.row.billingContent, '-')}}
              </template>
            </vxe-column>
            <vxe-column min-width="110" fixed="right"align="center" title="是否收款" field="receivablesStatus">
              <template slot-scope="scope">
                {{scope.row.receivablesStatus === '1'?'已收款':'未收款'}}
              </template>
            </vxe-column>
          </vxe-table>
        </el-tab-pane>
      </el-tabs>

      <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="close()" icon="el-icon-circle-close">关闭</el-button>
      <el-button size="small" v-if="method === 'edit'" type="primary" icon="el-icon-circle-check" @click="doSubmit('save')">确定</el-button>
    </span>

    <el-image-viewer
      v-if="showViewer"
      :on-close="closeViewer"
      :url-list="[url]"
      zIndex="9999"/>
    <WorkClientChooseForm ref="workClientChooseForm" @getWorkClientChoose="getWorkClientChoose"></WorkClientChooseForm>
      <WorkClientChooseRadio ref="workClientChooseRadio" @getWorkClientRadioChoose="getWorkClientChoose2"></WorkClientChooseRadio>
      <WorkClientForm ref="workClientForm"></WorkClientForm>
      <ProjectRecordsForm ref="projectRecordsForm"></ProjectRecordsForm>
      <InvoiceForm ref="invoiceFormDialog"></InvoiceForm>
      <ReportManagementForm ref="reportManagementForm"></ReportManagementForm>
    </el-dialog>
  </div>
</template>

<script>
  import ContractInfoService from '@/api/cw/workContract/ContractInfoService'
  import ProjectRecordsService from '@/api/cw/projectRecords/ProjectRecordsService'
  import ContractFileService from '../../../../api/cw/workContract/ContractFileService'
  import UpLoadComponent from '@/views/common/UpLoadComponent'
  import WorkClientChooseForm from '../workClientInfo/WorkClientChooseForm'
  import WorkClientChooseRadio from '../workClientInfo/WorkClientChooseRadio'
  import SelectTree from '@/components/treeSelect/treeSelect.vue'
  // import WorkClientForm from '../workClientInfo/WorkClientForm'
  import OSSSerive, {
    httpRequest,
    toHref,
    openWindowOnUrl,
    handleRemove,
    fileName
  } from '@/api/sys/OSSService'
  import moment from 'moment'
  import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
  import CwFinanceInvoiceService from '@/api/cw/invoice/CwFinanceInvoiceService'
  import ProjectReportService from '@/api/cw/reportManagement/ProjectReportService'
  // import ProjectRecordsForm from '../projectRecords/ProjectRecordsForm'
  export default {
    data () {
      return {
        visable: false,
        gridData: [],
        radio: 0,
        tableData: [],
        dataList: [],
        dataListNew: [],
        title: '',
        method: '',
        isSubmit: false,
        visible: false,
        loading: false,
        returnForm: {
          filedPaperType: '',
          filedType: '',
          contractFees: [],
          actualContractAmount: '',
          uscCode: '',
          customerId: '',  // 客户id
          address: '',
          filedNo: '',
          confirmFiledNo: '',
          clientId: '',
          name: '',
          contractDate: '',
          effectiveDate: '',
          closingDate: '',
          contractType: '',
          contractAmountType: '',
          contractAmount: '',
          predictAmount: '',
          contractOpposite: '',
          fees: '',
          contractFee: '',
          describes: '',
          contractSpecial: '',
          remarks: '',
          clientName: '',
          status: '',
          contractProperList: [],
          contractInfoList: [],
          customerNo: '',
          customerName: ''
        },
        inputForm: {
          filedPaperType: '',
          filedNo: '',
          confirmFiledNo: '',
          contractAmountType: '',
          contractFees: [],
          contractFee: '',
          customerNo: '',
          uscCode: '',
          customerId: '',  // 客户id
          address: '',
          filedType: '',
          contractNo: '',
          contractSerialNumber: '',
          contractType: '',
          contractName: '',
          payerSubject: '',
          paymentMethod: '',
          paymentDescribe: '',
          contractInfoId: '',
          signingDate: '',
          contractAmount: '',
          predictAmount: '',
          actualContractAmount: '',
          contractNum: '',
          contractStatus: '',
          paymentAgreement: '',
          changeNum: '',
          department: '',
          clientContacts: '',
          clientContactsPhone: '',
          contractApprovalType: '',
          createBy: JSON.parse(localStorage.getItem('user')).name,
          createId: JSON.parse(localStorage.getItem('user')).id,
          createDate: '',
          contractProperList: [],
          contractInfoList: []
        },
        activeName: 'uploadFile',
        activeNameTop: 'contract',
        filesArra2: [],
        fileList: [],
        isFlag: true,
        showViewer: false, // 显示查看器
        url: '',
        rowurl: '',
        src: '',
        onedit: false,
        type: '',
        loadProgress: 0, // 动态显示进度条
        progressFlag: false, // 关闭进度条
        promi: null,
        keyWatch: '',
        tableKeyClient: '1',
        projectList: [],
        projectForm: {
          projectName: '',
          projectNumber: ''
        },
        invoiceList: [],
        invoiceForm: {
          no: ''
        },
        reportForm: {
          reportNo: '',
          projectName: '',
          projectNumber: ''
        },
        reportList: []
      }
    },
    props: {
      businessId: {
        type: String,
        default: ''
      },
      formReadOnly: {
        type: Boolean,
        default: false
      },
      status: {
        type: String,
        default: ''
      }
    },
    components: {
      ElImageViewer,
      UpLoadComponent,
      WorkClientChooseForm,
      SelectTree,
      WorkClientChooseRadio,
      WorkClientForm: () => import('../workClientInfo/WorkClientForm'),
      ProjectRecordsForm: () => import('../projectRecords/ProjectRecordsForm'),
      InvoiceForm: () => import('../invoice/InvoiceForm'),
      ReportManagementForm: () => import('../reportManagement/ReportManagementForm')
    },
    ossService: null,
    // workContractService: null,
    contractInfoService: null,
    contractFileService: null,
    projectRecordsService: null,
    cwFinanceInvoiceService: null,
    projectReportService: null,
    created () {
      this.ossService = new OSSSerive()
      // this.workContractService = new WorkContractService()
      this.contractInfoService = new ContractInfoService()
      this.contractFileService = new ContractFileService()
      this.projectRecordsService = new ProjectRecordsService()
      this.cwFinanceInvoiceService = new CwFinanceInvoiceService()
      this.projectReportService = new ProjectReportService()
    },
    mounted () {
      window.onPreview = this.onPreview
    },
    computed: {
      officeName () {
        return JSON.parse(localStorage.getItem('user')).officeDTO.name
      },
      bus: {
        get () {
          // this.$refs.archiveFile.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()
            })
          }
        }
      }
    },
    methods: {
      // checkFiledNo () {
      //   let filedNo = this.inputForm.filedNo
      //   let confirmFiledNo = this.inputForm.confirmFiledNo
      //   if (filedNo !== confirmFiledNo) {
      //     this.$message.warning(`案卷号和确认案卷号不一致`)
      //     this.inputForm.confirmFiledNo = ''
      //   }
      // },
      getKeyWatch (keyWatch) {
        this.keyWatch = keyWatch
      },
      uploadVideoProcess (event, file, fileList) {
        this.progressFlag = true // 显示进度条
        this.loadProgress = parseInt(event.percent) // 动态获取文件上传进度
        if (this.loadProgress >= 100) {
          this.loadProgress = 100
          setTimeout(() => { this.progressFlag = false }, 1000) // 一秒后关闭进度条
        }
      },
      async toHref (row) {
        toHref(row)
      },
      onPreview (url) {
        this.url = url
        this.showViewer = true
      },
      // 关闭查看器
      closeViewer () {
        this.url = ''
        this.showViewer = false
      },
      init (method, id) {
        // console.log(method)
        // console.log('id', id)
        this.activeNameTop = 'contract'
        this.dataList = []
        this.dataListNew = []
        if (method === 'edit') {
          this.method = method
          this.title = '合同信息修改'
        } else {
          this.method = 'view'
          this.title = '合同信息详情'
        }
        this.inputForm = {
          contractOpposite: '',
          filedPaperType: '',
          filedType: '',
          filedNo: '',
          confirmFiledNo: '',
          contractAmountType: '',
          contractFee: '',
          contractFees: [],
          customerNo: '',
          uscCode: '',
          customerId: '',  // 客户id
          address: '',
          contractNo: '',
          contractSerialNumber: '',
          contractType: '',
          contractName: '',
          payerSubject: '',
          paymentMethod: '',
          paymentDescribe: '',
          signingDate: '',
          contractAmount: '',
          predictAmount: '',
          actualContractAmount: '',
          contractNum: '',
          contractStatus: '',
          paymentAgreement: '',
          changeNum: '',
          department: '',
          clientContacts: '',
          contractInfoId: '',
          clientContactsPhone: '',
          contractApprovalType: '',
          createBy: JSON.parse(localStorage.getItem('user')).name,
          createId: JSON.parse(localStorage.getItem('user')).id,
          createDate: '',
          contractProperList: [],
          contractInfoList: [],
          cwWorkClientContactDTOList: []
        }
        this.inputForm.id = id
        if (method === 'add') {
          // this.inputForm.contractAmountType = '1'
          this.title = `新建合同登记`
        } else if (method === 'edit') {
          this.title = '修改合同登记'
        } else if (method === 'view') {
          this.inputForm.showVi = false
          this.title = '查看合同登记'
        }
        this.visible = true
        this.loading = false
        this.$nextTick(() => {
          this.loading = true
          this.$refs.uploadFile.clearUpload()
          // this.$refs.archiveFile.clearUpload()
          // if (this.inputForm.filedType !== '0') {
          //   this.$refs.archiveFile.clearUpload()
          // }
          // 查询合同登记数据
          // console.log('this.inputForm.id', this.inputForm.id)
          this.contractInfoService.findById(this.inputForm.id).then(({data}) => {
            this.inputForm = this.recover(this.inputForm, data)
            // console.log('this.inputForm.filedPaperType', this.inputForm.filedPaperType)
            const f = []
            console.log('data.fees', data.fees)
            if (data.fees !== null && data.fees !== undefined && data.fees !== '') {
              data.fees.split(',').forEach(item => {
                if (item !== null && item !== undefined && item !== '') {
                  f.push(item)
                }
              })
            }
            this.inputForm.contractFees = f
            if (this.formReadOnly) {
              method = 'view'
            }
            // console.log('data', data)
            // console.log('this.inputForm.contractProperList', this.inputForm.contractProperList)
            // console.log('this.inputForm.contractInfoList', this.inputForm.contractInfoList)
            if (this.commonJS.isEmpty(this.inputForm.contractProperList)) {
              this.inputForm.contractProperList = []
            }
            if (this.commonJS.isEmpty(this.inputForm.contractInfoList)) {
              this.inputForm.contractInfoList = []
            }
            this.$refs.uploadFile.newUpload(method, this.inputForm.contractProperList, 'cwWorkContract', null, null, null, null, false)
            // this.$refs.archiveFile.newUpload('view', this.inputForm.contractInfoList, 'cwWorkContract', null, null, null, null, false)
            // this.$refs.archiveFile.setDividerName('', false)
            this.loading = false
          })
          // 获取关联项目信息
          this.projectRecordsService.getByContractId(this.inputForm.id).then((project) => {
            this.projectList = project.data
          })
          // 获取关联报告信息
          this.projectReportService.getIdByContractId(this.inputForm.id, this.reportForm).then(({data}) => {
            this.reportList = data
          })
          // 查询关联发票信息
          this.cwFinanceInvoiceService.getByContractId(this.inputForm.id, this.invoiceForm).then(({data}) => {
            let _this = this
            let _data = data
            const wait = function () {
              return new Promise((resolve, reject) => {
                _this.invoiceList = _data
                resolve()
              })
            }
            wait().then(() => {
              this.invoiceList.forEach(item => {
                item.account = parseFloat(item.account).toFixed(2)
                if (!this.commonJS.isEmpty(item.financeInvoiceDetailDTOList)) {
                  item.accountDetail = 0
                  let num = ''
                  item.financeInvoiceDetailDTOList.forEach((detail, index) => {
                    if (!this.commonJS.isEmpty(detail.account)) {
                      item.accountDetail = parseFloat(parseFloat(item.accountDetail) + parseFloat(detail.account)).toFixed(2)
                    }
                    if ((index + 1) !== item.financeInvoiceDetailDTOList.length) {
                      num = num + detail.number + ','
                    } else {
                      num = num + detail.number
                    }
                  })
                  item.number = num
                } else {
                  item.number = ''
                  item.accountDetail = ''
                }
              })
            })
          })
        }
        )
      },
      // 表单提交  保存数据
      doSubmit (status, callback) {
        if (/* this.$refs.archiveFile.checkProgress() || */ this.$refs.uploadFile.checkProgress()) {
          this.loading = false
          throw new Error()
        } else {
          if (status === 'save') {
            this.$refs['inputForm'].validate((valid) => {
              if (valid) {
                this.loading = true
                if (this.inputForm.filedPaperType !== '0' & this.inputForm.filedPaperType !== '') {
                  if (this.inputForm.filedNo === '' || this.inputForm.filedNo === undefined) {
                    this.loading = false
                    this.$message.error('请填写案卷号')
                    throw new Error('请填写案卷号')
                  }
                  // if (this.inputForm.confirmFiledNo === '' || this.inputForm.confirmFiledNo === undefined) {
                  //   this.loading = false
                  //   this.$message.error('请填写确认案卷号')
                  //   throw new Error('请填写确认案卷号')
                  // }
                }
                this.inputForm.status = '5'
                this.inputForm.filedType = '5'
                this.inputForm.contractProperList = this.$refs.uploadFile.getDataList()
                // this.inputForm.contractInfoList = this.$refs.archiveFile.getDataList()
                this.inputForm.fees = this.inputForm.contractFees.join(',')
                this.contractInfoService.save(this.inputForm).then(() => {
                  this.$emit('refreshDataList')
                  this.loading = false
                  this.close()
                }).catch(() => {
                  this.$refs.inputForm.resetFields()
                  this.loading = false
                })
              }
            })
          }
        }
      },
      tabHandleClick (event) {
        // console.log(event)
      },
      tabHandleClickTop (event) {
        // console.log(event)
      },
      saveData (data, method) {
        // console.log('data', data)
        this.inputForm = this.recover(this.inputForm, data)
        this.inputForm = JSON.parse(JSON.stringify(this.inputForm))
      },
      removeEvent (row, rowIndex, type) {
        if (type === 'client') {
          this.$refs.contactTable.remove(row)
          this.inputForm.cwWorkClientContactDTOList.splice(rowIndex, 1)
        }
      },
      openWorkClient () {
        this.$refs.workClientChooseForm.init()
      },
      openWorkClient2 () {
        this.$refs.workClientChooseRadio.init()
      },
      getWorkClientChoose (list) {
        // console.log('list', list)
        if (this.commonJS.isEmpty(this.inputForm.cwWorkClientContactDTOList)) {
          this.inputForm.cwWorkClientContactDTOList = []
        }
        let _this = this
        let _list = list
        const waitForEach = function () {
          return new Promise(function (resolve, reject) {
            _list.forEach((item) => {
              _this.inputForm.cwWorkClientContactDTOList.forEach(client => {
                if (item.no === client.no) {
                  _this.$message.error('已存在客户 “' + client.name + '”，请重新选择')
                  throw new Error('已存在客户 “' + client.name + '”，请重新选择')
                }
              })
            })
            resolve()
          })
        }
        waitForEach().then(() => {
          list.forEach(item => {
            this.$refs.contactTable.insertAt(item)
            this.inputForm.cwWorkClientContactDTOList.push(item)
            this.tableKeyClient = Math.random()
          })
        })
      },
      getWorkClientChoose2 (list) {
        if (this.commonJS.isEmpty(this.inputForm.cwWorkClientContactDTOList)) {
          this.inputForm.cwWorkClientContactDTOList = []
        }
        // console.log('list', list)
        let _this = this
        let _list = list
        const waitForEach = function () {
          return new Promise(function (resolve, reject) {
            _this.inputForm.cwWorkClientContactDTOList.forEach(client => {
              if (_list.no === client.no) {
                _this.$message.error('已存在客户 “' + client.name + '”，请重新选择')
                throw new Error('已存在客户 “' + client.name + '”，请重新选择')
              }
            })
            resolve()
          })
        }
        waitForEach().then(() => {
          // eslint-disable-next-line no-unused-vars
          let item = {
            no: list.no,
            name: list.name
          }
          // console.log('list', list)
          this.inputForm.customerNo = list.no
          this.inputForm.uscCode = list.uscCode
          this.inputForm.address = list.address
          this.inputForm.customerId = list.id
          this.inputForm.cwWorkClientContactDTOList.push(item)
          this.inputForm.clientContacts = list.name
          this.inputForm.clientContactsPhone = list.mobile
        })
      },
      close () {
        this.$refs.inputForm.resetFields()
        this.inputForm.clientName = ''
        this.visible = false
        this.showVi = true
        // if (this.inputForm.filedType !== '0') {
        //   this.$refs.archiveFile.clearUpload()
        // }
      },
      httpRequest (file) {
        httpRequest(file, fileName(file), 'workContract')
      },
      handleRemove () {
        this.fileList = handleRemove()
      },
      changes (file, fileList) {
        this.dataListNew = []
        this.dataList.forEach((item) => {
          this.dataListNew.push(item)
        })
        fileList.forEach((item) => {
          item.createDate = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
          item.createBy = this.$store.state.user.name
          this.dataListNew.push(item)
        })
        const isLt2M = file.size / 1024 / 1024 < 300
        if (isLt2M === false) {
          this.$message.error('文件大小不能超过 ' + 300 + 'M !')
          this.fileList = []
          this.filesArra2 = []
        }
      },
      async showFile (row) {
        await openWindowOnUrl(row)
      },
      // 排序
      sortChangeHandle (column) {
        this.orders = []
        if (column.order != null) {
          this.orders.push({column: this.$utils.toLine(column.prop), asc: column.order === 'ascending'})
        }
        this.refreshList()
      },
      deleteMsgById (row, index) {
        this.dataListNew.splice(index, 1)
        if (row.id !== null && row.id !== '' && row.id !== undefined) {
          this.ossService.deleteMsgById(row.id)
        }
      },
      twoDecimalPlaces (num) {
        let str = num.toString()
        var len1 = str.substr(0, 1)
        var len2 = str.substr(1, 1)
        // eslint-disable-next-line eqeqeq
        if (str.length > 1 && len1 == 0 && len2 != '.') {
          str = str.substr(1, 1)
        }
        // eslint-disable-next-line eqeqeq
        if (len1 == '.') {
          str = ''
        }
        // eslint-disable-next-line eqeqeq
        if (str.indexOf('.') != -1) {
          var str_ = str.substr(str.indexOf('.') + 1)
          // eslint-disable-next-line eqeqeq
          if (str_.indexOf('.') != -1) {
            str = str.substr(0, str.indexOf('.') + str_.indexOf('.') + 1)
          }
          if (str_.length > 2) {
            this.$message.warning(`金额小数点后只能输入两位，请正确输入！`)
            return (str = '')
          }
        }
        // eslint-disable-next-line no-useless-escape
        str = str.replace(/[^\d^\.]+/g, '') // 保留数字和小数点
        return str
      },
      positiveInteger (num) {
        let str = num.toString()
        var len1 = str.substr(0, 1)
        var len2 = str.substr(1, 1)
        // eslint-disable-next-line eqeqeq
        if (str.length > 1 && len1 == 0 && len2 != '.') {
          str = str.substr(1, 1)
        }
        // eslint-disable-next-line eqeqeq
        if (len1 == '.') {
          str = ''
        }
        // eslint-disable-next-line no-useless-escape
        str = str.replace(/[^\d^]+/g, '') // 保留数字
        return str
      },
      tableRowClassName ({row, rowIndex}) {
        row.index = rowIndex
      },
      handleRadioChange (val) {
        if (val) {
          this.radio = val.index
        }
      },
      // 关闭窗口时调用
      closeXTable () {
        this.closePop()
      },
      rowStyle (event) {
        return 'cursor:pointer;'
      },
      closePop () {
        this.visable = false
      },
      updateStatusById (type) {
        // console.log('type' + type)
        if (type === 'agree') {
          this.inputForm.filedType = '5'
          this.contractFileService.updateStatusById(this.inputForm)
        }
        // 驳回
        if (type === 'reject') {
          this.inputForm.filedType = '4'
          this.contractFileService.updateStatusById(this.inputForm)
        }
        if (type === 'reback') {
          this.inputForm.filedType = '3'
          this.contractFileService.updateStatusById(this.inputForm)
        }
        // 流程终止，调整为暂存状态
        if (type === 'hold') {
          this.inputForm.filedType = '1'
          this.contractFileService.updateStatusById(this.inputForm)
        }
      },
      checkData () {
        let begin = this.inputForm.effectiveDate
        let close = this.inputForm.closingDate
        if (close < begin) {
          this.$message.warning(`合同终止日期要大于合同开始日期`)
          this.inputForm.closingDate = ''
        }
      },
      changeContractFee () {
        let fee = ''
        let fees = this.inputForm.contractFees
        if (fees.length > 0) {
          fees.forEach(i => {
            if (i === '1') {
              i = '苏会协[2010]52号'
              fee = fee + ';' + i
            }
            if (i === '2') {
              i = '苏政办发[2010]101号'
              fee = fee + ';' + i
            }
            if (i === '3') {
              i = '苏价费[2010]284号'
              fee = fee + ';' + i
            }
            if (i === '4') {
              i = '发改价格[2010]196号'
              fee = fee + ';' + i
            }
            if (i === '5') {
              i = '其他'
              fee = fee + ';' + i
            }
            this.inputForm.contractFee = fee.substring(1, fee.length)
          })
        } else {
          this.inputForm.contractFee = ''
        }
      },
      // 查看客户信息详情
      viewClient (id) {
        this.$refs.workClientForm.init('view', id)
      },
      viewProject (id) {
        this.$refs.projectRecordsForm.init('view', id)
      },
      searchProject () {
        this.loading = true
        this.projectRecordsService.getByContractId(this.inputForm.id, this.projectForm).then(({data}) => {
          this.projectList = data
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      },
      refreshProjectForm () {
        this.$refs.projectForm.resetFields()
        this.searchProject()
      },
      searchInvoice () {
        this.loading = true
        this.cwFinanceInvoiceService.getByContractId(this.inputForm.id, this.invoiceForm).then(({data}) => {
          let _this = this
          let _data = data
          const wait = function () {
            return new Promise((resolve, reject) => {
              _this.invoiceList = _data
              resolve()
            })
          }
          wait().then(() => {
            this.invoiceList.forEach(item => {
              item.account = parseFloat(item.account).toFixed(2)
              if (!this.commonJS.isEmpty(item.financeInvoiceDetailDTOList)) {
                item.accountDetail = 0
                let num = ''
                item.financeInvoiceDetailDTOList.forEach((detail, index) => {
                  if (!this.commonJS.isEmpty(detail.account)) {
                    item.accountDetail = parseFloat(parseFloat(item.accountDetail) + parseFloat(detail.account)).toFixed(2)
                  }
                  if ((index + 1) !== item.financeInvoiceDetailDTOList.length) {
                    num = num + detail.number + ','
                  } else {
                    num = num + detail.number
                  }
                })
                item.number = num
              } else {
                item.number = ''
                item.accountDetail = ''
              }
            })
          })
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      },
      refreshInvoiceForm () {
        this.$refs.invoiceForm.resetFields()
        this.searchInvoice()
      },
      viewInvoice (flag, id) {
        this.$refs.invoiceFormDialog.init(flag, id)
      },
      searchReport () {
        this.loading = true
        this.projectReportService.getIdByContractId(this.inputForm.id, this.reportForm).then(({data}) => {
          this.reportList = data
          this.loading = false
        })
      },
      refreshReportForm () {
        this.$refs.reportForm.resetFields()
        this.searchReport()
      },
      viewReport (id) {
        this.$refs.reportManagementForm.init('view', id)
      }
    }
  }
</script>

<style>
  .tid_40 .vxe-body--column .vxe-cell{
    padding: 1px;
    text-align: center;
  }
  .tid_40 .vxe-header--row .col--last{
    text-align: center;
  }
  .tid_45 .vxe-body--column .vxe-cell{
    padding: 1px;
    text-align: center;
  }
  .tid_45 .vxe-header--row .col--last{
    text-align: center;
  }
</style>

<style scoped>
  .avatar{
    height: 100px;
  }
  .el-divider__text {
    font-weight: bold;
    font-size: 16px;
  }
</style>
