<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="100px">

      <el-form-item :label="$t('客户经理')" prop="followUpSalesmanList">
        <user-selector v-model="queryParams.followUpSalesmanList" multiple clearable @change="handleQuery" />
      </el-form-item>

      <el-form-item :label="$t('客户')" prop="searchCustomer">
        <el-input v-model.trim="queryParams.searchCustomer" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item :label="$t('联系方式')" prop="relationPhone">
        <el-input v-model.trim="queryParams.relationPhone" clearable @keyup.enter.native="handleQuery" @input="queryParams.relationPhone = queryParams.relationPhone.replace(/\s+/g, '')" />
      </el-form-item>

      <el-form-item :label="$t('销售阶段')" prop="saleStageList">
        <dict-selector :type="DICT_TYPE.CUSTOMER_FOLLOWUP_SALE_STAGE" multiple v-model="queryParams.saleStageList" clearable @change="handleQuery" />
      </el-form-item>

      <el-form-item :label="$t('编号')" prop="searchNumber" v-show="showSearch">
        <el-input v-model.trim="queryParams.searchNumber" :placeholder="$t('请输入报价单号、订单号')" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item :label="$t('客户状态')" prop="customerStatusList" v-show="showSearch">
        <dict-selector :type="DICT_TYPE.ECW_OFFER_CUSTOMER_STATUS" multiple v-model="queryParams.customerStatusList" clearable @change="handleQuery" />
      </el-form-item>

      <el-form-item :label="$t('询盘来源')" prop="inquirySourceList" v-show="showSearch">
        <dict-selector :type="DICT_TYPE.ECW_OFFER_INQUIRY_SOURCE" multiple v-model="queryParams.inquirySourceList" clearable @change="handleQuery" />
      </el-form-item>


      <el-form-item :label="$t('货物状态')" prop="cargoStatusList" v-show="showSearch">
        <dict-selector :type="DICT_TYPE.ECW_OFFER_CARGO_STATUS" multiple v-model="queryParams.cargoStatusList" clearable @change="handleQuery" />
      </el-form-item>

      <el-form-item :label="$t('运输方式')" prop="transportList" v-show="showSearch">
        <dict-selector :type="DICT_TYPE.ECW_TRANSPORT_TYPE" v-model="queryParams.transportList" multiple formatter="number" clearable @change="handleQuery" />
      </el-form-item>

      <el-form-item :label="$t('始发仓')" prop="startWarehouseIds" v-show="showSearch">
        <el-select v-model="queryParams.startWarehouseIds" multiple :placeholder="$t('请选择始发仓')" clearable @change="handleQuery">
          <el-option v-for="item in exportWarehouseList" :label="$l(item, 'title')" :value="item.id" :key="item.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item :label="$t('目的国')" prop="destCountryId" v-show="showSearch">
        <el-select v-model="destCountryId" multiple :label="destCountryId" :placeholder="$t('请选择目的国')" clearable @change="handleQuery">
          <el-option v-for="item in AddressProvince" :key="item.guojia" :label="item.guojiaName" :value="item.guojia"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('目的城市')" prop="objectiveId" v-show="showSearch">
        <el-select v-model="objectiveId" multiple :placeholder="$t('请选择目的城市')"  clearable @change="handleQuery">
          <el-option v-for="item in AddressCity" :key="item.shi" :label="item.shiName" :value="item.shi"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('目的仓')" prop="destWarehouseId" v-show="showSearch">
        <el-select v-model="destWarehouseId" multiple :placeholder="$t('请选择目的仓')" clearable @change="handleQuery">
          <el-option v-for="item in AddressTown" :key="item.id" :label="item.titleZh" :value="item.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item :label="$t('客户来源')" prop="sourceIds" v-show="showSearch">
        <dict-selector :type="DICT_TYPE.CUSTOMER_SOURCE" multiple v-model="queryParams.sourceIds" clearable @change="handleQuery" />
      </el-form-item>

      <el-form-item :label="$t('输单原因')" prop="reasonDictList" v-show="showSearch">
        <dict-selector :type="DICT_TYPE.ECW_OFFER_REASON_DICT" multiple v-model="queryParams.reasonDictList" clearable @change="handleQuery" />
      </el-form-item>

      <el-form-item :label="$t('区号')" prop="relationAreaCode" v-show="showSearch">
        <el-input v-model.trim="queryParams.relationAreaCode" :placeholder="$t('请输入客户')" clearable @keyup.enter.native="handleQuery" @input="queryParams.relationAreaCode = queryParams.relationAreaCode.replace(/\s+/g, '')" />
      </el-form-item>

      <el-form-item :label="$t('出货渠道')" prop="channelIds" v-show="showSearch">
        <selector :clearable="true" :options="channelList" :label-field="$l('name')" value-field="channelId" v-model="queryParams.channelIds" multiple @change="handleQuery"></selector>
      </el-form-item>
      <el-form-item :label="$t('商品')" prop="prodTitle" v-show="showSearch">
        <el-input v-model.trim="queryParams.prodTitle" :placeholder="$t('请输入商品类型、品名或品牌')" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item :label="$t('控货')" prop="control" v-show="showSearch">
        <dict-selector :type="DICT_TYPE.INFRA_BOOLEAN_STRING" v-model="queryParams.control" clearable @change="handleQuery" />
      </el-form-item>
      <el-form-item :label="$t('报关方式')" prop="customsType" v-show="showSearch">
        <dict-selector :type="DICT_TYPE.ECW_CUSTOMS_TYPE" v-model="queryParams.customsType" clearable @change="handleQuery" />
      </el-form-item>

      <el-form-item :label="$t('增值服务')" prop="serviceType" v-show="showSearch">
        <el-select v-model="queryParams.serviceType" :placeholder="$t('请选择')" clearable @change="handleQuery">
          <el-option :label="$t('普通订单')" :value="0"></el-option>
          <el-option :label="$t('集运服务')" :value="1"></el-option>
          <el-option :label="$t('海外仓')" :value="2"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item :label="$t('厂家')" prop="manufacturer" v-show="showSearch">
        <el-input v-model.trim="queryParams.manufacturer" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>

      <el-form-item :label="$t('厂家电话')" prop="manufacturerPhone" v-show="showSearch">
        <el-input v-model.trim="queryParams.manufacturerPhone" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>

      <el-form-item :label="$t('创建人')" prop="creatorIds" v-show="showSearch">
        <user-selector v-model="queryParams.creatorIds" multiple clearable @change="handleQuery" />
      </el-form-item>

      <el-form-item :label="$t('预计发货时间')" v-show="showSearch">
        <el-date-picker v-model="queryTmp.estimatedShippingTime" type="datetimerange" range-separator="-" :start-placeholder="$t('开始日期')" :end-placeholder="$t('结束日期')" value-format="yyyy-MM-dd HH:mm:ss" @change="handleQuery"> </el-date-picker>
      </el-form-item>
      <el-form-item :label="$t('有效期开始')" v-show="showSearch">
        <el-date-picker v-model="queryTmp.startTime" type="datetimerange" range-separator="-" :start-placeholder="$t('开始日期')" :end-placeholder="$t('结束日期')" value-format="yyyy-MM-dd HH:mm:ss" @change="handleQuery"> </el-date-picker>
      </el-form-item>
      <el-form-item :label="$t('有效期结束')" v-show="showSearch">
        <el-date-picker v-model="queryTmp.endTime" type="datetimerange" range-separator="-" :start-placeholder="$t('开始日期')" :end-placeholder="$t('结束日期')" value-format="yyyy-MM-dd HH:mm:ss" @change="handleQuery"> </el-date-picker>
      </el-form-item>

      <el-form-item :label="$t('创建时间')">
        <el-date-picker v-model="queryTmp.createTime" type="datetimerange" range-separator="-" :start-placeholder="$t('开始日期')" :end-placeholder="$t('结束日期')" value-format="yyyy-MM-dd HH:mm:ss" @change="handleQuery"> </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">{{ $t("搜索") }}</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">{{ $t("重置") }}</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['ecw:offer:create']">{{ $t("新增") }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading" v-hasPermi="['ecw:offer:export']">{{ $t("导出") }}</el-button>
      </el-col>
      <el-col :span="15" style="font-size: 19px" v-if="statistics">
        <!-- 订单列表显示搜索条件对应箱数、仓库实测、收款方数、重量 -->
        {{$t('汇总')}}：{{statistics.volume}}CBM/{{statistics.weight}}KG
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="list" border ref="dataTable" id="dataTable" :height="autoHeight">
      <el-table-column :label="$t('客户状态')" align="left" width="100" fixed>
        <template slot-scope="{ row }">
          <el-link type="primary" @click.native="$router.push('detail?offerId=' + row.offerId)">
            <dict-tag :type="DICT_TYPE.ECW_OFFER_CUSTOMER_STATUS" :value="row.customerStatus" />
          </el-link>
        </template>
      </el-table-column>
      <el-table-column :label="$t('客户编号')" align="left" width="100" fixed>
        <template slot-scope="{ row }">
          <router-link :to="`/customer/query/${row.customerId}`" class="link-type">
            {{ row.customerNumber }}
          </router-link>
        </template>
      </el-table-column>
      <el-table-column :label="$t('客户名称')" align="left" prop="customerName" fixed> </el-table-column>
      <el-table-column :label="$t('询盘来源')" align="left" width="100">
        <template slot-scope="{ row }">
          <dict-tag :type="DICT_TYPE.ECW_OFFER_INQUIRY_SOURCE" :value="row.inquirySource" />
        </template>
      </el-table-column>
      <el-table-column :label="$t('运输方式-渠道/目的仓')" width="200">
        <template slot-scope="{ row }">
          <dict-tag :type="DICT_TYPE.ECW_TRANSPORT_TYPE" :value="row.transportId" />
          <template v-if="row.channelName"> - {{ row.channelName }} </template>
          / {{ row.destWarehouseName }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('销售阶段')" align="left" width="100">
        <template slot-scope="{ row }">
          <dict-tag :type="DICT_TYPE.CUSTOMER_FOLLOWUP_SALE_STAGE" :value="row.saleStage" />
        </template>
      </el-table-column>
      <el-table-column :label="$t('总方数')" align="left" prop="volume" width="100" />
      <el-table-column :label="$t('总重量')" align="left" prop="weight" width="100" />
      <el-table-column :label="$t('上次跟进类型')" width="120">
        <template slot-scope="scope" v-if="scope.row.followupBackVO">
          <a href="javascript:void(0)" @click="handleCustomerFollowLink(scope.row.followupBackVO)" class="link-type">
            <dict-tag :type="DICT_TYPE.CUSTOMER_FOLLOWUP_TYPE" :value="scope.row.followupBackVO.followType" />
          </a>
        </template>
      </el-table-column>
      <el-table-column :label="$t('上次跟进时间')" width="180">
        <template slot-scope="scope" v-if="scope.row.followupBackVO">
          {{ parseTime(scope.row.followupBackVO.followTime) }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('上次跟进内容')" width="180">
        <template slot-scope="scope" v-if="scope.row.followupBackVO">
          {{ scope.row.followupBackVO.feedback }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('优惠信息')" width="180">
        <template slot-scope="scope">
          {{ scope.row.specialOffers }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('货物描述')" width="180">
        <template slot-scope="scope" v-if="scope.row.offerProds">
          <template v-for="row1 in scope.row.offerProds">
            <div>
              {{row1.prodTitleZh}}:<dict-tag :type="DICT_TYPE.ECW_IS_BRAND" :value="row1.brand"></dict-tag>-
              {{row1.volume}}CBM/{{row1.weight}}KG
            </div>
          </template>
        </template>
      </el-table-column>
      <el-table-column :label="$t('货物状态')" align="left" width="100">
        <template slot-scope="{ row }">
          <dict-tag :type="DICT_TYPE.ECW_OFFER_CARGO_STATUS" :value="row.cargoStatus" />
        </template>
      </el-table-column>
      <el-table-column :label="$t('预计发货时间')" align="left" prop="estimatedShippingTime" width="120" />
      <el-table-column :label="$t('厂家/电话')" align="left" width="100">
        <template slot-scope="{ row }">
          {{row.manufacturer}}/{{row.manufacturerPhone}}
        </template>
      </el-table-column>
      <el-table-column :label="$t('订单编号')" align="left" width="120">
        <template slot-scope="{ row }">
          <a class="el-link el-link--primary is-underline" href="javascript:;" @click="$router.push(`/order/detail?orderId=${row.orderId}`)">{{ row.orderNo }}</a>
        </template>
      </el-table-column>
      <el-table-column :label="$t('输单原因')" align="left" width="100">
        <template slot-scope="{ row }">
          <dict-tag :type="DICT_TYPE.ECW_OFFER_REASON_DICT" :value="row.reasonDict" />
        </template>
      </el-table-column>
      <el-table-column :label="$t('输单备注')" align="left" prop="reason" width="120" />
      <el-table-column :label="$t('客户经理')" align="left" prop="followUpSalesmanName"> </el-table-column>
      <el-table-column :label="$t('报价单号')" align="left" prop="number" width="150">
        <template slot-scope="{ row }">
          <el-link type="primary" @click.native="$router.push('detail?offerId=' + row.offerId)">{{ row.number }}</el-link>
        </template>
      </el-table-column>
      <el-table-column :label="$t('创建时间')" align="left" width="120">
        <template slot-scope="{ row }">
          <span>{{ parseTime(row.createTime, "{y}-{m}-{d} {h}:{i}:{s}") }}</span>
          <div style="display: flex; flex-wrap: wrap" v-if="row.specialPriceType">
            <el-button size="mini" style="margin-left: 20px" type="danger" circle>特</el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('掉入公海时间')" align="left" width="120">
        <template slot-scope="{ row }">
          {{ row.estimateEnterOpenSeaTime || row.enterOpenSeaTime }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('所报价格')" width="180">
        <template slot-scope="scope" v-if="scope.row.offerProds">
          <template v-for="row1 in scope.row.offerProds">
            {{row1.prodTitleZh}}:
            <template v-if="row1.charging == 1">
              <template v-if="!row1.oneSeaFreight">{{ $t("未报价") }}</template>
              <template>{{ $t("全包价") }} {{ row1.oneSeaFreight }} {{ currencyMap[row1.seaFreightCurrency] }} / {{ unitMap[row1.seaFreightVolume] }}</template>
            </template>
            <template v-else-if="!row1.oneSeaFreight && !row1.oneClearanceFreight">{{ $t("未报价") }}</template>
            <template v-else-if="row1.specialPriceType">
              <div style="color: red;font-weight: 700;">
                {{ $t("原价") }}
              </div>
              <div>
                {{ $t("运费") }}：{{ row1.originalSeaFreight }} {{ currencyMap[row1.seaFreightCurrency] }} / {{ unitMap[row1.seaFreightVolume] }}
              </div>
              <div>
                {{ $t("清关费") }}：{{ row1.originalClearanceFreight }} {{ currencyMap[row1.clearanceFreightCurrency] }} / {{ unitMap[row1.clearanceFreightVolume] }}
              </div>
              <div style="color: red;font-weight: 700;">
                {{ $t("特价") }}
              </div>
              <div>
                {{ $t("运费") }}：{{ row1.oneSeaFreight }} {{ currencyMap[row1.seaFreightCurrency] }} / {{ unitMap[row1.seaFreightVolume] }}
              </div>
              <div>
                {{ $t("清关费") }}：{{ row1.oneClearanceFreight }} {{ currencyMap[row1.clearanceFreightCurrency] }} / {{ unitMap[row1.clearanceFreightVolume] }}
              </div>
            </template>
            <template v-else>
              <div>{{ $t("运费") }}：{{ row1.oneSeaFreight }} {{ currencyMap[row1.seaFreightCurrency] }} / {{ unitMap[row1.seaFreightVolume] }}</div>
              <div v-if="row1.oneClearanceFreight">{{ $t("清关费") }}：{{ row1.oneClearanceFreight }} {{ currencyMap[row1.clearanceFreightCurrency] }} / {{ unitMap[row1.clearanceFreightVolume] }}</div>
              <div v-else>{{ $t("清关费未报价") }}</div>
            </template>
          </template>
        </template>
      </el-table-column>
      <el-table-column :label="$t('操作')" align="center" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <!--
          0 取消                                        恢复
          1 特价审批    编辑、跟进、          取消    删除
          2 草稿        编辑、                       删除
          3 需求确认    编辑、跟进、结果、特价、取消   删除
          4 赢单                                    删除
          5 输单                                    删除
          6 完成                                    删除
          7 跟进中      编辑、跟进、结果、特价、取消、 删除
          -->
          <el-dropdown>
            <el-button icon="el-icon-plus" circle type="primary"></el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="$router.push('detail?offerId=' + scope.row.offerId)" v-hasPermi="['ecw:offer:show']">{{ $t("详情") }}</el-dropdown-item>
              <el-dropdown-item @click.native="$router.push('edit?id=' + scope.row.offerId)" v-if="[1, 2, 3, 7].indexOf(scope.row.status) > -1" v-hasPermi="['ecw:offer:update']">{{ $t("编辑") }}</el-dropdown-item>
              <el-dropdown-item @click.native="$router.push('create?copyId=' + scope.row.offerId)" v-if="[1, 2, 3, 7].indexOf(scope.row.status) > -1" v-hasPermi="['ecw:offer:update']">{{ $t("复制") }}</el-dropdown-item>
              <el-dropdown-item @click.native="handleAddOffer(scope.row)" v-if="[1, 3, 7].indexOf(scope.row.status) > -1">{{ $t("跟进") }}</el-dropdown-item>
              <el-dropdown-item @click.native="$router.push(`result?offerId=${scope.row.offerId}&number=${scope.row.number}&saleStage=${scope.row.saleStage}`)" v-if="[3, 7].indexOf(scope.row.status) > -1" v-hasPermi="['ecw:offer:result']">{{ $t("结果") }}</el-dropdown-item>
              <el-dropdown-item @click.native="$router.push('/offer/special?offerId=' + scope.row.offerId)" v-if="[1, 3, 7].indexOf(scope.row.status) > -1" v-hasPermi="['ecw:offer:discount', 'ecw:offer:commission']">{{ $t("特价") }}</el-dropdown-item>
              <el-dropdown-item @click.native="cancel(scope.row.offerId)" v-if="[1, 3, 7].indexOf(scope.row.status) > -1" v-hasPermi="['ecw:offer:cancel']">{{ $t("取消") }}</el-dropdown-item>
              <el-dropdown-item @click.native="recovery(scope.row.offerId)" v-if="[0].indexOf(scope.row.status) > -1" v-hasPermi="['ecw:offer:recovery']">{{ $t("恢复") }}</el-dropdown-item>
              <el-dropdown-item @click.native="deleteOffer(scope.row.offerId)" v-if="[0, 1, 2, 3, 4, 5, 6, 7].indexOf(scope.row.status) > -1" v-hasPermi="['ecw:offer:delete']">{{ $t("删除") }}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize" @pagination="getList" />
    <CustomerFollow ref="customerFollow" @refresh="handleQuery" v-if="customerFollowVisible" @close="customerFollowVisible = false" :customer-id="curData.relationId" :customerService="curData.salesmanId" :customerNumber="curData.customerNumber" :offerId="curData.offerId" />
  </div>
</template>

<script>
import { deleteOffer, getOfferPage, statistics, exportOfferExcel, cancel, recovery, offerDeptPage, exportDeptOfferExcel } from "@/api/ecw/offer"
import { getChannelList } from "@/api/ecw/channel"
import { getRegionList } from "@/api/ecw/order"
import { getCurrencyList } from "@/api/ecw/currency"
import { getTradeCityList } from "@/api/ecw/region"
import { getWarehouseList } from "@/api/ecw/warehouse"
import UserSelector from "@/components/UserSelector"
import Selector from "@/components/Selector"
import Template from "@/views/cms/template/index.vue"
import CustomerFollow from "@/views/ecw/customer/components/customerFollow"
import { getUnitList } from "@/api/ecw/unit"
export default {
  name: "EcwOfferIndex",
  components: {
    Template,
    Selector,
    UserSelector,
    CustomerFollow
  },
  data() {
    return {
      customerFollowVisible: false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 报价单管理列表
      list: [],
      // 查询参数
      queryParams: {
        customerStatusList: [],
        salesmanIds: [],
        statusList: [],
        cargoStatusList: [],
        saleStageList: [],
        reasonDictList: [],
        inquirySourceList: [],
        importances: [],
        channelIds: [],
        sourceIds: [],
        transportList: [],
        followUpSalesmanList: [],
        pageNo: 1,
        pageSize: 10
      },
      queryTmp: {
        createTime: ["", ""],
        stopTime: ["", ""],
        estimatedShippingTime: ["", ""],
        startTime: ["", ""],
        endTime: ["", ""]
      },
      warehouseList: [],
      currencyList: [],
      tradeCityList: [],
      channelList: [],
      AddressCity: [],
      AddressProvince: [],
      AddressTown: [],
      destCountryId: null,
      objectiveId: null,
      destWarehouseId: null,
      // 选中数组
      ids: [],
      //目的国
      countryList: [],
      //目的城市
      cityList: [],
      //目的仓
      destWarehouseList: [],
      curData: {},
      dept: false, // 是否部门订单
      autoHeight: 500,
      unitList: [],
      statistics: {}
    }
  },
  computed: {
    unitMap() {
      let map = {}
      this.unitList.forEach((item) => {
        map[item.id] = this.$i18n.locale == "zh_CN" ? item.titleZh : item.titleEn
      })
      return map
    },
    isMobile() {
      const userAgent = navigator.userAgent || navigator.vendor || window.opera;
      // 匹配常见的移动设备标识
      const mobileIdentifiers = ['Android', 'webOS', 'iPhone', 'iPad', 'iPod', 'BlackBerry', 'Windows Phone'];
      return mobileIdentifiers.some(identifier => userAgent.includes(identifier));
    },
    currencyMap() {
      let map = {}
      this.currencyList.forEach((item) => {
        map[item.id] = this.$l(item, "title")
      })
      return map
    },
    exportWarehouseList() {
      /* tradeType 1 进口，2出口，3进出口 */
      return this.warehouseList.filter((item) => item.tradeType == 2 || item.tradeType == 3)
    },
    exportCityList() {
      return this.tradeCityList.filter((item) => item.type == 2)
    },
    importCityList() {
      return this.tradeCityList.filter((item) => item.type == 1)
    },
    transportTypes() {
      let obj = {}
      this.getDictDatas(this.DICT_TYPE.ECW_TRANSPORT_TYPE).forEach((item) => {
        obj[item.value] = item
      })
      return obj
    }
  },
  activated() {
    this.getList()
  },
  created() {
    console.log(this.getDictDatas(this.DICT_TYPE.ECW_OFFER_STATUS))

    console.log("offer index", this.$route)
    // 部门订单
    if (this.$route.fullPath.indexOf("dept") > -1) {
      this.dept = true
    }
    getUnitList().then((res) => (this.unitList = res.data))
    // getTradeCityList().then((res) => (this.tradeCityList = res.data))
    getWarehouseList().then((res) => {
      this.tradeCityList = res.data
      this.warehouseList = res.data
    })
    getCurrencyList().then((res) => {
      this.currencyList = res.data
    })

    this.getList()
    getChannelList().then((res) => (this.channelList = res.data))
    this.init()
  },
  watch: {
    showSearch() {
      this.$nextTick(() => {
        this.getHeight()
      })
    },
    destCountryId: {
      //监听当前地区值的变化，于与上方地区值进行了双向绑定
      deep: true, //深度监听
      handler() {
        //每当值省份值改变时其下地区值进行清空
        this.AddressCity = []
        this.AddressTown = []
        this.objectiveId = ""
        this.destWarehouseId = ""
        this.findByprovinceCode()
        if (this.destCountryId == "") {
          getRegionList(4, 4)
            .then(({ data }) => {
              this.AddressCity = data
            })
            .catch((error) => {
              console.log(error)
            })

          getRegionList(5, 5)
            .then(({ data }) => {
              this.AddressTown = data
            })
            .catch((error) => {
              console.log(error)
            })
        } else if (this.destCountryId != "" && this.objectiveId == "" && this.destWarehouseId == "") {
          getRegionList(2, this.destCountryId)
            .then(({ data }) => {
              this.AddressCity = data
            })
            .catch((error) => {
              console.log(error)
            })
          getRegionList(5, 5)
            .then(({ data }) => {
              this.AddressTown = data
            })
            .catch((error) => {
              console.log(error)
            })
        }
        //重新加载目的城市
        //目的城市

        //  getRegionList(4, 4).then(({data}) => {
        //     this.AddressCity = data;
        // })
        //  .catch(error => {
        //     console.log(error);
        //   });

        //   getRegionList(5, 5).then(({data}) => {
        //   this.AddressTown = data;
        // })
        //   .catch(error => {
        //     console.log(error);
        //   });
      }
    },
    objectiveId: {
      deep: true, //深度监听
      handler() {
        this.AddressTown = []
        this.destWarehouseId = ""
        this.findBycityCode()

        if (this.objectiveId != "" && this.destCountryId != "" && this.destWarehouseId == "") {
          //获取当前城市值id，获取该城市下区域
          getRegionList(3, this.objectiveId)
            .then(({ data }) => {
              this.AddressTown = data
            })
            .catch((error) => {
              console.log(error)
            })
        } else if (this.destCountryId == "" && this.objectiveId == "" && this.destWarehouseId == "") {
          getRegionList(5, 5)
            .then(({ data }) => {
              this.AddressTown = data
            })
            .catch((error) => {
              console.log(error)
            })
        } else if (this.destCountryId != "" && this.objectiveId == "" && this.destWarehouseId == "") {
          getRegionList(2, this.destCountryId)
            .then(({ data }) => {
              this.AddressCity = data
            })
            .catch((error) => {
              console.log(error)
            })
          getRegionList(5, 5)
            .then(({ data }) => {
              this.AddressTown = data
            })
            .catch((error) => {
              console.log(error)
            })
        }
      }
    },
    destWarehouseId: {
      deep: true, //深度监听
      handler() {
        if (this.objectiveId != "" && this.destCountryId != "" && this.destWarehouseId == "") {
          //获取当前城市值id，获取该城市下区域
          getRegionList(3, this.objectiveId)
            .then(({ data }) => {
              this.AddressTown = data
            })
            .catch((error) => {
              console.log(error)
            })
        } else if (this.destCountryId != "" && this.objectiveId == "" && this.destWarehouseId == "") {
          getRegionList(5, 5)
            .then(({ data }) => {
              this.AddressTown = data
            })
            .catch((error) => {
              console.log(error)
            })
        }
      }
    }
  },
  methods: {
    handleAddOffer(row) {
      console.log(row)
      this.curData = row
      this.customerFollowVisible = true
      this.$nextTick(() => {
        this.$refs["customerFollow"].handleAdd()
      })
    },
    init() {
      //加载时发起请求获取所有省份值
      getRegionList(1, 1)
        .then(({ data }) => {
          this.AddressProvince = data
          console.log(this.AddressProvince)
        })
        .catch((error) => {
          console.log(error)
        })
      //目的城市
      getRegionList(4, 4)
        .then(({ data }) => {
          this.AddressCity = data
        })
        .catch((error) => {
          console.log(error)
        })
      //目的仓
      getRegionList(5, 5)
        .then(({ data }) => {
          this.AddressTown = data
        })
        .catch((error) => {
          console.log(error)
        })
    },
    findByprovinceCode() {
      //获取当前省份值id，获取该省份下城市 destCountryId provinceCode

      getRegionList(2, this.destCountryId)
        .then(({ data }) => {
          this.AddressCity = data
        })
        .catch((error) => {
          console.log(error)
        })
    },
    findBycityCode() {
      //获取当前城市值id，获取该城市下区域
      getRegionList(3, this.objectiveId)
        .then(({ data }) => {
          this.AddressTown = data

          // 去重
          // let uniqueDataList = data.filter((item, index, self) => {
          // // 返回第一个匹配项的索引，用于判断当前项是否为第一个匹配项
          // const firstIndex = self.findIndex((obj) => obj.guojia === item.guojia);

          // // 如果当前项是第一个匹配项，则保留，否则过滤掉
          // return index === firstIndex;
          // });

          // this.AddressProvince = uniqueDataList
        })
        .catch((error) => {
          console.log(error)
        })
    },
    formatQuery() {
      let obj = {}
      //目的国
      if (this.startWarehouseId != null && this.startWarehouseId != "") {
        obj.startWarehouseIds = this.startWarehouseId
      }
      //目的国
      if (this.destCountryId != null && this.destCountryId != "") {
        obj.destCountryIds = this.destCountryId
      }
      //目的城市
      if (this.objectiveId != null && this.objectiveId != "") {
        obj.objectiveIds = this.objectiveId
      }
      //目的仓
      if (this.destWarehouseId != null && this.destWarehouseId != "") {
        obj.destWarehouseIds = this.destWarehouseId
      }
      obj.beginCreateTime = this.queryTmp.createTime[0]
      obj.endCreateTime = this.queryTmp.createTime[1]
      obj.beginStopTime = this.queryTmp.stopTime[0]
      obj.endStopTime = this.queryTmp.stopTime[1]
      obj.beginEstimatedShippingTime = this.queryTmp.estimatedShippingTime[0]
      obj.endEstimatedShippingTime = this.queryTmp.estimatedShippingTime[1]
      obj.beginStartTime = this.queryTmp.startTime[0]
      obj.endStartTime = this.queryTmp.startTime[1]
      obj.beginEndTime = this.queryTmp.endTime[0]
      obj.endEndTime = this.queryTmp.endTime[1]
      return obj
    },
    /** 查询列表 */
    getList() {
      this.statistics = {}
      this.loading = true
      let func = this.dept ? offerDeptPage : getOfferPage
      if(!this.dept) {
        statistics({
          ...this.queryParams,
          ...this.formatQuery()
        }).then((response) => {
          this.statistics = response.data
        })
      }
      // 执行查询
      func({
        ...this.queryParams,
        ...this.formatQuery()
      }).then((response) => {
        this.$nextTick(() => {
          this.list = response.data.list
          this.total = response.data.total
          this.loading = false
          this.getHeight()
        })
      })
    },
    handleCustomerFollowLink(row) {
      this.customerFollowVisible = true
      row.creatorName = row.creatorName * 1
      row.updaterName = row.updaterName * 1
      this.$nextTick((_) => {
        this.$refs["customerFollow"].handleView(row)
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1
      this.$nextTick(this.getList)
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNo: 1,
        pageSize: 10
      }
      this.queryTmp={
        createTime: ["", ""],
          stopTime: ["", ""],
          estimatedShippingTime: ["", ""],
          startTime: ["", ""],
          endTime: ["", ""]
      }
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      return this.$router.push("create")
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      return this.$router.push("edit?id=" + row.offerId)
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const offerId = row.offerId
      this.$modal
        .confirm(this.$t("是否确认删除报价单管理编号为{offerId}的数据项?", { offerId }))
        .then(function () {
          return deleteOffer(offerId)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess(this.$t("删除成功"))
        })
        .catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = { ...this.queryParams, ...this.formatQuery() }
      params.pageNo = undefined
      params.pageSize = undefined
      // 执行导出
      this.$confirm(this.$t("是否确认导出所有报价单管理数据项?"))
        .then(() => {
          this.exportLoading = true
          if (this.dept) {
            return exportDeptOfferExcel(params)
          } else return exportOfferExcel(params)
        })
        .then((response) => {
          this.$download.excel(response, "报价列表.xls")
          this.exportLoading = false
        })
        .catch(() => {})
    },
    cancel(id) {
      this.doAction(this.$t("确定要取消此报价单么？"), cancel, id)
    },
    recovery(id) {
      this.doAction(this.$t("确定要恢复此报价单么？"), recovery, id)
    },
    deleteOffer(id) {
      this.doAction(this.$t("确定要删除此报价单么？"), deleteOffer, id)
    },
    doAction(tips, action, id) {
      this.$confirm(tips)
        .then((res) => {
          return action(id)
        })
        .then(() => {
          this.$message.success("操作成功")
          this.handleQuery()
        })
    },
    //表格高度自适应
    getHeight() {
      if(!this.isMobile) {
        this.$refs.dataTable.doLayout()
        let getHeightFromBottom = (element, variableHeight) => {
          const elementRect = element.getBoundingClientRect().top;
          const windowHeight = document.documentElement.clientHeight;
          const elementHeightFromBottom = windowHeight - elementRect;
          const result = elementHeightFromBottom - variableHeight;
          return result;
        }
        const element = document.getElementById('dataTable');
        const variableHeight = 70; // 给定的变量高度 一般留于分页器高度
        this.autoHeight =getHeightFromBottom(element, variableHeight);
      }
    },
  }
}
</script>
