<template>
    <div class="content" v-loading="loading">
        <div class="cancel-btn">
            <div class="project-title">{{ $t('project.view') }}</div>
            <el-button icon="el-icon-arrow-left" plain size="mini" @click="cancel">{{ $t('common.back') }}
            </el-button>
        </div>
        <div class="card-wrapper">

          <!-- 规格信息 height="100%" max-height="50vh"-->
          <div class="card specifications">
            <div style="margin-bottom: 20px;">{{ $t('project.equipmentSpecifications') }}</div>
            <el-table :data="!this.$route.query.version ?equipmentList: this.form.machineList" border max-height="277px" v-loading="equipLoading"
                      show-summary :summary-method="getSummaries" :span-method="arraySpanMethod" ref="tableRef"
                      :header-cell-style="{ background: '#F4F6F8', color: '#92A2B5' }">
              <el-table-column label="No" type="index" width="50" align="center" />

              <!-- 来源 -->
              <el-table-column prop="quotationNo" :label="$t('lead.origin')" width="200" align="center">
                <template slot-scope="{row}">
                  <div class="disabled-box" style="height: 36px;display: flex;justify-content: center;align-items: center">
                      <span v-if="row.quotationNo" class="link-type" @click="handleView(row)">
                        {{ row.quotationNo }}
                      </span>
                    <span v-else  >
                        {{ row.origin}}
                    </span>
                  </div>
                </template>
              </el-table-column>

              <!--规格-->
              <el-table-column prop="standard" width="300" align="center" >
                <template slot="header" slot-scope="scope">
                  <el-tooltip class="item" effect="dark" placement="top">
                    <div slot="content">TWJ630/1.0-7/7/7 or KYS235-1000-3500</div>
                    <div style="">
                      <span>{{$t('project.standard')}}</span>
                      <i class="el-icon-info"></i>
                    </div>
                  </el-tooltip>
                </template>
                <template slot-scope="{row}">
                  <!--:disabled="!canEditC"-->
                  <el-input disabled v-model="row.standard" style="width: 100%;"
                            @blur="row.standard = $event.target.value.trim()"
                            @input="rowUpdate(row)" maxlength="100" clearable/>
                </template>
              </el-table-column>

              <!-- 梯型 -->
              <el-table-column prop="elevatorModel" :label="$t('project.elevatorModel')" width="200" align="center">
                <template slot="header" slot-scope="scope">
                  <el-tooltip class="item" effect="dark" placement="top">
                    <div slot="content">KW2600 or KYS</div>
                    <div>
                      <span>{{$t('project.elevatorModel')}}</span>
                      <i class="el-icon-info"></i>
                    </div>
                  </el-tooltip>
                </template>

                <template slot-scope="{row}">
                  <el-input disabled v-model="row.elevatorModel" style="width: 100%;"
                            @blur="row.elevatorModel = $event.target.value.trim()"
                            @input="rowUpdate(row)" maxlength="30" clearable/>
                </template>
              </el-table-column>



              <!-- 设备类型 -->
              <Column prop="equipmentType" :label="$t('project.equipmentType')" >
                <template slot-scope="{row}">
                  <el-select v-if="row.quotationNo"  disabled v-model="row.equipmentType" :placeholder="$t('common.pleaseSelect')"
                             style="width: 100%" @change="rowUpdate(row)">
                    <el-option v-for="item in dict.type.elevator_type" :key="item.value"
                               :label="item.label" :value="item.value"/>
                  </el-select>
                  <el-select v-else  disabled v-model="row.equipmentType" :placeholder="$t('common.pleaseSelect')"
                             style="width: 100%" @change="rowUpdate(row)">
                    <el-option v-for="item in dict.type.intentional_product" :key="item.value"
                               :label="item.label" :value="item.value"/>
                  </el-select>


                </template>
              </Column>

              <!-- 单价 -->
              <Column prop="amount" :label="$t('quotation.unitPriceLabel')">
                <template slot-scope="{row}">
                  <el-input-number disabled v-model="row.amount" style="width: 100%;" :controls="false"
                                   :max="99999999.99" :precision="2" v-thousands
                                   @change="(currentValue, oldValue) => rowUpdate(row, 1, currentValue, oldValue)"/>
                </template>
              </Column>

              <!--个数 -->
              <Column prop="equipmentQuantity" :label="$t('project.equipmentQuantity')" >
                <template slot-scope="{row}">
                  <el-input-number disabled v-model="row.equipmentQuantity" style="width: 100%;" :controls="false"
                                   :max="9999999" :precision="0"
                                   @change="(currentValue, oldValue) => rowUpdate(row, 2, currentValue, oldValue)"/>
                </template>
              </Column>

              <Column prop="" :label="$t('project.priceTotal')" align="right">
                <template slot-scope="{row}">
                        <span>
                          {{ totalPrice(row) }}
                        </span>
                </template>
              </Column>
              <!--操作-->
              <!--<el-table-column :label="$t('common.operate')" width="200" align="center">
                <template slot="header" slot-scope="scope">
                  <div >
                    <span>{{$t('common.operate')}}</span>
                    &lt;!&ndash;新增行&ndash;&gt;
                    <el-button v-if="canEditC" style="margin-left: 10px;" size="mini" type="primary" icon="el-icon-plus" plain @click="handleAddRow"
                    >&lt;!&ndash;添加行&ndash;&gt;</el-button>
                    &lt;!&ndash;确认&ndash;&gt;
                    <el-button v-if="hasChange" style="margin-left: 10px;" size="mini" type="primary" icon="el-icon-check" plain @click="handleConfirm"
                    >&lt;!&ndash;确认&ndash;&gt;</el-button>
                  </div>
                </template>
                <template slot-scope="{ row }">
                  &lt;!&ndash;v-if="!row.id" &ndash;&gt;
                  <el-button v-if="canEditC" size="small" type="text" @click.native.prevent="handleRemoveRow(row)">
                    {{ $t('common.delete') }}
                  </el-button>
                  <span v-else style="color: darkred">-</span>
                </template>
              </el-table-column>-->
            </el-table>
            <!--</div>-->

            <pagination :auto-scroll="false" :total="equipTotal" :page.sync="equipmentQueryParams.pageNum"
                        :limit.sync="equipmentQueryParams.pageSize" @pagination="getProjectEquip" />
          </div>

          <div class="others">
            <div class="card base-info left" :title="$t('lead.baseInfo')" :min-height="700" @toggle=baseInfoToggle>
              <!--<p>这里是折叠面板的内容。</p>-->
              <!--<p>可以放置任何内容。</p>-->
              <!--<div class="card base-info">-->
              <!--  <div style="margin-bottom: 20px;">{{ $t('lead.baseInfo') }}</div>-->
              <el-form class="project-form" ref="form" :model="form" label-position="top">
                <!--<el-row>-->
                <!--  <el-col :span="24">-->
                <!--    &lt;!&ndash;项目步骤进度&ndash;&gt;-->
                <!--    <el-form-item :label="$t('project.progress')" prop="progress">-->
                <!--      <ProjectProgress v-model="form.progress" confirm @change="confirmProgress"/>-->
                <!--    </el-form-item>-->
                <!--  </el-col>-->
                <!--</el-row>-->
                <!-- 驳回原因 -->
                <el-form-item v-if="form.status == '02'" :label="$t('project.refuseReason')" prop="refuseReason">
                  <el-input disabled v-model="form.refuseReason" type="textarea" style="width: 100%;"></el-input>
                </el-form-item>
                <!--丢单-->
                <el-form-item v-if="form.progress === '0% '" :label="$t('project.loseRemark')" prop="loseRemark">
                  <el-input disabled v-model="form.loseRemark" type="textarea" style="width: 100%;"></el-input>
                </el-form-item>
                <el-form-item v-if="form.progress === '0%'" :label="$t('project.delayRemark')" prop="delayRemark">
                  <el-input disabled v-model="form.delayRemark" type="textarea" style="width: 100%;"></el-input>
                </el-form-item>

                <el-row :gutter="20" v-if="form.progress === '0%' || form.progress === '0% '">
                  <el-col :span="12">
                    <!--原因分类-->
                    <Select disabled prop="reasonType" :data="dict.type.project_reason_type" :label="$t('project.reasonType')"
                            width="100%"/>
                    <!--<el-form-item :label="$t('project.reasonType')" prop="reasonType">-->
                    <!--  <el-select v-model="delayLostForm.reasonType" clearable-->
                    <!--             :placeholder="$t('common.pleaseSelect') + $t('project.reasonType')">-->
                    <!--    <el-option v-for="dict in dict.type.project_reason_type" :key="dict.value" :label="dict.label"-->
                    <!--               :value="dict.value"/>-->
                    <!--  </el-select>-->
                    <!--</el-form-item>-->
                  </el-col>
                  <el-col :span="12">
                    <!-- 竞争对手 -->
                    <el-form-item :label="$t('project.competitor')" prop="competitor">
                      <el-input disabled v-model="form.competitor" style="width: 100%;"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <!-- 项目名称 -->
                    <Input disabled prop="projectName" :label="$t('project.name')" width="100%"></Input>
                  </el-col>
                  <el-col :span="12">
                    <!-- 关联客户 -->
                    <!--<el-form-item :label="$t('project.relatedCustomer')" prop="accountId">-->
                    <!--    <el-select  style="width: 25vw;" v-model="form.accountId"-->
                    <!--        :placeholder="$t('common.pleaseSelect') + $t('project.relatedCustomer')">-->
                    <!--        <el-option v-for="item in accountList" :key="item.value" :label="item.label"-->
                    <!--            :value="item.value" />-->
                    <!--    </el-select>-->
                    <!--</el-form-item>-->

                    <el-form-item :label="$t('project.relatedCustomer')" prop="accountId">
                      <!--<el-input readonly class="disabled-box" value="ACC202406060006: 【小刘第六公司aaaa】" @click.native="goProjectView"></el-input>-->
                      <div class="disabled-box">
                                <span class="link-type" @click="goProjectView">
                                  {{ getProjectName() }}
                                </span>
                        <!--<el-link type="primary" :underline="false" @click="goProjectView">ACC202406060006: 【小刘第六公司aaaa】</el-link>-->
                      </div>
                    </el-form-item>


                    <!-- <Select prop="accountId" :data="accountList" :label="$t('project.relatedCustomer')"
                    :styleObj="{ width: '25vw' }"></Select> -->
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <!--<Select disabled prop="ownerAgent" :data="agentList" :label="$t('lead.agent')"-->
                    <!--        valueProp="agentId" labelProp="agentName"></Select>-->
                    <Input disabled prop="ownerAgentName" :label="$t('lead.agent')" width="100%"></Input>
                  </el-col>
                  <!--项目进度-->
                  <el-col :span="12">
                    <Input disabled prop="progress" :label="$t('project.progress')" width="100%"/>
                  </el-col>
                </el-row>

                <el-row :gutter="20">

                  <!--项目状态-->
                  <el-col :span="12">
                    <Select prop="progress_temp" :data="dict.type.project_progress" :label="$t('project.status')"
                            width="100%" disabled/>
                  </el-col>
                  <el-col :span="12">
                    <!-- 审批状态 -->
                    <Select :data="dict.type.project_status" :label="$t('project.approveStatus')" prop="status"
                            disabled width="100%"/>
                  </el-col>

                </el-row>
                <!-- 关联线索 -->
                <el-row :gutter="20">
                  <el-col :span="12">
                    <!-- 标杆项目 -->
                    <Select prop="modelFlag" :data="dict.type.project_flag" :label="$t('project.isModel')" disabled width="100%"/>
                  </el-col>
                  <el-col :span="12">
                    <!-- 项目类型 -->
                    <Select disabled prop="type" :data="dict.type.project_type" :label="$t('lead.segment')" width="100%"></Select>
                  </el-col>

                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <!-- 产品系列 -->
                    <Select disabled prop="segmentedMarket" :data="dict.type.project_market"
                            :label="$t('project.projectSegments')"></Select>
                  </el-col>
                  <el-col :span="12">
                    <!-- 区域 -->
                    <el-form-item :label="$t('project.area')" prop="areaId">
                      <treeselect class="treeselect w-100" v-model="form.areaId" disabled :noResultsText="$t('common.noResultsText')"
                                  :options="areaTree" :placeholder="$t('common.pleaseSelect') + $t('project.area')"
                                  :show-count="true" :normalizer="normalizer"></treeselect>
                    </el-form-item>
                  </el-col>

                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <!-- 国家 -->
                    <el-form-item :label="$t('project.countryId')" prop="countryId">
                      <el-select disabled v-model="form.countryId" class="w-100"
                                 :placeholder="$t('common.pleaseSelect') + $t('project.countryId')">
                        <el-option v-for="item in countryList" :key="item.value" :label="item.label"
                                   :value="item.value" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <!-- 城市 -->
                    <Input disabled prop="city" :label="$t('project.city')" width="100%"></Input>
                  </el-col>
                </el-row>


                <el-row :gutter="20">
                  <el-col :span="12">
                    <Select prop="currencyId" :data="dict.type.currency_type" :label="$t('project.currency')" disabled width="100%"/>
                  </el-col>
                  <el-col :span="12">
                    <!-- 关键决策人 -->
                    <Input disabled prop="keyContactPerson" :label="$t('project.keyContactPerson')" width="100%"></Input>
                  </el-col>

                </el-row>
                <el-row :gutter="20">

                  <el-col :span="12">
                    <!-- 关键决策人 职位 -->
                    <Input disabled prop="keyJobTitle" :label="$t('project.keyJobTitle')" width="100%"></Input>
                  </el-col>
                  <el-col :span="12">
                    <!-- 关键决策人 电话 -->
                    <el-form-item :label="$t('project.keyContact')" prop="keyContact">
                      <el-input disabled v-model.trim="form.keyContact"
                                :placeholder="$t('common.pleaseInput') + $t('project.keyContact')"
                                maxlength="100"></el-input>
                    </el-form-item>
                  </el-col>

                </el-row>
                <el-row :gutter="20">

                  <el-col :span="12">
                    <!-- 关键决策人 邮箱 -->
                    <el-form-item :label="$t('project.keyEmail')" prop="keyEmail">
                      <el-input disabled v-model.trim="form.keyEmail"
                                :placeholder="$t('common.pleaseInput') + $t('project.keyEmail')"
                                maxlength="100"></el-input>
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <!-- 计划成交月份  -> 客户决定日期 -->
                    <el-form-item :label="$t('account.planDealMonth')" prop="planDealMonth">
                      <el-date-picker style="width: 100%" disabled v-model="form.planDealMonth" type="date"
                                      :placeholder="$t('common.pleaseSelect') + $t('account.planDealMonth')">
                      </el-date-picker>
                    </el-form-item>
                  </el-col>

                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <!--预期安装开始日期-->
                    <DatePicker disabled :label="$t('project.expectedInstallStartDate')" prop="expectedInstallStartDate"
                                width="100%" type="date"/>
                  </el-col>

                  <el-col :span="12">
                    <!-- 联系人 -->
                    <Input disabled prop="contactPerson" :label="$t('project.contactPerson')"
                           width="100%"></Input>
                  </el-col>

                </el-row>
                <el-row :gutter="20">

                  <el-col :span="12">
                    <!-- 职位 -->
                    <el-form-item :label="$t('project.jobTitle')" prop="jobTitle">
                      <el-input disabled v-model.trim="form.jobTitle"
                                :placeholder="$t('common.pleaseInput') + $t('project.jobTitle')"
                                maxlength="100"></el-input>
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <!-- 电话 -->
                    <el-form-item :label="$t('project.contact')" prop="contact">
                      <el-input disabled v-model.trim="form.contact" maxlength="100"
                                minlength="5"
                                :placeholder="$t('common.pleaseInput') + $t('project.contact')"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <!-- 邮箱 -->
                    <el-form-item :label="$t('user.email')" prop="email">
                      <el-input disabled v-model.trim="form.email"
                                :placeholder="$t('common.pleaseInput') + $t('user.email')"
                                maxlength="100"></el-input>
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <!-- 负责人 -->
                    <Input disabled prop="ownerName" :label="$t('agent.head')" width="100%"></Input>
                  </el-col>

                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <!-- 项目地址 -->
                    <Input disabled prop="address" :label="$t('project.address')" width="100%"></Input>
                  </el-col>
                </el-row>



                <!-- 解决方案 -->
                <el-form-item :label="$t('project.solution')" prop="solution">
                  <el-input disabled v-model.trim="form.solution" type="textarea" style="width: 100%;"
                            :placeholder="$t('common.pleaseInput') + $t('project.solution')" maxlength="250"></el-input>
                </el-form-item>
                <!-- 特殊需求 -->
                <el-form-item :label="$t('project.specialRemark')" prop="specialRemark">
                  <el-input disabled v-model.trim="form.specialRemark" type="textarea" style="width: 100%;"
                            :placeholder="$t('common.pleaseInput') + $t('project.specialRemark')"
                            maxlength="250"></el-input>
                </el-form-item>
                <!-- 备注 -->
                <el-form-item :label="$t('common.remark')">
                  <el-input disabled v-model="form.remark" type="textarea" style="width: 100%;" maxlength="500"
                            show-word-limit :placeholder="$t('common.pleaseInput') + $t('common.remark')"></el-input>
                </el-form-item>
                <!-- 延期 -->
                <el-form-item v-if="form.status == '09'" :label="$t('project.delayRemark')" prop="delayRemark">
                  <el-input disabled v-model="form.delayRemark" type="textarea" style="width: 100%;"></el-input>
                </el-form-item>
                <!-- 丢单 -->
                <el-form-item v-if="form.status == '10'" :label="$t('project.loseRemark')" prop="loseRemark">
                  <el-input disabled v-model="form.loseRemark" type="textarea" style="width: 100%;"></el-input>
                </el-form-item>
              </el-form>
              <!--</div>-->
            </div>

            <!-- 跟进记录 -->
            <div v-if=" !$route.query.version" class="follows right">
              <!-- 快捷跟进 -->
              <!-- TODO 做个组件？-->
              <div class="card-item follows" v-if="canFollow()" v-hasPermi="['business:project:follow']">
                <div class="quick-follow-up">
                  <div class="title-row">
                    <div style="margin-bottom: 20px;">{{ $t('follow.fastTrack') }}</div>
                    <el-button type="primary" size="mini" @click="handleAddFollow">{{ $t('common.add') }}</el-button>
                  </div>
                  <el-form :model="fastFollowForm" label-position="top" ref="fastFollowForm">
                    <el-row :gutter="20">
                      <el-col :span="8">
                        <!-- 跟进方式 -->
                        <Select :data="dict.type.crm_follow_way" :label="$t('follow.followWay')" prop="followWay"
                                required/>
                      </el-col>
                      <el-col :span="8">
                        <!--联系人-->
                        <Select :data="contactList" :label="$t('follow.contactPerson')" clearable allow-create
                                filterable prop="contactPerson"  @change="contactPersonChange"
                                required />
                      </el-col>
                      <el-col :span="8">
                        <!--联系方式-->
                        <Input :label="$t('common.contact')" prop="contact" required width="100%"/>
                      </el-col>
                    </el-row>
                    <!-- 跟进内容及结果 -->
<!--                    <Input :label="$t('follow.followDesc')" prop="followDesc" required width="100%"/>-->
                    <Input type="textarea" prop="followDesc" :label="$t('follow.followDesc')" required width="100%" :rows="2"
                           :maxlength="500" />
                  </el-form>
                </div>

                <!-- 华丽分割 -->
                <!--<el-divider></el-divider>-->
              </div>

              <!-- 跟进记录 height="100%" max-height="95%"-->
              <div class="card-item follow-list">
                <div style="height: 22px;margin-bottom: 20px;">{{ $t('account.follow') }}</div>
                <el-table :data="followList" border v-loading="followLoading" height="33vh" max-height="70%"
                          :header-cell-style="{ background: '#F4F6F8', color: '#92A2B5' }" class="custom-table">
                  <el-table-column label="No" type="index" width="50" align="center" />
                  <!-- <el-table-column :label="$t('follow.followNo')" prop="followNo" width="200px"></el-table-column> -->
                  <el-table-column :label="$t('follow.followTime')" prop="followTime" width="150px">
                    <template slot-scope="{row}">
                      {{ getLocalTime(row.followTime, 'YYYY-MM-DD') }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="contactPerson" :label="$t('common.contactPerson')" show-overflow-tooltip
                                   ></el-table-column>
                  <el-table-column prop="contact" :label="$t('common.contact')" show-overflow-tooltip></el-table-column>
                  <!-- <el-table-column prop="createByName" :label="$t('account.followPerson')" show-overflow-tooltip
                                   width="120px"></el-table-column> -->
                  <el-table-column :label="$t('follow.followDesc')" prop="followDesc" width="200" show-overflow-tooltip></el-table-column>
                  <el-table-column fixed="right" :label="$t('common.operate')" align="center" >
                    <template slot-scope="{ row }">
                      <el-button size="small" type="text" @click.native.prevent="handleViewFollow(row)">
                        {{ $t('common.view') }}
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <pagination :auto-scroll="false" :total="followTotal" :page.sync="followQueryParams.pageNum"
                            :limit.sync="followQueryParams.pageSize" @pagination="getFollowList"/>
              </div>

              <!--关联报价-->
              <div class="card-item quotation-list">
                <div style="margin-bottom: 20px;">{{ $t('engineering.quotation') }}</div>
                <el-table :data="quotationList" height="33vh" border row-key="id" children="children"
                          :header-cell-style="{ background: '#F4F6F8', color: '#92A2B5' }" class="custom-table">
                  <!--<el-table-column label="No" type="index" width="50" align="center" />-->
                  <!--报价编号-->
                  <Column :label="$t('quotation.quotationNo')" prop="quotationNo" :min-width="200"/>
                  <!--版本号-->
                  <Column :label="$t('common.version')" prop="version"/>
                  <!--币种-->
                  <Column :label="$t('project.currency')" prop="currencyId" width="200px" searchType="select" :searchDict="dict.type.currency_type"/>
                  <!--梯形-->
                  <Column :label="$t('quotation.suitModel')" prop="elevatorModel"/>
                  <!--报价者-->
                  <Column :label="$t('quotation.quoter')" prop="nickName"/>
                  <!--最终价格-->
                  <Column :label="$t('quotation.finalPrice')" prop="finalPrice"/>
                  <!--附加费用-->
                  <Column :label="$t('quotation.additionalCost')" prop="additionalFees"/>
                  <!--提交时间-->
                  <Column :label="$t('quotation.submitTime')" prop="submitTime" align="center" :min-width="180" />
                  <!--报价状态-->
                  <Column :label="$t('quotation.quotationStatus')" prop="quotationStatus" :min-width="200" :searchDict="dict.type.quotation_status" searchType="select">
                    <template #default="{ row }">
                      <ColorDictTag
                        :bgc="statusColorMap[row.quotationStatus].bgc" :label="convertStatus(row.quotationStatus)"
                        :label-color="statusColorMap[row.quotationStatus].color" @click.native="main.showAuditHistory(row.id, [AUDIT_FLOW.QUOTATION, AUDIT_FLOW.BARGAIN].join(','))"
                      />
                    </template>
                  </Column>

                  <el-table-column fixed="right" :label="$t('common.operate')" width="100" align="center">
                    <template slot-scope="{ row }">
                      <el-button v-hasPermi="['bt:business:quotation:view']" icon="el-icon-view" size="mini" type="text"
                                 @click="handleQuotationView(row)">{{ $t('common.view') }}
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <pagination :auto-scroll="false" :total="quotationTotal" :page.sync="quotationQueryParams.pageNum"
                            :limit.sync="quotationQueryParams.pageSize" @pagination="getQuotationList" />

              </div>

              <!--关联出图-->
              <div class="card-item plot-list">
                <div style="margin-bottom: 20px;">{{ $t('engineering.associatedPlot') }}</div>
                <el-table :data="engineeringList" height="33vh" border
                          :header-cell-style="{ background: '#F4F6F8', color: '#92A2B5' }" class="custom-table">
                  <el-table-column label="No" type="index" width="50" align="center" />
                  <Column :label="$t('engineering.no')" prop="civilEngineeringNo" width="200px"/>
                  <Column :label="$t('quotation.quotationNo')" prop="quotationNo" width="200px"/>
                  <Column :label="$t('quotation.version')" prop="version" width="150px" />
                  <Column :label="$t('engineering.elevatorModel')" prop="elevatorModel" width="200px" />
                  <Column :label="$t('engineering.elevatorNumber')" prop="elevatorNumber" width="200px" />
                  <Column :label="$t('engineering.specification')" prop="specification" width="600px" align="left" />
                  <Column :label="$t('common.submitter')" prop="submitter" width="200px" />
                  <Column :label="$t('common.submitTime')" prop="createTime" width="200px" />
                  <Column :label="$t('engineering.status')" prop="status" searchType="select"
                          :searchDict="dict.type.plot_status" width="200px">
                          <template #default="{ row }">
                          <ColorDictTag :bgc="statusColorMap[row.status].bgc"
                                        :label="formatDict(row.status, dict.type.plot_status)"
                                        :label-color="statusColorMap[row.status].color"/>
                        </template>
                  </Column>
                  <Column :label="$t('common.operate')" :min-width="100" fixed="right" searchType="operate" >
                    <template #default="{ row }">
                      <el-button size="mini" type="text" icon="el-icon-view" @click="handleEngineeringView(row)"
                                 v-hasPermi="['civil:engineering:view']">{{ $t('common.view') }}</el-button>
                    </template>
                  </Column>
                </el-table>
                <pagination :auto-scroll="false" :total="engineeringTotal" :page.sync="engineeringQueryParams.pageNum"
                            :limit.sync="engineeringQueryParams.pageSize" @pagination="getEngineeringList" />
              </div>

            </div>
        </div>
        <FollowDialog ref="followDialog"></FollowDialog>
      </div>
    </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import FollowDialog from '@/views/crmManagement/follow/FollowDialog'
import {getProject, listEquipment, saveOrUpdateEquipment, updateProject, getHistory,listEquipmentProject} from '@/api/business/crm/project'
import {getAreaTree} from '@/api/common/common'
import {getAllNationList} from '@/api/user/country'
import {listAll} from '@/api/business/crm/account'
import {getRelatedContact} from '@/api/business/crm/contact'
import {addFollow, listByTypeAndBusinessId} from '@/api/business/crm/follow'
import {getOwnerList} from '@/api/system/user'
import {getLocalTime} from '@/utils/data/dataUtils'
import ProjectProgress from '@/views/crmManagement/project/ProjectProgress.vue'
import {isEmptyObject} from '@/utils/validate'
import InputNumber from '@/components/element/form/items/InputNumber.vue'
import DictColumn from '../../../components/element/table/DictColumn'
import Column from '@/components/element/table/Column.vue'
import Select from '@/components/element/form/items/Select.vue'
import {checkPermi} from '@/utils/permission'
import CustomCollapse from '@/views/components/CustomCollapse.vue'
import Thousands from '@/directive/thousands/thousands'
import ColorDictTag from '@/views/crmManagement/lead/ColorDictTag/index.vue'
import { listQuotation } from '@/api/business/quotation/quotation'
import { listEngineering } from '@/api/business/civil/engineering'
import { version } from 'vuex/dist/vuex.common.js'
import DatePicker from '@/components/element/form/items/DatePicker.vue'

const statusColorMap = {
  0: {
    color: "#24CA5D",
    bgc: "rgba(24,199,84,0.12)",
  },
  1: {
    color: '#FFC500',
    bgc: 'rgba(255,200,12,0.12)'
  },
  2: {
    color: '#24CA5D',
    bgc: 'rgba(24,199,84,0.12)'
  },
  3: {
    color: '#8B71FD',
    bgc: 'rgba(139,113,253,0.12)'
  },
  4: {
    color: '#0DCCD7',
    bgc: 'rgba(13,204,215,0.12)'
  },
  5: {
    color: '#218AFC',
    bgc: '#E5F1FF'
  },
  6: {
    color: '#FC5821',
    bgc: 'rgba(252,88,33,0.12)'
  },
  7: {
    color: '#FC5821',
    bgc: 'rgba(252,88,33,0.12)'
  },
  8: {
    color: '#AD2BBF',
    bgc: 'rgba(163,32,181,0.12)'
  },
  9: {
    color: '#0B8B21',
    bgc: 'rgba(11,139,33,0.12)'
  },
  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 {
    dicts: ['plot_status','project_flag', 'project_market', 'project_type', 'project_status', 'currency_type', 'lead_industry', 'crm_follow_way', 'intentional_product', 'project_progress', 'elevator_type', 'project_reason_type','quotation_status'],
    components: { ColorDictTag,DatePicker, Column, DictColumn, InputNumber, ProjectProgress, Treeselect, FollowDialog, Select,CustomCollapse },
    inject: ["main"],
    directives: {
      Thousands
    },
    data() {
        return {
            projectId: null,
            form: {},
            accountList: [],
            leadList: [],
            countryList: [],
            areaTree: [],
            contactList: [],
            followList: [],
            ownerList: [],
            loading: false,
            equipLoading: false,
            // 实际总页码
            equipActualMaxPageNum: 1,
            // 实际总数
            equipActualTotal: 0,

            equipTotal: 0,
            equipmentQueryParams: {
                pageNum: 1,
                pageSize: 10,
                removeIds: []
            },
            // 虚拟行
            equipmentVirtualList: [],

            followLoading: false,

            followQueryParams: {
                pageNum: 1,
                pageSize: 10
            },
            followTotal: 0,

          fastFollowForm: {
            followType: '2',
            businessId: null,
            followWay: null,
            followDesc: null,
          },

          // 报价 start
          statusColorMap: statusColorMap,
          quotationList: [],
          quotationQueryParams: {
            projectId: this.projectId,
            pageNum: 1,
            pageSize: 10
          },
          quotationTotal: 0,
          // 报价 end

          // 出图 start
          engineeringList: [],
          engineeringQueryParams: {
            projectId: this.projectId,
            pageNum: 1,
            pageSize: 10
          },
          engineeringTotal: 0,

          // ================设备规格列表 start ======================
          equipmentList:[],

          // 这个值是为了让辅助saveOrUpdateMap参与响应式计算，早知道不用Map了。。。
          uniId: 0,
          saveOrUpdateMap: new Map(),
          equipmentForm: {
            removeIds: [],
            saveOrUpdateList: [],
          },
          actualTotalCount: 0,
          actualTotalAmount: 0,
          followTableMaxH: '40vh'
          // ================设备规格列表 end ======================

        }
    },

    computed: {
      hasChange() {
        this.uniId++
        return this.saveOrUpdateMap.size > 0 || this.equipmentVirtualList.length > 0 || this.equipmentQueryParams.removeIds.length > 0
      },
      canEditC() {
        return this.canEdit() && checkPermi(['business:project:edit']) && !this.$route.query.version
      },

      // 设备数量合计
      equipQuantityTotal() {
        // 注意这里的uniId是需要的，因为saveOrUpdateMap是Map类型，vue无法监听Map的变化，需要一个变量来触发计算属性的重新计算.一开始图方便使用了Map。。
        const uniId = this.uniId
        // console.log('this.actualTotalCount ::', this.actualTotalCount )
        // 实际数据部分的数量合计
        const actualCount = this.actualTotalCount + Array.from(this.saveOrUpdateMap.values()).reduce((total, item) => {
          // console.log('item:', item.equipmentQuantity, item.originalEquipmentQuantity)

          if (item.originalEquipmentQuantity) {
            return total + ((item.equipmentQuantity||0) - (item.originalEquipmentQuantity||0))
          } else {
            return total
          }
        }, 0)

        // console.log('actualCount:', actualCount)
        // 虚拟数据部分的数量合计
        const virtualCount = this.equipmentVirtualList.reduce((total, item) => {
          return total + (item.equipmentQuantity||0)
        }, 0)

        // console.log('virtualCount:', virtualCount)
        return actualCount + virtualCount
      },

      equipPriceTotal() {
        // 注意这里的uniId是需要的，因为saveOrUpdateMap是Map类型，vue无法监听Map的变化，需要一个变量来触发计算属性的重新计算.一开始图方便使用了Map。。
        const uniId = this.uniId
        // 实际数据部分的金额合计
        const actualAmount = this.actualTotalAmount + Array.from(this.saveOrUpdateMap.values()).reduce((total, item) => {
          // console.log('item:', item.amount, item.equipmentQuantity, item.originalEquipmentAmount, item.originalEquipmentQuantity)
          if (item.originalEquipmentQuantity || item.originalEquipmentAmount) {
            return total + ((item.amount||0) * (item.equipmentQuantity||0) - (item.originalEquipmentAmount||item.amount) * (item.originalEquipmentQuantity||0))
          } else {
            return total
          }
        }, 0)

        // console.log('actualAmount:', actualAmount)
        // 虚拟数据部分的金额合计
        const virtualAmount = this.equipmentVirtualList.reduce((total, item) => {
          return total + (item.amount||0) * (item.equipmentQuantity||0)
        }, 0)

        // console.log('virtualAmount:', virtualAmount)
        return actualAmount + virtualAmount
      }
    },
    async created() {
        this.language = this.$i18n.locale;
        this.projectId = this.$route.params && this.$route.params.projectId;
        this.loading = true;
        await this.getProject();
        await this.initData();
        this.getFollowList();
        this.getQuotationList();
        this.getEngineeringList();
        await this.getActualProjectEquip();
        this.loading = false;
    },
    methods: {
      // valueChanged(value, row) {
      //   row.amount = value;
      //   if (!!row.id) {
      //     this.uniId++
      //     this.saveOrUpdateMap.set(row.id, row)
      //   }
      // },
        getLocalTime,
        async getProject() {
            const version = this.$route.query && this.$route.query.version;
            const api = version ? getHistory : getProject;
            const response = await api(this.projectId, version)
            this.form = response.data;
            this.form.progress_temp = this.form.progress
            if (this.form.startTime && this.form.overTime) {
                this.$set(this.form, 'period', [this.form.startTime, this.form.overTime]);
            } else {
                this.$set(this.form, 'period', []);
            }
            this.getRelatedContact(this.form.accountId);
        },

        async getProjectEquip(page) {
          // console.log('obj:', page)
          // console.log('queryPage', this.equipmentQueryParams)
          this.equipLoading = true
          try {
            // console.log('queryPageNum: ', this.equipmentQueryParams.pageNum, '; ActualMaxPageNum: ', this.equipActualMaxPageNum)

            // 页容量切换
            if (page && page.isSizeChange) {
              await this.getActualProjectEquip()
            }
            // console.log('equipActualTotal:', this.equipActualTotal)

            // 实际分页最后一页的数据个数
            // this.equipActualTotal < this.equipmentQueryParams.pageSize ? this.equipActualMaxPageNum = 1 : this.equipActualMaxPageNum = Math.ceil(this.equipActualTotal / this.equipmentQueryParams.pageSize)
            // const countOfActualLastPage = this.equipActualTotal > this.equipmentQueryParams.pageSize ? this.equipActualTotal % this.equipmentQueryParams.pageSize : this.equipActualTotal
            const countOfActualLastPage = this.equipActualTotal % this.equipmentQueryParams.pageSize
            // countOfActualLastPage 有两种 0： 1是实际数据刚好一页，2是实际没有数据（this.equipActualTotal = 0）
            // 虚拟行索引偏移量： 从实际最后一页的最后一个数据开始到补满一页的数据数； indexOffset 一定大于 0 小于等于 pageSize
            const indexOffset = 0 === countOfActualLastPage ? 0 : this.equipmentQueryParams.pageSize - countOfActualLastPage

            // 如果当前页码小于等于实际最大页码:需要查询数据库
            // 当前页与实际页码数字差值 Difference
            const pageDifference = this.equipmentQueryParams.pageNum - this.equipActualMaxPageNum
            // console.log('当前页与实际页码数字差值-pageDifference：', pageDifference)

            if (pageDifference <= 0) {
            // if (this.equipmentQueryParams.pageNum <= this.equipActualMaxPageNum) {
              this.equipmentQueryParams.projectId = this.projectId
              await listEquipmentProject(this.equipmentQueryParams).then(response => {
                let total = response.total + this.equipmentVirtualList.length
                let list = response.rows
                // console.log('data:', response.data)
                this.actualTotalAmount = response.data?.totalAmount || 0
                this.actualTotalCount = response.data?.totalCount || 0
                // 如果equipmentForm.saveOrUpdateList中存在的数据，将list中id相同的数据替换掉
                if (this.saveOrUpdateMap.size > 0) {
                  list = list.map(item => {
                    let saveOrUpdateItem = this.saveOrUpdateMap.get(item.id)
                    if (saveOrUpdateItem) {
                      return saveOrUpdateItem
                    }
                    return item
                  })
                }
                // 最后一页同时有实际数据和虚拟数据： 如果当前页码等于实际最大页码，且虚拟行有数据，且索引偏移量小于当前页码数据长度
                if (this.equipmentQueryParams.pageNum === this.equipActualMaxPageNum && this.equipmentVirtualList.length > 0/*  && indexOffset < this.equipmentQueryParams.pageSize */) {
                  // 这里的索引虽然从 0 开始，但是 slice 左闭右开，所以不用减 1
                  // const endIndex = Math.min(indexOffset, this.equipmentVirtualList.length)

                  // let endIndex
                  // if (indexOffset === 0) {
                  //   endIndex = Math.min(this.equipmentQueryParams.pageSize, this.equipmentVirtualList.length)
                  // } else {
                  //   endIndex = Math.min(indexOffset, this.equipmentVirtualList.length)
                  // }

                  let endIndex = Math.min(
                    indexOffset === 0 ? this.equipmentQueryParams.pageSize : indexOffset,
                    this.equipmentVirtualList.length
                  );

                  list = list.concat(this.equipmentVirtualList.slice(0, Math.max(0, endIndex)))

                }
                this.equipmentList = list
                this.equipTotal = total
              })
            } else {
              // 当前页与实际页码差值
              // const tempNum = this.equipmentQueryParams.pageNum - this.equipActualMaxPageNum

              // TODO 校验页码范围正确性
              this.equipmentList = this.equipmentVirtualList.slice((pageDifference - 1) * this.equipmentQueryParams.pageSize + indexOffset, pageDifference * this.equipmentQueryParams.pageSize + indexOffset)
              this.equipTotal = this.equipActualTotal + this.equipmentVirtualList.length
            }
          } finally {
            this.equipLoading = false
          }

          // console.log('this.equipmentVirtualList::', this.equipmentVirtualList)
        },

        async initData() {
            await Promise.all([
                this.getAccountList(),
                this.getCountryList(),
                this.getAreaTree(),
                this.getOwnerList()
            ]).then(([accountList, countryList, agentTree, ownerList]) => {
                this.accountList = accountList.map(item => {
                    return {
                        value: item.accountId,
                        label: item.accountNo + ": 【" + item.accountName + "】"
                    }
                });
                this.countryList = countryList.map(item => {
                    let label = '';
                    switch (this.language) {
                        case 'chinese':
                            label = item.countryName
                            break;
                        case 'english':
                            label = item.countryNameUS
                            break;
                        case 'russia':
                            label = item.countryNameRU
                            break;
                        case 'spanish':
                            label = item.countryNameES
                            break;
                    }
                    return {
                        value: item.countryId,
                        label: label
                    }
                });
                this.areaTree = agentTree;
                this.ownerList = ownerList;
            });
        },
        normalizer(node) {
            switch (this.language) {
                case 'chinese':
                    return {
                        label: node.label,
                    };
                case 'english':
                    return {
                        label: node.labelUS,
                    };
                case 'russia':
                    return {
                        label: node.labelRU,
                    };
                case 'spanish':
                    return {
                        label: node.labelES,
                    };
            }
        },
        /** 获取字典数据匹配的值 */
        formatDict(value, dictData) {
            return dictData.find(dict => dict.value == value)?.label;
        },
        /** 查询客户所有人列表 */
        getOwnerList() {
            return getOwnerList().then(response => {
                return response.data;
            })
        },
        /** 获取地区树 */
        getAreaTree() {
            return getAreaTree().then(response => {
                return response.data;
            });
        },
        /** 查询国家列表 */
        getCountryList() {
            return getAllNationList().then(response => {
                return response.data;
            })
        },
        /** 查询客户列表 */
        getAccountList() {
            return listAll().then(response => {
                return response.rows;
            })
        },
        /** 查询联系人列表 */
        getRelatedContact(accountId) {
            getRelatedContact({ accountId: accountId }).then(response => {
                this.contactList = response.rows.map(item => {
                    return {
                        value: item.contactId,
                        label: item.contactName,
                        phone: item.phone,
                    }
                })
              // 添加项目联系人
              if (this.form.contactPerson) {
                this.contactList.push({
                  value: this.form.contactPerson,
                  label: this.form.contactPerson,
                  phone: this.form.contact
                })
              }

            })
        },
        /** 查询跟进记录列表 */
        getFollowList() {
          this.followLoading = false
          try {
            this.followQueryParams.businessId = this.projectId;
            this.followQueryParams.followType = '2';
            listByTypeAndBusinessId(this.followQueryParams).then(response => {
              this.followList = response.rows;
              this.followTotal = response.total;
            })
          } finally {
            this.followLoading = false
          }
        },
        cancel() {
            // this.$tab.closeOpenPage({ path: "/project" });
            this.$tab.closePage();
        },
        /** 查看跟进记录 */
        handleViewFollow(row) {
            let param = {
                flag: '3',
                followId: row.followId,
                leadId: null,
                accountId: null,
                projectId: this.projectId
            }
            this.$refs.followDialog.dialogItemInit(param);
        },

      // 确认进度
      async confirmProgress(val) {

        const progress = this.form.progress
        try {
          await this.$modal.confirm(this.$t('project.progressUpdateConfirm'))
        } catch (e) {
          return
        }

        this.form.progress = val.value
        try {
          // TODO 这个更新方法太重了，考虑重写一个接口轻量化更新
          const response = await updateProject(this.form)
          if (response.code === 200) {
            this.$modal.msgSuccess(this.$t('common.editSuccess'));
            this.$store.commit('refreshProject');
          } else {
            this.$modal.msgError(response.msg);
          }
        } catch (e) {
        }
        // this.form.progress_temp = val.value
        this.getProject()
      },

      goProjectView() {
        this.$tab.openPage(this.$t('account.view'), '/account-edit/index/' + this.form.accountId, { type: 'view' });

      },
      handleView(row) {
        this.$tab.closePage({name: 'EditQuotation', path: '/quotation/editQuotation'})
        this.$tab.openPage(
              this.$t("quotation.view"),
              "/quotation/editQuotation",
              { type: "view", quotationId: row.id }
            );
      },

      getProjectName() {
        return this.accountList.find(item => item.value === this.form.accountId)?.label || '-'
      },

      handleAddFollow() {
        // 校验成功发送请求
        this.$refs.fastFollowForm.validate(async valid => {
          if (valid) {
            this.fastFollowForm.businessId = this.form.projectId
            this.fastFollowForm.followTime = new Date();

            const response = await addFollow(this.fastFollowForm);
            if (response.code === 200) {
              this.$modal.msgSuccess(this.$t('common.addSuccess'));
              this.$refs.fastFollowForm.resetFields();
              this.getFollowList();
              // 触发刷新
              this.$store.commit('refreshProject');
            } else {
              this.$modal.msgError(response.msg);
            }

          }
        })
      },

      contactPersonChange(res) {
        // console.log('contactPerson change:::', res)
        if (!isEmptyObject(res)) {
          // 因为后端的sql xml是这样写的。。。
          this.fastFollowForm.contactPerson = res.label
          this.fastFollowForm.contact = res.phone
          this.fastFollowForm.contactPersonName = res.label
        } else {
          // allow-create
          this.fastFollowForm.contactPerson = this.fastFollowForm.contactPerson || ''
          this.fastFollowForm.contactPersonName = this.fastFollowForm.contactPersonName || this.fastFollowForm.contactPerson

        }
      },
      /** 当前项目是否可以编辑 */
      canEdit() {
        return this.$store.getters.roles.includes('sales_director') || this.form.owner === this.$store.getters.userId;
      },
      canFollow() {
        return this.form.status != '01' && this.form.status != '02' && this.canEdit()
      },

      // 报价 start
      getQuotationList() {

        this.quotationQueryParams.projectId = this.projectId
        listQuotation(this.quotationQueryParams)
          .then((response) => {
            this.quotationList = response.rows
            this.quotationTotal = response.total
          })
      },

      convertStatus(status) {
        if (!status) return '-'
        console.log("this.dict.type.quotation_status======>",this.dict.type.quotation_status)
        const check = this.dict.type.quotation_status.filter(
          (item) => item.value == status
        )
        if (check && check.length > 0) {
          return check[0].label
        } else {
          return '-'
        }
      },

      async handleQuotationView(row) {
        await this.$tab.closePage({name: 'EditQuotation', path: '/quotation/editQuotation'})
        await this.$tab.openPage(this.$t('quotation.view'), '/quotation/editQuotation', {
          type: 'view',
          quotationId: row.id
        })
      },
      // 报价 end

      // 出图 start
      getEngineeringList() {
        this.engineeringQueryParams.projectId = this.projectId
        listEngineering(this.engineeringQueryParams)
          .then((response) => {
            this.engineeringList = response.rows
            this.engineeringTotal = response.total
          })
      },

      handleEngineeringView(row) {
        this.$tab.openPage(this.$t('engineering.view'), '/civil/plot-view', { id: row.id })
      },

      // 出图 end

      // ======================================

      // 添加行 跳到最后一页添加，保存信息下来用户切换页码后恢复（同时添加到一个单独的list中）。只有存在添加的数据时，显示确认按钮
      async handleAddRow() {
        // 当前最大页码
        const maxPageNum = Math.ceil(this.equipTotal / this.equipmentQueryParams.pageSize)
        // 如果不在最后一页，查询并跳到最后一页
        if (this.equipmentQueryParams.pageNum !== maxPageNum) {
          console.log('不在最后一页，查询并跳到最后一页')
          this.equipmentQueryParams.pageNum = maxPageNum
          await this.getProjectEquip()
        }

        const item = {
          standard: null,
          elevatorModel: null,
          equipmentType: null,
          equipmentQuantity: null,
          amount: null,
          projectId: this.projectId
        }

        this.equipmentVirtualList.push(item)

        // 添加的时候判断有没有超过 pageSize，如果超过继续添加到下一页
        if (this.equipmentList.length < this.equipmentQueryParams.pageSize) {
          console.log('当前页添加')
          this.equipmentList.push(item)
          this.equipTotal++
        } else {
          console.log('下一页添加')
          this.equipmentQueryParams.pageNum++
          this.getProjectEquip()

        }
      },

      handleRemoveRow(row) {
        // console.log('remove row:::', row)
        this.equipTotal--

        // console.log('equipmentList::::::::', this.equipmentList)
        // 当前最大页码
        const newEquipMaxPageNum = Math.ceil(this.equipTotal / this.equipmentQueryParams.pageSize)
        // 从最后一页删除到上一页时，显示错误
        if (newEquipMaxPageNum !== this.equipmentQueryParams.pageNum && this.equipmentList.length === 1) {
          this.equipmentQueryParams.pageNum = newEquipMaxPageNum
        }

        if (!!row.id) {
          this.equipmentQueryParams.removeIds.push(row.id)
          // 如果删除的行在变更列表中，从变更列表中删除
          if (this.saveOrUpdateMap.has(row.id)) {
            this.uniId++
            this.saveOrUpdateMap.delete(row.id)
          }
          // 确保this.equipActualTotal-- 不会小于0
          if (this.equipActualTotal > 0) {
            this.equipActualTotal--
          }

          const newEquipActualMaxPageNum = Math.ceil(this.equipActualTotal / this.equipmentQueryParams.pageSize)
          // console.log('newEquipActualMaxPageNum:::', newEquipActualMaxPageNum)
          // console.log('this.equipActualMaxPageNum:::', this.equipActualMaxPageNum)
          if (newEquipActualMaxPageNum !== this.equipActualMaxPageNum) {

            this.equipActualMaxPageNum = newEquipActualMaxPageNum === 0 ? 1 : newEquipActualMaxPageNum

            // this.equipmentQueryParams.pageNum = newEquipActualMaxPageNum
            // this.equipActualMaxPageNum = newEquipActualMaxPageNum
          }
        } else {
          this.equipmentVirtualList = this.equipmentVirtualList.filter(item => item !== row)
        }
        this.getProjectEquip()
      },

      totalPrice(row) {
        // return (row.amount * row.equipmentQuantity).toFixed(2) || 0
        return this.toDecimal2(this.numFormat((row.amount||0) * (row.equipmentQuantity||0)))
      },

      /**
       * 行更新
       *
       * @param row 当前行
       * @param calcType 参与计算 默认false
       * @param curV 当前值
       * @param oldV 旧值
       */
      rowUpdate(row, calcType, curV, oldV) {
        // console.log('rowUpdate:::', row, calcType, curV, oldV)
        // 实际数据才需要处理，新增未保存
        if (!!row.id) {
          this.uniId++
          // 将数据库旧值（原始值）存一下 要求 数据源中不能有originalEquipmentAmount和originalEquipmentQuantity
          if (!!calcType && oldV ) {
            if (1 === calcType && !row.originalEquipmentAmount) {
              row.originalEquipmentAmount = oldV
            }
            if (2 === calcType && !row.originalEquipmentQuantity) {
              row.originalEquipmentQuantity = oldV
            }
            // 更新数据 确保触发 vue 的反应式更新 用$set试试？
            this.$nextTick(() => {
              console.log('重新渲染table')
              // this.equipmentList = this.equipmentList.map(item => {
              //   if (item.id === row.id) {
              //     item.amount = row.amount
              //   }
              //   return item
              // })

              this.equipmentList = [...this.equipmentList]
              this.$refs.tableRef.doLayout();
            });
          }
          this.saveOrUpdateMap.set(row.id, row)
        }
        // console.log('saveOrUpdateMap:::', this.saveOrUpdateMap)
      },
      async handleConfirm() {

        this.equipmentForm.saveOrUpdateList = [...this.saveOrUpdateMap.values(), ...this.equipmentVirtualList]

        // 校验
        for (let equipment of this.equipmentForm.saveOrUpdateList) {
          // 规格不能为空
          if (!equipment.standard) {
            this.$modal.msgError(this.$t('project.standard') + this.$t('common.notEmpty'))
            return
          }
          // 梯型不能为空
          if (!equipment.elevatorModel) {
            this.$modal.msgError(this.$t('project.elevatorModel') + this.$t('common.notEmpty'))
            return
          }
          // 设备类型不能为空
          if (!equipment.equipmentType) {
            this.$modal.msgError(this.$t('project.equipmentType') + this.$t('common.notEmpty'))
            return
          }
          if (!equipment.equipmentQuantity) {
            this.$modal.msgError(this.$t('project.equipmentQuantity') + this.$t('common.notEmpty'))
            return
          }
          if (equipment.equipmentQuantity <= 0) {
            this.$modal.msgError(this.$t('project.equipmentQuantity') + this.$t('common.cannotBeLe') + '0')
            return
          }
          if (!equipment.amount) {
            this.$modal.msgError(this.$t('quotation.unitPriceLabel') + this.$t('common.notEmpty'))
            return
          }
          if (equipment.amount <= 0) {
            this.$modal.msgError(this.$t('quotation.unitPriceLabel') + this.$t('common.cannotBeLe') + '0')
            return
          }
        }
        // 至少保留一条数据
        if (this.equipTotal === 0) {
          this.$modal.msgError(this.$t('common.keepAtLeastOne') + this.$t('project.equipmentSpecifications'))
          return
        }

        this.equipmentForm.removeIds = this.equipmentQueryParams.removeIds
        this.equipLoading = true

        try {
          // await this.$modal.confirm(this.$t('project.progressUpdateConfirm'))
          const response = await saveOrUpdateEquipment(this.equipmentForm)
          if (response.code === 200) {
            this.$modal.msgSuccess(this.$t('common.editSuccess'));
            this.$store.commit('refreshProject');
            // 清空
            this.equipmentVirtualList = []
            this.uniId++
            this.saveOrUpdateMap.clear()
            this.equipmentQueryParams.removeIds = []

            await this.getActualProjectEquip()
          } else {
            this.$modal.msgError(response.msg);
          }
        } catch (e) {

        } finally {
          this.equipLoading = false
        }
      },

      // 获取原始实际数据
      async getActualProjectEquip() {
        const {pageNum, pageSize} = this.equipmentQueryParams
        const response = await listEquipmentProject({pageNum, pageSize, projectId: this.projectId})
        this.equipActualTotal = response.total
        this.equipTotal = response.total
        this.equipActualMaxPageNum = Math.ceil(this.equipActualTotal / pageSize)
        this.equipmentList = response.rows
        this.actualTotalAmount = response.data?.totalAmount || 0
        this.actualTotalCount = response.data?.totalCount || 0
      },

      baseInfoToggle(isActive, height) {
        // console.log('isA:', isActive)
        if (isActive) {
          this.followTableMaxH = '950px'
        } else {
          this.followTableMaxH = '40vh'
        }

      },

      arraySpanMethod({ row, column, rowIndex, columnIndex }) {
        this.$nextTick(() => {
          if (this.$refs.tableRef.$el) {
            let current = this.$refs.tableRef.$el
              .querySelector(".el-table__footer-wrapper")
              .querySelector(".el-table__footer");
            let cell = current.rows[0].cells;
            for(let i = 1;i<4;i++) {
              cell[i].style.display = "none";
            }
            cell[0].colSpan = "6"; // 合并单元格
            cell[0].style.textAlign = 'left'
            cell[5].style.textAlign = 'right'
          }
        });
      },

      getSummaries(param) {
        // const { columns, data } = param;
        const sums = [];
        sums[0] = this.$t('common.total');
        sums[4] = this.equipQuantityTotal || '-';
        sums[5] = this.toDecimal2(this.numFormat(this.equipPriceTotal))
        return sums;
      },

    },

  // updated() {
  //   this.$nextTick(() => {
  //     this.$refs["tableRef"] && this.$refs["tableRef"].doLayout();
  //   });
  // },

}
</script>

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

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

::v-deep .treeselect {
    .vue-treeselect__single-value {
        color: #C0C4CC;
    }

    .vue-treeselect__control {
        border-color: #E4E7ED;
        background-color: #F5F7FA;
    }
}

.content {
    //width: 100%;
    padding: 24px;

    .cancel-btn {
        margin-bottom: 16px;
        display: flex;
        justify-content: space-between;

        .project-title {
            font-size: 18px;
            font-weight: bold;
        }
    }


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

  .card-wrapper {
    display: flex;
    flex-direction: column;
    //align-items: center;
    //justify-content: space-evenly;

    & > div {
    //  flex 高度撑满
    //  align-self: stretch;
    }

    .specifications {
      max-height: 45vh;
      //max-height: 45vh;
    }



    .others {
      display: flex;
      margin-top: 24px;
    }

    .left {
      //width: 57vw;
      flex: 1;
      display: flex;
      flex-direction: column;

      .base-info {
        //flex: 2;
        margin-top: 24px;
      }
    }

    .right {
      width: 35vw;
      margin-left: 24px;

      .card-item + .card-item {
        margin-top: 24px;
      }

      //gap: 24px;
    }



    .follows {
      display: flex;
      flex-direction: column;

      .quick-follow-up {
        .title-row {
          display: flex;
          justify-content: space-between;
          align-items: center;
        }
      }

      //.follow-list {
      //  flex: 1;
      //}
    }

    .card-item {
      //width: 100%;
      //height: 100%;
      //max-height: 50vh;
      flex: 1;
      background-color: white;
      padding: 20px;
      box-shadow: 0 2px 10px 0 #CED6DD;
      border-radius: 6px;
    }
  }

}

::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;
  }
}

::v-deep .el-table--medium .el-table__header-wrapper .el-table__cell {
  padding: 1px;
}


//表头fixed列导致的不整洁
::v-deep  .custom-table.el-table--medium .el-table__cell{
  padding: 0px !important;
}


</style>

