<template>
  <div class="app-container">
    <!-- 搜索 -->
    <el-card>
      <el-form
        :model="queryParams"
        ref="queryForm"
        size="small"
        inline
        class="card"
      >
          <el-form-item :label="$t('自编号')" prop="selfNo">
            <el-input v-model="queryParams.selfNo" clearable></el-input>
          </el-form-item>
          <el-form-item :label="$t('始发仓')" :rules="{required: true, message: $t('请选择始发仓')}" prop="startWarehouseIdList">
            <el-select v-model="queryParams.startWarehouseIdList" multiple :placeholder="$t('请选择')" clearable>
              <el-option
                v-for="item in exportWarehouseList"
                :key="item.id"
                :label="$l(item, 'title')"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('目的国')" :rules="{required: true, message: $t('请选择目的国')}" prop="destCountryId">
            <el-select v-model="queryParams.destCountryId" :placeholder="$t('请选择')" filterable default-first-option>
              <el-option
                v-for="item in countryList"
                :key="item.id"
                :label="$l(item, 'title')"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('目的仓')" prop="destWarehouseIdList">
            <el-select v-model="queryParams.destWarehouseIdList" multiple :placeholder="queryParams.destCountryId ? $t('请选择') : $t('请先选择目的国')" clearable>
              <el-option
                v-for="item in importWarehouseList"
                :key="item.id"
                :label="$l(item, 'title')"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('自编号状态')" prop="boxStatus">
            <dict-selector :type="DICT_TYPE.BOX_ORDER_SHIPMENT_STATE" v-model="queryParams.boxStatus" clearable></dict-selector>
          </el-form-item>
          <el-form-item :label="$t('结算时间')"  prop="dateFilter">
            <el-date-picker v-model="dateFilter" 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('是否结算')" prop="slStatus">
            <dict-selector :type="DICT_TYPE.SETTLEMENT_STATUS" v-model="queryParams.slStatus" clearable></dict-selector>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="handleQuery"
              :loading="loading"
            >{{$t('查询')}}</el-button>
            <el-button type="primary" :loading="exporting" icon="el-icon-download" @click="handleExport">{{$t('导出搜索')}}</el-button>
          </el-form-item>
      </el-form>
    </el-card>
    <el-table
      v-loading="loading"
      :data="list"
      border
      class="card"
      :element-loading-text="$t('汇总计算中...')"
      show-summary
      :summary-method="getSummary"
    >
      <el-table-column :label="$t('是否结算')" align="center">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.SETTLEMENT_STATUS" :value="scope.row.slStatus"></dict-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('No.柜号')" align="center" prop="selfNo">
        <template slot-scope="scope">
          <el-button v-if="permissions.indexOf('selfno:report:detail') > -1" type="text" @click="$router.push('./self_no_report_detail?containerNumber=' + scope.row.selfNo)">{{scope.row.selfNo}}</el-button>
          <span v-else>{{scope.row.selfNo}}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('应收款(Accounts receivable)USD')" prop="summaryInfo.netReceiptsCollectFreightFeeGroup">
        <template slot-scope="{row}">
          {{row.summaryInfo.receivableTotalFee}}{{row.summaryInfo.receivableTotalFeeCurrency}}
        </template>
      </el-table-column>
      <el-table-column :label="$t('应收款 RECEIVABLE')" align="center" prop="summaryInfo.receivableTotalFeeGroup">
        <el-table-column :label="$t('运费 FREIGHT') + ColumnCurrencyName('Freight')" prop="summaryInfo.netReceiptsCollectFreightFeeGroup">
          <template slot-scope="{row}">
            {{row.summaryInfo.totalReceivableFreightFee}}{{row.summaryInfo.totalFreightFeeCurrency}}
          </template>
        </el-table-column>
        <el-table-column :label="$t('清关费 CLEARING FEE') + ColumnCurrencyName('Clearance')">
          <template slot-scope="{row}">
            {{row.summaryInfo.totalReceivableClearanceFee}}{{row.summaryInfo.totalClearanceFeeCurrency}}
          </template>
        </el-table-column>
        <el-table-column :label="$t('额外费用 EXTRAL FEE') + ColumnCurrencyName('Other')">
          <template slot-scope="{row}">
            {{row.summaryInfo.totalReceivableOtherFee}}{{row.summaryInfo.totalOtherFeeCurrency}}
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column :label="'received in ' + (dstCountryName || $t('目的国')) + `(${$t('目的地实收')})`" align="center" prop="">
        <el-table-column :label="$t('运费') + ColumnCurrencyName('Freight')" prop="summaryInfo.netReceiptsCollectFreightFeeGroup">
          <template slot-scope="{row}">
            {{row.summaryInfo.totalNetReceiptsCollectFreightFee}}{{row.summaryInfo.totalFreightFeeCurrency}}
          </template>
        </el-table-column>
        <el-table-column :label="$t('清关费') + ColumnCurrencyName('Clearance')" prop="summaryInfo.netReceiptsCollectClearanceFeeGroup">
          <template slot-scope="{row}">
            {{row.summaryInfo.totalNetReceiptsCollectClearanceFee}}{{row.summaryInfo.totalClearanceFeeCurrency}}
          </template>
        </el-table-column>
        <el-table-column :label="$t('额外费用') + ColumnCurrencyName('Other')" prop="summaryInfo.netReceiptsCollectOtherFeeGroup">
          <template slot-scope="{row}">
            {{row.summaryInfo.totalNetReceiptsCollectOtherFee}}{{row.summaryInfo.totalOtherFeeCurrency}}
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column :label="$t('received in China(中国实收)')" align="center" prop="" >
        <el-table-column :label="$t('运费') + ColumnCurrencyName('Freight')" prop="summaryInfo.netReceiptsAdvanceFreightFeeGroup">
          <template slot-scope="{row}">
            {{row.summaryInfo.netReceiptsAdvanceFreightFee}}{{row.summaryInfo.totalFreightFeeCurrency}}
          </template>
        </el-table-column>
        <el-table-column :label="$t('清关费') + ColumnCurrencyName('Clearance')" prop="summaryInfo.netReceiptsAdvanceClearanceFeeGroup">
          <template slot-scope="{row}">
            {{row.summaryInfo.totalNetReceiptsAdvanceClearanceFee}}{{row.summaryInfo.totalClearanceFeeCurrency}}
          </template>
        </el-table-column>
        <el-table-column :label="$t('额外费用') + ColumnCurrencyName('Other')" prop="summaryInfo.netReceiptsAdvanceOtherFeeGroup">
          <template slot-scope="{row}">
            {{row.summaryInfo.totalNetReceiptsAdvanceOtherFee}}{{row.summaryInfo.totalOtherFeeCurrency}}
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column :label="$t('Discounts 折扣')" align="center" prop="">
        <el-table-column :label="$t('运费') + ColumnCurrencyName('Freight')" prop="summaryInfo.discountFreightFeeGroup">
          <template slot-scope="{row}">
            {{row.summaryInfo.discountFreightFee}}{{row.summaryInfo.totalFreightFeeCurrency}}
          </template>
        </el-table-column>
        <el-table-column :label="$t('清关费') + ColumnCurrencyName('Clearance')" prop="summaryInfo.discountClearanceFeeGroup">
          <template slot-scope="{row}">
            {{row.summaryInfo.discountClearanceFee}}{{row.summaryInfo.totalClearanceFeeCurrency}}
          </template>
        </el-table-column>
        <el-table-column :label="$t('额外费用') + ColumnCurrencyName('Other')" prop="summaryInfo.discountOtherFeeGroup">
          <template slot-scope="{row}">
            {{row.summaryInfo.discountOtherFee}}{{row.summaryInfo.totalOtherFeeCurrency}}
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column :label="$t('操作')" v-if="permissions.indexOf('selfno:report:detail') > -1">
        <template slot-scope="scope">
          <el-button type="text" @click="$router.push('./self_no_report_detail?containerNumber=' + scope.row.selfNo)">{{$t('查看')}}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.rows"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { getCurrencyPage } from "@/api/ecw/currency";
import {getWarehouseList} from '@/api/ecw/warehouse'
import store from "@/store";
import {boxSettlementPage, exportSettlementExcel} from "@/api/ecw/box";
import {getListTree} from "@/api/ecw/region";
import Decimal from 'decimal.js'
export default {
  name: 'EcwFinancialSelfnoreport',
  data() {
    return {
      loading: false, // 是否加载中
      dateFilter:[], // 筛选时间
      list: [],
      total: 0,
      queryParams: {
        page: 1,
        rows: 10,
        startWarehouseIdList:[],
        destWarehouseIdList: []
      },
      // tradeCityList: [],
      currencyList:[],
      warehouseList:[],
      countryList: [],
      // 导出中状态
      exporting: false
    };
  },
  activated(){
    // 如果有必须的条件则查询
    if(this.queryParams.startWarehouseIdList.length && this.queryParams.dstCountryId){
      this.getList();
    }
  },
  created() {
    getCurrencyPage(this.params).then(res => this.currencyList = res.data.list)
    // getTradeCityList().then((res) => (this.tradeCityList = res.data));
    // 默认不查询,必须选择目的国以后才可以查询 this.getList();
    getWarehouseList().then(res => this.warehouseList = res.data)
    getListTree({treeType: 1}).then(r => {
      this.countryList = r.data
    })
  },
  watch:{
    // 目的国变更后要重置目的仓
    'queryParams.destCountryId': function(){
      this.$set(this.queryParams, 'destWarehouseId', '')
    }
  },
  computed: {
    permissions(){
      return store.getters.permissions
    },
    /*exportCityList() {
      return this.tradeCityList.filter((item) => item.type === 2);
    },
    importCityList() {
      return this.tradeCityList.filter((item) => item.type === 1);
    },*/
    exportWarehouseList(){
      /* tradeType 1 进口,2出口,3进出口 */
      return this.warehouseList.filter(item => +item.tradeType === 2 || +item.tradeType === 3)
    },
    importWarehouseList(){
      // 目的仓根据选择的目的国过滤
      if(!this.queryParams.destCountryId) return []
      return this.warehouseList.filter(item => {
        return this.queryParams.destCountryId === item.guojia && ( +item.tradeType === 1 || +item.tradeType === 3)
      })
    },
    // 目的国名称
    dstCountryName(){
      if(!this.queryParams.destCountryId) return null
      const country = this.countryList.find(item => item.id == this.queryParams.destCountryId)
      if(!country) return null
      return this.$l(country, 'title')
    },
    // 获取列的货币名称 columnName 取值为Other, Freight, Clearance
    ColumnCurrencyName(){
      return (columnName, wrapper = true) => {
        if(!this.list.length) return ''
        let field = `total${columnName}FeeCurrency`
        return wrapper ? `(${this.list[0]['summaryInfo'][field]})` : this.list[0]['summaryInfo'][field]
      }
    }
  },
  methods: {
    getCurrencyLabel(id){
      const item = this.currencyList.find(item => item.id === id);
      if(!item)return ''
      return this.$l(item, 'title')
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      let params = {
        ...this.queryParams,
        startWarehouseIdList: this.queryParams.startWarehouseIdList.join(','),
        destWarehouseIdList: this.queryParams.destWarehouseIdList.join(',')
      }
      this.addBeginAndEndTime(params, this.dateFilter, "JsDate", false);
      // 执行查询
      boxSettlementPage(params).then((response) => {
        this.list = response.data.list;
        this.total = response.data.total;
      }).finally(() => {
        this.loading = false;
      })
    },
    getTotal(field){
      let total = new Decimal(0)
      this.list.forEach(item => {
        total = total.plus(item.summaryInfo[field] || 0)
      })
      return total.toNumber()
    },
    // 返回汇总行数据
    getSummary(){
      const FreightCurrencyName = this.ColumnCurrencyName('Freight', false)
      const ClearanceCurrencyName = this.ColumnCurrencyName('Clearance', false)
      const OtherCurrencyName = this.ColumnCurrencyName('Other', false)
      const data = [
        this.$t('合计'),
        '',
        // 应收款
        this.getTotal('receivableTotalFee') + 'USD',
        // 应收运费
        this.getTotal('totalReceivableFreightFee') + FreightCurrencyName,
        // 应收清关费
        this.getTotal('totalReceivableClearanceFee') + ClearanceCurrencyName,
        // 应收其他费用
        this.getTotal('totalReceivableOtherFee') + OtherCurrencyName,
        // 目的地实收运费
        this.getTotal('totalNetReceiptsCollectFreightFee') + FreightCurrencyName,
        // 目的地实收清关费
        this.getTotal('totalNetReceiptsCollectClearanceFee') + ClearanceCurrencyName,
        // 目的地实收其他费用
        this.getTotal('totalNetReceiptsCollectOtherFee') + OtherCurrencyName,
        // 中国实收运费
        this.getTotal('netReceiptsAdvanceFreightFee') + FreightCurrencyName,
        // 中国实收清关费
        this.getTotal('netReceiptsAdvanceClearanceFee') + ClearanceCurrencyName,
        // 中国实收其他费用
        this.getTotal('netReceiptsAdvanceOtherFee') + OtherCurrencyName,
        // 运费折扣
        this.getTotal('discountFreightFee') + FreightCurrencyName,
        // 清关费折扣
        this.getTotal('discountClearanceFee') + ClearanceCurrencyName,
        // 其他费用折扣
        this.getTotal('discountOtherFee') + OtherCurrencyName,
      ]
      console.log('sum', {data})
      return data
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.$refs.queryForm.validate().then(() => {
        this.queryParams.page = 1;
        this.getList();
      })

    },
    handleReset(){
      this.$refs['queryForm'].resetFields()
      this.dateFilter = []
      this.handleQuery()
    },
    // 导出搜索
    handleExport(){
      this.$refs.queryForm.validate().then(() => {
        this.exporting = true
        let params = {...this.queryParams}
        this.addBeginAndEndTime(params, this.dateFilter, "JsDate", false);
        exportSettlementExcel(params).then(res => {
          this.$download.excel(res, 'shipment-summary.xls');
        }).finally(() => {
          this.exporting = false
        })
      })
    }
  },
};
</script>

<style scoped>
.card {
  margin-top: 20px;
}
.dialog-footer {
  padding: 40px;
}
.card-title {
  font-size: 18px;
  font-weight: bold;
  display: inline-block;
}
</style>