<template>
  <div class="account-container">
    <div class="account-title" style="margin-bottom: 16px;align-items: center;display: flex;width:97.6vw">
      {{ accountTitle }}
      <div style="margin-left: auto;">
        <!--        保存草稿-->
        <el-button v-hasPermi="['bt:business:eq:saveDraft']" type="primary" @click="saveDraft" icon="el-icon-document-add" v-if="typeIn(['add','edit'])">{{ $t('quotation.saveDraft') }}</el-button>
        <!--        新增/更新报价-->
        <el-button v-hasPermi="['bt:business:eq:saveAndSubmit']" type="primary" @click="submitForm" icon="el-icon-circle-check" v-if="typeIn(['add','edit'])">{{ $t('audit.saveAndSubmit') }}</el-button>
        <!--        评审通过-->
        <el-button v-hasPermi="['bt:business:eq:reviewAccept']" type="primary" @click="handleReviewAccept" v-if="typeIn(['techReview'])">
          <i class="el-icon-pass"/>{{ $t('quotation.reviewAccept') }}
        </el-button>
        <!--        评审拒绝-->
        <el-button v-hasPermi="['bt:business:eq:reviewReject']" type="primary" @click="handleReviewReject" v-if="typeIn(['techReview'])">
          <i class="el-icon-reject"/>{{ $t('quotation.reviewReject') }}
        </el-button>
        <!--        财务确认-->
        <el-button v-hasPermi="['bt:business:eq:treasureConfirm']" type="primary" @click="handleTreasureConfirm" v-if="typeIn(['treasureInquiry'])">
          <i class="el-icon-pass"/>{{ $t('quotation.treasureConfirm') }}
        </el-button>
        <!--        销售确认-->
        <el-button v-hasPermi="['bt:business:eq:salesConfirm']" type="primary" @click="handleSalesConfirm" v-if="typeIn(['salesConfirm'])">
          <i class="el-icon-pass"/>{{ $t('quotation.salesConfirm') }}
        </el-button>
        <!--        销售驳货-->
        <el-button v-hasPermi="['bt:business:eq:salesConfirm']" type="primary" @click="handleSalesReject" v-if="typeIn(['salesConfirm'])">
          <i class="el-icon-reject"/>{{ $t('quotation.salesReject') }}
        </el-button>
        <!--        发起议价-->
        <el-button v-hasPermi="['bt:business:eq:confirmBargain']" type="primary" icon="el-icon-circle-check" @click="confirmBargain" v-if="typeIn(['bargain'])">
          {{ $t('quotation.confirmBargain') }}
        </el-button>
        <!--        议价审批 - 通过-->
        <el-button v-hasPermi="['bt:business:eq:bargainPass']" type="primary" @click="bargainPass" v-if="typeIn(['bargainApproval'])">
          <i class="el-icon-pass"/>{{ $t('project.pass') }}
        </el-button>
        <!--        议价审批 - 驳回-->
        <el-button v-hasPermi="['bt:business:eq:bargainReject']" type="primary" @click="bargainRejectDialogShow" v-if="typeIn(['bargainApproval']) && ![114].includes(Number(flowStatus))">
          <i class="el-icon-reject"/>{{ $t('quotation.reject') }}
        </el-button>
        <!--        接受价格-->
        <el-button v-hasPermi="['bt:business:eq:acceptPrice']" type="primary" @click="acceptPrice" v-if="typeIn(['bargainConfirm', 'bargainAccept'])">
          <i class="el-icon-pass"/>{{ $t('quotation.acceptPrice') }}
        </el-button>
        <!--        议价(不接受价格)-->
        <el-button v-hasPermi="['bt:business:eq:rejectPrice']" type="primary" @click="rejectPrice" v-if="typeIn(['bargainConfirm'])">
          <i class="el-icon-reject"/>{{ $t('quotation.negotiatedPrice') }}
        </el-button>

        <!--        返回-->
        <el-button @click="cancel" icon="el-icon-remove-outline">{{ $t('common.cancel') }}</el-button>
      </div>
    </div>
    <div class="content">
      <div class="card card-base card-full">
        <!--        <div class="flex-center-left mb16">-->
        <!--          <img class="item-size" src="@/assets/images/account-item.png" alt="">-->
        <!--          <div class="card-title">{{ $t('quotation.baseInfo') }}</div>-->
        <!--        </div>-->
        <el-form class="account-form" ref="form" :model="form" :rules="rules" label-position="top">
          <el-row :gutter="24" >
            <template v-if="versionFlag">
              <el-col :span="6">
                <!--报价编号-->
                <el-form-item :label="$t('quotation.quotationNo')" prop="quotationNo">
                  <el-input :disabled="true" v-model="form.quotationNo" style="width:16vw;"
                            :placeholder="$t('common.pleaseInput') + $t('quotation.quotationNo')">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <!--版本 -->
                <el-form-item :label="$t('quotation.version')" prop="version">
                  <el-input :disabled="true" v-model="form.version"
                            :placeholder="$t('common.pleaseInput') + $t('quotation.version')" style="width: 16vw;"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <!--报价者 -->
                <el-form-item :label="$t('quotation.quoter')" prop="quoter">
                  <el-input :disabled="true" v-model="form.quoter"
                            :placeholder="$t('common.pleaseInput') + $t('quotation.quoter')" style="width: 16vw;"/>
                </el-form-item>
              </el-col>
            </template>
            <el-col :span="type === 'add'? 12 : 6">
              <!-- 关联项目 -->
              <el-form-item :label="$t('follow.relatedProject')" prop="relatedProjectId">
                <el-select v-if="!disableFlag" v-model="form.relatedProjectId" @change="projectChange" :filterable="true"
                          :placeholder="$t('common.pleaseSelect') + $t('follow.relatedProject')" :style="{width: type === 'add'? '40vw': '16vw'}">
                  <el-option v-for="item in projectList" :key="Number(item.value)"
                            :label="item.label" :value="Number(item.value)"/>
                </el-select>
                <div v-else class="disabled-box" :style="{width: type === 'add'? '40vw': '16vw'}">
                  <span class="link-type" @click="$router.push('/project-view/' + form.projectId)">
                    {{ form.projectNo }}
                  </span>
                </div>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row  :gutter="24" >
            <el-col :span="6">
            <!--币种 -->
            <el-form-item :label="$t('project.currency')" prop="currencyId">
              <!--                <el-select :disabled="disableFlag" v-model="form.currencyId" clearable style="width:16vw;"-->
              <!--                           :placeholder="$t('common.pleaseSelect') + $t('project.currency')">-->
              <!--                  <el-option v-for="dict in currencyList" :key="dict.currencyId"-->
              <!--                             :label="dict.currencyName" :value="dict.currencyId"/>-->
              <!--                </el-select>-->
              <el-select :disabled="true" v-model="form.currencyId" clearable style="width:16vw;"
                          :placeholder="$t('common.pleaseSelect') + $t('project.currency')">
                <el-option v-for="dict in dict.type.currency_type" :key="dict.value"
                            :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            </el-col>
            <el-col :span="6">
              <!--代理商-->
              <el-form-item :label="$t('agent.agent')" prop="agentId">
                <el-select :disabled="true" v-model="form.agentId" clearable style="width:16vw;"
                          :placeholder="$t('common.pleaseSelect') + $t('agent.agent')">
                  <el-option v-for="dict in agentList" :key="dict.value"
                            :label="dict.label" :value="dict.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <!--国家 -->
              <el-form-item :label="$t('account.country')" prop="countryId">
                <el-select :disabled="true" v-model="form.countryId" clearable style="width:16vw;"
                          :placeholder="$t('common.pleaseSelect') + $t('account.country')">
                  <el-option v-for="dict in countryList" :key="Number(dict.value)"
                            :label="dict.label" :value="Number(dict.value)"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <!--城市 -->
              <el-form-item :label="$t('project.city')" prop="city">
                <el-input :disabled="true" v-model="form.city" maxlength="100" clearable style="width:16vw;"
                          :placeholder="$t('common.pleaseInput') + $t('project.city')"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <!-- 电梯一览 -->
        <div class="contact-box">
          <div class="flex-center-left mb16">
            <img class="item-size" src="@/assets/images/account-item.png">
            <div class="card-title">{{ $t('quotation.elevatorView') }}</div>
          </div>
          <div>
            <el-button v-hasPermi="['bt:business:eq:addElevator']" type="primary" icon="el-icon-plus" size="mini" @click="addLine" v-if="typeIn(['add','edit'])">
              {{ $t('quotation.addElevator') }}
            </el-button>
            <div class="leave-msg" @click="startChat" v-if="typeNotIn(['add','edit'])">
              <div class="chat-div">
                <img class="chat-img" :src="require('@/assets/images/liaotianshi.svg')">
              </div>
              <div class="chat-room">{{ $t('quotation.leaveMsg') }}</div>
            </div>
          </div>
          <el-table :data="elevatorList" max-height="310px" v-loading="tableLoading" style="margin-bottom: 30px"
                    :header-cell-style="tableHeaderStyle" :border="true" class="table-class">
            <el-table-column prop="index" label="No." type="index" width="50"></el-table-column>
            <el-table-column prop="elevatorModel" :label="$t('elevatorModel.elevatorModel')" min-width="150px"/>
            <el-table-column prop="elevatorNumber" :label="$t('quotation.count')" min-width="100px"/>
            <el-table-column prop="elevatorCode" :label="$t('quotation.elevatorNo')" min-width="200px"/>
            <el-table-column prop="specification" :label="$t('quotation.specification')" min-width="300px"/>
            <!--            基价-->
            <el-table-column prop="basicPrice" :label="`${$t('quotation.basicPrice')}`" v-if="typeNotIn(['add','edit']) && Number(form.quotationStatus) >= 6 && checkPermi(['business:quotation:sys'])" min-width="120px" align="right">
              <template slot-scope="scope">
                {{ currencyParam() + ' ' + numFormat(scope.row.basicPrice) }}
              </template>
            </el-table-column>

            <!--            层站差价-->
            <el-table-column prop="floorDiffPrice" :label="`${$t('quotation.floorDiffPrice')}`" v-if="typeNotIn(['add','edit']) && Number(form.quotationStatus) >= 6 && checkPermi(['business:quotation:sys'])" min-width="120px" align="right">
              <template slot-scope="scope">
                {{ currencyParam() + ' ' + numFormat(scope.row.floorDiffPrice) }}
              </template>
            </el-table-column>

            <!--            其他选配价-->
            <el-table-column prop="otherOptionalPrice" :label="`${$t('quotation.otherOptionalPrice')}`" v-if="typeNotIn(['add','edit']) && Number(form.quotationStatus) >= 6 && checkPermi(['business:quotation:sys'])" min-width="140px" align="right">
              <template slot-scope="scope">
                {{ currencyParam() + ' ' + numFormat(scope.row.otherOptionalPrice) }}
              </template>
            </el-table-column>

            <!--            价格-->
            <el-table-column prop="price" :label="`${$t('quotation.price')}`" v-if="typeNotIn(['add','edit']) && Number(form.quotationStatus) >= 6 && checkPermi(['business:quotation:sys'])" min-width="120px" align="right">
              <template slot-scope="scope">
                {{ currencyParam() + ' ' + numFormat(scope.row.price) }}
              </template>
            </el-table-column>
            <!--            最终价格-->
            <el-table-column prop="finalPrice" :label="$t('quotation.finalPrice')" v-if="typeIn(['view'])  && Number(form.quotationStatus) >= 9 && checkPermi(['business:quotation:sys'])" min-width="120px" align="right">
              <template slot-scope="scope">
                <span v-if="scope.row.finalPrice != null">{{ currencyParam() + ' ' + numFormat(scope.row.finalPrice) }}</span>
                <span v-else>-</span>
              </template>
            </el-table-column>

            <!--            基价折率-->
            <el-table-column prop="discountRate" :label="$t('quotation.benchmarkPriceRate')" v-if="typeIn(['bargainApproval','bargainConfirm']) && !agentFlag && checkPermi(['business:quotation:sys'])" min-width="300px" align="center">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.discountRate" style="width: 250px;" @change="tableDiscountRateChange(scope.row)" :disabled="![111, 112, 113, 114, 115].includes(Number(flowStatus))"
                                 v-if="typeIn(['bargainApproval'])" :controls="false" :min="1"  :precision="4"
                                 :placeholder="$t('common.pleaseInput') + $t('quotation.basicRate')"/>
                <span v-else>{{ toDecimal4(scope.row.discountRate) }}</span>
              </template>
            </el-table-column>
            <!--            折后价格-->
            <el-table-column prop="discountPrice" :label="`${$t('quotation.discountedPrice')}`" v-if="(Number(form.quotationStatus) >= 8 && form.quotationStatus != '10') || (typeIn(['bargainApproval','bargainConfirm']) && !agentFlag && checkPermi(['business:quotation:sys']))" min-width="180px" align="right">
              <template slot-scope="scope">
                {{ currencyParam() + ' ' + numFormat(scope.row.discountPrice) }}
              </template>
            </el-table-column>
            <!--            是否标准-->
            <el-table-column prop="systemCheckResult" :label="$t('quotation.isStandard')" v-if="typeIn(['techReview','buyerInquiry','treasureInquiry'])" min-width="100px" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.systemCheckResult === '00'" style="color: #218AFC">{{ convertCheckResult(scope.row.systemCheckResult) }}</span>
                <span v-else style="color: #D71943">{{ convertCheckResult(scope.row.systemCheckResult) }}</span>
              </template>
            </el-table-column>
            <el-table-column :label="$t('quotation.civilImage')" width="220px" align="center" v-if="type !== 'add' && $route.query.typeParam !== 'copy'">
              <template slot-scope="scope">
                <el-upload :limit="1" v-if="scope.row.quotationId"
                  :class="{ 'disabled-upload': Boolean(elevatorList[scope.$index].file) }"
                  :file-list="scope.row.fileList" :headers="headers"
                  :on-remove="(file, fileList) => handleRemove(file, fileList, scope.$index)"
                  :on-success="(response, file) => handleUploadSuccess(response, file, scope.$index, scope.row.id)"
                  :on-exceed="handleExceed" :on-preview="() => handlePictureCardPreview2(scope.row.file)"
                  :show-file-list="Boolean(elevatorList[scope.$index].file)" :action="uploadImgUrl">
                  <el-button size="small" v-if="!elevatorList[scope.$index].file">{{ $t('import.upload') }}</el-button>
                </el-upload>
              </template>
            </el-table-column>
            <!--            报价状态-->
            <el-table-column prop="quotationStatus" :label="$t('quotation.quotationStatus')" v-if="typeNotIn(['add'])" min-width="180px" align="center">
              <template slot-scope="scope">
                <ColorDictTag :bgc="statusColorMap[scope.row.quotationStatus].bgc"
                              :label="convertStatus(scope.row.quotationStatus)"
                              :label-color="statusColorMap[scope.row.quotationStatus].color"/>
              </template>
            </el-table-column>

            <el-table-column prop="createTime1" :label="$t('common.createTime')" min-width="150px"/>
            <el-table-column prop="operate" :label="$t('common.operate')" :width="getOperateColWidth()" fixed="right">
              <template slot-scope="scope">
                <!--                价格明细-->
                <el-button size="mini" v-hasPermi="['business:quotation:sys']" v-if="typeNotIn(['add']) && Number(form.quotationStatus) >= 1 && checkPermi(['business:quotation:sys'])"
                           type="text" @click="toPriceDetail(scope.row)">
                  <i class="el-icon-price-detail"/>{{ $t('quotation.priceDetailLabel') }}
                </el-button>
                <!--                系统评审-->
                <el-button v-hasPermi="['bt:business:eq:systemReviewResult']" size="mini" v-if="typeIn(['techReview']) && scope.row.systemCheckResult === '00'"
                           type="text" @click="toTechReview(scope.row,true)">
                  <i class="el-icon-sys-result"/>{{ $t('quotation.systemReviewResult') }}
                </el-button>
                <!--                技术评审-->
                <el-button v-hasPermi="['bt:business:eq:techReview']" size="mini" v-if="typeIn(['techReview']) && scope.row.systemCheckResult === '01'"
                           type="text" @click="toTechReview(scope.row,false)">
                  <i class="el-icon-tech"/>{{ $t('quotation.techReview') }}
                </el-button>
                <!--                财务报价-->
                <el-button v-hasPermi="['bt:business:eq:treasureQuotation']" size="mini" v-if="typeIn(['treasureInquiry'])  && scope.row.systemCheckResult === '01'"
                           type="text" @click="toQuotation(scope.row,1)">
                  <i class="el-icon-treasurer"/>{{ $t('quotation.treasureQuotation') }}
                </el-button>
                <!--                查看-->
                <el-button v-hasPermi="['bt:business:eq:techReview']" icon="el-icon-view" size="mini" v-if="typeIn(['add','edit'])"
                           type="text" @click="handleView(scope.row,false)">{{ $t('common.view') }}
                </el-button>
                <!--                编辑-->
                <el-button v-hasPermi="['bt:business:eq:techReview']" icon="el-icon-edit" size="mini" v-if="typeIn(['add','edit'])"
                           type="text" @click="handleUpdate(scope.row)">{{ $t('common.edit') }}
                </el-button>
                <!--                删除-->
                <el-button v-hasPermi="['bt:business:eq:techReview']" icon="el-icon-delete" size="mini" v-if="typeIn(['add','edit'])"
                           type="text" @click="handleDelete(scope.row)">{{ $t('common.delete') }}
                </el-button>
                <!--                电梯详细-->
                <el-button size="mini" v-if="typeNotIn(['add','edit'])"
                           type="text" @click="handleView(scope.row,false)">
                  <i class="el-icon-elevator-detail"/>{{ $t('quotation.elevatorDetail') }}
                </el-button>
                <!--                复制-->
                <el-button v-hasPermi="['bt:business:eq:techReview']" icon="el-icon-document-copy" size="mini" v-if="typeIn(['add','edit'])"
                           type="text" @click="handleCopy(scope.row)">{{ $t('common.copy') }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!--          <pagination v-show="total > 0 && typeNotIn(['add','edit'])"-->
          <!--                      :total="total"-->
          <!--                      :page.sync="pageNum" :limit.sync="pageSize" @pagination="getList"/>-->

        </div>
      </div>

      <div class="card card-base" style="width: 97.6vw;margin-top: 20px" v-if="typeIn(['bargain','bargainApproval','bargainConfirm','bargainAccept'])">
        <div class="flex-center-left mb16">
          <img class="item-size" src="@/assets/images/account-item.png" alt="">
          <div class="card-title">{{ $t('quotation.negotiatedPrice') }}</div>
        </div>
        <el-form class="account-form" ref="priceForm" :model="priceForm" label-position="top">
          <!--接收议价-->
          <div v-if="typeIn(['bargainAccept'])">
            <el-row :gutter="20">
              <el-col :span="8">
                <!-- 价格合计 -->
                <el-form-item :label="$t('quotation.totalQuotation')" prop="priceTotal">
                  <!--                  <el-input v-model="priceForm.priceTotalFormat" style="width: 16vw;" disabled key="priceTotal0"-->
                  <!--                            :placeholder="$t('common.pleaseInput') + $t('quotation.priceTotal')"/>-->
                  <span style="color: #D31017;font-weight: bold;font-size: 15px;padding-right: 5px;">{{ currencyParam()}}</span>
                  <span style="color: #D31017;font-weight: bold;font-size: 20px;">{{priceForm.priceTotalFormat}}</span>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <!--议价-->
          <div v-if="typeIn(['bargain'])">
            <el-row :gutter="20">
              <el-col :span="8">
                <!-- 价格合计 -->
                <el-form-item :label="$t('quotation.totalQuotation')" prop="priceTotal">
<!--                  <el-input v-model="priceForm.priceTotalFormat" style="width: 16vw;" disabled key="priceTotal0"-->
<!--                            :placeholder="$t('common.pleaseInput') + $t('quotation.priceTotal')"/>-->
                  <span style="color: #D31017;font-weight: bold;font-size: 15px;padding-right: 5px;">{{ currencyParam()}}</span>
                  <span style="color: #D31017;font-weight: bold;font-size: 20px;">{{priceForm.priceTotalFormat}}</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="3" v-if="this.priceForm.bargainMethod === 1">
                <!--价格 -->
                <el-form-item :label="$t('quotation.exceptedPrice')" prop="discountPriceTotal">
                  <span style="color: #000000;font-weight: bold;font-size: 15px;padding-right: 5px;">{{ currencyParam()}}</span>
                  <span style="width: 16vw;font-weight: bold;font-size: 20px;">{{priceForm.expectedPriceFormat}}</span>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <!-- 议价方式 -->
                <el-form-item :label="$t('quotation.bargainMethod')" prop="bargainMethod">
                  <el-select v-model="priceForm.bargainMethod" style="width:16vw;" key="bargainMethod"
                             :placeholder="$t('common.pleaseSelect') + $t('quotation.bargainMethod')">
                    <el-option v-for="dict in bargainMethodList" :key="dict.value"
                               :label="dict.label" :value="dict.value"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="5" v-if="this.priceForm.bargainMethod === 1">
                <!-- 折率 -->
                <el-form-item :label="$t('quotation.discountRate')" prop="discountRate">
                  <el-input-number v-model="priceForm.expectedRate" style="width: 16vw;" :precision="4" key="discountRate0"
                                   :min="0" @change="expectedRateChange" :controls="false"
                                   :placeholder="$t('common.pleaseInput') + $t('quotation.discountRate')"/>
                </el-form-item>
              </el-col>
              <el-col :span="5" v-if="this.priceForm.bargainMethod === 0">
                <!--价格 -->
                <el-form-item :label="$t('quotation.exceptedPrice')" prop="discountPriceTotal">
                  <el-input-number v-model="priceForm.expectedPrice" style="width: 16vw;" :precision="0" class="input-price" :min="0" key="discountPriceTotal0"
                                 @change="expectedPriceChange" :controls="false"
                                   :placeholder="$t('common.pleaseInput') + $t('quotation.price')"/>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!--议价审批-->
<!--          <div v-if="typeIn(['bargainApproval']) || (typeIn(['bargainConfirm']) && !agentFlag)">-->
          <div v-if="typeIn(['bargainApproval'])">
            <el-row :gutter="24">
              <el-col :span="5">
                <!-- 价格合计 -->
                <el-form-item :label="$t('quotation.totalQuotation')+':'" prop="priceTotal">
                  <span style="color: #000000;font-weight: bold;font-size: 15px;padding-right: 5px;">{{ currencyParam()}}</span>
                  <span style="font-weight: bold;font-size: 20px;">{{priceForm.priceTotalFormat}}</span>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <!-- 希望价格 -->
                <el-form-item :label="$t('quotation.exceptedPrice')+':'" prop="expectedPrice">
                  <span style="color: #000000;font-weight: bold;font-size: 15px;padding-right: 5px;">{{ currencyParam()}}</span>
                  <span style="font-weight: bold;font-size: 20px;">{{priceForm.expectedPriceFormat}}</span>
                  <span v-if="!agentFlag"> ({{$t('quotation.benchmarkPriceRate')}}{{priceForm.expectedBasicRate}}%)</span>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <!-- 价格合计 -->
                <el-form-item :label="$t('quotation.saleTotalQuotation')+':'" prop="priceTotal">
                  <span style="color: #D31017;font-weight: bold;font-size: 15px;padding-right: 5px;">{{ currencyParam()}}</span>
                  <span style="color: #D31017;font-weight: bold;font-size: 20px;">{{priceForm.discountPriceFormat}}</span>
                  <span v-if="!agentFlag"> ({{$t('quotation.benchmarkPriceRate')}}{{priceForm.discountRate}}%)</span>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!--议价确认-->
          <div v-if="typeIn(['bargainConfirm'])">
            <el-row :gutter="20">
              <el-col :span="8">
                <!-- 价格合计 -->
                <el-form-item :label="$t('quotation.totalQuotation')+':'" prop="priceTotal">
<!--                  <el-input v-model="priceForm.priceTotalFormat" style="width: 16vw;" disabled key="priceTotal3"
                            :placeholder="$t('common.pleaseInput') + $t('quotation.priceTotal')"/>-->
                  <span style="color: #D31017;font-weight: bold;font-size: 15px;padding-right: 5px;">{{ currencyParam()}}</span>
                  <span style="color: #b1b0b0;font-weight: bold;font-size: 20px;text-decoration: line-through;">{{priceForm.priceTotalFormat}}</span>
                  <span style="color: #D31017;font-weight: bold;font-size: 20px;"> {{priceForm.discountPriceFormat}}</span>
                  <span v-if="!agentFlag"> ({{$t('quotation.discountRate')}}{{priceForm.discountRate}}%)</span>
                </el-form-item>
              </el-col>
<!--              <el-col :span="8">
                &lt;!&ndash; 希望价格 &ndash;&gt;
                <el-form-item :label="$t('quotation.exceptedPrice')" prop="expectedPrice">
                  <el-input v-model="priceForm.expectedPriceFormat" style="width: 16vw;" disabled class="input-price" key="expectedPrice3"
                            :placeholder="$t('common.pleaseInput') + $t('quotation.exceptedPrice')"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                &lt;!&ndash;折后价格 &ndash;&gt;
                <el-form-item :label="$t('quotation.discountedPrice')" prop="discountPrice">
                  <el-input v-model="priceForm.discountPriceFormat" style="width: 16vw;" disabled class="input-price" key="discountPrice3"
                            :placeholder="$t('common.pleaseInput') + $t('quotation.discountedPrice')"/>
                </el-form-item>
              </el-col>-->
            </el-row>
          </div>
        </el-form>
      </div>

      <div class="card card-base" style="width: 97.6vw;margin-top: 20px" v-if="type === 'view' && Number(form.quotationStatus) >= 6 && checkPermi(['business:quotation:totalPrice'])">
        <div class="flex-center-left mb16">
          <img class="item-size" src="@/assets/images/account-item.png" alt="">
          <div class="card-title" v-if="form.quotationStatus !== '9'">{{ $t('quotation.negotiatedPrice') }}</div>
          <div class="card-title" v-if="form.quotationStatus === '9'">{{ $t('project.priceTotal') }}</div>
        </div>
        <el-form class="account-form" ref="priceForm" :model="priceForm" label-position="top">
          <!--议价-->
          <div v-if="form.quotationStatus === '6' || form.quotationStatus ==='10'">
            <el-row :gutter="20">
              <el-col :span="5">
                <!-- 价格合计 -->
                <el-form-item :label="$t('quotation.totalQuotation')" prop="priceTotal">
                  <span style="color: #D31017;font-weight: bold;font-size: 15px;padding-right: 5px;">{{ currencyParam()}}</span>
                  <span style="color: #D31017;font-weight: bold;font-size: 20px;">{{priceForm.priceTotalFormat}}</span>
                </el-form-item>
              </el-col>
              <el-col :span="5" v-if="form.quotationStatus ==='10'">
                <!-- 希望价格 -->
                <el-form-item :label="$t('quotation.exceptedPrice')+':'" prop="expectedPrice">
                  <span style="color: #000000;font-weight: bold;font-size: 15px;padding-right: 5px;">{{ currencyParam()}}</span>
                  <span style="font-weight: bold;font-size: 20px;">{{priceForm.expectedPriceFormat}}</span>
                  <span v-if="!agentFlag"> ({{$t('quotation.benchmarkPriceRate')}}{{priceForm.expectedBasicRate}}%)</span>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!--议价审批-->
          <div v-if="form.quotationStatus === '7'">
            <el-row :gutter="24">
              <el-col :span="5">
                <!-- 价格合计 -->
                <el-form-item :label="$t('quotation.totalQuotation')+':'" prop="priceTotal">
                  <span style="color: #000000;font-weight: bold;font-size: 15px;padding-right: 5px;">{{ currencyParam()}}</span>
                  <span style="font-weight: bold;font-size: 20px;">{{priceForm.priceTotalFormat}}</span>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <!-- 希望价格 -->
                <el-form-item :label="$t('quotation.exceptedPrice')+':'" prop="expectedPrice">
                  <span style="color: #000000;font-weight: bold;font-size: 15px;padding-right: 5px;">{{ currencyParam()}}</span>
                  <span style="font-weight: bold;font-size: 20px;">{{priceForm.expectedPriceFormat}}</span>
                  <span v-if="!agentFlag"> ({{$t('quotation.benchmarkPriceRate')}}{{priceForm.expectedBasicRate}}%)</span>
                </el-form-item>
              </el-col>
              <el-col :span="5" v-if="form.quotationStatus === '7' && !agentFlag && Number(flowStatus) > 111">
                <!-- 价格合计 -->
                <el-form-item :label="$t('quotation.saleTotalQuotation')+':'" prop="priceTotal">
                  <span style="color: #D31017;font-weight: bold;font-size: 15px;padding-right: 5px;">{{ currencyParam()}}</span>
                  <span style="color: #D31017;font-weight: bold;font-size: 20px;">{{priceForm.discountPriceFormat}}</span>
                  <span v-if="!agentFlag"> ({{$t('quotation.benchmarkPriceRate')}}{{priceForm.discountRate}}%)</span>
                </el-form-item>
              </el-col>
<!--              <el-col :span="5" v-if="form.quotationStatus === '8'">
                &lt;!&ndash; 价格合计 &ndash;&gt;
                <el-form-item :label="$t('quotation.priceTotal')+':'" prop="priceTotal">
                  <span style="color: #D31017;font-weight: bold;font-size: 20px;">{{priceForm.discountPriceFormat}}</span>
                  <span> ({{$t('quotation.benchmarkPriceRate')}}{{priceForm.discountRate}}%)</span>
                </el-form-item>
              </el-col>-->
            </el-row>
          </div>

          <!--议价确认-->
          <div v-if="Number(form.quotationStatus) >= 8 && form.quotationStatus != '10'">
            <el-row :gutter="20">
              <el-col :span="8">
                <!-- 价格合计 -->
                <el-form-item :label="$t('quotation.totalQuotation')+':'" prop="priceTotal">
                  <span style="color: #D31017;font-weight: bold;font-size: 15px;padding-right: 5px;">{{ currencyParam()}}</span>
                  <span style="color: #b1b0b0;font-weight: bold;font-size: 20px;text-decoration: line-through;" v-if="bargainPriceFlag">{{priceForm.priceTotalFormat}}</span>
                  <span style="color: #D31017;font-weight: bold;font-size: 20px;"> {{priceForm.discountPriceFormat}}</span>
                  <span v-if="!agentFlag"> ({{$t('quotation.discountRate')}}{{priceForm.discountRate}}%)</span>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>
      </div>

      <div class="card card-base" style="width: 97.6vw;margin-top: 20px" v-if="typeIn(['bargainApproval'])">
        <div class="flex-center-left mb16">
          <img class="item-size" src="@/assets/images/account-item.png" alt="">
          <div class="card-title">{{ $t('common.remark') }}</div>
        </div>
        <el-form class="account-form" ref="priceForm" :model="form" label-position="top">
          <el-input type="textarea" v-model="form.remark" maxlength="500" style="width:100%" show-word-limit :rows="4"/>
        </el-form>
      </div>

      <!--          采购确认/财务确认-->
      <el-dialog
        width="35%"
        :title="quotationConfirmDialogTitle"
        :visible.sync="quotationConfirmDialogVisible"
        :close-on-click-modal="false"
        append-to-body>
        <el-form class="account-form" label-position="top" ref="quotationConfirmForm" :model="quotationConfirmForm" :rules="quotationConfirmRules">
          <el-row v-if="typeIn(['buyerInquiry'])">
            <el-col :span="24">
              <!-- 预计采购工期 -->
              <el-form-item :label="$t('quotation.estimatedProcurementPeriod')" prop="estimatedProcurementPeriod">
                <el-input-number v-model="quotationConfirmForm.estimatedProcurementPeriod" :precision="0" :min="0" :max="999999999" style="width: 16vw" :controls="false"
                                 :placeholder="$t('common.pleaseInput') + $t('quotation.estimatedProcurementPeriod')"></el-input-number>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row>
            <el-col :span="24">
              <!--备注 -->
              <el-form-item :label="$t('common.remark')" prop="remark">
                <el-input v-model="quotationConfirmForm.remark" type="textarea" maxlength="500" show-word-limit :rows="5" style="width: 32.3vw"
                          :placeholder="$t('common.pleaseInput') + $t('common.remark')"/>
              </el-form-item>
            </el-col>

          </el-row>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button type="primary" icon="el-icon-circle-check" @click="handleQuotationConfirm">{{ $t('common.confirm') }}</el-button>
          <el-button icon="el-icon-remove-outline" @click="quotationConfirmDialogVisible = false">{{ $t('common.cancel') }}</el-button>
        </div>
      </el-dialog>


      <!--          评审通过/驳回弹窗-->
      <el-dialog
        width="35%"
        :title="reviewResultDialogTitle"
        :visible.sync="reviewResultDialogVisible"
        :close-on-click-modal="false"
        append-to-body>
        <el-form ref="reviewConfirmForm" class="account-form" label-position="top" :model="reviewConfirmForm" :rules="reviewRules">
          <el-row>
            <el-col :span="24" v-if="reviewAcceptFlag">
              <!-- 可行性 -->
              <el-form-item :label="$t('quotation.feasible')" prop="feasible">
                <el-select :disabled="true" v-model="reviewConfirmForm.feasible" style="width:16vw;">
                  <el-option v-for="item in feasibleList" :key="item.value"
                             :label="item.label" :value="item.value"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="reviewAcceptFlag">
            <el-col :span="24">
              <!-- 预计工期 -->
              <el-form-item :label="$t('quotation.estimatedPeriod')" prop="estimatedPeriod">
                <el-input-number v-model="reviewConfirmForm.estimatedPeriod" :min="0" :max="999999999" style="width: 16vw" :controls="false"
                                 :placeholder="$t('common.pleaseInput') + $t('quotation.estimatedProcurementPeriod')"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24" v-if="reviewAcceptFlag">
              <!--备注 -->
              <el-form-item :label="$t('common.remark')" prop="remark">
                <el-input v-model="reviewConfirmForm.remark" type="textarea" maxlength="500" show-word-limit :rows="5" style="width: 100%;margin-right: 20px"
                          :placeholder="$t('common.pleaseInput') + $t('common.remark')"/>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row>
            <el-col :span="24" v-if="!reviewAcceptFlag">
              <!--驳回原因 -->
              <el-form-item :label="$t('quotation.rejectReason')" prop="rejectReason">
                <el-input v-model="reviewConfirmForm.rejectReason" type="textarea" maxlength="500" show-word-limit :rows="5" style="width: 100%;margin-right: 20px"
                          :placeholder="$t('common.pleaseInput') + $t('quotation.rejectReason')"/>
              </el-form-item>
            </el-col>

          </el-row>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button type="primary" icon="el-icon-circle-check" @click="reviewConfirm">{{ $t('common.confirm') }}</el-button>
          <el-button icon="el-icon-remove-outline" @click="reviewResultDialogVisible = false">{{ $t('common.cancel') }}</el-button>
        </div>
      </el-dialog>

      <!--          议价驳回-->
      <el-dialog
        width="35%"
        :title="$t('quotation.bargainReject')"
        :visible.sync="bargainRejectVisible"
        :close-on-click-modal="false"
        append-to-body>
        <el-form ref="bargainRejectForm" class="account-form" label-position="top" :model="bargainRejectForm" :rules="reviewRules">
          <el-row>
            <el-col :span="24">
              <!--驳回原因 -->
              <el-form-item :label="$t('quotation.rejectReason')" prop="rejectReason">
                <el-input v-model="bargainRejectForm.rejectReason" type="textarea" maxlength="500" show-word-limit :rows="5" style="width: 100%;margin-right: 20px"
                          :placeholder="$t('common.pleaseInput') + $t('quotation.rejectReason')"/>
              </el-form-item>
            </el-col>

          </el-row>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button type="primary" icon="el-icon-circle-check" @click="bargainReject">{{ $t('common.confirm') }}</el-button>
          <el-button icon="el-icon-remove-outline" @click="bargainRejectVisible = false">{{ $t('common.cancel') }}</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {listAllProject} from "@/api/business/crm/project";
import {addQuotation, getPrice, getQuotationDetail, getSalesDiscountByFlow, updateQuotation} from "@/api/business/quotation/quotation";
import {listSpecification, uploadSpecCivilImage} from "@/api/business/quotation/specification";
import store from '../../store'
import {listModelNewAll} from "@/api/business/crm/elevatorModel";
import ColorDictTag from "@/views/crmManagement/lead/ColorDictTag/index.vue";
import {audit} from "@/api/system/flow";
import {
  acceptBargainPrice,
  rejectBargainPrice,
  selectTqBargainPriceList,
  startBargain
} from "@/api/business/quotation/bargainPrice";
import {createChatRoom} from "@/api/common/MessageChat";
import { getToken } from "@/utils/auth";
import {downloadFileByPath} from "@/api/file/file.js";
import { checkPermi } from '@/utils/permission'

const statusColorMap = {
  0: {
    color: "#24CA5D",
    bgc: "rgba(24,199,84,0.12)",
  },
  1: {
    color: "#8B71FD",
    bgc: "rgba(139,113,253,0.12)",
  },
  2: {
    color: "#0DCCD7",
    bgc: "rgba(13,204,215,0.12)",
  },
  3: {
    color: "#218AFC",
    bgc: "#E5F1FF",
  },
  4: {
    color: "#FC5821",
    bgc: "rgba(252,88,33,0.12)",
  },
  5: {
    color: "#AD2BBF",
    bgc: "rgba(163,32,181,0.12)",
  },
  6: {
    color: "#0B8B21",
    bgc: "rgba(11,139,33,0.12)",
  },
  7: {
    color: '#D71943',
    bgc: '#FAEDED'
  },
  8: {
    color: '#F83863',
    bgc: 'rgba(215, 25, 67, 0.07)'
  },
  9: {
    color: '#E4A148',
    bgc: 'rgba(228, 161, 72, 0.17)'
  },
  10: {
    color: '#8DAACC',
    bgc: 'rgba(141, 170, 204, 0.18)'
  },
  11: {
    color: 'rgba(25, 108, 215, 1)',
    bgc: 'rgba(25, 108, 215, 0.18)'
  },
  12: {
    color: 'rgba(18, 233, 164, 1)',
    bgc: 'rgba(18, 233, 164, 0.17)'
  },
  undefined: {
    color: "#D71943",
    bgc: "#FAEDED",
  },
  null: {
    color: "#D71943",
    bgc: "#FAEDED",
  },
};

const labelSuffix = {
  chinese: '',
  english: 'US',
  russia: 'RU',
  spanish: 'ES',
}

export default {
  name: "EditQuotation",
  components: {ColorDictTag},
  dicts: ['account_status', 'currency_type', 'project_type', 'elevator_type', 'quotation_status', 'system_check_result'],
  data() {
    return {
      // 报价进来的时候的审批节点
      flowStatus: null,
      // 议价驳回表单
      bargainRejectForm: {rejectReason: null},
      // 议价驳回弹窗
      bargainRejectVisible: false,
      // 表头style
      tableHeaderStyle: {'background-color': '#F4F6F8', 'border-right': '1px solid #dfdcdc', 'color': '#92A2B5'},
      // 下载文件url前缀
      baseApi: process.env.VUE_APP_BASE_API,
      // 议价ID
      bargainId: null,
      // 技术评审/采购询价/财务询价临时JSON
      reviewResultJson: {},
      // 技术评审表单
      reviewConfirmForm: {
        estimatedPeriod: null,
        rejectReason: null,
      },
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      baseUrl: process.env.VUE_APP_BASE_FILE_URL,
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      // 报价列表
      quotationList: [],
      // 报价表格
      quotationTableLoading: false,
      // 评审表格loading
      reviewTableLoading: false,
      // 议价方式
      bargainMethodList: [
        {label: this.$t('quotation.bargainPrice'), value: 0},
        {label: this.$t('quotation.bargainDiscount'), value: 1}
      ],
      // 价格表单
      priceForm: {
        // 议价方式
        bargainMethod: 0,
        // 价格合计
        priceTotal: null,
        priceTotalFormat: null,
        // 基准价格合计
        originalBasicPrice: null,
        originalOptionalPrice: null,
        originalPriceTotal: null,
        basicPrice: null,
        basicPriceFormat: null,
        // 选配加价合计
        optionalPrice: null,
        optionalPriceFormat: null,
        // 希望价格
        expectedPrice: null,
        expectedPriceFormat: null,
        // 希望折率
        expectedRate: 100,
        // 希望基准价格折率
        expectedBasicRate: 100,
        // 折后价格-价格合计
        discountPrice: null,
        discountPriceFormat: null,
        // 折后价格-基价折率
        discountRate: null,
      },
      // 评审弹窗标题
      reviewDialogTitle: null,
      // 评审弹窗
      reviewDialogVisible: false,
      // 系统评审结果 true  技术评审 false
      reviewCaseFlag: true,
      // 评审通过 true  评审驳回 false
      reviewAcceptFlag: true,
      // 可行性列表
      feasibleList: [{label: '可行', value: 0}],
      // 技术评审
      reviewForm: {
        elevatorType: null,
        elevatorModelId: null,
        elevatorNumber: null,
      },
      // 评审通过/驳回弹窗标题
      reviewResultDialogTitle: null,
      // 评审通过/驳回弹窗
      reviewResultDialogVisible: false,
      // 采购报价:0  财务报价:1
      quotationCase: 0,
      // 采购/财务确认表单
      quotationConfirmForm: {
        estimatedProcurementPeriod: null,
        remark: '无',
      },
      // 评审结果列表
      reviewResultList: [],
      // 电梯型号列表
      allElevatorModelList: [],
      // 报价页面表单
      quotationForm: {
        elevatorType: null,
        elevatorModelId: null,
        elevatorNumber: null,
      },
      // 报价页面可见
      quotationDialogVisible: false,
      // 报价页面标题
      quotationDialogTitle: null,
      // 报价确认页面可见
      quotationConfirmDialogVisible: false,
      // 报价确认页面标题
      quotationConfirmDialogTitle: null,
      type: 'view',
      form: {
        relatedProjectId: null,
        quotationNo: null,
        currencyId: null,
        agentId: null,
        countryId: null,
        city: null,
        projectTypeId: null,
        version: null,
        quoter: null,
        discountFlag: null,
        createBy:null,
        remark: '无',
      },
      elevatorList: [],
      // +++++页面不好分页，数据在缓存+++++++
      total: 0,
      pageNum: 1,
      pageSize: 100000,
      // +++++++++++++++++++++++++++++++
      ownerList: [],
      multipleSelection: [],
      countryList: [],
      agentList: [],
      projectList: [],
      accountTitle: '新增报价',
      disableFlag: false,
      versionFlag: false,
      // 项目表单校验
      rules: {
        relatedProjectId: [
          {required: true, message: this.$t('common.pleaseSelect') + this.$t('follow.relatedProject'), trigger: 'change'}
        ],
        currencyId: [
          {required: true, message: this.$t('common.pleaseSelect') + this.$t('project.currency'), trigger: 'change'}
        ],
        agentId: [
          {required: true, message: this.$t('common.pleaseSelect') + this.$t('agent.agent'), trigger: 'change'}
        ],
        city: [
          {required: true, message: this.$t('common.pleaseSelect') + this.$t('project.city'), trigger: 'change'}
        ],
        countryId: [
          {required: true, message: this.$t('common.pleaseSelect') + this.$t('account.country'), trigger: 'change'}
        ],
        projectTypeId: [
          {required: true, message: this.$t('common.pleaseSelect') + this.$t('project.type'), trigger: 'change'}
        ],
        quoter: [
          {required: true, message: this.$t('common.pleaseInput') + this.$t('quotation.quoter'), trigger: 'blur'}
        ],
      },
      // 技术评审校验
      reviewRules: {
        estimatedPeriod: [
          {required: true, message: this.$t('common.pleaseInput') + this.$t('quotation.estimatedPeriod'), trigger: 'blur'}
        ],
        rejectReason: [
          {required: true, message: this.$t('common.pleaseInput') + this.$t('quotation.rejectReason'), trigger: 'blur'}
        ],
      },
      // 采购确认校验
      quotationConfirmRules: {
        estimatedProcurementPeriod: [
          {required: true, message: this.$t('common.pleaseInput') + this.$t('quotation.estimatedProcurementPeriod'), trigger: 'blur'}
        ],
      },
      userInfo: null,
      // 是否为代理商
      agentFlag: false,
      // 电梯编号  校验编辑还是新增
      elevatorSet: new Set(),
      quotationId: null,
      tableLoading: false,
      statusColorMap: statusColorMap,
      // 是否销售
      salesFlag: true,
      // // 币种汇率
      // currencyList: [],
      // 已存在的电梯编号
      elevatorCodeSet: new Set(),
      typeParam:null,
      quotationIdCopy:null,
      bargainPriceFlag:false,
    };
  },
  async created() {
    this.$modal.loading();
    // 判断是否为代理商
    let userInfo = this.$store.state.user.userInfo;
    this.agentFlag = userInfo.deptId !== 0
    console.log('是否代理商', this.agentFlag)
    console.log('用户信息', this.$store.state.user.userInfo)
    this.quotationId = this.$route.query && this.$route.query.quotationId;
    this.flowStatus = this.$route.query && this.$route.query.flowStatus;
    this.typeParam = this.$route.query && this.$route.query.typeParam;
    console.log("this.$route.query-->",this.$route.query);
    this.userInfo = this.$store.state.user.userInfo
    this.initType();
    if (this.type !== 'add') {
      await this.initPriceInfo()
      await this.initForm();
      await this.getList();
      // await this.initAllCurrencyList();
    } else {
      // await this.initUsableCurrencyList();
      if(this.typeParam && this.typeParam === 'copy'){
        await this.initForm();
        await this.getList();
      }
      this.tableLoading = false
    }
    this.initProjectCountry();
    await this.initElevatorModel()
    const obj = Object.assign({}, this.$route, {title: this.accountTitle})
    await this.$tab.updatePage(obj);
    this.getStoreElevatorInfo();
    this.$modal.closeLoading();
    if(this.type === 'view'){
      selectTqBargainPriceList({quotationId:this.quotationId}).then(res => {
        if(res && res.rows && res.rows.length > 0){
          this.bargainPriceFlag = true;
        }
      })
    }
  },
  computed: {
    localLabelSuffix() {
      return labelSuffix[this.$i18n.locale] || '';
    }
  },
  watch: {
    "form.discountFlag": function() {
      if (!this.elevatorList || this.elevatorList.length === 0) {
        return
      }
      // 统计总价
      this.elevatorList.forEach(row => {
        row.discountBasicPrice = Math.round(row.originalBasicPrice * (row.discountRate / 100))
        row.discountOptionalPrice = row.originalOptionalPrice
        row.discountPrice = Math.round(row.discountBasicPrice + row.discountOptionalPrice)
        // 单独用于计算总折率
        row.discountBasicPriceAll = row.originalBasicPrice * row.discountRate / 100
        row.discountPriceAll = row.discountBasicPriceAll + row.discountOptionalPrice
      })
      this.calculateDiscountPriceTotal()
    }
  },
  activated() {
    console.log('用户信息', this.$store.state.user.userInfo)
    this.quotationId = this.$route.query && this.$route.query.quotationId;
    this.userInfo = this.$store.state.user.userInfo
    // todo 切换画面是否需要清楚表单数据
    this.$refs['form'].clearValidate();
    this.initType();
    const obj = Object.assign({}, this.$route, {title: this.accountTitle})
    this.$tab.updatePage(obj);
    this.getStoreElevatorInfo();
    // 技术评审读取数据
    if (this.typeIn(['techReview'])) {
      console.log('评审信息', this.$store.state.elevators.techReviewObj)
    }
  },
  methods: {
    handleCopy(row){
      let param = {...row}
      let elevator = this.$store.state.elevators[row.id];
      if(elevator){
        store.commit('PUT_ELEVATOR', elevator)
      }
      param.id = Date.now()
      this.elevatorSet.add(Number(param.id))
      console.log(param)
      this.elevatorList.push(param)
    },
    checkPermi,
    currencyParam(){
      let currencyTypeList = this.dict.type.currency_type;
      if(currencyTypeList){
        let currencyParam = currencyTypeList.find(item => item.value === this.form.currencyId)
        if(currencyParam){
          return currencyParam.raw.remark
        }
      }
    },
    // 获取列宽度
    getOperateColWidth() {
      switch (this.type) {
        case 'add':
          return 300;
        case 'edit':
          return 300;
        case 'buyerInquiry':
          return 250;
        case 'treasureInquiry':
          return 250;
        case 'techReview':
          return 300;
        default:
          return 200;
      }
    },
    // // 币种汇率初始化
    // async initUsableCurrencyList() {
    //   let response = await getUsableCurrencyRate()
    //   this.currencyList = response.rows
    // },
    // 币种汇率初始化
    // async initAllCurrencyList() {
    //   let response = await listAllCurrency()
    //   this.currencyList = response.rows
    // },
    // 接受价格
    async acceptPrice() {
      let confirm = await this.$modal.confirm(this.$t('quotation.isSure') + '?')
        .catch(() => {
        });
      if (confirm !== 'confirm') {
        console.log("接受价格取消", confirm)
        return;
      }
      acceptBargainPrice(this.quotationId).then(response => {
        this.$modal.msgSuccess(this.$t('common.operateSuccess'));
        this.$tab.closeOpenPage("/quotation/quotation");
      })
    },
    // 驳回（重新议价）
    async rejectPrice() {
      let confirm = await this.$modal.confirm(this.$t('quotation.isSure') + '?')
        .catch(() => {
        });
      if (confirm !== 'confirm') {
        console.log("接受价格取消", confirm)
        return;
      }
      rejectBargainPrice(this.quotationId).then(response => {
        this.$modal.msgSuccess(this.$t('common.operateSuccess'));
        this.$tab.closeOpenPage({path: "/quotation/quotation"});
      })
    },
    // 议价通过
    async bargainPass() {
      for (let i = 0; i < this.elevatorList.length; i++) {
        if (!this.elevatorList[i].discountRate || this.elevatorList[i].discountRate == 0) {
          this.$modal.msgError(this.$t('quotation.basicDiscountRateEmpty'));
          return
        }
      }
      let bargainObj = {
        bargainId: this.bargainId,
        quotationId: this.quotationId,
        tableList: this.elevatorList,
        discountRate: this.priceForm.discountRate
      }
      let auditForm = {
        // 审批流
        auditFlow: 2,
        // 业务id  报价id
        businessId: this.quotationId,
        // 审批结果
        status: 200,
        // 备注
        remark: `销售申请折扣价格合计:${this.currencyParam()} ${this.priceForm.discountPriceFormat}，平均基价折率:${this.priceForm.discountRate}%，备注：${this.form.remark || '无'}`,
        // 业务参数
        businessObj: bargainObj
      }

      let res = await getSalesDiscountByFlow(this.flowStatus);
      let msg = this.$t(this.flowStatus === '114' ? 'quotation.outOfDiscountManager':'quotation.outOfDiscount')

      // 计算折扣点数
      const ratePoint = Math.round((this.priceForm.priceTotal - this.priceForm.originalOptionalPrice) * 1000000 / this.priceForm.originalBasicPrice) / 10000 - Number(this.priceForm.discountRate)
      console.log('ratePoint', ratePoint)
      if ((ratePoint >= 0 && res.data.minDiscount >= ratePoint) || (ratePoint < 0 && res.data.maxDiscount >= Math.abs(ratePoint))) {
        msg = this.$t('quotation.isSure')
      }

      let confirm = await this.$modal.confirm(msg + '?')
        .catch(() => {
        });
      if (confirm !== 'confirm') {
        console.log("取消", confirm)
        return;
      }

      audit(auditForm).then(response => {
        this.$modal.msgSuccess(this.$t('common.operateSuccess'));
        this.$tab.closeOpenPage({path: "/quotation/quotation"});
      })
    },
    handleRemove(file, fileList, index) {
      this.elevatorList[index].fileList.splice(0, 1)
      this.$set(this.elevatorList[index], 'file', undefined);
      uploadSpecCivilImage({businessId: this.elevatorList[index].id, filePath: undefined}).then(response => {
          this.$message.success(this.$t('common.operateSuccess'))
        })
    },
    handleExceed(files, fileList) {
      this.$modal.msgError(this.$t('common.fileCountAlert', [this.limit]));
    },
    async handlePictureCardPreview2(file) {
      downloadFileByPath(file, false);
    },
    // 上传成功
    handleUploadSuccess(res, file, index, specId) {
      if (res.code === 200) {
        this.$set(this.elevatorList[index], 'file', file.response.fileName || undefined);
        // 将图片绑定到规格
        uploadSpecCivilImage({businessId: specId, filePath: file.response.fileName}).then(response => {
          this.$message.success(this.$t('common.operateSuccess'))
        })

      } else {
        this.$modal.msgError(res.msg);
        this.$set(this.elevatorList[index], 'file', undefined);
        this.elevatorList[index].fileList.splice(0, 1)
      }
    },
    // 议价驳回弹窗
    bargainRejectDialogShow() {
      this.bargainRejectVisible = true
      this.$nextTick(() => this.$refs['bargainRejectForm'].resetFields())
    },
    // 议价驳回
    async bargainReject() {
      let valid = await this.$refs['bargainRejectForm'].validate()
      if (!valid) {
        return
      }

      for (let i = 0; i < this.elevatorList.length; i++) {
        if (!this.elevatorList[i].discountRate || this.elevatorList[i].discountRate == 0) {
          this.$modal.msgError(this.$t('quotation.basicDiscountRateEmpty'));
          return
        }
      }
      let bargainObj = {
        quotationId: this.quotationId,
      }
      let auditForm = {
        // 审批流
        auditFlow: 2,
        // 业务id  报价id
        businessId: this.quotationId,
        // 审批结果
        status: 30,
        // 备注
        remark: '基价折率:' + this.priceForm.discountRate + '%，驳回原因：' + this.bargainRejectForm.rejectReason + '，备注：' + (this.form.remark || '无'),
        // 业务参数
        businessObj: bargainObj
      }
      // let msg = this.$t('quotation.isTurnDown')

      // let confirm = await this.$modal.confirm(msg + '?')
      //   .catch(() => {
      //   });
      // if (confirm !== 'confirm') {
      //   console.log("取消", confirm)
      //   return;
      // }
      audit(auditForm).then(response => {
        this.$modal.msgSuccess(this.$t('common.operateSuccess'));
        this.$tab.closeOpenPage({path: "/quotation/quotation"});
      })
    },
    tableDiscountRateChange(row) {
      if (row.discountRate) {
        row.discountBasicPrice = Math.round(row.originalBasicPrice * (row.discountRate / 100))
        row.discountOptionalPrice = row.originalOptionalPrice
        row.discountPrice = row.discountBasicPrice + row.discountOptionalPrice
        // 单独用于计算总折率
        row.discountBasicPriceAll = row.originalBasicPrice * row.discountRate / 100
        row.discountPriceAll = row.discountBasicPriceAll + row.discountOptionalPrice
      } else {
        row.discountPrice = '-'
      }
      this.calculateDiscountPriceTotal()
    },
    calculateDiscountPriceTotal() {
      let discountPriceTotal = 0;
      let discountPriceTotalAll = 0;
      let discountBasicPriceTotal = 0;
      let discountOptionalPriceTotal = 0;
      let flag = false
      let originalBasicPriceTotal = 0
      let originalOptionalPriceTotal = 0
      let originalPriceTotal = 0
      let basicPriceTotal = 0
      let optionalPriceTotal = 0
      for (let i = 0; i < this.elevatorList.length; i++) {
        let item = this.elevatorList[i]
        if (!item.discountRate) {
          flag = true
          break
        }
        discountPriceTotal += (item.finalPrice || item.discountPrice) * item.elevatorNumber
        discountPriceTotalAll += item.discountPriceAll * item.elevatorNumber
        discountBasicPriceTotal += item.discountBasicPriceAll * item.elevatorNumber
        discountOptionalPriceTotal += item.discountOptionalPrice * item.elevatorNumber

        originalBasicPriceTotal += item.originalBasicPrice * item.elevatorNumber
        originalOptionalPriceTotal += item.originalOptionalPrice * item.elevatorNumber
        originalPriceTotal += (item.originalBasicPrice + item.originalOptionalPrice) * item.elevatorNumber

        basicPriceTotal += item.basicPrice * item.elevatorNumber
        optionalPriceTotal += item.optionalPrice * item.elevatorNumber
      }
      if (flag) {
        this.priceForm.discountPrice = '-'
        this.priceForm.discountRate = '-'
      } else {
        this.$set(this.priceForm, 'discountPrice', discountPriceTotal)
        this.$set(this.priceForm, 'discountPriceFormat', this.numFormat(discountPriceTotal))

        // 重新计算总折率
        const rate = (discountPriceTotalAll - originalOptionalPriceTotal) / originalBasicPriceTotal
        let finalDiscount = (Math.round(((rate) * 1000000)) / 10000).toFixed(4)
        this.$set(this.priceForm, 'discountRate', finalDiscount)
      }
    },
    // 发起议价
    async confirmBargain() {
      if (this.priceForm.priceTotal === 0) {
        this.$message.error(this.$t('quotation.priceTotalError'))
        return
      }
      if (!this.priceForm.expectedPrice || !this.priceForm.expectedRate) {
        this.$message.error(this.$t('quotation.expectedPriceEmpty'))
        return
      }
      if (this.priceForm.expectedPrice == 0 || this.priceForm.expectedRate == 0) {
        this.$message.error(this.$t('quotation.expectedPriceEmpty'))
        return
      }
      let confirm = await this.$modal.confirm(this.$t('quotation.isSure') + '?')
        .catch(() => {
        });
      if (confirm !== 'confirm') {
        console.log("发起议价取消", confirm)
        return;
      }
      let form = {
        quotationId: this.quotationId,
        expectedPrice: this.priceForm.expectedPrice,
        expectedRate: this.priceForm.expectedRate
      }
      startBargain(form).then(response => {
        this.$message.success(this.$t('common.operateSuccess'))
        this.$tab.closeOpenPage({path: "/quotation/quotation"});
      })
    },
    // 议价-折率变换
    expectedRateChange() {
      if (this.priceForm.expectedRate || this.priceForm.expectedRate === 0) {
        this.priceForm.expectedPrice = Math.round(this.priceForm.priceTotal * (this.priceForm.expectedRate / 100)).toFixed(0)
        this.priceForm.expectedPriceFormat = this.numFormat(this.priceForm.expectedPrice)
        this.priceForm.expectedRateFormat = this.numFormat(this.priceForm.expectedRate)
      } else {
        this.priceForm.expectedPrice = null
      }
    },
    // 议价-折后价格变换
    expectedPriceChange() {
      if (this.priceForm.expectedPrice) {
        this.priceForm.expectedRate = (Math.round(this.priceForm.expectedPrice / this.priceForm.priceTotal * 1000000) / 10000).toFixed(4)
        this.priceForm.expectedRateFormat = this.numFormat(this.priceForm.expectedRate)
        this.priceForm.expectedPriceFormat = this.numFormat(this.priceForm.expectedPrice)
      } else {
        this.priceForm.expectedRate = undefined
        this.priceForm.expectedRateFormat = '-'
      }
    },
    async initPriceInfo() {
      let response = await getPrice(this.quotationId)
      if (!response.data) {
        return
      }
      this.bargainId = response.data.bargainId
      console.log(response.data)
      this.priceForm = {
        bargainMethod: 0,
        // 价格合计
        priceTotal: response.data.priceTotal,
        priceTotalFormat: response.data.priceTotalFormat,
        // 基准价格合计
        originalBasicPrice: response.data.originalBasicPrice,
        originalOptionalPrice: response.data.originalOptionalPrice,
        originalPriceTotal: response.data.originalPriceTotal,
        basicPrice: response.data.basicPrice,
        basicPriceFormat: response.data.basicPriceFormat,
        // 选配加价合计
        optionalPrice: response.data.optionalPrice,
        optionalPriceFormat: response.data.optionalPriceFormat,
        // 希望价格
        expectedPrice: response.data.expectedPrice,
        expectedPriceFormat: response.data.expectedPriceFormat,
        // 价格折率
        expectedRate: response.data.expectedRate,
        // 基准价格折率
        expectedBasicRate: response.data.expectedBasicRate,
        // // 折后价格-价格合计
        discountPrice: response.data.discountPrice,
        // // 折后价格-基价折率
        discountRate: response.data.discountRate,
        discountPriceFormat: this.numFormat(response.data.discountPrice)
      }

    },
    toPriceDetail(row) {
      let params = {
        'elevatorType': row.elevatorType,
        'elevatorModelId': row.elevatorModelId,
        'elevatorNumber': row.elevatorNumber,
        'specificationId': row.id
      }
      // await this.$tab.closePage({name: 'SysQuotation/:id(\\d+)', path: '/quotation/sysQuotation/'+row.id})
      this.$tab.openPage(this.$t('quotation.priceDetailLabel'), '/quotation/sysQuotation/' + row.id, params);
    },
    // 跳转到技术评审页面   系统评审：true 技术评审：false
    async toTechReview(row, reviewCaseFlag) {
      let params = {
        'elevatorType': row.elevatorType,
        'elevatorModelId': row.elevatorModelId,
        'elevatorNumber': row.elevatorNumber,
        'specificationId': row.id,
        'reviewCaseFlag': reviewCaseFlag,
        'flowStatus': this.flowStatus
      }
      await this.$tab.closePage({name: 'TechReview', path: '/quotation/techReview'})
      if (reviewCaseFlag === true) {
        this.$tab.openPage(this.$t("quotation.systemReviewResult"), '/quotation/techReview', params);
      } else {
        this.$tab.openPage(this.$t("quotation.techReview"), '/quotation/techReview', params);
      }
    },
    // 销售确认
    async handleSalesConfirm() {
      let confirm = await this.$modal.confirm(this.$t('quotation.isSure') + '?')
        .catch(() => {
        });
      if (confirm !== 'confirm') {
        console.log("销售确认取消", confirm)
        return;
      }

      //   评审通过:200  评审驳回:30
      let auditForm = {
        // 审批流
        auditFlow: 1,
        // 业务id  报价id
        businessId: this.quotationId,
        // 审批结果
        status: 200,
        // 备注
        remark: '无',
        // 业务参数
        businessObj: {}
      }
      console.log('销售', auditForm)
      audit(auditForm).then(response => {
        this.$modal.msgSuccess(this.$t('common.operateSuccess'));
        this.$tab.closeOpenPage({path: "/quotation/quotation"});
      })
    },
    // 财务确认
    handleTreasureConfirm() {
      // 判断单价是否都已设置
      if (this.elevatorList !== null && this.elevatorList.length > 0) {
        for (let i = 0; i < this.elevatorList.length; i++) {
          if ('00' == this.elevatorList[i].systemCheckResult) {
            continue
          }
          let list = this.$store.state.elevators.treasurerQuotationObj[this.elevatorList[i].id]
          if (list !== null && list !== undefined && list.length > 0) {
            for (let j = 0; j < list.length; j++) {
              // 财务上浮未设置
              if (list[j].quotationFlagElectric == '1' && list[j].floatPercent === undefined) {
                this.$message.error(this.$t('quotation.setTreasurePriceRate'))
                return
              }
              if (list[j].quotationFlagMachine == '1' && list[j].floatPercentMachine === undefined) {
                this.$message.error(this.$t('quotation.setTreasurePriceRate'))
                return
              }
            }
          } else {
            this.$message.error(this.$t('quotation.setTreasurePriceRate'))
            return;
          }
        }
      }
      this.quotationConfirmForm = {
        estimatedProcurementPeriod: 0,
        remark: '无',
      }
      this.quotationCase = 1
      this.quotationConfirmDialogVisible = true
      this.quotationConfirmDialogTitle = this.$t('quotation.treasureConfirm')
    },
    // 采购/财务最终确认
    handleQuotationConfirm() {
      let remark = '';
      //   评审通过:200  评审驳回:30
      let auditCode = this.reviewAcceptFlag ? 200 : 30;

      switch (this.quotationCase) {
        // 采购报价
        case 0:
          remark = '预计采购工期：' + this.quotationConfirmForm.estimatedProcurementPeriod + '天，备注：' + this.quotationConfirmForm.remark
          this.$refs['quotationConfirmForm'].validate((result) => {
            if (result) {
              let businessObj = {
                reviewResultJson: this.$store.state.elevators.buyerQuotationObj
              }
              let auditForm = {
                // 审批流
                auditFlow: 1,
                // 业务id  报价id
                businessId: this.quotationId,
                // 审批结果
                status: auditCode,
                // 备注
                remark: remark,
                // 业务参数
                businessObj: businessObj
              }
              console.log('采购确认', auditForm)
              audit(auditForm).then(response => {
                this.$emit("CLEAR_BUYER_REVIEW")
                this.quotationConfirmDialogVisible = false
                this.$modal.msgSuccess(this.$t('common.operateSuccess'));
                this.$tab.closeOpenPage({path: "/quotation/quotation"});
              })
            }
          })
          break;
        // 财务报价
        case 1:
          // 财务报价确认
          remark = '备注：' + this.quotationConfirmForm.remark
          let businessObj = {
            reviewResultJson: this.$store.state.elevators.treasurerQuotationObj
          }
          let auditForm = {
            // 审批流
            auditFlow: 1,
            // 业务id  报价id
            businessId: this.quotationId,
            // 审批结果
            status: auditCode,
            // 备注
            remark: remark,
            // 业务参数
            businessObj: businessObj
          }
          console.log('财务确认', auditForm)
          audit(auditForm).then(response => {
            this.$emit("CLEAR_TREASURER_REVIEW")
            this.quotationConfirmDialogVisible = false
            this.$modal.msgSuccess(this.$t('common.operateSuccess'));
            this.$tab.closeOpenPage({path: "/quotation/quotation"});
          })
          break;
      }
    },
    // 技术评审确认
    reviewConfirm() {

      // 判断单价是否都已设置
      if (this.reviewAcceptFlag && this.elevatorList !== null && this.elevatorList.length > 0) {
        for (let i = 0; i < this.elevatorList.length; i++) {
          if ('00' == this.elevatorList[i].systemCheckResult) {
            // 过滤标准的电梯规格
            continue
          }
          let list = this.$store.state.elevators.techReviewObj[this.elevatorList[i].id]
          console.log('列表', list)
          if (list !== null && list !== undefined && list.length > 0) {
            console.log('单条', list)
            for (let j = 0; j < list.length; j++) {
              console.log('单价', list[j].buyerPrice)
              // 采购单价未设置
              if (this.flowStatus == '101' && list[j].quotationFlagElectric == '1'  && list[j].buyerPrice !==0 && !list[j].buyerPrice) {
                this.$message.error(this.$t('quotation.setSalesPrice'))
                return
              }
              if (this.flowStatus == '105' &&list[j].quotationFlagMachine == '1' && list[j].buyerPriceMachine !== 0 && !list[j].buyerPriceMachine) {
                this.$message.error(this.$t('quotation.setSalesPrice'))
                return
              }
            }
          } else {
            this.$message.error(this.$t('quotation.setSalesPrice'))
            return;
          }
        }
      }

      this.$refs['reviewConfirmForm'].validate((valid) => {
        if (!valid) {
          console.log('技术评审校验未通过XXXXXXXXXXX')
          return;
        }
        console.log('技术评审校验通过')
        //   评审通过:200  评审驳回:30
        let auditCode = this.reviewAcceptFlag ? 200 : 30;
        let remark
        if (this.reviewAcceptFlag) {
          remark = '可行性：可行，预计工期：' + this.reviewConfirmForm.estimatedPeriod + '天，备注：' + this.reviewConfirmForm.remark
        } else {
          remark = '驳回原因：' + this.reviewConfirmForm.rejectReason
        }
        let businessObj = {
          reviewResultJson: this.$store.state.elevators.techReviewObj
        }
        console.log('remark', remark)
        let auditForm = {
          // 审批流
          auditFlow: 1,
          // 业务id  报价id
          businessId: this.quotationId,
          // 审批结果
          status: auditCode,
          // 备注
          remark: remark,
          // 业务参数
          businessObj: businessObj
        }
        audit(auditForm).then(response => {
          this.reviewResultDialogVisible = false
          // 清空技术评审缓存
          store.commit('CLEAR_TECH_REVIEW')
          this.$modal.msgSuccess(this.$t('common.operateSuccess'));
          this.$tab.closeOpenPage({path: "/quotation/quotation"});
        })
      })
    },
    // 评审通过view
    handleReviewAccept() {
      this.reviewAcceptFlag = true
      this.reviewResultDialogVisible = true
      this.reviewResultDialogTitle = this.$t("quotation.reviewAcceptTitle")
      this.reviewConfirmForm = {
        'feasible': 0,
        'estimatedPeriod': 0,
        'remark': '无',
        'rejectReason': null
      }
    },
    // 评审驳回view
    handleReviewReject() {
      this.reviewAcceptFlag = false
      this.reviewResultDialogVisible = true
      this.reviewResultDialogTitle = this.$t("quotation.reviewRejectTitle")
      this.reviewConfirmForm = {
        'feasible': 0,
        'estimatedPeriod': 0,
        'remark': null,
        'rejectReason': null
      }
    },
    // 销售驳回驳回view
    handleSalesReject() {
      this.reviewAcceptFlag = false
      this.reviewResultDialogVisible = true
      this.reviewResultDialogTitle = this.$t("quotation.salesRejectTitle")
      this.reviewConfirmForm = {
        'feasible': 0,
        'estimatedPeriod': 0,
        'remark': null,
        'rejectReason': null
      }
    },
    //跳转采购财务报价页面   采购报价 0  财务报价 1
    async toQuotation(row, caseId) {
      let params = {
        'specificationId': row.id,
        'elevatorType': row.elevatorType,
        'elevatorModelId': row.elevatorModelId,
        'elevatorNumber': row.elevatorNumber,
        'caseId': caseId,
      }
      await this.$tab.closePage({name: 'BuyerTreasurerQuotation', path: '/quotation/buyerTreasurerQuotation'})
      if (caseId === 0) {
        this.$tab.openPage(this.$t('quotation.buyerQuotation'), '/quotation/buyerTreasurerQuotation', params);
      } else {
        this.$tab.openPage(this.$t('quotation.treasureQuotation'), '/quotation/buyerTreasurerQuotation', params);
      }
    },
    async initElevatorModel() {
      let form = {
        needAll: true
      }
      const response = await listModelNewAll(form);
      if (response.rows) {
        response.rows.forEach(item => {
          this.allElevatorModelList.push(
            {
              'label': item.elevatorModel,
              'value': item.id,
            }
          )
        })
      }
    },
    async initForm() {
      if (this.quotationId) {
        getQuotationDetail(this.quotationId).then(response => {
          if (response.data) {
            let data = response.data
            this.form.quotationNo = data.quotationNo
            this.form.version = data.version
            this.form.projectTypeId = Number(data.type)
            this.form.currencyId = data.currencyId
            this.form.agentId = Number(data.agentId)
            this.form.countryId = data.countryId
            this.form.city = data.city
            this.form.quoter = data.quoter
            this.form.relatedProjectId = data.projectId
            this.form.priceTotal = data.priceTotal
            this.form.benchmarkPriceTotal = data.benchmarkPriceTotal
            this.form.optionalPriceTotal = data.optionalPriceTotal
            this.form.areaId = data.areaId
            this.form.updateTime = data.updateTime
            this.form.quotationStatus = data.quotationStatus
            this.form.projectNo = data.projectNo
            this.form.projectId = data.projectId
            this.form.discountFlag = data.discountFlag
            this.form.countryDiscountRate = data.countryDiscountRate
            this.form.createBy = data.createBy
          }
        })
      }
    },
    // 从文件URL中获取文件名
    getFileName(fileNameUrl) {
      let fileName = '';
      if (fileNameUrl) {
        fileName = fileNameUrl.substring(fileNameUrl.lastIndexOf('/') + 1);
      }
      return fileName;
    },
    async getList() {
      if (this.quotationId) {
        this.tableLoading = true
        let form = {
          pageNum: 1,
          pageSize: 9999999,
          quotationId: this.quotationId,
          bargainId: this.bargainId
        }
        let response = await listSpecification(form)
        this.elevatorList = response.rows
        this.elevatorList.forEach(item => {
          item.fileList = item.file && item.file.length > 0 ? [{ name: this.getFileName(item.file), url: this.baseUrl + item.file }] : []
        })

        console.log('获取电梯规格列表')
        this.elevatorList.forEach(item => {
          this.elevatorSet.add(Number(item.id))
        })
        console.log('电梯已存在的ID', this.elevatorSet)
        this.total = response.total
        this.tableLoading = false

        // 统计总价
        this.elevatorList.forEach(row => {
          row.discountBasicPrice = Math.round(row.originalBasicPrice * (row.discountRate / 100))
          row.discountOptionalPrice = row.originalOptionalPrice
          row.discountPrice = Math.round(row.discountBasicPrice + row.discountOptionalPrice)
          // 单独用于计算总折率
        row.discountBasicPriceAll = row.originalBasicPrice * row.discountRate / 100
        row.discountPriceAll = row.discountBasicPriceAll + row.discountOptionalPrice
        })
        this.calculateDiscountPriceTotal()
      }
    },
    // 获取电梯页面传过来的电梯信息
    getStoreElevatorInfo() {
      debugger
      let elevatorId = this.$route.query && this.$route.query.elevatorId;
      if (elevatorId) {
        let elevator = this.$store.state.elevators[elevatorId];
        if (!elevator) {
          console.log('无法从内存获取电梯参数', elevator)
          return
        }
        console.log('检查电梯是否存在', this.elevatorSet, elevatorId, this.elevatorSet.has(Number(elevatorId)))
        if (this.elevatorSet.has(Number(elevatorId))) {
          this.initElevatorCodeSet(Number(elevatorId))
          console.log("重复编辑电梯", elevatorId, elevator)
          elevator.elevatorCode = this.setElevatorCode(elevator.elevatorNumber, elevator.elevatorGroupCode)
          // 替换电梯列表
          for (let i = 0; i < this.elevatorList.length; i++) {
            if (this.elevatorList[i].id == elevatorId) {
              //保留创建时间
              elevator.createTime1 = this.elevatorList[i].createTime1
              this.$set(this.elevatorList, i, elevator);
            }
          }
        } else {
          this.initElevatorCodeSet()
          // 设置电梯编号
          elevator.elevatorCode = this.setElevatorCode(elevator.elevatorNumber, elevator.elevatorGroupCode)
          console.log("新增电梯", elevatorId, elevator)
          this.elevatorSet.add(Number(elevatorId));
          this.elevatorList.push(elevator);
        }
      }
      console.log('电梯列表', this.elevatorList)
    },
    // 初始化电梯编号
    initElevatorCodeSet(elevatorId) {
      this.elevatorCodeSet = new Set()
      for (let i = 0; i < this.elevatorList.length; i++) {
        let itemElevator = this.elevatorList[i]
        if (elevatorId == itemElevator.id) {
          console.log('电梯编号跳过 [' + elevatorId + ']')
          continue
        }
        if (itemElevator.elevatorCode) {
          let list = itemElevator.elevatorCode.split(',')
          if (list && list.length > 0) {
            for (let j = 0; j < list.length; j++) {
              this.elevatorCodeSet.add(list[j])
            }
          }
        }
      }
    },
    // 设置电梯编号
    setElevatorCode(elevatorNumber, elevatorGroupCode) {
      let elevatorCode = ''
      for (let i = 0; i < elevatorNumber; i++) {
        if (i !== 0) {
          elevatorCode += ','
        }
        let itemElevatorCode = this.getUsableElevatorCode(elevatorGroupCode, (i + 1))
        this.elevatorCodeSet.add(itemElevatorCode)
        elevatorCode += itemElevatorCode
      }
      return elevatorCode
    },
    // 获取可用的电梯编号
    getUsableElevatorCode(elevatorCode, num) {
      let number = num
      while (true) {
        let item = elevatorCode + '-' + number
        if (this.elevatorCodeSet.has(item)) {
          number += 1
        } else {
          return item
        }
      }
    },
    // 项目变更
    projectChange(key) {
      let checkProjectList = this.projectList.filter(item => item.value === key)
      console.log('代理change', key, checkProjectList)
      if (checkProjectList.length > 0) {
        this.form.projectTypeId = checkProjectList[0].projectTypeId
        this.form.countryId = checkProjectList[0].countryId
        this.form.city = checkProjectList[0].city
        this.form.areaId = checkProjectList[0].areaId
        this.form.agentId = checkProjectList[0].ownerAgent
        this.form.agentDiscountRate = checkProjectList[0].agentDiscountRate
        this.form.countryDiscountRate = checkProjectList[0].countryDiscountRate
        this.form.countryDiscountRate = checkProjectList[0].countryDiscountRate
        if (this.typeIn(['add'])) {
          this.form.currencyId = checkProjectList[0].currencyId
        }

        this.agentList = []
        let agent = {
          'label': checkProjectList[0].ownerAgentName,
          'value': checkProjectList[0].ownerAgent
        }
        // 代理商为总部时特殊处理
        if (agent.value == 0) {
          agent.label = this.$t('common.head')
        }
        console.log("代理商", agent)
        this.agentList.push(agent)
      } else {
        this.form.projectTypeId = null
        this.form.countryId = null
        this.form.city = null
        this.form.areaId = null
      }
      console.log("表单", this.form)
      console.log('电梯详细', this.$store.state.elevators)
    },
    async initProjectCountry() {
      let form = {
        language: this.$i18n.locale,
      }
      // 新增时过滤审批通过的
      if (this.typeIn(['add'])) {
        form.status = '03'
      } else {
        form.projectId = this.form.relatedProjectId
      }
      const response = await listAllProject(form);
      console.log('项目列表请求', response)
      if (response.rows) {
        let countryList = []
        response.rows.forEach(item => {
          let label = item.projectNo + ':' + item.projectName + '-' + item.countryName + '-' + item.city
          if (item.developer) {
            label += '-' + item.developer
          }
          this.projectList.push({
            label: label,
            value: item.projectId,
            projectTypeId: Number(item.type),
            countryId: item.countryId,
            currencyId: item.currencyId,
            city: item.city,
            areaId: item.areaId,
            ownerAgent: item.ownerAgent,
            ownerAgentName: item.ownerAgentName,
            agentDiscountRate: item.agentDiscountRate,
            countryDiscountRate: item.countryDiscountRate
          })
          countryList.push(
            {
              'label': item.countryName,
              'value': item.countryId,
            }
          )
        })
        this.countryList = Array.from(new Map(countryList.map(item => [item['value'], item])).values());
        if (this.typeNotIn(['add'])) {
          this.projectChange(this.form.relatedProjectId)
        }
        if(this.typeParam && this.typeParam === 'copy'){
          this.projectChange(this.form.relatedProjectId)
        }
      }
    },
    async handleView(row, viewFlag) {
      store.commit('PUT_ELEVATOR', row)
      await this.$tab.closePage({name: 'Elevator', path: '/quotation/elevator'})
      let form = {
        'type': viewFlag ? 'view' : 'detail',
        'quotationType': this.type,
        'elevatorId': row.id,
        'quotationId': this.quotationId,
        'areaId': row.areaId
      }
      await this.$tab.openPage(this.$t('elevator.view'), '/quotation/elevator', form);
    },
    async handleUpdate(row) {
      if (this.form.areaId == null) {
        this.$modal.msgError(this.$t('plot.selectProject'));
        return
      }
      let elevatorModelId = ''
      this.elevatorList.forEach(item => {
        if (item.elevatorModelId !== row.elevatorModelId) {
          if (elevatorModelId === '') {
            elevatorModelId += item.elevatorModelId
          } else {
            elevatorModelId += ',' + item.elevatorModelId
          }
        }
      })
      store.commit('PUT_ELEVATOR', row)
      await this.$tab.closePage({name: 'Elevator', path: '/quotation/elevator'})
      await this.$tab.openPage(this.$t('elevator.edit'), '/quotation/elevator',
        {
          'type': 'edit',
          'quotationType': this.type,
          'elevatorId': row.id,
          'quotationId': this.quotationId,
          'areaId': row.areaId,
          'elevatorModelIdStr': elevatorModelId,
          'countryId': this.form.countryId
        });
    },
    /** 新增电梯 */
    async addLine() {
      if (this.form.areaId == null) {
        this.$modal.msgError(this.$t('plot.selectProject'));
        return
      }
      let elevatorModelId = ''
      this.elevatorList.forEach(item => {
        if (elevatorModelId === '') {
          elevatorModelId += item.elevatorModelId
        } else {
          elevatorModelId += ',' + item.elevatorModelId
        }
      })
      await this.$tab.closePage({name: 'Elevator', path: '/quotation/elevator'})
      await this.$tab.openPage(this.$t('elevator.add'), '/quotation/elevator',
        {
          'type': 'add',
          'quotationType': this.type,
          'quotationId': this.quotationId,
          'areaId': this.form.areaId,
          'elevatorModelIdStr': elevatorModelId,
          'countryId': this.form.countryId
        });
    },
    /** 返回上个页面 */
    cancel() {
      this.$tab.closePage();
    },
    handleDelete(row) {
      this.$modal.confirm(this.$t('common.isDelete')).then(() => {
        console.log('删除电梯', row.id)
        this.elevatorList = this.elevatorList.filter(item =>
          item.id != row.id
        )
        this.elevatorSet.delete(Number(row.id))
        store.commit('DEL_ELEVATOR', {id: row.id})
        this.$modal.msgSuccess(this.$t('common.deleteSuccess'));
      }).catch(e => {
        console.error(e)
      });
    },
    initType() {
      this.type = this.$route.query && this.$route.query.type;
      switch (this.type) {
        case 'add':
          this.accountTitle = this.$t('quotation.add');
          this.form.quoter = this.userInfo.nickName
          break;
        case 'edit':
          this.accountTitle = this.$t('quotation.edit');
          this.versionFlag = true
          break;
        case 'view':
          this.accountTitle = this.$t('quotation.showView');
          this.versionFlag = true
          break;
        //   技术评审
        case 'techReview':
          this.accountTitle = this.$t('quotation.techReview');
          this.versionFlag = true
          break;
        //   采购询价
        case 'buyerInquiry':
          this.accountTitle = this.$t('quotation.buyerInquiry');
          this.versionFlag = true
          break;
        //   财务询价
        case 'treasureInquiry':
          this.accountTitle = this.$t('quotation.treasureInquiry');
          this.versionFlag = true
          break;
        //   销售确认
        case 'salesConfirm':
          this.accountTitle = this.$t('quotation.salesConfirm');
          this.versionFlag = true
          break;
        //  议价
        case 'bargain':
          this.accountTitle = this.$t('quotation.negotiatedPrice');
          this.versionFlag = true
          break;
        //   议价审批
        case 'bargainApproval':
          this.accountTitle = this.$t('quotation.bargainApproval');
          this.versionFlag = true
          break;
        //   议价确认
        case 'bargainConfirm':
          this.accountTitle = this.$t('quotation.bargainConfirm');
          this.versionFlag = true
          break;
        // 接受价格
        case 'bargainAccept':
          this.accountTitle = this.$t('quotation.acceptPrice');
          this.versionFlag = true
          break;
      }
      this.disableFlag = this.typeNotIn(['add']);
    },
    /** 提交按钮 */
    submitForm: function () {
      if (!this.elevatorList || this.elevatorList.length === 0) {
        this.$modal.msgError(this.$t('elevator.required'));
        return
      }
      this.$refs['form'].validate((valid) => {
        if (valid) {
          console.log('电梯列表', this.elevatorList)
          let commitForm = {
            projectId: this.form.relatedProjectId,
            currencyId: this.form.currencyId,
            agentId: this.form.agentId,
            quotationStatus: '1',
            elevatorList: this.elevatorList
          }
          // let currency = this.currencyList.filter(item => item.currencyId == this.form.currencyId)
          // commitForm.exchangeRate = currency[0].exchangeRate
          // 排他性注解用到
          commitForm.updateTime = this.form.updateTime
          commitForm.agentDiscountRate = this.form.agentDiscountRate
          commitForm.countryDiscountRate = this.form.countryDiscountRate
          commitForm.areaId = this.form.areaId

          console.log('币种id', this.form.currencyId)
          console.log('提交参数', commitForm)
          this.$modal.loading();
          if(this.typeParam && this.typeParam === 'copy'){
            this.quotationId = null;
          }
          if (this.quotationId != null) {
            // 编辑
            commitForm.quotationId = this.quotationId
            commitForm.id = this.quotationId
            updateQuotation(commitForm).then(response => {
              this.$modal.msgSuccess(this.$t('quotation.submitSuccess'));
              this.$tab.closeOpenPage({path: "/quotation/quotation"});
            }).finally(() => {
              this.$modal.closeLoading();
            })
          } else {
            // 新增
            addQuotation(commitForm).then(response => {
              this.$modal.msgSuccess(this.$t('quotation.submitSuccess'));
              this.$tab.closeOpenPage({path: "/quotation/quotation"});
            }).finally(() => {
              this.$modal.closeLoading();
            })
          }
          console.log("提交表单", commitForm)
        }
      });
    },
    saveDraft() {
      if (!this.elevatorList || this.elevatorList.length === 0) {
        this.$modal.msgError(this.$t('elevator.required'));
        return
      }
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let commitForm = {
            projectId: this.form.relatedProjectId,
            currencyId: this.form.currencyId,
            agentId: this.form.agentId,
            quotationStatus: '0',
            elevatorList: this.elevatorList
          }
          // let currency = this.currencyList.filter(item => item.currencyId == this.form.currencyId)
          // commitForm.exchangeRate = currency[0].exchangeRate
          // 排他性注解用到
          commitForm.updateTime = this.form.updateTime
          commitForm.agentDiscountRate = this.form.agentDiscountRate
          commitForm.countryDiscountRate = this.form.countryDiscountRate
          commitForm.areaId = this.form.areaId

          console.log('币种id', this.form.currencyId)
          console.log('提交参数', commitForm)
          let successMsg = this.$t('common.addSuccess')
          this.$modal.loading();
          if(this.typeParam && this.typeParam === 'copy'){
            this.quotationId = null;
          }
          if (this.quotationId != null) {
            // 编辑
            commitForm.quotationId = this.quotationId
            commitForm.id = this.quotationId
            successMsg = this.$t('common.editSuccess')
            updateQuotation(commitForm).then(response => {
              this.$modal.msgSuccess(successMsg);
              this.$tab.closeOpenPage({path: "/quotation/quotation"});
            }).finally(() => {
              this.$modal.closeLoading();
            })
          } else {
            // 新增
            addQuotation(commitForm).then(response => {
              this.$modal.msgSuccess(successMsg);
              this.$tab.closeOpenPage({path: "/quotation/quotation"});
            }).finally(() => {
              this.$modal.closeLoading();
            })
          }
          // let successMsg = this.$t('common.addSuccess')
          // // 新增
          // addQuotation(commitForm).then(response => {
          //   this.$modal.msgSuccess(successMsg);
          //   this.$tab.closeOpenPage({path: "/quotation/quotation"});
          // })
        }
      });
    },
    typeIn(types) {
      return types.indexOf(this.type) !== -1
    },
    typeNotIn(types) {
      return types.indexOf(this.type) === -1
    },
    // value 转 label
    convertStatus(status) {
      if (!status) return '-'
      const check = this.dict.type.quotation_status.filter(item => item.value == status)
      if (check && check.length > 0) {
        return check[0].label
      } else {
        return '-'
      }
    },
    convertCheckResult(status) {
      if (!status) return '-'
      const check = this.dict.type.system_check_result.filter(item => item.value == status)
      if (check && check.length > 0) {
        return check[0].label
      } else {
        return '-'
      }
    },
    startChat() {
      let row = {
        //报价单id
        "quotationId": this.quotationId,
        "chatName": this.form.quotationNo
      }
      console.log('聊天室创建参数', row)
      createChatRoom(row)
    }
  }
}
</script>

<style lang="scss" rel="stylesheet/scss" scoped>
::v-deep .account-form .el-form-item--medium .el-form-item__label {
  line-height: 10px;
}

::v-deep .el-form-item {
  margin-bottom: 20px;
}

::v-deep .upload-file-list .ele-upload-list__item-content {
  width: 500px;
}

::v-deep .upload {
  .upload-file-uploader {
    height: 0;
  }
}

.mt30 {
  margin-top: 30px;
}

// ::v-deep .el-icon-document {
//     width: 350px;
//     overflow: hidden;
//     white-space: nowrap;
//     text-overflow: ellipsis;
// }

.account-container {
  padding: 16px 1vw;

  .account-title {
    font-family: Arial, Arial;
    font-weight: bold;
    font-size: 18px;
    line-height: 21px;
  }

  .mt16 {
    margin-top: 16px;
  }

  .mb16 {
    margin-bottom: 16px;
  }

  .mb20 {
    margin-bottom: 20px;
  }

  .ml20 {
    margin-left: 1vw;
  }

  .contact-box {
    margin-bottom: 50px;
  }

  .col-padding-left {
    padding-left: 10px;
  }

  .col-padding-right {
    padding-right: 10px;
  }

  .max-width {
    max-width: 20vw;
  }

  .flex-center-left {
    display: flex;
    align-items: center;
    justify-content: left;
  }

  .account-select {
    margin: 16px 0;
  }

  .select-box {
    display: flex;
  }

  .select-item {
    cursor: pointer;
    margin-right: 10px;
    padding: 10px 20px;
    font-family: Arial, Arial;
    font-weight: bold;
    font-size: 18px;
    color: #3C485B;
    line-height: 21px;
    border: 1px solid transparent;
  }

  .selected {
    border-radius: 6px;
    background: #FFFFFF;
    box-shadow: 0px 2px 10px 0px #CED6DD;
    color: #D31017;
    border: 1px solid #D31017;
  }

  .content {
    width: 100%;
    //display: flex;

    .card {
      background: #FFFFFF;
      box-shadow: 0px 2px 10px 0px #CED6DD;
      border-radius: 6px;
      padding: 20px;
    }

    .card-title {
      font-family: Arial, Arial;
      font-size: 16px;
      font-weight: bold;
      color: rgba(0, 0, 0, 0.85);
      line-height: 18px;
    }

    .card-base {
      width: 53.5vw;
      //position: relative;

      .button-group {
        position: absolute;
        bottom: 10px;
        right: 20px;
      }
    }

    .card-height {
      height: 1332px;
    }

    .card-mini {
      width: 43vw;
      height: 450px;
    }

    .card-full {
      width: 97.6vw;
    }
  }

  .item-size {
    width: 14px;
    height: 14px;
    margin-right: 6px;
  }
}

::v-deep .el-dialog__body {
  padding-bottom: 0px;
}

.input-price ::v-deep .el-input__inner {
  color: #D71943 !important; /* 修改文字颜色 */
}

.table-class {
  margin-top: 20px;
}

//.table-class ::v-deep .el-table__row {
//  td:not(.is-hidden):last-child {
//    left: 0.5px !important;
//    right: 0.5px !important;
//  }
//}

.leave-msg {
  user-select: none;
  cursor: pointer;
  display: flex;
  float: right;
  border: 1px solid #D71943;
  border-radius: 3px;
  padding-top: 1px;
  height: 29px;
  padding-left: 6px;
  padding-right: 6px;
  background-color: rgba(253, 230, 232, 0.5);
  margin-bottom: 16px;

  .chat-div {
    display: inline-block;
    height: 29px;

    .chat-img {
      width: 25px;
      margin-right: 2px;
    }
  }

  .chat-room {
    line-height: 25px;
    color: #D71943;
    display: inline-block;
    font-weight: bold;
    height: 29px;
  }
}

.leave-msg:hover {
  background-color: rgba(253, 230, 232, 1);
}

.el-input-number ::v-deep .el-input__inner {
  text-align: left;
}

::v-deep .el-icon-price-detail {
  background: url('~@/assets/icons/quotation/price-detail.png') center no-repeat;
  background-size: cover;
  margin-right: 5px;
}

.el-icon-price-detail:before {
  content: "替";
  color: #FFFFFF;
  opacity: 0.0;
  font-size: 12px;
}

::v-deep .el-icon-tech {
  background: url('~@/assets/icons/quotation/tech.png') center no-repeat;
  background-size: cover;
  margin-right: 5px;
}

.el-icon-tech:before {
  content: "替";
  color: #FFFFFF;
  opacity: 0.0;
  font-size: 12px;
}

::v-deep .el-icon-bargain {
  background: url('~@/assets/icons/quotation/bargain.png') center no-repeat;
  background-size: cover;
  margin-right: 5px;
}

.el-icon-bargain:before {
  content: "替";
  color: #FFFFFF;
  opacity: 0.0;
  font-size: 12px;
}

::v-deep .el-icon-pass {
  background: url('~@/assets/icons/quotation/pass.png') center no-repeat;
  background-size: cover;
  margin-right: 5px;
}

.el-icon-pass:before {
  content: "替";
  color: #FFFFFF;
  opacity: 0.0;
  font-size: 12px;
}

::v-deep .el-icon-reject {
  background: url('~@/assets/icons/quotation/reject.png') center no-repeat;
  background-size: cover;
  margin-right: 5px;
}

.el-icon-reject:before {
  content: "替";
  color: #FFFFFF;
  opacity: 0.0;
  font-size: 12px;
}

::v-deep .el-icon-bargain-confirm {
  background: url('~@/assets/icons/quotation/bargain-confirm.png') center no-repeat;
  background-size: cover;
  margin-right: 5px;
}

.el-icon-bargain-confirm:before {
  content: "替";
  color: #FFFFFF;
  opacity: 0.0;
  font-size: 12px;
}

::v-deep .el-icon-buyer {
  background: url('~@/assets/icons/quotation/buyer.png') center no-repeat;
  background-size: cover;
  margin-right: 5px;
}

.el-icon-buyer:before {
  content: "替";
  color: #FFFFFF;
  opacity: 0.0;
  font-size: 12px;
}

::v-deep .el-icon-treasurer {
  background: url('~@/assets/icons/quotation/treasurer.png') center no-repeat;
  background-size: cover;
  margin-right: 5px;
}

.el-icon-treasurer:before {
  content: "替";
  color: #FFFFFF;
  opacity: 0.0;
  font-size: 12px;
}

::v-deep .el-icon-sys-result {
  background: url('~@/assets/icons/quotation/sys-result.png') center no-repeat;
  background-size: cover;
  margin-right: 5px;
}

.el-icon-sys-result:before {
  content: "替";
  color: #FFFFFF;
  opacity: 0.0;
  font-size: 12px;
}

::v-deep .el-icon-elevator-detail {
  background: url('~@/assets/icons/quotation/elevator-detail.png') center no-repeat;
  background-size: cover;
  margin-right: 5px;
}

.el-icon-elevator-detail:before {
  content: "替";
  color: #FFFFFF;
  opacity: 0.0;
  font-size: 12px;
}

.para-checkbox ::v-deep .el-checkbox__inner {
  width: 20px;
  height: 20px;
}

.para-checkbox ::v-deep .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner {
  background-color: #e0e0e3;
  border-color: #DCDFE6;
}

.para-checkbox ::v-deep .el-checkbox__input.is-disabled .el-checkbox__inner {
  background-color: #e0e0e3;
  border-color: #DCDFE6;
}

.para-checkbox ::v-deep .el-checkbox__inner::after {
  width: 6px;
  height: 14px;
  border: 2px solid #FFF !important;
  border-left: 0 !important;
  border-top: 0 !important;
  top: -1px;
  left: 5px;
}
::v-deep .disabled-upload {
  margin-top: -10px;
}
::v-deep .disabled-upload .el-icon-close-tip {
  display: none !important;
}
::v-deep .disabled-upload .el-upload--text {
  display: none !important;
}

::v-deep .disabled-box {
  background-color: #F5F7FA;

  border-radius: 4px;
  border: 1px solid #E4E7ED;
  box-sizing: border-box;

  outline: 0;
  padding: 0 15px;


  .el-input__inner {
    background-color: #F5F7FA;
    border-color: #E4E7ED;
    //鼠标手
    cursor: pointer;
  }
}
</style>
