<template>
  <div class="account-container">
    <div class="account-title mb20">
      {{ accountTitle }}
      <div style="display: inline-block;float: right;margin-right: 5px">
        <!--        保存草稿-->
        <el-button type="primary" @click="saveDraft" icon="el-icon-document-add" v-if="typeIn(['add','edit'])">{{ $t('quotation.saveDraft') }}</el-button>
        <!--        新增/更新报价-->
        <el-button type="primary" @click="submitForm" icon="el-icon-circle-check" v-if="typeIn(['add','edit'])">{{ $t('audit.saveAndSubmit') }}</el-button>
        <!--        评审通过-->
        <el-button type="primary" @click="handleReviewAccept" icon="el-icon-circle-check" v-if="typeIn(['techReview'])">{{ $t('quotation.reviewAccept') }}</el-button>
        <!--        评审拒绝-->
        <el-button type="primary" @click="handleReviewReject" icon="el-icon-circle-check" v-if="typeIn(['techReview'])">{{ $t('quotation.reviewReject') }}</el-button>

        <!--        采购确认-->
        <el-button type="primary" @click="handleBuyerConfirm" icon="el-icon-circle-check" v-if="typeIn(['buyerInquiry'])">{{ $t('quotation.buyerConfirm') }}</el-button>
        <!--        财务确认-->
        <el-button type="primary" @click="handleTreasureConfirm" icon="el-icon-circle-check" v-if="typeIn(['treasureInquiry'])">{{ $t('quotation.treasureConfirm') }}</el-button>
        <!--        销售确认-->
        <el-button type="primary" @click="handleSalesConfirm" icon="el-icon-circle-check" v-if="typeIn(['salesConfirm'])">{{ $t('quotation.salesConfirm') }}</el-button>

        <!--        发起议价-->
        <el-button type="primary" @click="confirmBargain" icon="el-icon-circle-check" v-if="typeIn(['bargain'])">{{ $t('quotation.confirmBargain') }}</el-button>

        <!--        议价审批 - 通过-->
        <el-button type="primary" @click="bargainPass" v-if="typeIn(['bargainApproval'])">{{ $t('project.pass') }}</el-button>
        <!--        议价审批 - 驳回-->
        <el-button type="primary" @click="bargainReject" v-if="typeIn(['bargainApproval'])">{{ $t('quotation.reject') }}</el-button>

        <!--        接受价格-->
        <el-button type="primary" @click="acceptPrice" v-if="typeIn(['bargainConfirm'])">{{ $t('quotation.acceptPrice') }}</el-button>
        <!--        议价-->
        <el-button type="primary" @click="rejectPrice" v-if="typeIn(['bargainConfirm'])">{{ $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="20">
            <el-col :span="16">
              <!-- 关联项目 -->
              <el-form-item :label="$t('follow.relatedProject')" prop="relatedProjectId">
                <el-select :disabled="disableFlag" v-model="form.relatedProjectId" @change="projectChange"
                           :placeholder="$t('common.pleaseSelect') + $t('follow.relatedProject')" style="width:48.15vw;">
                  <el-option v-for="item in projectList" :key="Number(item.value)"
                             :label="item.label" :value="Number(item.value)"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <!--币种 -->
              <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 dict.type.currency_type" :key="Number(dict.value)"
                             :label="dict.label" :value="Number(dict.value)"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <!--代理商-->
              <el-form-item :label="$t('agent.agent')" prop="agentId">
                <el-select :disabled="disableFlag || agentFlag" v-model="form.agentId" clearable style="width:16vw;"
                           :placeholder="$t('common.pleaseSelect') + $t('agent.agent')">
                  <el-option v-for="dict in agentList" :key="Number(dict.value)"
                             :label="dict.label" :value="Number(dict.value)"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <!--国家 -->
              <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="8">
              <!--城市 -->
              <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-row :gutter="20">
            <el-col :span="8">
              <!--项目类型 -->
              <el-form-item :label="$t('project.type')" prop="projectTypeId">
                <el-select :disabled="true" v-model="form.projectTypeId" clearable style="width:16vw;"
                           :placeholder="$t('common.pleaseSelect') + $t('project.city')">
                  <el-option v-for="dict in dict.type.project_type" :key="Number(dict.value)"
                             :label="dict.label" :value="Number(dict.value)"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <!--报价者 -->
              <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>

            <el-col :span="8">
              <!--版本 -->
              <el-form-item :label="$t('quotation.version')" prop="version" v-if="versionFlag">
                <el-input :disabled="disableFlag" v-model="form.version"
                          :placeholder="$t('common.pleaseInput') + $t('quotation.version')" style="width: 16vw;"/>
              </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" alt="">
            <div class="card-title">{{ $t('quotation.elevatorView') }}</div>
          </div>
          <div v-if="typeIn(['add','edit'])">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="addLine">
              {{ $t('quotation.addElevator') }}
            </el-button>
          </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="80px"/>
            <el-table-column prop="elevatorCode" :label="$t('quotation.elevatorNo')" min-width="150px"/>
            <el-table-column prop="specification" :label="$t('quotation.specification')" min-width="300px"/>

            <el-table-column prop="price" :label="$t('quotation.price')" v-if="typeNotIn(['add','edit','techReview'])" min-width="100px"/>
            <el-table-column prop="finalPrice" :label="$t('quotation.finalPrice')" v-if="typeNotIn(['add','edit','techReview'])" min-width="100px">
              <template slot-scope="scope">
                <span v-if="scope.row.finalPrice != null">{{ 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" min-width="300px">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.discountRate" style="width: 250px;" :min="0" @change="tableDiscountRateChange(scope.row)" v-if="typeIn(['bargainApproval'])"
                                 :placeholder="$t('common.pleaseInput') + $t('quotation.basicRate')"/>
                <span v-else>{{ scope.row.discountRate }}</span>
              </template>
            </el-table-column>
            <!--            折后价格-->
            <el-table-column prop="discountPrice" :label="$t('quotation.discountedPrice')" v-if="typeIn(['bargainApproval','bargainConfirm']) && !agentFlag" min-width="180px"/>

            <!--            是否标准-->
            <el-table-column prop="systemCheckResult" :label="$t('quotation.isStandard')" v-if="typeIn(['techReview','buyerInquiry','treasureInquiry'])" min-width="100px">
              <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 prop="quotationStatus" :label="$t('quotation.quotationStatus')" v-if="typeNotIn(['add','edit'])" min-width="180px">
              <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="200px"/>
            <el-table-column prop="operate" :label="$t('common.operate')" min-width="200px" fixed="right">
              <template slot-scope="scope">
                <!--                电梯详细-->
                <el-button v-hasPermi="['user:agent:edit']" size="mini" v-if="typeNotIn(['add','edit'])"
                           type="text" @click="handleView(scope.row)">{{ $t('quotation.elevatorDetail') }}
                </el-button>
                <!--                系统评审-->
                <el-button v-hasPermi="['user:agent:edit']" size="mini" v-if="typeIn(['techReview']) && scope.row.systemCheckResult === '00'"
                           type="text" @click="handleTechReview(scope.row,true)">{{ $t('quotation.systemReviewResult') }}
                </el-button>
                <!--                技术评审-->
                <el-button v-hasPermi="['user:agent:edit']" size="mini" v-if="typeIn(['techReview']) && scope.row.systemCheckResult === '01'"
                           type="text" @click="handleTechReview(scope.row,false)">{{ $t('quotation.techReview') }}
                </el-button>
                <!--                采购报价-->
                <el-button v-hasPermi="['user:agent:edit']" size="mini" v-if="typeIn(['buyerInquiry'])  && scope.row.systemCheckResult === '01'"
                           type="text" @click="handleQuotation(scope.row,0)">{{ $t('quotation.buyerQuotation') }}
                </el-button>
                <!--                财务报价-->
                <el-button v-hasPermi="['user:agent:edit']" size="mini" v-if="typeIn(['treasureInquiry'])  && scope.row.systemCheckResult === '01'"
                           type="text" @click="handleQuotation(scope.row,1)">{{ $t('quotation.treasureQuotation') }}
                </el-button>
                <!--                查看-->
                <el-button v-hasPermi="['user:agent:edit']" icon="el-icon-view" size="mini" v-if="typeIn(['add','edit'])"
                           type="text" @click="handleView(scope.row)">{{ $t('common.view') }}
                </el-button>
                <!--                更新-->
                <el-button v-hasPermi="['user:agent:edit']" 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="['user:agent:edit']" icon="el-icon-delete" size="mini" v-if="typeIn(['add','edit'])"
                           type="text" @click="handleDelete(scope.row)">{{ $t('common.delete') }}
                </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'])">
        <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(['bargain'])">
            <el-row :gutter="20">
              <el-col :span="8">
                <!-- 价格合计 -->
                <el-form-item :label="$t('quotation.priceTotal')" prop="priceTotal">
                  <el-input v-model="priceForm.priceTotal" style="width: 16vw;" disabled
                            :placeholder="$t('common.pleaseInput') + $t('quotation.priceTotal')"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <!-- 议价方式 -->
                <el-form-item :label="$t('quotation.bargainMethod')" prop="bargainMethod">
                  <el-select v-model="priceForm.bargainMethod" style="width:16vw;"
                             :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="8" 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;" :min="0" @change="expectedRateChange"
                                   :placeholder="$t('common.pleaseInput') + $t('quotation.discountRate')"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <!--价格 -->
                <el-form-item :label="$t('quotation.exceptedPrice')" prop="discountPriceTotal">
                  <el-input-number v-model="priceForm.expectedPrice" style="width: 16vw;" :precision="2" class="input-price"
                                   :disabled="this.priceForm.bargainMethod === 1" @change="expectedPriceChange"
                                   :placeholder="$t('common.pleaseInput') + $t('quotation.price')"/>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!--议价审批-->
          <div v-if="typeIn(['bargainApproval']) || (typeIn(['bargainConfirm']) && !agentFlag)">
            <el-row :gutter="20">
              <el-col :span="8">
                <!-- 价格合计 -->
                <el-form-item :label="$t('quotation.priceTotal')" prop="priceTotal">
                  <el-input disabled v-model="priceForm.priceTotal"
                            :placeholder="$t('common.pleaseInput') + $t('quotation.priceTotal')" style="width: 16vw;"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <!-- 基准价格合计 -->
                <el-form-item :label="$t('quotation.benchmarkPriceTotal')" prop="benchmarkPriceTotal">
                  <el-input disabled v-model="priceForm.basicPrice"
                            :placeholder="$t('common.pleaseInput') + $t('quotation.benchmarkPriceTotal')" style="width: 16vw;"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <!--适配加价合计 -->
                <el-form-item :label="$t('quotation.optionalPriceTotal')" prop="currencyId">
                  <el-input disabled v-model="priceForm.optionalPrice"
                            :placeholder="$t('common.pleaseInput') + $t('quotation.optionalPriceTotal')" style="width: 16vw;"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <!-- 希望价格 -->
                <el-form-item :label="$t('quotation.exceptedPrice')" prop="expectedPrice">
                  <el-input disabled v-model="priceForm.expectedPrice" class="input-price"
                            :placeholder="$t('common.pleaseInput') + $t('quotation.exceptedPrice')" style="width: 16vw;"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <!-- 基准价格折率 -->
                <el-form-item :label="$t('quotation.benchmarkPriceRate')" prop="benchmarkPriceRate">
                  <el-input disabled v-model="priceForm.expectedBasicRate"
                            :placeholder="$t('common.pleaseInput') + $t('quotation.benchmarkPriceRate')" style="width: 16vw;"/>
                </el-form-item>
              </el-col>
            </el-row>
            <div class="flex-center-left mb16">
              <img class="item-size" src="@/assets/images/account-item.png" alt="">
              <div class="card-title">{{ $t('quotation.discountedPrice') }}</div>
            </div>
            <el-row :gutter="20">
              <el-col :span="8">
                <!-- 价格合计 -->
                <el-form-item :label="$t('quotation.priceTotal')" prop="priceTotal">
                  <el-input disabled v-model="priceForm.discountPrice" class="input-price"
                            :placeholder="$t('common.pleaseInput') + $t('quotation.priceTotal')" style="width: 16vw;"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <!-- 基准价格折率 -->
                <el-form-item :label="$t('quotation.benchmarkPriceRate')" prop="relatedProjectId">
                  <el-input disabled v-model="priceForm.discountRate"
                            :placeholder="$t('common.pleaseInput') + $t('quotation.benchmarkPriceRate')" style="width: 16vw;"/>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!--议价确认-->
          <div v-if="typeIn(['bargainConfirm']) && agentFlag">
            <el-row :gutter="20">
              <el-col :span="8">
                <!-- 价格合计 -->
                <el-form-item :label="$t('quotation.priceTotal')" prop="bargainMethod">
                  <el-input v-model="priceForm.priceTotal" style="width: 16vw;" disabled
                            :placeholder="$t('common.pleaseInput') + $t('quotation.priceTotal')"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <!-- 希望价格 -->
                <el-form-item :label="$t('quotation.exceptedPrice')" prop="discountRate">
                  <el-input v-model="priceForm.expectedPrice" style="width: 16vw;" disabled class="input-price"
                            :placeholder="$t('common.pleaseInput') + $t('quotation.exceptedPrice')"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <!--折后价格 -->
                <el-form-item :label="$t('quotation.discountedPrice')" prop="discountPriceTotal">
                  <el-input v-model="priceForm.discountPrice" style="width: 16vw;" disabled class="input-price"
                            :placeholder="$t('common.pleaseInput') + $t('quotation.discountedPrice')"/>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

        </el-form>
      </div>

      <!--          采购/财务报价弹窗-->
      <el-dialog :title="quotationDialogTitle" :model="quotationForm" :visible.sync="quotationDialogVisible" width="90%">
        <el-form class="account-form" label-position="top" :model="quotationForm">
          <el-row :gutter="20">
            <el-col :span="8">
              <!-- 电梯类型 -->
              <el-form-item :label="$t('paraLibrary.elevatorType')" prop="elevatorType">
                <el-select :disabled="true" v-model="quotationForm.elevatorType" style="width:20vw;">
                  <el-option v-for="item in dict.type.elevator_type" :key="item.value"
                             :label="item.label" :value="item.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <!--电梯型号 -->
              <el-form-item :label="$t('elevatorModel.elevatorModel')" prop="elevatorModelId">
                <el-select :disabled="true" v-model="quotationForm.elevatorModelId" style="width:20vw;">
                  <el-option v-for="dict in allElevatorModelList" :key="Number(dict.value)"
                             :label="dict.label" :value="Number(dict.value)"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <!--数量 -->
              <el-form-item :label="$t('quotation.count')" prop="elevatorNumber">
                <el-input :disabled="true" v-model="quotationForm.elevatorNumber" style="width:20vw;">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div :class="{ 'contact-box': type != 'view' }">
          <div class="flex-center-left mb16">
            <img class="item-size" src="@/assets/images/account-item.png" alt="">
            <div class="card-title">{{ $t('quotation.reviewResultList') }}</div>
          </div>

          <el-table :data="quotationList" max-height="310px" v-loading="quotationTableLoading"
                    :header-cell-style="tableHeaderStyle" :border="true" class="table-class">
            <el-table-column label="No." type="index" width="50"></el-table-column>
            <!--            评审项目-->
            <el-table-column prop="markupName" :label="$t('quotation.reviewProject')" min-width="150px"/>
            <!--            关联参数-->
            <el-table-column prop="relatedParaInfo" :label="$t('quotation.relatedParamInfo')" min-width="300px"/>
            <!--            系统评审结果-->
            <el-table-column prop="systemCheckResult" :label="$t('quotation.systemReviewResult')" min-width="150px">
              <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 prop="nonStandardReason" :label="$t('quotation.reason')" min-width="300px">
              <template slot-scope="scope">
                <span style="color: #D71943">{{ scope.row.nonStandardReason }}</span>
              </template>
            </el-table-column>
            <!--            附件-->
            <el-table-column prop="solution" :label="$t('common.annex')" min-width="200px">
              <template slot-scope="scope">
                <span v-if="scope.row.fileList">
                  <span v-for="(item, index)  in scope.row.fileList">
                    <a :href="baseApi + item.filePath" :download="item.realFileName" style="color: #218AFC;text-decoration: underline">{{ item.realFileName }}</a>
                    <span v-if="index !== scope.row.fileList.length - 1">，</span>
                  </span>
                </span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <!--            数量-->
            <el-table-column prop="quantity" :label="$t('quotation.count')" min-width="80"/>
            <!--            单位-->
            <el-table-column prop="unit" :label="$t('quotation.unit')" min-width="80"/>
            <!--            采购价格-->
            <el-table-column prop="buyerPrice" :label="$t('quotation.unitPrice')" :min-width="type === 'buyerInquiry'?'280px':'80px'">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.buyerPrice" :precision="2" :min="0" v-if="typeIn(['buyerInquiry'])"
                                 :placeholder="$t('common.pleaseInput') + $t('quotation.unitPrice')" @change="unitPriceChange(scope.row)"></el-input-number>
                <span v-else>{{ scope.row.buyerPrice }}</span>
              </template>
            </el-table-column>
            <!--            财务价格上浮-->
            <el-table-column prop="floatPercent" :label="$t('quotation.floatPercent')" min-width="280px" v-if="typeIn(['treasureInquiry'])">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.floatPercent"
                                 :placeholder="$t('common.pleaseInput') + $t('quotation.floatPercent')" @change="floatPercentChange(scope.row)"></el-input-number>
              </template>
            </el-table-column>
            <!--            财务报价-->
            <el-table-column prop="treasurerPrice" :label="$t('quotation.treasurerPrice')" min-width="140" v-if="typeIn(['treasureInquiry'])"/>
            <!--            总计-->
            <el-table-column prop="total" :label="$t('quotation.totalPrice')" min-width="100px"/>
          </el-table>
        </div>

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


      <!--          采购确认/财务确认-->
      <el-dialog
        width="35%"
        :title="quotationConfirmDialogTitle"
        :visible.sync="quotationConfirmDialogVisible"
        append-to-body>
        <el-form class="account-form" label-position="top" :model="quotationConfirmForm">
          <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" :min="0" style="width: 16vw"
                                 :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"
        append-to-body>
        <el-form class="account-form" label-position="top" :model="reviewConfirmForm">
          <el-row>
            <el-col :span="24" v-if="reviewAcceptFlag">
              <!-- 可行性 -->
              <el-form-item :label="$t('quotation.feasible')" prop="estimatedPeriod">
                <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" style="width: 16vw"
                                 :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="remark">
                <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 :title="reviewDialogTitle" :model="reviewForm" :visible.sync="reviewDialogVisible" width="90%">
        <el-form class="account-form" label-position="top" :model="reviewForm">
          <el-row :gutter="20">
            <el-col :span="8">
              <!-- 电梯类型 -->
              <el-form-item :label="$t('paraLibrary.elevatorType')" prop="elevatorType">
                <el-select :disabled="true" v-model="reviewForm.elevatorType" style="width:20vw;">
                  <el-option v-for="item in dict.type.elevator_type" :key="item.value"
                             :label="item.label" :value="item.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <!--电梯型号 -->
              <el-form-item :label="$t('elevatorModel.elevatorModel')" prop="elevatorModelId">
                <el-select :disabled="true" v-model="reviewForm.elevatorModelId" style="width:20vw;">
                  <el-option v-for="dict in allElevatorModelList" :key="Number(dict.value)"
                             :label="dict.label" :value="Number(dict.value)"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <!--数量 -->
              <el-form-item :label="$t('quotation.count')" prop="elevatorNumber">
                <el-input :disabled="true" v-model="reviewForm.elevatorNumber" style="width:20vw;">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <div :class="{ 'contact-box': type != 'view' }">
          <div class="flex-center-left mb16">
            <img class="item-size" src="@/assets/images/account-item.png" alt="">
            <div class="card-title">{{ $t('quotation.reviewResultList') }}</div>
          </div>
          <el-table :data="reviewResultList" max-height="310px" v-loading="reviewTableLoading"
                    :header-cell-style="tableHeaderStyle" :border="true" class="table-class">
            <el-table-column label="No." type="index" width="50"></el-table-column>
            <!--            评审项目-->
            <el-table-column prop="markupName" :label="$t('quotation.reviewProject')" min-width="100px"/>
            <!--            关联参数信息-->
            <el-table-column prop="relatedParaInfo" :label="$t('quotation.relatedParamInfo')" min-width="300px"/>
            <!--            系统评审结果-->
            <el-table-column prop="systemCheckResult" :label="$t('quotation.systemReviewResult')" min-width="150px">
              <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 prop="nonStandardReason" :label="$t('quotation.reason')" min-width="200px">
              <template slot-scope="scope">
                <span style="color: #D71943">{{ scope.row.nonStandardReason }}</span>
              </template>
            </el-table-column>
            <!--            附件-->
            <el-table-column prop="solution" :label="$t('common.annex')" min-width="200px" v-if="!reviewCaseFlag">
              <template slot-scope="scope">
                <span v-if="scope.row.fileList && scope.row.fileList.length > 0">
                  <span v-for="(item, index)  in scope.row.fileList">
                    <a :href="baseApi + item.filePath" :download="item.realFileName" style="color: #218AFC;text-decoration: underline">{{ item.realFileName }}</a>
                    <span v-if="index !== scope.row.fileList.length - 1">，</span>
                  </span>
                </span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <!--            解决方案-->
            <el-table-column prop="solution" :label="$t('quotation.solution')" min-width="200px" v-if="!reviewCaseFlag">
              <template slot-scope="scope">
                <el-input v-if="scope.row.systemCheckResult === '01'" v-model="scope.row.solution" :placeholder="$t('common.pleaseInput') + $t('quotation.solution')"></el-input>
                <span v-else>{{ scope.row.solution }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" icon="el-icon-circle-check" @click="techReviewConfirm" v-if="!reviewCaseFlag">{{ $t('common.confirm') }}</el-button>
          <el-button icon="el-icon-remove-outline" @click="reviewDialogVisible = false">{{ $t('common.cancel') }}</el-button>
        </div>
      </el-dialog>
    </div>


  </div>
</template>

<script>
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {listAllAgent} from "@/api/user/agent";
import {listAllProject} from "@/api/business/crm/project";
import {addQuotation, getSalesDiscount, updateQuotation} from "@/api/business/quotation/quotation";
import {listSpecification} from "@/api/business/quotation/specification";
import {getQuotationDetail, getPrice} from "@/api/business/quotation/quotation";
import store from '../../store'
import {listModelNewAll} from "@/api/business/crm/elevatorModel";
import ColorDictTag from "@/views/crmManagement/lead/ColorDictTag/index.vue";
import {listAllPriceDetail} from "@/api/business/quotation/priceDetail";
import {audit} from "@/api/system/flow";
import {acceptBargainPrice, rejectBargainPrice, startBargain} from "@/api/business/quotation/bargainPrice";

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: '#D71943',
    bgc: '#FAEDED'
  },
  9: {
    color: '#D71943',
    bgc: '#FAEDED'
  },
  10: {
    color: '#D71943',
    bgc: '#FAEDED'
  },
  11: {
    color: '#D71943',
    bgc: '#FAEDED'
  },
  12: {
    color: '#D71943',
    bgc: '#FAEDED'
  },
  undefined: {
    color: '#D71943',
    bgc: '#FAEDED'
  },
  null: {
    color: '#D71943',
    bgc: '#FAEDED'
  }
}

export default {
  name: "EditQuotation",
  components: {ColorDictTag},
  dicts: ['account_status', 'currency_type', 'project_type', 'elevator_type', 'quotation_status', 'system_check_result'],
  data() {
    return {
      // 表头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: {},
      // 报价列表
      quotationList: [],
      // 报价表格
      quotationTableLoading: false,
      // 评审表格loading
      reviewTableLoading: false,
      // 议价方式
      bargainMethodList: [
        {label: '按照价格议价', value: 0},
        {label: '按照折率议价', value: 1}
      ],
      // 价格表单
      priceForm: {
        // 议价方式
        bargainMethod: 0,
        // 价格合计
        priceTotal: null,
        // 基准价格合计
        basicPrice: null,
        // 选配加价合计
        optionalPrice: null,
        // 希望价格
        expectedPrice: null,
        // 希望折率
        expectedRate: 100,
        // 希望基准价格折率
        expectedBasicRate: 100,
        // 折后价格-价格合计
        discountPrice: 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: null,
      },
      // 评审结果列表
      reviewResultList: [
        {
          reviewProject: '轿壁材质',
          relatedParamInfo: '轿壁材质左：XXXXXX、轿壁材质右：XXXXXX、轿壁材质后：XXXXXX',
          systemReviewResult: '非标准',
          reason: '选择的轿壁材质的价格，系统中不存在。',
          count: 3,
          unit: '项',
          unitPrice: 30,
          floatPercent: 0,
          treasurerPrice: 30,
          totalPrice: 90,
        }
      ],
      // 电梯型号列表
      allElevatorModelList: [],
      // 报价页面表单
      quotationForm: {
        elevatorType: null,
        elevatorModelId: null,
        elevatorNumber: null,
      },
      // 报价页面可见
      quotationDialogVisible: false,
      // 报价页面标题
      quotationDialogTitle: null,
      // 报价确认页面可见
      quotationConfirmDialogVisible: false,
      // 报价确认页面标题
      quotationConfirmDialogTitle: null,
      type: 'view',
      form: {
        relatedProjectId: null,
        currencyId: null,
        agentId: null,
        countryId: null,
        city: null,
        projectTypeId: null,
        version: null,
        quoter: null,
      },
      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'), trigger: 'change'}
        ],
        currencyId: [
          {required: true, message: this.$t('common.pleaseSelect'), trigger: 'change'}
        ],
        agentId: [
          {required: true, message: this.$t('common.pleaseSelect'), trigger: 'change'}
        ],
        city: [
          {required: true, message: this.$t('common.pleaseSelect'), trigger: 'change'}
        ],
        countryId: [
          {required: true, message: this.$t('common.pleaseSelect'), trigger: 'change'}
        ],
        projectTypeId: [
          {required: true, message: this.$t('common.pleaseSelect'), trigger: 'change'}
        ],
        quoter: [
          {required: true, message: this.$t('common.pleaseInput'), trigger: 'blur'}
        ],
      },
      userInfo: null,
      // 是否为代理商
      agentFlag: false,
      elevatorSet: new Set(),
      quotationId: null,
      tableLoading: false,
      statusColorMap: statusColorMap,
      // 是否销售
      salesFlag: true,
    };
  },
  async created() {
    console.log('用户信息', this.$store.state.user.userInfo)
    this.quotationId = this.$route.query && this.$route.query.quotationId;
    this.userInfo = this.$store.state.user.userInfo
    this.initType();
    await this.initAgent();
    await this.initProjectCountry();
    // 获取价格合计
    if (this.typeIn(['bargain', 'bargainApproval', 'bargainConfirm'])) {
      await this.initPriceInfo()
    }
    if (this.type !== 'add') {
      await this.getList();
      this.initForm();
    } else {
      this.tableLoading = false
    }
    // 获取折扣价格
    if (this.typeIn(['bargainApproval', 'bargainConfirm'])) {
      this.calculateDiscountPriceTotal()
    }
    await this.initElevatorModel()
    const obj = Object.assign({}, this.$route, {title: this.accountTitle})
    await this.$tab.updatePage(obj);
    this.getStoreElevatorInfo();
  },
  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();
  },
  methods: {
    // 接受价格
    acceptPrice() {
      acceptBargainPrice(this.quotationId).then(response => {
        this.$modal.msgSuccess(this.$t('common.operateSuccess'));
        this.$tab.closeOpenPage({path: "/quotation/quotation"});
      })
    },
    // 驳回（重新议价）
    rejectPrice() {
      rejectBargainPrice(this.quotationId).then(response => {
        this.$modal.msgSuccess(this.$t('common.operateSuccess'));
        this.$tab.closeOpenPage({path: "/quotation/quotation"});
      })
    },
    // 议价通过
    async bargainPass() {
      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.priceForm.discountRate + '%',
        // 业务参数
        businessObj: bargainObj
      }
      let res = await getSalesDiscount(this.quotationId);
      let confirm = await this.$confirm(this.$t('quotation.discountRateMsg', [res.data.minDiscount, res.data.maxDiscount]), this.$t('common.tips'))
        .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"});
      })
    },
    // 议价驳回
    async bargainReject() {
      let bargainObj = {
        quotationId: this.quotationId,
      }
      let auditForm = {
        // 审批流
        auditFlow: 2,
        // 业务id  报价id
        businessId: this.quotationId,
        // 审批结果
        status: 30,
        // 备注
        remark: '基价折率:' + this.priceForm.discountRate + '%',
        // 业务参数
        businessObj: bargainObj
      }
      let res = await getSalesDiscount(this.quotationId);
      let confirm = await this.$confirm(this.$t('quotation.discountRateMsg', [res.data.minDiscount, res.data.maxDiscount]), this.$t('common.tips'))
        .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) {
      // 本行的折后价格
      row.discountPrice = row.basicPrice * (row.discountRate / 100) + row.optionalPrice
      console.log('本行折后价格', row.discountPrice)
      this.calculateDiscountPriceTotal()
    },
    // 计算折后价格
    calculateDiscountPriceTotal() {
      // 折前基础价格
      let basicPriceTotal = 0;
      // 折前选配
      let optionalPriceTotal = 0;
      // 折后基础价格
      let discountBasicPriceTotal = 0;
      this.elevatorList.forEach(item => {
        basicPriceTotal += item.basicPrice * item.elevatorNumber
        optionalPriceTotal += item.optionalPrice * item.elevatorNumber
        discountBasicPriceTotal += item.basicPrice * (item.discountRate / 100) * item.elevatorNumber
      })
      // 折后价格
      this.priceForm.discountPrice = optionalPriceTotal + discountBasicPriceTotal
      // 折后价格基价折率
      this.priceForm.discountRate = (discountBasicPriceTotal / basicPriceTotal) * 100

    },
    // 发起议价
    confirmBargain() {
      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() {
      this.priceForm.expectedPrice = this.priceForm.priceTotal * (this.priceForm.expectedRate / 100)
    },
    // 议价-折后价格变换
    expectedPriceChange() {
      this.priceForm.expectedRate = this.priceForm.expectedPrice / this.priceForm.priceTotal * 100
    },
    async initPriceInfo() {
      await getPrice(this.quotationId).then(response => {
        this.bargainId = response.data.bargainId
        this.priceForm = {
          bargainMethod: 0,
          // 价格合计
          priceTotal: response.data.priceTotal,
          // 基准价格合计
          basicPrice: response.data.basicPrice,
          // 选配加价合计
          optionalPrice: response.data.optionalPrice,
          // 希望价格
          expectedPrice: response.data.expectedPrice,
          // 价格折率
          expectedRate: response.data.expectedRate,
          // 基准价格折率
          expectedBasicRate: response.data.expectedBasicRate,
          // 折后价格-价格合计
          discountPrice: response.data.discountPrice,
          // 折后价格-基价折率
          discountRate: response.data.discountRate,
        }
      })
    },
    // 系统评审：true 技术评审：false
    handleTechReview: function (row, reviewCaseFlag) {
      this.reviewCaseFlag = reviewCaseFlag
      this.reviewDialogTitle = reviewCaseFlag ? this.$t("quotation.systemReviewResult") : this.$t("quotation.techReview")
      this.reviewDialogVisible = true
      this.reviewTableLoading = true
      this.reviewResultList = []
      this.reviewForm = {
        id: row.id,
        elevatorType: row.elevatorType,
        elevatorModelId: row.elevatorModelId,
        elevatorNumber: row.elevatorNumber,
      }
      console.log('系统评审/技术评审 参数', row.id, row)
      let form = {
        specificationId: row.id
      }
      // 优先从缓存取
      let obj = this.reviewResultJson[row.id];
      console.log('评审结果列表缓存值', obj)
      if (obj !== undefined) {
        console.log('评审结果列表从缓存获取')
        this.reviewTableLoading = false
        this.reviewResultList = obj
      } else {
        console.log('评审结果列表从后端获取')
        listAllPriceDetail(form).then(response => {
          this.reviewTableLoading = false
          this.reviewResultList = response.rows
        })
      }
    },
    // 技术评审确认
    techReviewConfirm() {
      this.reviewResultJson[this.reviewForm.id] = this.reviewResultList
      console.log('技术评审 解决方案 确认 ', this.reviewResultJson)
      this.reviewDialogVisible = false

      // let form = {
      //   priceDetailList: this.reviewResultList,
      // }
      // updateSolution(form).then(response => {
      //   this.reviewDialogVisible = false
      //   this.$message.success(this.$t('common.editSuccess'))
      // })
    },
    // 采购确认
    handleBuyerConfirm() {
      // 判断单价是否都已设置
      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.reviewResultJson[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 (list[j].buyerPrice <= 0 || list[j].buyerPrice == null) {
                this.$message.error(this.$t('quotation.setSalesPrice'))
                return
              }
            }
          } else {
            this.$message.error(this.$t('quotation.setSalesPrice'))
            return;
          }
        }
      }
      this.quotationConfirmForm = {
        estimatedProcurementPeriod: 0,
        remark: '',
      }
      this.quotationCase = 0
      this.quotationConfirmDialogVisible = true
      this.quotationConfirmDialogTitle = this.$t('quotation.buyerConfirm')
    },
    // 销售确认
    handleSalesConfirm() {
      //   评审通过:200  评审驳回:30
      let auditForm = {
        // 审批流
        auditFlow: 1,
        // 业务id  报价id
        businessId: this.quotationId,
        // 审批结果
        status: 200,
        // 备注
        remark: '',
        // 业务参数
        businessObj: {}
      }
      console.log('销售', auditForm)
      audit(auditForm).then(response => {
        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.reviewResultJson[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].floatPercent)
              // 采购单价未设置
              if (list[j].floatPercent <= 0 || list[j].floatPercent == null) {
                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 = '';
      switch (this.quotationCase) {
        // 采购报价
        case 0:
          remark = '预计采购工期：' + this.quotationConfirmForm.estimatedProcurementPeriod + '天，备注：' + this.quotationConfirmForm.remark
          break;
        // 财务报价
        case 1:
          // 财务报价确认
          remark = '备注：' + this.quotationConfirmForm.remark
          break;
      }
      //   评审通过:200  评审驳回:30
      let auditCode = this.reviewAcceptFlag ? 200 : 30;
      let businessObj = {
        reviewResultJson: this.reviewResultJson
      }
      let auditForm = {
        // 审批流
        auditFlow: 1,
        // 业务id  报价id
        businessId: this.quotationId,
        // 审批结果
        status: auditCode,
        // 备注
        remark: remark,
        // 业务参数
        businessObj: businessObj
      }
      console.log('采购确认，财务确认', auditForm)
      audit(auditForm).then(response => {
        this.quotationConfirmDialogVisible = false
        this.$tab.closeOpenPage({path: "/quotation/quotation"});
      })
    },
    // 评审确认
    reviewConfirm() {
      //   评审通过: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.reviewResultJson
      }
      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
        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': ''
      }
    },
    // 评审驳回view
    handleReviewReject() {
      this.reviewAcceptFlag = false
      this.reviewResultDialogVisible = true
      this.reviewResultDialogTitle = this.$t("quotation.reviewRejectTitle")
      this.reviewConfirmForm = {
        'feasible': 0,
        'estimatedPeriod': 0,
        'remark': '',
        'rejectReason': ''
      }
    },
    // 采购/财务报价最终确认
    handleQuotationFinalConfirm() {
      this.quotationList.forEach(item => {
        item.elevatorNumber = this.quotationForm.elevatorNumber
      })
      console.log('报价列表', this.quotationList)
      switch (this.quotationCase) {
        case 0:
          // 采购报价最终确认
          this.reviewResultJson[this.quotationForm.id] = this.quotationList
          console.log('采购报价 确认 ', this.quotationList)
          this.quotationDialogVisible = false
          break;
        case 1:
          // 财务报价最终确认
          this.reviewResultJson[this.quotationForm.id] = this.quotationList
          console.log('财务报价 确认 ', this.quotationList)
          this.quotationDialogVisible = false
          break;
      }
    },
    //采购报价 0  财务报价 1
    handleQuotation(row, caseId) {
      this.quotationCase = caseId
      this.quotationDialogVisible = true
      this.quotationForm = {
        id: row.id,
        elevatorType: row.elevatorType,
        elevatorModelId: row.elevatorModelId,
        elevatorNumber: row.elevatorNumber,
      }
      switch (caseId) {
        case 0:
          // 采购报价
          this.quotationDialogTitle = this.$t('quotation.buyerQuotation')
          break;
        case 1:
          // 财务报价
          this.quotationDialogTitle = this.$t('quotation.treasureQuotation')
          break;
      }
      let form = {
        specificationId: row.id,
        systemCheckResult: '01',
      }
      this.quotationTableLoading = true
      // 优先从缓存取
      let obj = this.reviewResultJson[row.id];
      console.log('评审结果列表缓存值', obj)
      if (obj !== undefined) {
        console.log('评审结果列表从缓存获取')
        this.quotationTableLoading = false
        this.quotationList = obj
      } else {
        console.log('评审结果列表从后端获取')
        listAllPriceDetail(form).then(response => {
          this.quotationTableLoading = false
          this.quotationList = response.rows
        })
      }
    },
    // 价格上浮& 修改联动
    floatPercentChange(row) {
      let quantity = row.quantity
      if (quantity == null) {
        quantity = 1
      }
      if (row.floatPercent !== null) {
        row.treasurerPrice = row.buyerPrice * (row.floatPercent / 100 + 1)
        row.total = row.treasurerPrice * quantity
      } else {
        row.total = row.buyerPrice * quantity
      }
    },
    // 采购弹窗报价修改联动
    unitPriceChange(row) {
      if (row.buyerPrice !== null) {
        let quantity = row.quantity
        if (quantity == null) {
          quantity = 1
        }
        row.total = row.buyerPrice * quantity
      } else {
        row.total = 0
      }
    },
    async initElevatorModel() {
      const response = await listModelNewAll();
      if (response.rows) {
        response.rows.forEach(item => {
          this.allElevatorModelList.push(
            {
              'label': item.elevatorModel,
              'value': item.id,
            }
          )
        })
      }
    },
    initForm() {
      if (this.quotationId) {
        console.log('基本信息1111111')
        getQuotationDetail(this.quotationId).then(response => {
          if (response.data) {
            console.log('222222222222222222')
            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
          }
        })
      }
    },
    async getList() {
      if (this.quotationId) {
        this.tableLoading = true
        let form = {
          // pageNum: this.pageNum,
          // pageSize: this.pageSize,
          quotationId: this.quotationId,
          bargainId: this.bargainId
        }
        await listSpecification(form).then(response => {
          this.elevatorList = response.rows
          this.elevatorList.forEach(item => {
            this.elevatorSet.add(Number(item.id))
          })
          console.log('电梯已存在的ID', this.elevatorSet)
          this.total = response.total
        }).finally(() => {
          this.tableLoading = false
        })
      }
    },
    // 获取电梯页面传过来的电梯信息
    getStoreElevatorInfo() {
      let elevatorId = this.$route.query && this.$route.query.elevatorId;
      if (elevatorId !== undefined) {
        let elevator = this.$store.state.elevators[elevatorId];
        console.log('检查电梯是否存在', this.elevatorSet, elevatorId, this.elevatorSet.has(Number(elevatorId)))
        if (this.elevatorSet.has(Number(elevatorId))) {
          console.log("重复编辑电梯", elevatorId, elevator)
          if (elevator !== undefined && elevator != null) {
            // 替换电梯列表
            for (let i = 0; i < this.elevatorList.length; i++) {
              if (this.elevatorList[i].id == elevatorId) {
                //保留创建时间
                elevator.createTime = this.elevatorList[i].createTime
                this.$set(this.elevatorList, i, elevator);
              }
            }
          } else {
            console.log("编辑电梯内存获取失败")
          }
        } else {
          console.log("新增电梯", elevatorId)
          if (elevator !== undefined && elevator != null) {
            this.elevatorSet.add(Number(elevatorId));
            this.elevatorList.push(elevator);
          } else {
            console.log("新增电梯内存获取失败")
          }
        }
      }
      console.log('电梯列表', this.elevatorList)
    },
    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
      } else {
        this.form.projectTypeId = null
        this.form.countryId = null
        this.form.city = null
        this.form.areaId = null
      }
      console.log('电梯详细', this.$store.state.elevators)
    },
    async initProjectCountry() {
      let form = {
        language: this.$i18n.locale,
      }
      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,
            city: item.city,
            areaId: item.areaId,
          })
          countryList.push(
            {
              'label': item.countryName,
              'value': item.countryId,
            }
          )
        })
        this.countryList = Array.from(new Map(countryList.map(item => [item['value'], item])).values());
      }
    },
    async initAgent() {
      // 判断是否为代理商
      let userInfo = this.$store.state.user.userInfo;
      // 是否代理商初始化
      // this.agentFlag = userInfo.deptId !== 0
      this.agentFlag = false
      console.log('agentId', userInfo.deptId)
      let params = {}
      if (this.agentFlag === true) {
        params = {
          'agentId': userInfo.deptId
        }
        this.form.agentId = userInfo.deptId
      } else {
        params = {
          'parentSalerId': userInfo.userId
        }
      }
      const response = await listAllAgent(params);
      if (response.rows) {
        response.rows.forEach(item => {
          this.agentList.push(
            {
              'label': item.agentName,
              'value': item.agentId,
            }
          )
        })
        this.agentList.push(
          {
            'label': '张三',
            'value': 49,
          }
        )
        if (this.agentFlag === true) {
          this.form.agentId = userInfo.deptId;
        }
      }
    },
    handleView(row) {
      store.commit('PUT_ELEVATOR', row)
      this.$tab.openPage(this.$t('elevator.view'), '/quotation/elevator', {type: 'view', quotationType: this.type, 'elevatorId': row.id, 'quotationId': this.quotationId});
    },
    handleUpdate(row) {
      store.commit('PUT_ELEVATOR', row)
      this.$tab.openPage(this.$t('elevator.edit'), '/quotation/elevator', {type: 'edit', quotationType: this.type, 'elevatorId': row.id, 'quotationId': this.quotationId});
    },
    /** 新增电梯 */
    addLine() {
      if (this.form.areaId == null) {
        // this.$modal.msgSuccess(this.$t('common.deleteSuccess'));
        this.$modal.msgError('请先选择关联项目');
        return
      }
      this.$tab.openPage(this.$t('elevator.add'), '/quotation/elevator', {type: 'add', quotationType: this.type, 'quotationId': this.quotationId, 'areaId': this.form.areaId});
    },
    /** 返回上个页面 */
    cancel() {
      this.$tab.closeOpenPage({path: "/quotation/quotation"});
    },
    handleDelete(row) {
      this.$modal.confirm(this.$t('common.isDelete')).then(() => {
        console.log('删除电梯', row.id)
        this.elevatorList = this.elevatorList.filter(item =>
          item.id != 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;
      }
      this.disableFlag = this.typeNotIn(['add']);
    },
    /** 提交按钮 */
    submitForm: function () {
      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
          }
          console.log('提交参数', commitForm)
          let successMsg = this.$t('common.addSuccess')
          if (this.quotationId != null) {
            // 编辑
            commitForm.quotationId = this.quotationId
            successMsg = this.$t('common.editSuccess')
            updateQuotation(commitForm).then(response => {
              this.$modal.msgSuccess(successMsg);
              this.$tab.closeOpenPage({path: "/quotation/quotation"});
            })
          } else {
            // 新增
            addQuotation(commitForm).then(response => {
              this.$modal.msgSuccess(successMsg);
              this.$tab.closeOpenPage({path: "/quotation/quotation"});
            })
          }
          console.log("提交表单", commitForm)
        }
      });
    },
    saveDraft() {
      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
          }
          console.log('提交参数', commitForm)
          let successMsg = this.$t('common.addSuccess')
          if (this.quotationId != null) {
            // 编辑
            commitForm.quotationId = this.quotationId
            successMsg = this.$t('common.editSuccess')
            updateQuotation(commitForm).then(response => {
              this.$modal.msgSuccess(successMsg);
              this.$tab.closeOpenPage({path: "/quotation/quotation"});
            })
          } else {
            // 新增
            addQuotation(commitForm).then(response => {
              this.$modal.msgSuccess(successMsg);
              this.$tab.closeOpenPage({path: "/quotation/quotation"});
            })
          }
          // 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 '-'
      }
    }
  }
}
</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 {
    right: 0.5px;
    bottom: 0.5px;
  }
}

</style>
