<template>
  <div class="account-container" v-loading="loading">
    <div class="top"  style="margin-bottom: 20px">
      <div class="account-title">{{ contractTitle }}</div>
      <div class="button-group">
        <el-button v-if="!disableFlag" type="primary" icon="el-icon-circle-check" @click="submitForm"
                   :loading="submitLoading">{{ $t('common.confirm') }}
        </el-button>
        <el-button  @click="cancel" icon="el-icon-remove-outline">
          {{ $t('common.cancel') }}
        </el-button>
        <!--        <el-button v-if="type == 'view'" icon="el-icon-arrow-left" plain size="mini" @click="cancel">-->
        <!--          {{ $t('common.back') }}-->
        <!--        </el-button>-->
      </div>
    </div>


    <div class="content">
      <!-- 合同信息 ----新增 -->
      <div class="card card-base" :class="{ 'card-full': true }">
        <div class="flex-center-left mb16">
          <img class="item-size" src="../../assets/images/account-item.png" alt="">
          <div class="card-title">{{ $t('contract.contract')+$t('contract.information') }}</div>
        </div>
        <el-form class="contract-form" ref="form" :model="form" :rules="type != 'view' ? rules : {}"
                 label-position="top">
          <el-row :gutter="20">
            <el-col :span="8">
              <!--合同号-->
              <Input :disabled="true" prop="contractNo" :label="$t('contract.contractNo')" :required="false"
                     :width="disableFlag ? '16vw' : '80%'" :maxlength="50"></Input>
            </el-col>
            <el-col :span="8">
              <!--合同名-->
              <Input :disabled="disableFlag" prop="contractName" :label="$t('lift.contractName')" :required="!disableFlag"
                     :width="disableFlag ? '16vw' : '80%'" :maxlength="200"></Input>
            </el-col>

            <el-col :span="8">
              <!-- 业务员 -->
              <Select :disabled="true" prop="salesman" :data="ownerList" :label="$t('contract.salesman')"
                      valueProp="userId" labelProp="nickName" :required="!disableFlag"
                      :styleObj="disableFlag ? { width: '16vw' } : { width: '80%' }"></Select>

            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <!-- 区域 -->
              <el-form-item :label="$t('user.area')" prop="areaId">
                <treeselect v-model="form.areaId" :flat="true" :options="areaTree" :noResultsText="$t('common.noResultsText')"
                            :placeholder="$t('common.pleaseSelect') + $t('user.area')"
                            :style="disableFlag ? { width: '16vw' } : { width: '80%' }"
                            :show-count="true" class="w-100" :disabled="disableFlag"
                            @input="areaChange" @select="selectArea">
                  <div slot="option-label" slot-scope="{ node }" style="white-space: nowrap; font-size: 14px">
                    {{ node.raw['label' + localLabelSuffix] ? node.raw['label' + localLabelSuffix] : "" }}
                  </div>
                  <div slot="value-label" slot-scope="{ node }">
                    {{ node.raw['label' + localLabelSuffix] ? node.raw['label' + localLabelSuffix] : "" }}
                  </div>
                </treeselect>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <!-- 国家 -->
              <Select :disabled="disableFlag" prop="countryId" :data="nationList"
                      :label="$t('account.country')" :required="!disableFlag"
                      :styleObj="disableFlag ? { width: '16vw' } : { width: '80%' }"></Select>
            </el-col>
            <el-col :span="8">
              <!--城市-->
              <Input :disabled="disableFlag" prop="city" :label="$t('project.city')" :required="!disableFlag"
                     :width="disableFlag ? '16vw' : '80%'" :maxlength="30"></Input>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <!-- 代理商 -->
              <Select :disabled="disableFlag" prop="agentId" :data="agentList" :label="$t('agent.agent')" @change="changeAgentId"
                      valueProp="agentId" labelProp="agentName" :required="!disableFlag"
                      :styleObj="disableFlag ? { width: '16vw' } : { width: '80%' }"></Select>
            </el-col>
            <el-col :span="8">
              <!--终端客户-->
              <Select :disabled="disableFlag" prop="endCustomers" :label="$t('contract.endCustomers')" :required="!disableFlag"  :data="endCustomersList"
                      :styleObj="disableFlag ? { width: '16vw' } : { width: '80%' }"></Select>
            </el-col>
            <el-col :span="8">
              <!-- 付款方式 -->
              <Select :disabled="disableFlag" prop="paymentMethod" :data="dict.type.contract_payment_method"
                      :label="$t('contract.paymentMethod')" :required="!disableFlag"
                      :styleObj="disableFlag ? { width: '16vw' } : { width: '80%' }"></Select>
            </el-col>

          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <!-- 贸易条款 -->
              <Select :disabled="disableFlag" prop="tradeTerms" :data="dict.type.contract_trade_terms"
                      :label="$t('contract.tradeTerms')" :required="!disableFlag"
                      :styleObj="disableFlag ? { width: '16vw' } : { width: '80%' }"></Select>
            </el-col>
            <el-col :span="8">
              <!-- 销售模式 -->
              <Select :disabled="disableFlag" prop="salesModel" :data="dict.type.contract_sales_model"
                      :label="$t('contract.salesModel')" :required="!disableFlag"
                      :styleObj="disableFlag ? { width: '16vw' } : { width: '80%' }"></Select>
            </el-col>
            <el-col :span="8">
              <!--币种 -->
              <Select :data="dict.type.currency_type" :disabled="disableFlag"
                      :label="$t('contract.currencyId')" prop="currencyId" :required="!disableFlag"
                      :styleObj="disableFlag ? { width: '16vw' } : { width: '80%' }"
              />
            </el-col>

          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <!-- 合同金额 :required="!disableFlag"-->
              <el-form-item prop="amount" :label="$t('contract.amount')"  :maxlength="100" >
                <MoneyInput  v-model="form.amount" @change="item=>valueAmount(item)" :inputValue="form.amount" :zeroLength="2" :style="{width:disableFlag ? '16vw' : '80%'}" placeholder="请输入合同金额" :disabled="disableFlag" class="money-input-class"></MoneyInput>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <!-- 签单日期 -->
              <DatePicker :label="$t('contract.signingDate')"   :mini-able="false"
                          :required="!disableFlag" prop="signingDate" width="100%" :disabled="disableFlag"
                          :width="disableFlag ? '16vw' : '80%'"/>
            </el-col>
            <el-col :span="8">
              <!-- 付款比例 -->
              <Select :disabled="disableFlag" prop="paymentRatio" :data="dict.type.contract_payment_ratio"
                      :label="$t('contract.paymentRatio')" :required="!disableFlag"
                      :styleObj="disableFlag ? { width: '16vw' } : { width: '80%' }"></Select>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <!--地址-->
              <Input :disabled="disableFlag" prop="address" :label="$t('contract.address')" :required="!disableFlag"
                     :width="disableFlag ? '16vw' : '80%'" :maxlength="200"></Input>
            </el-col>

            <el-col :span="8">
              <!--电话-->
              <Input :disabled="disableFlag" prop="telephone" :label="$t('contract.telephone')" :required="!disableFlag"
                     :width="disableFlag ? '16vw' : '80%'" :maxlength="200"></Input>
            </el-col>

            <el-col :span="8">
              <!--邮件-->
              <Input :disabled="disableFlag" prop="email" :label="$t('contract.email')" :required="!disableFlag"
                     :width="disableFlag ? '16vw' : '80%'" :maxlength="50"></Input>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <!--装船口岸-->
              <Input :disabled="disableFlag" prop="shipmentPort" :label="$t('contract.shipmentPort')" :required="!disableFlag"
                     :width="disableFlag ? '16vw' : '80%'" :maxlength="50"></Input>
            </el-col>
            <el-col :span="8">
              <!--装船期限-->
              <DatePicker :label="$t('contract.shipmentDeadline')"   :mini-able="false"
                          :required="!disableFlag" prop="shipmentDeadline" width="100%" :disabled="disableFlag"
                          :width="disableFlag ? '16vw' : '80%'"/>
            </el-col>

            <el-col :span="8">
              <!--目的口岸-->
              <Input :disabled="disableFlag" prop="destinationPort" :label="$t('contract.destinationPort')" :required="!disableFlag"
                     :width="disableFlag ? '16vw' : '80%'" :maxlength="200"></Input>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <!--商标-->
              <Input :disabled="disableFlag" prop="shippingMark" :label="$t('contract.shippingMark')" :required="!disableFlag"
                     :width="disableFlag ? '16vw' : '80%'" :maxlength="200"></Input>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="16">
              <!-- 备注 -->
              <Input :disabled="disableFlag" prop="remark" :label="$t('common.remark')" width="90%"
                     :maxlength="500" type="textarea"></Input>
            </el-col>
          </el-row>
          <el-form-item :label="$t('account.file')" prop="file">
            <FileUpload v-model="form.file" :buttonText="$t('common.uploadFile')" :class="{ 'upload': false }"
                        :disabled="disableFlag" :fileType="[]" :isShowTip="false"/>
          </el-form-item>
        </el-form>

        <el-divider ></el-divider>

        <!-- 设备一览 -->
        <div  :class="{ 'contact-box': !disableFlag }">
          <div class="flex-center-left mb16">
            <img class="item-size" src="../../assets/images/account-item.png" alt="">
            <div class="card-title">{{ $t('contract.equipmentOverview') }}</div>
          </div>
          <div v-if="!disableFlag" class="mb16">
            <!--选择报价单-->
            <el-button type="primary"  size="mini" @click="selectQuotation">
              <img src="~@/assets/icons/contract/quotationSelection.png" alt="Custom Image" class="el-icon-addition" style="width: 13px; height: 13px;" />
              {{ $t('contract.selectQuotation') }}</el-button>
            <!--手动添加-->
            <el-button size="mini"  plain @click="manuallyAdd" :disabled="false">
              <img src="~@/assets/icons/contract/addManually.png" alt="Custom Image" class="el-icon-addition" style="width: 13px; height: 13px;" />
              {{ $t('contract.manuallyAdd') }}</el-button>
            <!--附加费用-->
            <el-button size="mini" plain :disabled="false"  @click="equipmentAddFees()">
              <img src="~@/assets/icons/quotation/addition.png" alt="Custom Image" class="el-icon-addition" style="width: 13px; height: 13px;" />
              {{ $t('contract.equipmentAddFees') }}</el-button>
          </div>

          <el-table :data="equipmentList" @selection-change="handleSelectionChange" max-height="380px" border ref="equipmentTabRef"
                    show-summary :summary-method="getSummaries"
                    :header-cell-style="{ background: '#F4F6F8', color: '#92A2B5' }">
            <el-table-column label="No" type="index" width="60" align="center"></el-table-column>
            <!--电梯号-->
            <el-table-column prop="elevatorCode" :label="$t('lift.elevatorCode')" width="120px" align="center"></el-table-column>
            <!--来源-->
            <el-table-column prop="origin" :label="$t('contract.origin')" width="100px" align="center">
              <template slot-scope="scope">
                <span>{{ formatDict(scope.row.origin, dict.type.contract_lift_origin) }}</span>
              </template>
            </el-table-column>·
            <!--设备类型-->
            <!-- <Column label="设备类型" prop="elevatorType" :showSearch="true" searchType="select" :searchDict="dict.type.elevator_type" :min-width="200"/>-->
            <el-table-column prop="elevatorType" :label="$t('lift.elevatorType')" width="120px" align="center">
              <template slot-scope="scope">
                <span>{{ formatDict(scope.row.elevatorType, dict.type.elevator_type) }}</span>
              </template>
            </el-table-column>
            <!--梯型-->
            <el-table-column prop="elevatorModel" :label="$t('lift.elevatorModel')" width="160px" align="center"></el-table-column>
            <!--规格-->
            <el-table-column prop="specification" :label="$t('lift.specification')" width="180px" align="center" show-overflow-tooltip></el-table-column>
            <!--报价编号-版本-->
            <el-table-column prop="quotationNoVersion" :label="$t('lift.quotationNoVersion')" width="200px" align="center"></el-table-column>
            <!--单价-->
            <el-table-column prop="unitPrice" :label="$t('lift.unitPrice')" width="150px" align="right">
              <template slot-scope="scope">
                {{ toDecimal2(numFormat(scope.row.unitPrice)) }}
              </template>
            </el-table-column>
            <!--项目名称-->
            <el-table-column prop="projectName" :label="$t('lift.projectName')" width="200px" align="center"></el-table-column>
            <!--报价者-->
            <el-table-column prop="quoter" :label="$t('lift.quoter')" width="200px" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.origin == 0">{{ getNickName(scope.row.quoter) }}</span>
                <span v-if="scope.row.origin == 1">{{ scope.row.quoter }}</span>
              </template>
            </el-table-column>
            <!--数量-->
            <el-table-column prop="count" :label="$t('lift.count')" width="80px" align="center"></el-table-column>

            <!--报价折扣-->
            <el-table-column prop="quotationDiscount" :label="$t('lift.quotationDiscount')" width="100px" align="center" :formatter="formatDiscount"></el-table-column>
            <!--附加费用-->
            <el-table-column prop="additionalCost" :label="$t('lift.additionalCost')" width="180px" align="right">
              <template slot-scope="scope">
                {{ toDecimal2(numFormat(scope.row.additionalCost)) }}
              </template>
            </el-table-column>
            <el-table-column  label="总价" prop="liftAmount"  width="180px" align="right">
              <template slot-scope="{row}">
                {{ toDecimal2(numFormat(row.liftAmount)) }}
              </template>
            </el-table-column >

            <el-table-column v-if="type != 'view'" :label="$t('common.operate')" width="150px" fixed="right" align="center">
              <template slot-scope="scope">
                <el-button size="mini" v-if="scope.row.origin == 1" type="text" icon="el-icon-edit" @click="equipmentEdit(scope.row,scope.$index)">{{ "编辑" }}</el-button>
                <el-button size="mini" v-if="!disableFlag" type="text" icon="el-icon-delete" @click="equipmentDelete(scope.$index)">{{ "删除" }}</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-divider v-if="disableFlag"></el-divider>

        <!--        变更履历-->
        <div v-if="type == 'view'" :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('contract.changeHistory') }}</div>
          </div>
          <el-table :data="amendmentList" @selection-change="handleSelectionChange" max-height="280px" border ref="amendmentTabRef"
                    :header-cell-style="{ background: '#F4F6F8', color: '#92A2B5' }">
            <!--版本号-->
            <el-table-column prop="version" :label="$t('contract.version')"  align="center" ></el-table-column>
            <!--变更人-->
            <el-table-column prop="updateBy" :label="$t('contract.updateBy')"  align="center">
              <template #default="{ row }">

                <span>{{ getNickName(row.updateBy) }}</span>
              </template>
            </el-table-column>
            <!--变更日期-->
            <el-table-column prop="updateTime" :label="$t('contract.updateTime')"  align="center" :formatter="formatDate"></el-table-column>
            <!--合同金额-->
            <el-table-column prop="amount" :label="$t('contract.amount')" align="right" >
              <template slot-scope="scope">
                {{ toDecimal2(numFormat(scope.row.amount)) }}
              </template>
            </el-table-column>
            <!--备注-->
            <el-table-column prop="changeRemark" :label="$t('contract.changeOrToVoidRemark')"  align="center" min-width="350"></el-table-column>
            <el-table-column  :label="$t('common.operate')"   align="center">
              <template slot-scope="scope">
                <el-button size="mini"  type="text" icon="el-icon-view" @click="handleHistory(scope.row)">{{ "查看" }}</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!--      变更原因-->
        <div v-if="type === 'amendment' || type === 'toVoid'" style="padding-bottom: 100px">
          <div style="font-weight: 700;font-size: 16px;color: #606266;margin-bottom:10px" ><span style="color: red;">*</span> {{type === 'amendment'?$t('contract.changeRemark'):$t('contract.toReason')}}</div>
          <div>
            <el-input :disabled="disableFlag" v-model="amendmentForm.remark" :label="type === 'amendment'?$t('contract.changeRemark'):$t('contract.toReason')" ref="remarkInput"
                      :maxlength="500" type="textarea" style="width: 50%;height: 100px" :rows="5" ></el-input>
          </div>
        </div>
      </div>
      <FollowDialog ref="followDialog"></FollowDialog>
    </div>
    <!--选择报价单dialog-->
    <el-dialog :close-on-click-modal="false" :title="$t('lift.pleaseSelectQuotation')" :visible.sync="quotationOpen"
               append-to-body
               custom-class="edit-dialog" width="80vw">
      <card-table-zy :row-key="getRowKey" ref="quotationTableRef" :modalData="quotationList" labelWidth="120px"
                     :searchParams="userQueryParams"
                     @pagination="changeAgentId"
                     :loading="targetLoading" :tableSearch="true"
                     :reserve-selection="true" @cancel="handleUserCancel" @select="handleUserSelect"
                     @columnSearch="changeAgentId"
                     @resetList="resetUserQueryParams"
                     :delProp="['createTime']">
        <el-table-column type="selection" width="50" align="center"/>
        <Column :label="$t('lift.elevatorCode')" prop="elevatorCode" :searchParams="userQueryParams" :showSearch="true" width="120px"/>
        <Column :label="$t('lift.elevatorType')"  prop="elevatorType" searchType="select" :searchParams="userQueryParams" :searchDict="dict.type.elevator_type" width="150px" :showSearch="true"/>
        <Column :label="$t('lift.elevatorModel')"  prop="elevatorModel" :searchParams="userQueryParams" :showSearch="true" width="150px"/>
        <Column :label="$t('lift.specification')"  prop="specification" :searchParams="userQueryParams" :showSearch="true"/>
        <Column :label="$t('lift.quotationNoVersion')"  prop="quotationNoVersion" :searchParams="userQueryParams" :showSearch="true"/>
        <Column :label="$t('lift.unitPrice')"  prop="unitPrice" :searchParams="userQueryParams" >
          <template slot-scope="scope">
            {{ toDecimal2(numFormat(scope.row.unitPrice)) }}
          </template>
        </Column>
        <Column :label="$t('lift.projectName')"  prop="projectName" :searchParams="userQueryParams" :showSearch="true"/>
        <Column :label="$t('lift.quoter')"  prop="quoter" :searchParams="userQueryParams" :showSearch="true">
          <template slot-scope="scope">
            {{ getNickName(scope.row.quoter) }}
          </template>
        </Column>
        <Column :label="$t('lift.count')"  prop="count" :searchParams="userQueryParams" :showSearch="false"/>

        <Column :label="$t('lift.quotationDiscount')"  prop="quotationDiscount" :searchParams="userQueryParams" :showSearch="true"/>
        <Column :label="$t('lift.additionalCost')"  prop="additionalCost" :searchParams="userQueryParams" :showSearch="false">
          <template slot-scope="scope">
            {{ toDecimal2(numFormat(scope.row.additionalCost)) }}
          </template>
        </Column>
        <Column :label="$t('quotation.quotationStatus')" prop="quotationStatus" :min-width="250" :searchParams="userQueryParams" :searchDict="dict.type.quotation_status.filter(it => (it.value >= '6' && it.value <= '9'))" :showSearch="true" :selectMore="true" searchType="select"/>
        <Column :label="$t('common.operate')" :min-width="180" :showSearch="true" fixed="right" searchType="operate" :searchParams="userQueryParams"></Column>

      </card-table-zy>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-circle-check" type="primary" @click="quotationSubmitForm">{{
            $t('common.confirm')
          }}
        </el-button>
        <el-button icon="el-icon-remove-outline" @click="quotationCancel">{{
            $t('common.cancel')
          }}
        </el-button>
      </div>
    </el-dialog>
    <!-- 设备手动添加添加或修改对话框 -->
    <el-dialog :close-on-click-modal="false" :title="equipmentTitle" :visible.sync="equipmentOpen" append-to-body
               custom-class="edit-dialog" width="40vw"
    >
      <el-form ref="equipmentForm" :model="equipmentForm" :rules="equipmentFormRules" label-position="top" label-width="80px">
        <el-row :gutter="24">
          <el-col :span="12">
            <Select :disabled="disableFlag" prop="elevatorType" :data="dict.type.elevator_type"
                    :label="$t('lift.elevatorType')" required width="100%"></Select>
          </el-col>

          <el-col :span="12">
            <!-- 电梯号-->
            <Input :label="$t('lift.elevatorCode')" :disabled="readOnly" prop="elevatorCode" width="100%" required/>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <!-- 梯型-->
            <Input :label="$t('lift.elevatorModel')" :disabled="readOnly" prop="elevatorModel" width="100%" required/>
          </el-col>
          <el-col :span="12">
            <!-- 规格-->
            <Input :label="$t('lift.specification')" :disabled="readOnly" prop="specification" width="100%" required/>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <!-- 报价编号-版本-->
            <Input :label="$t('lift.reviewFormNumber')" :disabled="readOnly" prop="quotationNoVersion" width="100%" required/>
          </el-col>

          <el-col :span="12">
            <!-- 项目名称-->
            <Select  prop="projectName" :data="projectNameList" :label="$t('lift.projectName')" :clearable="false" :disabled="readOnly" required  :popper-append-to-body="false"  class="my-select"></Select>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <!-- 报价折扣-->
            <InputNumber :label="$t('lift.quotationDiscount')" :disabled="readOnly" prop="quotationDiscount" width="100%" :step="0.0001"  :precision="4" :min="0" :max="100" required/>
          </el-col>
          <el-col :span="12">
            <!-- 评审折扣-->
            <InputNumber :label="$t('lift.reviewDiscount')" :disabled="readOnly" prop="reviewDiscounts" :step="0.0001"  :precision="4" :min="0" :max="100" width="100%" />
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <!-- 电梯数量-->
            <InputNumber :label="$t('lift.count')" :disabled="readOnly" prop="count" width="100%" :min="1" required/>
          </el-col>

          <el-col :span="12">
            <!-- 单价-->
            <el-form-item prop="unitPrice" :label="$t('lift.unitPrice')" :disabled="readOnly"  width="100%" >
              <MoneyInput v-model="equipmentForm.unitPrice" @change="item=>valueUnit(item)" :inputValue="equipmentForm.unitPrice" :zeroLength="2" :placeholder="'请输入单价'" class="money-input-class"  ></MoneyInput>
            </el-form-item>

          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <!-- 产品类别-->
            <Select :data="dict.type.product_category" :disabled="readOnly"
                    :label="$t('lift.productCategory')" prop="productCategory" required
            />
          </el-col>
          <el-col :span="12">
            <!-- 报价者-->
            <Input :label="$t('lift.quoter')" :disabled="readOnly" prop="quoter" width="100%" required/>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <!-- 币种-->
            <Select :data="dict.type.currency_type" :disabled="readOnly" :label="$t('contract.currencyId')" prop="currencyId" required/>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button v-if="!readOnly" icon="el-icon-circle-check" type="primary" @click="equipmentSubmitForm">{{ $t('common.confirm') }}</el-button>
        <el-button icon="el-icon-remove-outline" @click="equipmentCancel">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>

    <!-- 附加费用添加或修改对话框 -->
    <el-dialog :title="$t('quotation.additionalCost')" :visible.sync="additionalCostOpen" :close-on-click-modal="false" width="80%">
      <div class="ml20">
        <el-table :data="additionalCostList" max-height="280px" v-loading="tableLoading" border>
          <el-table-column label="NO" type="index" width="50"></el-table-column>
          <!--项目名称-->
          <el-table-column prop="projectName" :label="$t('project.projectName')" width="120" align="center"></el-table-column>
          <!--报价编号-版本-->
          <el-table-column prop="quotationNoVersion" :label="$t('lift.quotationNoVersion')" width="200px" align="center"></el-table-column>
          <!--币种-->
          <el-table-column prop="currencyId" :label="$t('project.currency')" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ formatDict(scope.row.currencyId, dict.type.currency_type) }}</span>
            </template>
          </el-table-column>
          <!--电梯型号-->
          <el-table-column prop="elevatorModel" :label="$t('elevatorModel.elevatorModel')" width="120" align="center"></el-table-column>
          <!--电梯号-->
          <el-table-column prop="elevatorCode" :label="$t('lift.elevatorCode')" width="250" align="center"></el-table-column>
          <!--规格-->
          <el-table-column prop="specification" :label="$t('quotation.specification')" width="200" align="center" show-overflow-tooltip></el-table-column>
          <!--数量-->
          <el-table-column prop="count" :label="$t('lift.count')" width="120" align="right"></el-table-column>
          <!--单价-->
          <el-table-column prop="unitPrice" :label="$t('lift.unitPrice')" width="140" align="right">
            <template #default="{ row }">
              {{ toDecimal2(numFormat(row.unitPrice || 0)) }}
            </template>
          </el-table-column>
          <!--预计内陆运费-->
          <Column :label="$t('lift.planInlandFreightCost')" prop="planInlandFreightCost">
            <template slot-scope="scope">
              <MoneyInput :inputValue="scope.row.planInlandFreightCost" :zeroLength="2"
                          @change="item=>valueChanged(item,scope.row,'planInlandFreightCost')" :style="{color:scope.row.planInlandFreightCost > 99999999.99 ?'red':'green'}"></MoneyInput>
            </template>
          </Column>

          <!--          预计海运费-->
          <Column :label="$t('lift.planOceanFreight')" prop="planOceanFreight">
            <template slot-scope="scope">
              <MoneyInput :inputValue="scope.row.planOceanFreight" :zeroLength="2"
                          @change="item=>valueChanged(item,scope.row,'planOceanFreight')" :style="{color:scope.row.planOceanFreight > 99999999.99 ?'red':'green'}"></MoneyInput>
            </template>
          </Column>

          <!--评审运费-->
          <Column :label="$t('lift.reviewShippingCosts')" prop="reviewShippingCosts">
            <template slot-scope="scope">
              <MoneyInput :inputValue="scope.row.reviewShippingCosts" :zeroLength="2"
                          @change="item=>valueChanged(item,scope.row,'reviewShippingCosts')" :style="{color:scope.row.reviewShippingCosts > 99999999.99 ?'red':'green'}"></MoneyInput>
            </template>
          </Column>
          <!--评审佣金-->
          <Column :label="$t('lift.reviewCommission')" prop="reviewCommission">
            <template slot-scope="scope">
              <MoneyInput :inputValue="scope.row.reviewCommission" :zeroLength="2"
                          @change="item=>valueChanged(item,scope.row,'reviewCommission')" :style="{color:scope.row.reviewCommission > 99999999.99 ?'red':'green'}"></MoneyInput>
            </template>
          </Column>
          <!--          其他费用-->
          <Column :label="$t('lift.otherFees')" prop="otherFees">
            <template slot-scope="scope">
              <MoneyInput :inputValue="scope.row.otherFees" :zeroLength="2"
                          @change="item=>valueChanged(item,scope.row,'otherFees')" :style="{color:scope.row.otherFees > 99999999.99 ?'red':'green'}"></MoneyInput>
            </template>
          </Column>
          <!--附加费用-->
          <!--          <Column :label="$t('lift.additionalCost')" prop="additionalCost" align="right">-->
          <!--            <template slot-scope="{row}">-->
          <!--              <span >-->
          <!--                <span>{{ toDecimal2(numFormat(row.additionalCost)) }}</span>-->
          <!--              </span>-->
          <!--            </template>-->
          <!--          </Column>-->

          <Column label="总价" prop="liftAmount" align="right">
            <template slot-scope="{row}">
              <span >
                <span>{{ toDecimal2(numFormat(row.liftAmount)) }}</span>
              </span>
            </template>
          </Column>
          <!--          备注-->
          <el-table-column prop="remark" :label="$t('common.remark')" min-width="200px">
            <template slot-scope="scope">
              <el-tooltip effect="dark" :content="scope.row.remark" placement="top">
                <el-input v-model="scope.row.remark" maxlength="500" show-word-limit
                          :placeholder="$t('common.pleaseInput') + $t('common.remark')"></el-input>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="additionalCostSubmitForm" icon="el-icon-circle-check"  v-if="equipmentList.length > 0">{{ $t('common.confirm') }}</el-button>
        <el-button @click="additionalCostFormCancel" icon="el-icon-remove-outline">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {getAreaTreeByUser} from "@/api/common/common";
import {getAllNationList} from "@/api/user/country";
import {getAllOwnerList, getAreaOwnerList, getAuthRole, getCountryByAreaId} from "@/api/system/user";
import FileUpload from "@/components/FileUpload";
import {getLocalTime} from "@/utils/data/dataUtils"
import FollowDialog from "@/views/crmManagement/follow/FollowDialog";
import CommonSelect from "../../components/element/form/items/CommonSelect";
import PageSelect from "../../components/element/form/items/PageSelect";
import {getAgent, selectByOwner} from '@/api/user/agent'
import CustomCollapse from '../components/CustomCollapse'
import Column from '../../components/element/table/Column'
import DatePicker from "@/components/element/form/items/DatePicker.vue";
import InputNumber from "@/components/element/form/items/InputNumber.vue";
import {getQuotation4Contract} from "@/api/business/quotation/quotation";
import MoneyInput from "@/components/element/form/items/moneyInput.vue";
import CardTableZy from "@/components/element/table/CardTableZy.vue";
import {align} from "quill/ui/icons";
import {getProjectName} from "@/api/business/crm/project";
import {addContract, getContractById, updateContract} from "@/api/contract/contract";
import {listLift} from "@/api/contract/lift";
import {comdify, delcommafy} from "@/utils/money";
import {getContractHistory4Contract, listContractHistory} from "@/api/contract/contractHistory";
import {getI18nDictName} from "../../utils/dict/DictFind";
import {getAccountByAgent} from "@/api/business/crm/account";
import Vue from "vue";

export default {
  name: "Contract-Edit",
  dicts: ['quotation_status','account_status',  'elevator_type',  'currency_type' ,'contract_sales_model','contract_payment_method','contract_payment_ratio','contract_trade_terms','product_category','contract_lift_origin'],
  components: {
    CardTableZy,
    MoneyInput, InputNumber, DatePicker, Column, CustomCollapse, PageSelect, CommonSelect, FileUpload, Treeselect, FollowDialog},
  data() {
    return {
      // 是否第一次进入编辑
      isFirstEdit: false,
      contractId: null,
      type: '',
      form: {
        file: "",
        leadIds: [],
        amount:0
      },
      rules: {
        amount: [
          {required: true, message: this.$t('contract.amount') + this.$t('common.notEmpty'), trigger: "change"}
        ],
        areaId: [
          {required: true, message: this.$t('user.area') + this.$t('common.notEmpty'), trigger: "change"}
        ],
      },
      nationList: [],
      areaList: [],
      equipmentList: [],
      contactShowList: [],
      leadList: [],
      myLeadList: [],
      projectList: [],
      followList: [],
      areaOwnerList: [],
      multipleSelection: [],
      deleteDisabled: true,
      fileType: ["jpg", "png", "jpeg", "doc", "docx", "xls", "xlsx", "ppt", "txt", "pdf"],
      leadTotal: 0,
      projectTotal: 0,
      followTotal: 0,
      selectedIndex: 0,
      accounts: [],
      contractTitle: '',
      areaTree: [],
      disableFlag: false,
      language: null,
      loading: false,
      submitLoading: false,
      leadLoading: false,
      leadOption: [],
      selectLeadParams: {
        pageNum: 1,
        pageSize: 10,
      },
      selectLeadList: [],
      defaultData: [],

      agentList: [],
      open: false,
      amendmentForm:{

      },
      // 用户查询参数
      userQueryParams: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      // 被选择的用户列表
      userSelectionListNowSet: new Set(),
      selectUserIdSet: new Set(),
      targetLoading:false,
      // 需要二次确认
      needSecondaryConfirm: 0,
      //业务员
      ownerList: [],
      //变更履历
      amendmentList:[],

      /**设备手动添加 */
      readOnly:false,
      equipmentOpen :false,
      equipmentTitle:'',
      equipmentFormRules :{
        elevatorType: [
          {required: true, message: this.$t('common.pleaseSelect') + "电梯类型", trigger: "change"}
        ],
        unitPrice: [
          {required: true, message: this.$t('common.pleaseInput') + "单价", trigger: "blur"}
        ],
      },
      equipmentForm :{
        unitPrice:''
      },
      //电梯型号
      elevatorModelList: [],
      quotationOpen:false,
      quotationList:[],
      quotationAddList:[],
      //项目名称
      projectNameList:[],
      //终端客户
      endCustomersList:[],
      //附加费用
      additionalCostOpen:false,
      additionalCostForm:{},
      additionalCostList:[],
      tableLoading:false,
      contractHistory:{},
      currentEquipmentRow:{},
    };
  },

  watch:{
    form(newValue,oldValue){
      if(newValue)
        if(newValue.agentId !== oldValue.agentId){
          this.changeAgentId()
        }
    },

  },
  computed: {
    align() {
      return align
    },
    localLabelSuffix() {
      return localStorage.getItem('labelSuffix') || '';
    },
    getRowKey(row) {
      return row.id;
    }
  },

  async created() {
    this.permissionChar = this.$store.state.user.permissionChar
    this.language = this.$i18n.locale;
    //初始化点击button的类型
    this.initType();
    this.contractId = this.$route.params.contractId ;
    this.loading = true;

    try {
      //获取地区
      this.getAreaTree();
      //获取代理商List
      await this.getAgentListByOwner();
      //不是新增
      if (this.type != 'add') {
        //判断是否存在履历id historyId
        //非新增并且只是查询
        console.log("this.type===============>",this.type)
        if (this.type == 'history') {
          this.getHistoryForm();
        } else {
          //编辑或者变更
          await this.getAccount();

        }
      } else {
        //新增地方的逻辑
        this.$set(this.form,'salesman',this.$store.state.user.userInfo.userId)
        this.$set(this.form,'signingDate',this.getCurrentDate())
      }
      this.getAllOwnerList();
    } finally {
      this.loading = false;
    }

  },
  activated() {
    this.initType();
    const obj = Object.assign({}, this.$route, {title: this.contractTitle})
    this.$tab.updatePage(obj);
  },
  methods: {
    formatDiscount(row, column, cellValue) {
      return cellValue ? parseFloat(cellValue).toFixed(4) : '0.0000';
    },
    getI18nDictName,
    getLocalTime,
    initType() {
      this.type = this.$route.query.type;
      switch (this.type) {
        case 'add':
          this.contractTitle = "合同新增";
          break;
        case 'edit':
          this.contractTitle = "合同编辑";
          this.isFirstEdit = true
          break;
        case 'view':
          this.contractTitle = "合同查看";
          break;
        case 'amendment':
          this.contractTitle = "合同变更";
          this.isFirstEdit = true
          break;
        case 'toVoid':
          this.contractTitle = "合同作废";
          this.isFirstEdit = true
          break;
        case 'history':
          this.contractTitle = "合同履历";
          this.isFirstEdit = true
          break;

      }
      this.disableFlag = this.type == 'view' || this.type == 'history';
    },
    // 区域发生变化
    async areaChange(val) {
      if (val) {
        await this.getCountryByAreaId(val)
      } else {
        this.$set(this.form, "countryId", null);
      }
    },
    async selectArea(val) {
      this.$nextTick(() => {
        // 表单重新校验区域
        this.$refs['form'].validateField(['areaId']);
      })
    },
    async getCountryByAreaId(areaId) {
      const agentId = this.form.agentId
      // if (!agentId || agentId <= 0) {
        if (this.form.areaId) {
          const resp = await getCountryByAreaId(this.form.areaId)
          this.nationList = resp.data
        }
      // } else {
      //   const response = await getAgent(agentId)
      //   this.nationList = response.data?.countryList || []
      // }

      this.nationList = this.nationList.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
        }
      });
      const countryIdExists = this.nationList.some(nation => nation.value === this.form.countryId);
      // 如果只有一个国家，就直接选中
      if(this.nationList.length === 0){

      }
      else if (this.nationList.length === 1) {
        this.form.countryId = this.nationList[0].value
      }
      else if (!countryIdExists) {
        this.form.countryId = null;
      }
    },
    // 获取地区树
    getAreaTree() {
      getAreaTreeByUser().then(response => {
        this.areaTree = response.data;
        // 如果只有一个区域：列表中只有一个且没有子节点，则直接选中
        if (this.areaTree.length === 1 && (!this.areaTree[0].children || this.areaTree[0].children?.length === 0)) {
          this.form.areaId = this.areaTree[0].id
          this.getCountryByAreaId(this.areaTree[0].id)
        }
      });
    },

    /** 获取所有国家列表 */
    getNationList() {
      getAllNationList().then(response => {
        this.nationList = response.data.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
          }
        });
      })
    },


    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.deleteDisabled = this.multipleSelection.length === 0;
    },
    handleSelectionChangeQuotation(val){
      if(val.length > 0){
        this.quotationAddList = [...val]
      }
    },
    /** 选择报价单 */
    selectQuotation() {
      if(this.form.agentId == null){
        //请选择代理商
        this.$message.error(this.$t('lift.pleaseSelectAgent'))
      }
      else if(this.quotationList.length ===  0){
        //该代理商未找到对应的报价单
        this.$message.error(this.$t('lift.agentNotExistQuotation'))
      }else {
        //选择报价单
        this.resetUserQueryParams()
        this.quotationOpen = true
      }
      //alert("用户点击了手动添加按钮")
    },
    /**手动添加 */
    manuallyAdd(){
      // this.equipmentForm = {
      //   unitPrice:0
      // }
      this.resetEquipmentSubmitForm()
      console.log("!this.form.agentId=============>",!this.form.agentId)
      console.log("this.form.agentId != 0=============>",this.form.agentId !== 0)
      if(!this.form.agentId && this.form.agentId !== 0 ){
        //请选择代理商
        this.$message.error(this.$t('lift.pleaseSelectAgent'))
      }else{
        //新增设备 equipmentAdd
        this.equipmentTitle = this.$t('lift.equipmentAdd')
        this.equipmentOpen = true
      }

    },
    /** 返回上个页面 */
    cancel() {
      this.$tab.closePage();
    },

    /** 查询合同履历详情 */
    async getHistoryForm() {
      if (this.contractId !== null) {
        await getContractHistory4Contract(this.contractId).then(response => {
          this.form = response.data;
          this.form.amount = comdify(delcommafy(this.form.amount), 2);
          this.equipmentList = response.data.tqContractLiftHistoryList
        });
      }
    },
    /** 查询合同信息 */
    async getAccount() {
      if (this.contractId !== null) {
        await getContractById(this.contractId).then(response => {
          this.form = response.data;
          this.form.amount = comdify(delcommafy(this.form.amount), 2);
          if(this.form.contractNo && this.type != 'history'){
            //获取履历信息
            listContractHistory({contractNo:this.form.contractNo}).then(resHis=>{
              // if(res && res.)
              this.amendmentList = resHis.rows
            })
          }
          //获取设备数据
          listLift({contractNo:this.form.contractNo}).then(res=>{
            if(res ){
              this.equipmentList = res.rows
              //暂存履历信息
              this.contractHistory = {...this.form}
              this.contractHistory.tqContractLiftHistoryList = [...this.equipmentList]
            }
          })
        });
      }
    },
    /** 合同提交按钮 */
    submitForm: async function () {
      // 变更合同
      if (this.type === 'amendment' ||this.type ==='toVoid' ) {
        //变更信息为空  提示
        if(!this.amendmentForm.remark){
          //变更原因不能为空
          this.$message.error(this.type === 'amendment'? this.$t('lift.changeReasonNotNull') : this.$t('lift.toVoidReasonNotNull'));
          this.$nextTick(() => {
            this.$refs.remarkInput.$el.querySelector('textarea').focus(); // 聚焦到输入框
          });
          return;
        }
      }
      if(this.equipmentList.length === 0){
        this.$message.error("设备不能为空！")
        return;
      }
      //将金额中的千分位符号恢复
      this.form.amount = delcommafy(this.form.amount)
      this.$refs["form"].validate(async valid => {
        if (valid) {
          this.submitLoading = true;
          let contract = Object.assign({}, this.form);
          //合同生成审批流flag为1
          contract.generateTasksFlag = '1'
          contract.needFileFlag = '1'
          contract.tqContractLiftList = this.equipmentList
          if (this.contractId != 0 && contract.id !== undefined) {
            //变更或者编辑之后     将状态设置为审批中
            contract.approveStatus =  '0'
            if(this.type === 'amendment'  ){
              //补充变更原因
              this.contractHistory.changeRemark =  this.amendmentForm.remark
              //添加履历信息
              contract.tqContractHistory = Object.assign({}, this.contractHistory);
            }
            updateContract(contract).then(response => {
              if (response && response.code == 200) {
                this.$modal.msgSuccess(this.type === 'amendment' ? this.$t('common.operateSuccess'):this.$t('common.editSuccess'));
                this.$tab.closeOpenPage({path: "/contract/contract"});
                this.$store.commit('getCountryList');
              } else {
                this.$modal.msgError(response.msg);
              }
            }).catch(() => {
            });
          } else {
            // 新增
            contract.approveStatus = '0'  //初始状态是审核中
            addContract(contract).then(response => {
              if (response.code == 200) {
                this.$modal.msgSuccess(this.$t('common.addSuccess'));
                this.$tab.closeOpenPage({path: "/contract/contract"});
              } else {
                this.$modal.msgError(response.msg);
              }
            }).catch(() => {
            });
          }
          this.submitLoading = false;
        }
      });
    },

    /**设备一览附加费用*/
    async equipmentAddFees() {
      // 查询汇率
      this.additionalCostOpen = true;
      this.additionalCostList = [...this.equipmentList]
      this.additionalCostList.some(item=>{
        item.planInlandFreightCost = comdify(delcommafy(item.planInlandFreightCost?item.planInlandFreightCost:0), 2);
        item.planOceanFreight = comdify(delcommafy(item.planOceanFreight?item.planOceanFreight:0), 2);
        item.reviewShippingCosts = comdify(delcommafy(item.reviewShippingCosts?item.reviewShippingCosts:0), 2);
        item.reviewCommission = comdify(delcommafy(item.reviewCommission?item.reviewCommission:0), 2);
        item.otherFees = comdify(delcommafy(item.otherFees?item.otherFees:0), 2);
      })
    },

    /**设备一览修改*/
    equipmentEdit(row,index){
      //编辑设备
      this.equipmentTitle = "编辑设备"
      // this.resetEquipmentSubmitForm()
      console.log("row===============================>",row)
      this.equipmentOpen = true
      //记录当前行
      row.index = index
      //将当前行内容赋值给编辑表
      this.equipmentForm = {...row}
    },

    /**设备一览删除*/
    equipmentDelete(index){
      this.$modal.confirm(this.$t('common.isDelete')).then(function () {
      }).then(() => {
        this.equipmentList.splice(Number(index), 1); // 直接删除行
        this.$modal.msgSuccess(this.$t('common.deleteSuccess'));
      }).catch(() => { });
    },

    getAgentListByOwner() {
      return selectByOwner(this.$store.getters.userId).then(res => {
        this.agentList = res.data;
        // 默认选中第一个
        if (!this.form.ownerAgent && this.agentList.length > 0) {
          this.form.ownerAgent = this.agentList[0].agentId;
          this.getCountryByAreaId()
        }
      })
    },

    /** 判断是否有权限 */
    hasPermission() {
      return this.$store.getters.roles.includes('sales_director') || this.form.owner === this.$store.getters.userId;
    },

    formatDate(row, column, cellValue) {
      if (!cellValue) return '';
      const date = new Date(cellValue);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    },
    //获取当前日期
    getCurrentDate() {
      const today = new Date();
      return [today.getFullYear(), String(today.getMonth() + 1).padStart(2, '0'), String(today.getDate()).padStart(2, '0')].join('-');
    },
    /** 查询客户所有人列表 */
    getAllOwnerList() {
      getAllOwnerList({onlySalesRole: false}).then(res => {
        this.ownerList = res.data;
      })
      //获取业务员
      getAuthRole(this.form.salesman?this.form.salesman:this.$store.state.user.userInfo.userId).then(response => {
        const newUser = response.user;

        // 检查 ownerList 中是否已经存在相同的 user
        const exists = this.ownerList.some(owner => owner.userId === newUser.userId); // 假设 userId 是唯一标识

        if (!exists) {
          this.ownerList.push(newUser); // 只有在不存在时才添加
        }
      })

    },
    //设备一览提交
    equipmentSubmitForm(){
      this.$refs["equipmentForm"].validate(async valid => {
        if(valid){
          if(this.equipmentForm.origin  == 1){
            console.log("编辑")
            this.equipmentForm.liftAmount = this.equipmentForm.unitPrice+ this.equipmentForm.additionalCost
            if(this.equipmentForm.count > 1){
              for (let i = 1; i < this.equipmentForm.count; i++) {
                const equipmentEntry = {...this.equipmentForm,id:null, count: 1};
                this.equipmentList.push(equipmentEntry);
              }
              this.$set(this.equipmentForm,"count",1)
            }
            this.$nextTick(() => {
              Vue.set(this.equipmentList, this.equipmentForm.index, this.equipmentForm)
              // this.equipmentList[this.equipmentForm.index] = { ...this.equipmentForm }
            })
            console.log("this.equipmentList=========>",this.equipmentList)
            console.log("this.equipmentList[this.equipmentForm.index]=========>",this.equipmentList[this.equipmentForm.index])
            console.log("this.equipmentForm.index======>",this.equipmentForm.index)
            console.log("this.equipmentForm======>",this.equipmentForm)
            //编辑成功
            this.$message.success(this.$t('common.editSuccess'))
          }else{
            console.log("新增")
            this.$set(this.equipmentForm,"origin",1)
            for (let i = 0; i < this.equipmentForm.count; i++) {
              this.equipmentList.push({...this.equipmentForm, count: 1,additionalCost:0.00,
                liftAmount:this.equipmentForm.unitPrice,
                otherFees :0.00,
                reviewCommission:0.00,
                reviewShippingCosts :0.00,
                planOceanFreight :0.00,
                planInlandFreightCost:0.00
              });
              console.log("this.equipmentList=================>",this.equipmentList)
            }
            //添加成功
            this.$message.success(this.$t('common.addSuccess'))
          }
          this.equipmentOpen = false
        }
      })

    },
    equipmentCancel(){
      this.equipmentOpen = false
    },
    //重置设备一览的form表
    resetEquipmentSubmitForm() {
      this.$nextTick(() => {
        if (this.$refs["equipmentForm"]) {
          this.$refs["equipmentForm"].resetFields();
        }
      });
      // this.equipmentForm = {}
    },
    //代理商改变   更改选择报价单列表
    async resetUserQueryParams(){
      this.$set(this.userQueryParams,"elevatorCode",null)
      this.$set(this.userQueryParams,"elevatorType",null)
      this.$set(this.userQueryParams,"elevatorModel",null)
      this.$set(this.userQueryParams,"specification",null)
      this.$set(this.userQueryParams,"quotationNoVersion",null)
      this.$set(this.userQueryParams,"unitPrice",null)
      this.$set(this.userQueryParams,"projectName",null)
      this.$set(this.userQueryParams,"quoter",null)
      this.$set(this.userQueryParams,"quotationDiscount",null)
      this.$set(this.userQueryParams,"quotationStatus",null)
      await this.changeAgentId()
    },
    async changeAgentId(){
      //清除设备一览
      this.equipmentList = []
      if(this.form.agentId || this.form.agentId === 0 ){
        let params = {...this.userQueryParams,agentId:this.form.agentId}
        console.log(" this.params.quotationStatus=============================>", params.quotationStatus)
        console.log("typeof this.params.quotationStatus=============================>",typeof params.quotationStatus)

        getQuotation4Contract(params).then(res=>{
          if(res ){
            this.quotationList = res.rows
            this.userQueryParams.total = res.total
            // 跨页回显
            this.quotationList.forEach((row) => {
              const bool = this.selectUserIdSet.has(row.elevatorCode+row.quotationNoVersion)
              if (bool) {
                this.$nextTick(() => {
                  this.$refs['quotationTableRef'].$refs['table'].toggleRowSelection(row, true)
                  const userSelectionArray = Array.from(this.userSelectionListNowSet);
                  const hasItem = userSelectionArray.some(item => item.quotationNoVersion === row.quotationNoVersion);
                  if (!hasItem) {
                    this.userSelectionListNowSet.add(row)
                  }
                })
              }
            })
            //this.getAllRoleOptions()
          }
        })
        //获取终端客户
        await getAccountByAgent(this.form.agentId).then(res=>{
          if(res && res.code === 200){
            if(res.data == null || res.data.length === 0){
              //该代理商无相关的终端客户
              this.$message.error("该代理商无相关的终端客户")
            }
            const uniqueKeys = new Set();
            this.endCustomersList = res.data
              .filter(item => {
                if (uniqueKeys.has(item.accountId)) {
                  return false; // 如果已经存在，则过滤掉
                }
                uniqueKeys.add(item.accountId); // 添加到 Set 中
                return true; // 保留该项
              })
              .map(item => {
                return {
                  value: item.accountId,
                  label: item.accountName
                };
              });
            // 检查 endCustomersList 中是否包含 this.form.endCustomers 的值
            const hasEndCustomer = this.endCustomersList.some(item => item.value === this.form.endCustomers);
            if (!hasEndCustomer) {
              this.$set(this.form, 'endCustomers', null);
            }
          }
        })
        //获取项目名称
        getProjectName(this.form.agentId).then(res=>{
          if(res && res.code === 200){
            const uniqueItems = new Set();
            this.projectNameList = res.data
              .filter(item => {
                if (uniqueItems.has(item)) {
                  return false; // 如果已经存在，则过滤掉
                }
                uniqueItems.add(item); // 否则，添加到 Set 中
                return true; // 保留该项
              })
              .map(item => ({
                value: item,
                label: item
              }));
          }
        })
      }else{
        console.log("代理商空了")
        //清除终端客户
        this.$set(this.form, 'endCustomers', null);
        this.endCustomersList = []


      }

    },
    //选择报价单的取消选中
    handleUserCancel(rows) {
      rows.forEach(row => {
        this.userSelectionListNowSet.forEach(item => {
          if (item.elevatorCodeitem +item.quotationNoVersion === row.elevatorCodeitem + row.quotationNoVersion) {
            this.userSelectionListNowSet.delete(item);
            this.selectUserIdSet.delete(row.elevatorCode+row.quotationNoVersion);
          }
        });
      })
    },
    //选择报价单的选中
    handleUserSelect(rows) {
      rows.forEach(row => {
        if (!this.selectUserIdSet.has(row.elevatorCode+row.quotationNoVersion)) {
          this.selectUserIdSet.add(row.elevatorCode+row.quotationNoVersion)
          this.userSelectionListNowSet.add(row)
        }
      })
    },
    //关闭报价单界面
    quotationCancel(){
      this.quotationOpen = false
    },
    //提交报价单界面
    quotationSubmitForm(){
      const myArray = Array.from(this.userSelectionListNowSet);
      if (myArray.length <= 0) {
        //请选择数据
        this.$message.error("请选择数据")
        return console.log("myArray.length <= 0")
      }
      if (myArray.length <= 0) {
      }
      if (this.equipmentList.length > 0) {
        // 判断选择的用户列表是否都已存在于已选择的列表中
        const allSelectedAlready = myArray.every(item => this.equipmentList.some(target => {
          //设置未自动获取  选择报价单方式
          item.origin = 0
          return target.elevatorCode+target.quotationNoVersion === target.elevatorCode+item.quotationNoVersion
        }));
        if (allSelectedAlready) {
          this.$message.error(this.$t('trainList.choiceAgain'));
        } else {
          this.userSelectionListNowSet.forEach(item => {
            if (!this.equipmentList.find(target => {
              return target.elevatorCode+target.quotationNoVersion === target.elevatorCode+item.quotationNoVersion
            })) {
              this.equipmentList.unshift(item);
            }
          });
        }
      } else {
        this.equipmentList = JSON.parse(JSON.stringify(myArray));
      }
      this.quotationOpen = false
    },
    getNickName(quoter) {
      let owner = this.ownerList.filter(item => item.userId == quoter)
      return owner && owner.length > 0 ? owner[0].nickName : quoter
    },
    formatDict(value, dictData) {
      return dictData.find(dict => dict.value == value)?.label;
    },
    //设备一览合计计算
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = this.$t('common.total');
          return;
        }
        if([7, 10,12, 13].includes(index)){
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
          }
          if([7, 12, 13].includes(index)){
            sums[index] = this.toDecimal2(this.numFormat(Number(delcommafy(sums[index])))) || 0.00
          }
        }
      });
      return sums;
    },
    valueAmount(value){
      this.$nextTick(() => {
        this.$set(this.form,'amount',value)
      })
    },
    valueUnit(value){
      this.$nextTick(() => {
        this.$set(this.equipmentForm,'unitPrice',value)
      })
      console.log("this.equipmentForm.unitPrice",this.equipmentForm.unitPrice)
    },
    valueChanged(value, rowAmount,column) {
      this.$nextTick(() => {
        this.$set(rowAmount,column,value)
        this.$set(rowAmount,'additionalCost',this.sumPrice1(rowAmount))
        // this.$set(rowAmount,'liftAmount',this.sumPrice(rowAmount))
      })
    },
    additionalCostSubmitForm(){
      //将值重新赋回设备
      this.equipmentList = [...this.additionalCostList]
      this.$modal.msgSuccess(this.$t("common.operateSuccess"));
      this.additionalCostOpen = false
    },
    additionalCostFormCancel(){
      this.additionalCostOpen = false
    },
    sumPrice1(row){
      if(isNaN(row.unitPrice)){
        row.unitPrice = 0.00
      }
      if(isNaN(row.planInlandFreightCost)){
        row.planInlandFreightCost = 0.00
      }
      if(isNaN(row.planOceanFreight)){
        row.planOceanFreight = 0.00
      }
      if(isNaN(row.reviewShippingCosts)){
        row.reviewShippingCosts = 0.00
      }
      if(isNaN(row.reviewCommission)){
        row.reviewCommission = 0.00
      }
      if(isNaN(row.otherFees)){
        row.otherFees = 0.00
      }
      let amount = (Number(delcommafy(row.planInlandFreightCost)) +
        Number(delcommafy(row.planOceanFreight)) +
        Number(delcommafy(row.reviewShippingCosts)) +
        Number(delcommafy(row.reviewCommission))+
        Number(delcommafy(row.otherFees))).toFixed(2) || 0.00
      row.additionalCost = amount
      row.liftAmount = (Number(delcommafy(amount))+Number(delcommafy(row.unitPrice))).toFixed(2)
      return amount
    },
    handleHistory(row){
      this.$tab.openPage("查看合同", '/contract-edit/index/' + row.id, {type: 'history'});
    },
  }
}
</script>

<style lang="scss" rel="stylesheet/scss" scoped>


::v-deep .edit-dialog {
  .el-dialog__body {
    min-height: 50vh;
    max-height: 75vh;
    overflow: auto;
    padding: 30px 50px;
  }

  .el-dialog__footer {
    padding: 10px 50px 20px 50px;
  }

  .el-form-item--medium .el-form-item__content, .el-form-item--medium .el-form-item__label {
    line-height: 25px;
  }

  .el-form--label-top .el-form-item__label {
    padding: 0;
  }

  .el-form .el-row:last-child .el-form-item {
    margin-bottom: 0;
  }
  .vue-treeselect .vue-treeselect__control {
    padding: 0 10px;
  }
}

::v-deep .contract-form .el-form-item--medium .el-form-item__label {
  line-height: 12px;
}

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

::v-deep .el-link.el-link--default {
  padding-left: 15px;
}

//::v-deep .treeselect {
//    .vue-treeselect__single-value {
//        color: #C0C4CC;
//    }
//
//    .vue-treeselect__control {
//        border-color: #E4E7ED;
//        background-color: #F5F7FA;
//    }
//}

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

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

  .input-width {
    width: 48vw;
  }

  .mt16 {
    margin-top: 16px;
  }

  .mb16 {
    margin-bottom: 16px;
  }

  .ml20 {
    margin-left: 1vw;
  }

  .top {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .button-group {
    display: flex;
  }

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

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

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

  .account-select {
    margin: 16px 0;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .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;

    & > div {
      align-self: stretch;
    }

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

    .card-height {
      max-height: 1292px;
    }

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

    .card-full {
      width: 97.6vw;
    }

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

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


::v-deep .apply-shake .el-input__inner {
  //border-color: #F56C6C !important;
  border-color: var(--current-color) !important;
}

::v-deep .money-input-class input{
  text-align: left !important;
}

::v-deep .el-icon-addition {
  background-size: cover;
  margin-right: 5px;
}


::v-deep  .my-select .el-select-dropdown__item {
  width: 320px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

::v-deep .my-select .el-select-dropdown__item:hover {
  overflow: visible; /* 鼠标悬停时显示全部内容 */
  white-space: nowrap; /* 设置换行 */
  max-height: none; /* 去掉最大高度限制 */
  background: white; /* 可选，用于突出显示悬停 */
  z-index: 1; /* 确保悬停时的元素在上层 */
}


</style>
