<template>
  <div class="app-container">
    <card-table :loading="loading" :modalData="quotationList" :searchParams="queryParams" :tableSearch="true" labelWidth="120px" @columnSearch="handleQuery"
                @pagination="getList" :row-key="rowKey" :children="children" @resetList="resetQuery" max-height="600px" @sortChange="sortChange"
                @selection-change="handleSelectionChange">
      <template #operations="{ selections }">
        <el-button v-hasPermi="['bt:business:quotation:add']" icon="el-icon-plus" size="mini" type="primary" @click="handleAdd">{{ $t('quotation.addQuotation') }}
        </el-button>
        <el-button v-hasPermi="['bt:business:quotation:export']" icon="el-icon-download" plain size="mini"
                   @click="handleExportQuotationList">{{ $t('quotation.exportExcel') }}
        </el-button>
        <el-button v-hasPermi="['bt:business:quotation:export']" icon="el-icon-download" plain size="mini"
                   @click="() => handleExport(false)">{{ $t('quotation.exportQuotation') }}
        </el-button>
        <el-button v-hasPermi="['bt:business:quotation:export']" icon="el-icon-view" plain size="mini"
                   @click="() => handleExport(true)">{{ $t('quotation.previewQuotation') }}
        </el-button>
        <el-button v-hasPermi="['bt:business:quotation:copy']" icon="el-icon-plus" plain size="mini" :disabled="!ids || ids.length === 0"
                   @click="copyVersion">{{ $t('quotation.copyVersion') }}
        </el-button>
        <el-button v-hasPermi="['bt:business:quotation:add']" icon="el-icon-document-copy" size="mini"  plain
                   :disabled="!ids || ids.length !== 1" @click="copyData">{{ $t('quotation.copyData') }}
        </el-button>
      </template>
      <template #default="{ list }">
        <el-table-column align="center" type="selection" width="55" :selectable="checkSelectable"/>


        <!--报价编号-->
<!--        <Column :label="$t('quotation.quotationNo')" :showSearch="true" prop="quotationVersion" :min-width="200"-->
<!--                fixed width="200px" sortable="custom">-->
<!--          <template #default="{ row }">-->
<!--            <span @click="handleView(row,0)" class="link-type">{{ row.quotationVersion }}</span>-->
<!--          </template>-->
<!--        </Column>-->

        <!--报价编号-->
        <Column :label="$t('quotation.quotationNo')" :showSearch="true" prop="quotationNo" :min-width="200"
                fixed width="200px" sortable="custom">
          <template #default="{ row }">
            <span @click="handleView(row,0)" class="link-type">{{ row.quotationNo }}</span>
          </template>
        </Column>
        <!--版本号-->
        <Column :label="$t('common.version')" prop="version" width="80px"/>
        <!--报价状态-->
        <Column :label="$t('quotation.quotationStatus')" prop="quotationStatus" :min-width="250" :searchDict="dict.type.quotation_status" :showSearch="true" :selectMore="true" searchType="select" width="170px">
          <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(','), agentFlag)"/>
          </template>
        </Column>
        <!--项目名称-->
        <Column :label="$t('project.projectName')" :showSearch="true" prop="projectName"/>
<!--        &lt;!&ndash;项目类型&ndash;&gt;-->
<!--        <Column :label="$t('project.type')" prop="type" :showSearch="true" searchType="select" :searchDict="dict.type.project_type" width="200px" :selectMore="true"/>-->
<!--        &lt;!&ndash;项目细分市场&ndash;&gt;-->
<!--        <Column :label="$t('project.projectSegments')" prop="segmentedMarket" :showSearch="true" searchType="select" :searchDict="dict.type.project_market" width="200px" :selectMore="true"/>-->
        <!--国家-->
        <Column :label="$t('project.countryId')" prop="countryId" :showSearch="true" width="150px" searchType="select" :searchDict="countryList" :selectMore="true"/>
        <!--城市-->
        <Column :label="$t('project.city')" prop="city" :showSearch="true" width="150px" :selectMore="true"/>
        <!--梯形-->
        <Column :label="$t('quotation.suitModel')" prop="elevatorModel" :showSearch="true"/>
        <!--币种-->
        <Column :label="$t('project.currency')" prop="currencyId" :showSearch="true" searchType="select" :searchDict="dict.type.currency_type" width="150px" :selectMore="true"/>
        <!--最终价格-->
        <Column :label="$t('quotation.price')" prop="finalPrice" align="right" width="120px" v-if="checkPermi(['business:quotation:totalPrice'])">
          <template #default="{ row }">
            {{ Number(row.quotationStatus) >= 6 ? numFormat(row.finalCurrencyPrice ? row.finalCurrencyPrice : row.price) : '-' }}
          </template>
        </Column>
        <!--附加费用-->
        <Column :label="$t('quotation.additionalCost')" prop="additionalFees" align="right" width="120px"  v-if="checkPermi(['business:quotation:totalPrice'])">
          <template #default="{ row }">
            {{ Number(row.quotationStatus) >= 6 ? numFormat(row.additionalFees) : '-' }}
          </template>
        </Column>
        <Column :label="$t('quotation.totalPriceLabel')" prop="additionalFees" align="right" width="120px" v-if="checkPermi(['business:quotation:totalPrice'])">
          <template #default="{ row }">
            {{ Number(row.quotationStatus) >= 6 ? numFormat(row.finalCurrencyPrice ? row.finalCurrencyPrice + row.additionalFees : row.price + row.additionalFees): '-' }}
          </template>
        </Column>
        <!--报价者-->
        <Column :label="$t('quotation.quoter')" prop="nickName" :showSearch="true"/>
        <!--提交时间-->
        <Column :label="$t('quotation.submitTime')" prop="submitTime" align="center" :min-width="300" :showSearch="true" searchType="dateRange"/>
        <!--操作-->
        <Column :label="$t('common.operate')" :min-width="250" :showSearch="true" fixed="right" searchType="operate" :showoverflowtooltip="false">
          <template #default="{ row }">
            <!--            查看详情-->
            <!--            <el-button v-hasPermi="['business:quotation:detail']" icon="el-icon-view" size="mini" type="text" v-if="quotationIn(row,['8'])"-->
            <!--                       @click="handleDetail(row)">{{ $t('common.view') }}详情-->
            <!--            </el-button>-->
            <!--            查看-->
            <!--            <el-button v-hasPermi="['bt:business:quotation:view']" icon="el-icon-view" size="mini" type="text"-->
            <!--                       @click="handleView(row,0)">{{ $t('common.view') }}-->
            <!--            </el-button>-->
            <!--            编辑-->
            <el-button v-hasPermi="['bt:business:quotation:edit']" icon="el-icon-edit" size="mini" type="text" v-if="quotationIn(row,['0']) && isInPerson(row)"
                       @click="handleUpdate(row)">{{ $t('common.edit') }}
            </el-button>
            <!--            接受价格-->
            <el-button v-hasPermi="['bt:business:eq:acceptPrice']" size="mini" type="text" v-if="quotationIn(row,['6']) && isInPerson(row)"
                       @click="handleBargain(row,3)">
              <i class="el-icon-bargain-confirm"/>{{ $t('quotation.acceptPrice') }}
            </el-button>
            <!--            技术评审-->
            <el-button v-hasPermi="['bt:business:quotation:techReview']" size="mini" v-if="quotationIn(row,['1']) && isAuditor(row.flow)"
                       type="text" @click="handleView(row,1)">
              <i class="el-icon-tech"/>{{ $t('quotation.techReview') }}
            </el-button>
            <!--            采购询价-->
            <el-button v-hasPermi="['bt:business:quotation:buyerInquiry']" size="mini" v-if="quotationIn(row,['3']) && isAuditor(row.flow)"
                       type="text" @click="handleView(row,2)">
              <i class="el-icon-buyer"/>{{ $t('quotation.buyerInquiry') }}
            </el-button>
            <!--            财务询价-->
            <el-button v-hasPermi="['bt:business:quotation:treasureInquiry']" size="mini" v-if="quotationIn(row,['4']) && isAuditor(row.flow)"
                       type="text" @click="handleView(row,3)">
              <i class="el-icon-treasurer"/>{{ $t('quotation.treasureInquiry') }}
            </el-button>
            <!--            销售确认-->
            <el-button v-hasPermi="['bt:business:quotation:salesConfirm']" size="mini" v-if="quotationIn(row,['5']) && isAuditor(row.flow)"
                       type="text" @click="handleView(row,4)">
              <i class="el-icon-saler"/>{{ $t('quotation.salesConfirm') }}
            </el-button>
            <!--            议价-->
            <el-button v-hasPermi="['bt:business:quotation:negotiatedPrice']" size="mini" type="text" v-if="quotationIn(row, ['6','10']) && isInPerson(row)"
                       @click="handleBargain(row,0)">
              <i class="el-icon-bargain"/>{{ $t('quotation.negotiatedPrice') }}
            </el-button>
            <!--            议价审批-->
            <el-button v-hasPermi="['bt:business:quotation:bargainApproval']" size="mini" type="text" v-if="quotationIn(row,['7']) && isAuditor(row.flow)"
                       @click="handleBargain(row,1)">
              <i class="el-icon-approval"/>{{ $t('quotation.bargainApproval') }}
            </el-button>
            <!--            议价确认-->
            <el-button v-hasPermi="['bt:business:quotation:bargainConfirm']" size="mini" type="text" v-if="quotationIn(row,['8']) && isInPerson(row)"
                       @click="handleBargain(row,2)">
              <i class="el-icon-bargain-confirm"/>{{ $t('quotation.bargainConfirm') }}
            </el-button>
            <!--            附加费用-->
            <el-button v-hasPermi="['bt:business:quotation:additionalCost']" size="mini" type="text" v-if="row.quotationStatus != '11' && Number(row.quotationStatus) >= 6"
                       @click="showAdditionalCost(row)">
              <i class="el-icon-addition"/>{{ $t('quotation.additionalCost') }}
            </el-button>
          </template>
        </Column>
      </template>
    </card-table>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="$t('quotation.additionalCost')" :visible.sync="open" :close-on-click-modal="false" width="60%">
      <!--      <div class="card-title mb16">{{ $t('lead.baseInfo') }}</div>-->
      <!--      <div>-->
      <el-form :model="form" label-width="100px">
        <el-row>
          <el-col :span="12">
            <!--项目编号 -->
            <el-form-item :label="$t('project.projectNo')" prop="projectNo">
              <el-input :disabled="true" v-model="form.projectNo" maxlength="100" :placeholder="$t('common.pleaseInput') + $t('project.projectNo')"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!--项目名称 -->
            <el-form-item :label="$t('project.name')" prop="name">
              <el-input :disabled="true" v-model="form.projectName" maxlength="100" :placeholder="$t('common.pleaseInput') + $t('project.projectNo')"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <!--币种 -->
            <el-form-item :label="$t('project.currency')" prop="currency">
              <el-select :disabled="true" v-model="form.currencyId" class="w-100" :placeholder="$t('common.pleaseSelect') + $t('project.currency')">
                <el-option v-for="dict in dict.type.currency_type" :key="dict.value"
                           :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!--报价编号 -->
            <el-form-item :label="$t('quotation.quotationNo')" prop="quotationNo">
              <el-input :disabled="true" v-model="form.quotationNo" maxlength="100" :placeholder="$t('common.pleaseInput') + $t('quotation.quotationNo')"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <!--版本 -->
            <el-form-item :label="$t('common.version')" prop="accountName">
              <el-input :disabled="true" v-model="form.version" maxlength="100" :placeholder="$t('common.pleaseInput') + $t('common.version')"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
          </el-col>
        </el-row>
      </el-form>
      <!--      </div>-->
      <!--      <div class="card-title mb16">{{ $t('quotation.additionalCost') }}</div>-->
      <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="elevatorModel" :label="$t('elevatorModel.elevatorModel')" width="120" align="center"></el-table-column>
          <!--          电梯编号-->
          <el-table-column prop="elevatorCode" :label="$t('quotation.elevatorCode')" width="250" align="center"></el-table-column>
          <!--          规格-->
          <el-table-column prop="specification" :label="$t('quotation.specification')" width="200" align="center"></el-table-column>
          <!--          数量-->
          <el-table-column prop="elevatorNumber" :label="$t('quotation.elevatorNumber')" width="120" align="center"></el-table-column>
          <!--          单价-->
          <el-table-column prop="price" :label="$t('quotation.price')" width="120" align="right">
            <template #default="{ row }">
              {{ toDecimal2(numFormat(row.price || 0)) }}
            </template>
          </el-table-column>
          <!--          内陆运费-->
          <Column :label="$t('quotation.landShipFees')" prop="landShipFees">
            <template slot-scope="scope">
              <MoneyInput :inputValue="scope.row.landShipFees" :zeroLength="2"
                          @change="item=>valueChanged(item,scope.row,'landShipFees')" :style="{color:scope.row.landShipFees > 99999999.99 ?'red':'green'}"></MoneyInput>
            </template>
          </Column>
          <!--          海运费-->
          <Column :label="$t('quotation.seaShipFees')" prop="seaShipFees">
            <template slot-scope="scope">
              <MoneyInput :inputValue="scope.row.seaShipFees" :zeroLength="2"
                          @change="item=>valueChanged(item,scope.row,'seaShipFees')" :style="{color:scope.row.seaShipFees > 99999999.99 ?'red':'green'}"></MoneyInput>
            </template>
          </Column>
          <!--          佣金-->
          <Column :label="$t('quotation.commissionFees')" prop="commissionFees">
            <template slot-scope="scope">
              <MoneyInput :inputValue="scope.row.commissionFees" :zeroLength="2"
                          @change="item=>valueChanged(item,scope.row,'commissionFees')" :style="{color:scope.row.commissionFees > 99999999.99 ?'red':'green'}"></MoneyInput>
            </template>
          </Column>
          <!--          其他费用-->
          <Column :label="$t('quotation.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('quotation.totalPriceLabel')" prop="" align="right">
            <template slot-scope="{row}">
              <span >
                {{ toDecimal2(numFormat(sumPrice(row))) }}
              </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="submitForm" icon="el-icon-circle-check" :disabled="!this.additionalCostList || this.additionalCostList.length == 0"
                   v-if="additionalCostList.length > 0">{{ $t('common.confirm') }}
        </el-button>
        <el-button @click="cancel" icon="el-icon-remove-outline">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>


    <el-dialog :title="$t('quotation.exportQuotation')" :visible.sync="quotationExportOpen"  width="400px" append-to-body>
      <el-form ref="form" :model="quotationExportForm">
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('quotation.tradeType')" label-width="120px">
              <el-select v-model="quotationExportForm.tradeType" :placeholder="$t('common.pleaseSelect') + $t('quotation.tradeType')" @change="handleImageChange" style="width: 200px;">
                <el-option v-for="dict in dict.type.contract_trade_terms" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('quotation.targetPort')" label-width="120px">
<!--              <el-input v-model="quotationExportForm.targetPort" :maxlength="100" style="width: 200px;" @change="handleImageChange"/>-->
              <el-select v-model="quotationExportForm.targetPort" :placeholder="$t('common.pleaseSelect') + $t('quotation.targetPort')" @change="handleImageChange" style="width: 200px;">
                <el-option v-for="dict in dict.type.target_port" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('quotation.previewImage')" label-width="120px">
              <ImageUpload v-model="quotationExportForm.path" :isShowTip="false" :limit="1" @input="handleImageChange"/>
            </el-form-item>
          </el-col>
        </el-row>

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

<script>
import Column from "@/components/element/table/Column.vue";
import ColorDictTag from "@/views/crmManagement/lead/ColorDictTag/index.vue";
import {getAllNationList} from "@/api/user/country";
import {copyVersion, listQuotation, uploadQuotationImage, getQuotationImage} from "@/api/business/quotation/quotation";
import {batchAdd, batchAddNew, listByQuotationId, listByQuotationIdNew} from "@/api/business/quotation/fees";
import {parseTime} from "@/utils/ruoyi";
import {mapGetters} from "vuex";
import {listAllCurrency} from "@/api/user/currency";
import MoneyInput from '../../components/element/form/items/moneyInput'
import {delcommafy,comdify} from "@/utils/money";
import ImageUpload from "@/components/ImageUpload/index";
import { checkPermi } from '@/utils/permission'

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

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

export default {
  name: "Quotation",
  inject: ["main"],
  components: {Column, ColorDictTag,MoneyInput, ImageUpload},
  dicts: [
    "quotation_status",
    "project_type",
    "project_market",
    "currency_type",
    "fees_type",
    "contract_trade_terms",
    "target_port"
  ],
  data() {
    return {
      // 用户信息
      userInfo: this.$store.state.user.userInfo,
      // 控制附加费用是否可以编辑  true 不可编辑
      additionalCostDisabledFlag: false,
      rowKey: "id",
      children: "children",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      quotationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      countryList: [],
      form: {},
      quotationExportOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        quotationNo: null,
        projectName: null,
        elevatorModel: null,
        type: [],
        segmentedMarket: [],
        countryId: [],
        city: null,
        currencyId: [],
        elevatorMode: null,
        nickName: null,
        createTime: [],
        quotationStatus: [],
        beginTime: null,
        endTime: null,
        submitTime: []
      },
      statusColorMap: statusColorMap,
      additionalCostList: [],
      deleteDisabled: true,
      multipleSelection: [],
      language: null,
      // 汇率
      exchangeRate: 0,
      // 币种列表
      currencyList: [],
      tableLoading: false,
      quotationExportForm: {
        targetPort: '',
        tradeType: '',
        path: null,
      },
      agentFlag: false,
      previewFlag: false,
    };
  },
  async created() {
    this.language = this.$i18n.locale;
    await this.initCurrencyList();
    this.getNationList();
    const {businessNo} = this.$route.query;
    if (businessNo) {
      this.queryParams.quotationNo = businessNo
    }
    this.getList();
    let userInfo = this.$store.state.user.userInfo;
    this.agentFlag = userInfo.deptId !== 0
  },
  computed: {
    ...mapGetters(["userId"]),
    localLabelSuffix() {
      return labelSuffix[this.$i18n.locale] || "";
    },
  },
  activated() {
    const {businessNo} = this.$route.query;
    if (businessNo) {
      this.queryParams.quotationNo = businessNo
    }
    this.getList();
  },
  methods: {
    checkPermi,
    sumPrice(row){
      // 总价（数量 * 价格 + 内陆运费 + 海运费 + 佣金 + 其他费用）
      let amount = (Number(delcommafy(row.price)) * Number(row.elevatorNumber) +
                    Number(delcommafy(row.landShipFees)) +
                    Number(delcommafy(row.seaShipFees)) +
                    Number(delcommafy(row.commissionFees)) +
                    Number(delcommafy(row.otherFees))).toFixed(2) || 0.00
      return amount
    },
    valueChanged(value, rowAmount,columnName) {
      this.$nextTick(() => {
        this.$set(rowAmount,columnName,value)
      })
    },
    // 是否本人
    isInPerson(row) {
      return row.createBy == this.userInfo.userId
    },
    // 币种初始化
    async initCurrencyList() {
      let response = await listAllCurrency()
      if (response) {
        let list = response.rows
        this.currencyList = []
        for (let i = 0; i < list.length; i++) {
          let item = list[i]
          this.currencyList.push({
            label: item.currencyName,
            value: item.currencyId,
          })
        }
      }
    },
    // 控制表格行是否可以点击
    checkSelectable(row, index) {
      // return row.selectable
      return true
    },
    additionalCostSelection(selection) {
      this.multipleSelection = selection;
      this.deleteDisabled = this.multipleSelection.length === 0;
    },
    addLine() {
      this.additionalCostList.push({feesType: '0', exchange_rate: this.exchangeRate, convertedAmount: '-'})
      for (let i = 0; i < this.additionalCostList.length; i++) {
        this.additionalCostList[i].index = i;
      }
    },
    deleteLine() {
      this.multipleSelection.forEach((account) => {
        this.additionalCostList = this.additionalCostList.filter((item) => {
          return item.index !== account.index;
        });
      });
      for (let i = 0; i < this.additionalCostList.length; i++) {
        this.additionalCostList[i].index = i;
      }
    },
    async showAdditionalCost(row) {
      // 查询汇率
      this.exchangeRate = row.exchangeRate
      this.additionalCostList = [];
      this.open = true;
      // this.currencyList = []
      // this.currencyList.push({
      //   'currencyId': row.currencyId,
      //   'currencyName': row.currencyName
      // })
      // console.log("币种", this.currencyList)
      console.log('币种', this.currencyList)
      this.form = {
        quotationId: row.id,
        projectNo: row.projectNo,
        projectName: row.projectName,
        currencyId: row.currencyId + '',
        quotationNo: row.quotationNo,
        version: row.version,
      };
      this.tableLoading = true;

      let than = this;
      console.log("附加费用", this.form);
      listByQuotationIdNew(this.form.quotationId)
        .then((response) => {
          this.additionalCostList = response.rows;
          this.additionalCostList.some(item=>{
            item.landShipFees = comdify(delcommafy(item.landShipFees), 2);
            item.seaShipFees = comdify(delcommafy(item.seaShipFees), 2);
            item.commissionFees = comdify(delcommafy(item.commissionFees), 2);
            item.otherFees = comdify(delcommafy(item.otherFees), 2);
          })
        }).finally(() => {
        this.tableLoading = false;
      });
    },
    cancel() {
      this.open = false;
    },
    // 附加费用提交
    /*async submitForm() {
      for (let i = 0; i < this.additionalCostList.length; i++) {
        if (!this.additionalCostList[i].additionalFees && this.additionalCostList[i].additionalFees !== 0) {
          this.$modal.msgError(this.$t("quotation.additionalCostEmpty"));
          return
        }
      }
      let additionalFeesList = [];
      if (this.additionalCostList.length > 0) {
        this.additionalCostList.forEach((item) => {
          additionalFeesList.push({
            quotationId: this.form.quotationId,
            feesType: item.feesType,
            currencyId: this.form.currencyId,
            exchangeRate: this.exchangeRate,
            additionalFees: item.additionalFees,
            remark: item.remark,
          });
        });
      }

      let param = {
        quotationId: this.form.quotationId,
        additionalFeesList: additionalFeesList,
      };
      console.log("提交参数", param);
      let response = await batchAdd(param)
      this.$modal.msgSuccess(this.$t("common.operateSuccess"));
      this.open = false;
      this.getList()
    },*/
    async submitForm() {
      // for (let i = 0; i < this.additionalCostList.length; i++) {
      //   if (!this.additionalCostList[i].additionalFees && this.additionalCostList[i].additionalFees !== 0) {
      //     this.$modal.msgError(this.$t("quotation.additionalCostEmpty"));
      //     return
      //   }
      // }
      // 处理千分位
      this.additionalCostList.some(item => {
        item.landShipFees = delcommafy(item.landShipFees);
        item.seaShipFees = delcommafy(item.seaShipFees);
        item.commissionFees = delcommafy(item.commissionFees);
        item.otherFees = delcommafy(item.otherFees);
      })
      let response = await batchAddNew(this.additionalCostList)
      this.$modal.msgSuccess(this.$t("common.operateSuccess"));
      this.open = false;
      this.getList()
    },
    copyVersion() {
      console.log("选中行", this.ids);
      if (this.ids && this.ids.length > 0) {
        this.$modal.loading();
        copyVersion({ids: this.ids})
          .then((response) => {
            this.getList();
            this.$modal.msgSuccess(this.$t("common.operateSuccess"));
          })
          .finally(() => {
            this.$modal.closeLoading();
          });
      }
    },
    // value 转 label
    convertStatus(status) {
      if (!status) return "-";
      const check = this.dict.type.quotation_status.filter(
        (item) => item.value == status
      );
      if (check && check.length > 0) {
        return check[0].label;
      } else {
        return "-";
      }
    },
    /** 获取所有国家列表 */
    getNationList() {
      getAllNationList().then((response) => {
        this.countryList = 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,
          };
        });
      });
    },
    /** 查询报价列表 */
    getList() {
      console.log("查詢參數", this.queryParams);
      this.loading = true;
      listQuotation(this.queryParams)
        .then((response) => {
          this.quotationList = response.rows;
          this.queryParams.total = response.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.quotationNo = null;
      this.queryParams.elevatorModel = null;
      this.queryParams.projectName = null;
      this.queryParams.type = [];
      this.queryParams.segmentedMarket = [];
      this.queryParams.countryId = [];
      this.queryParams.city = null;
      this.queryParams.currencyId = [];
      this.queryParams.elevatorMode = null;
      this.queryParams.nickName = null;
      this.queryParams.submitTime = [];
      this.queryParams.beginTime = null;
      this.queryParams.endTime = null;
      this.queryParams.quotationStatus = [];
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;

      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    async handleAdd() {
      await this.$tab.closePage({name: 'EditQuotation', path: '/quotation/editQuotation'})
      await this.$tab.openPage(this.$t("quotation.add"), "/quotation/editQuotation", {
        type: "add",
      });
    },
    //复制报价单
    async copyData(){
      await this.$tab.closePage({name: 'EditQuotation', path: '/quotation/editQuotation'})
      await this.$tab.openPage(this.$t("quotation.add"), "/quotation/editQuotation", {
        type: "add",
        typeParam:"copy",
        quotationId:this.ids[0]
      });
    },
    async handleBargain(row, caseId) {
      await this.$tab.closePage({name: 'EditQuotation', path: '/quotation/editQuotation'})
      console.log("报价id", row);
      switch (caseId) {
        case 0:
          // 议价
          await this.$tab.openPage(
            this.$t("quotation.view"),
            "/quotation/editQuotation",
            {type: "bargain", quotationId: row.id}
          );
          break;
        case 1:
          // 议价审批
          await this.$tab.openPage(
            this.$t("quotation.view"),
            "/quotation/editQuotation",
            {
              type: "bargainApproval",
              quotationId: row.id,
              flowStatus: row.flow?.status,
            }
          );
          break;
        case 2:
          // 议价确认
          await this.$tab.openPage(
            this.$t("quotation.view"),
            "/quotation/editQuotation",
            {type: "bargainConfirm", quotationId: row.id}
          );
          break;
        case 3:
          // 接受价格
          await this.$tab.openPage(
            this.$t("quotation.acceptPrice"),
            "/quotation/editQuotation",
            {type: "bargainAccept", quotationId: row.id}
          );
          break;
      }
    },
    async handleView(row, caseId) {
      await this.$tab.closePage({name: 'EditQuotation', path: '/quotation/editQuotation'})
      console.log("报价id", row);
      switch (caseId) {
        case 0:
          // 查看
          await this.$tab.openPage(
            this.$t("quotation.view"),
            "/quotation/editQuotation",
            {type: "view", quotationId: row.id, flowStatus: row.flow?.status,}
          );
          break;
        case 1:
          // 技术评审
          await this.$tab.openPage(
            this.$t("quotation.techReview"),
            "/quotation/editQuotation",
            {
              type: "techReview",
              quotationId: row.id,
              flowStatus: row.flow?.status,
            }
          );
          break;
        case 2:
          // 采购询价
          await this.$tab.openPage(
            this.$t("quotation.buyerInquiry"),
            "/quotation/editQuotation",
            {type: "buyerInquiry", quotationId: row.id, flowStatus: row.flow?.status,}
          );
          break;
        case 3:
          // 财务询价
          await this.$tab.openPage(
            this.$t("quotation.treasureInquiry"),
            "/quotation/editQuotation",
            {type: "treasureInquiry", quotationId: row.id, flowStatus: row.flow?.status,}
          );
          break;
        case 4:
          // 销售确认
          await this.$tab.openPage(
            this.$t("quotation.salesConfirm"),
            "/quotation/editQuotation",
            {type: "salesConfirm", quotationId: row.id, flowStatus: row.flow?.status,}
          );
          break;
      }
    },
    async handleDetail(row) {
      await this.$tab.closePage({name: 'EditQuotation', path: '/quotation/editQuotation'})
      console.log("报价id", row);
      await this.$tab.openPage(
        this.$t("quotation.view"),
        "/quotation/quotationDetail",
        {type: "view", quotationId: row.id}
      );
    },
    async handleUpdate(row) {
      await this.$tab.closePage({name: 'EditQuotation', path: '/quotation/editQuotation'})
      await this.$tab.openPage(
        this.$t("quotation.edit"),
        "/quotation/editQuotation",
        {type: "edit", quotationId: row.id}
      );
    },
    handleOperateHistory(row) {
      this.$tab.openPage(
        this.$t("quotation.operateHistory"),
        "/quotation/operateHistory",
        {}
      );
    },
    /** 导出按钮操作 */
    handleExport(preview) {
      if (!this.ids || this.ids.length === 0) {
        this.$message.error("请选择一条数据")
        return
      }
      if (this.ids.length > 1) {
        this.$message.error("只能选择一条数据")
        return
      }
      this.getQuotationImageInfo()
      this.quotationExportOpen = true
      this.previewFlag = preview
    },
    handleExportQuotation(){
      if (this.previewFlag) {
        this.$tab.refreshPage({name: 'Preview', path: "/quotation/preview", query: {id: this.ids[0]}})
        this.quotationExportOpen = false
        return
      }
      let fileName = this.$t('quotation.quotation') + parseTime(new Date(), '{y}{m}{d}') + '.pdf'
      this.download("/business/quotation/export/" + this.ids[0], {}, fileName, {skipDownload: true}).then(res => {
        this.quotationExportOpen = false
      })
    },
    handleExportQuotationList(){
      let {pageNum, pageSize, ...params} = this.queryParams;
      let fileName = this.$t('quotation.quotation') + parseTime(new Date(), '{y}{m}{d}') + '.xlsx'
      this.download("business/quotation/exportList" ,params , fileName).then(res => {
        this.quotationExportOpen = false
      })
    },
    cancelExportQuotation(){
      this.quotationExportOpen = false
    },
    handleImageChange(){
      const data = {
        businessId: this.ids[0],
        filePath: this.quotationExportForm.path,
        tradeType: this.quotationExportForm.tradeType,
        targetPort: this.quotationExportForm.targetPort
      }
      uploadQuotationImage(data).then(response => {
        this.getQuotationImageInfo()
      })
    },
    getQuotationImageInfo(){
      getQuotationImage(this.ids[0]).then(res => {
        if (res.data && res.data.length>0) {
          this.quotationExportForm.path = res.data[0].filePath
           this.quotationExportForm.tradeType = res.data[0].tradeType
           this.quotationExportForm.targetPort = res.data[0].targetPort
        } else {
           this.quotationExportForm.path = ''
           this.quotationExportForm.tradeType = ''
           this.quotationExportForm.targetPort = ''
        }
      })
    },
    quotationIn(row, quotationList) {
      return quotationList.indexOf(row.quotationStatus) !== -1
    },
    quotationNotIn(row, quotationList) {
      return quotationList.indexOf(row.quotationStatus) === -1
    },
    sortChange({column, prop, order}) {
      if (order === 'ascending') {
        this.queryParams.orderByColumn = prop;
        this.queryParams.isAsc = 'asc';
      } else if (order === 'descending') {
        this.queryParams.orderByColumn = prop;
        this.queryParams.isAsc = 'desc';
      } else {
        this.queryParams.orderByColumn = null;
        this.queryParams.isAsc = null;
      }
      this.getList();
    },
  },
};
</script>

<!--style-->
<style scoped>
::v-deep .el-dialog__body {
  padding-bottom: 0px;
}

.w-100 {
  width: 100%;
}

.mb16 {
  margin-bottom: 16px;
}

.ml20 {
  margin-left: 20px;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

.el-icon-approval:before {
  content: "替";
  color: #FFFFFF;
  opacity: 0.0;
  font-size: 12px;
}
</style>
