<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="108px">
      <el-form-item :label="$t('自编号')" prop="selfNo">
        <el-input v-model="queryParams.selfNo" :placeholder="$t('请输入自编号')" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item :label="$t('出货渠道')" prop="shippingChannelIdList">
        <el-select v-model="queryParams.shippingChannelIdList" multiple :placeholder="$t('请选择出货渠道')" clearable>
          <el-option v-for="item in channelList" :label="$l(item, 'name')" :value="item.channelId" :key="item.channelId"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item :label="$t('始发仓')" prop="startWarehouseIdList">
        <el-select v-model="queryParams.startWarehouseIdList" multiple :placeholder="$t('请选择始发仓')" clearable>
          <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="countryIdList">
        <el-select v-model="countryIdList" multiple :label="countryIdList" :placeholder="$t('请选择目的国')" clearable>
          <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="destCityIdList">
        <el-select v-model="destCityIdList" multiple :placeholder="$t('请选择目的城市')" style="width: 200px" clearable>
          <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="destWarehouseIdList">
        <el-select v-model="destWarehouseIdList" multiple :placeholder="$t('请选择目的仓')" style="width: 200px" clearable>
          <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="shipmentStatusAirList">
        <el-select v-model="queryParams.shipmentStatusAirList" :placeholder="$t('请选择状态')" clearable size="small" multiple>
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.BOX_AIR_SHIPMENT_STATE)" :key="dict.value" :label="$l(dict, 'label')" :value="dict.value" />
        </el-select>
      </el-form-item>
      <!-- <el-row> -->
        <el-form-item :label="$t('时间')" prop="date">
          <el-select v-model="queryParams.dateType" :placeholder="$t('请选择时间类型')" clearable size="small">
            <el-option v-for="item in dateTypes" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="">
          <el-date-picker v-model="queryParams.dateRangeCreateTime" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange" range-separator="-" :start-placeholder="$t('开始日期')" :end-placeholder="$t('结束日期')" />
        </el-form-item>
        <el-form-item :label="$t('提单制作')" prop="ladingBillStatus">
          <el-select v-model="queryParams.ladingBillStatus" :placeholder="$t('请选择提单制作状态')" clearable size="small">
            <el-option v-for="(item,index) in ladingBillStatusData" :key="index" :label="item" :value="index">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('起运港')" v-show="showSearch">
          <dockSelect v-model="queryParams.bigPortIdList" :placeholder="$t('请选择起运港')" portType="2" :allDocks="allDocks" clearable multiple />
        </el-form-item>
        <el-form-item :label="$t('目的港')" v-show="showSearch">
          <dockSelect v-model="queryParams.destPortIdList" :placeholder="$t('请选择目的港')" portType="2" :allDocks="allDocks" clearable multiple />
        </el-form-item>
        <el-form-item :label="$t('目的港清关')" prop="destinationClearance" v-show="showSearch">
          <el-select v-model="queryParams.destinationClearance" :placeholder="$t('请选择目的港清关')" clearable size="small">
            <el-option v-for="item in destinationClearanceData" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('发货方式')" prop="deliveryType" v-show="showSearch">
          <el-select v-model="queryParams.deliveryType" :placeholder="$t('请选择发货方式')" clearable size="small" multiple>
            <el-option v-for="item in deliveryTypeData" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item :label="$t('航程')" prop="voyage" v-show="showSearch">
          <el-select v-model="queryParams.voyage">
            <el-option
              v-for="item in voyageData"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('订舱代理')" v-show="showSearch">
          <supplierSelect v-model="queryParams.shipperId" :companyType="'5'" :placeholder="$t('请选择订舱代理')" :allSupplier="allSupplier" clearable multiple />
        </el-form-item>
        <el-form-item :label="$t('航空公司')" v-show="showSearch">
          <supplierSelect v-model="queryParams.airlineCompanyIdList"  :placeholder="$t('请选择航空公司')" company-type="10" :allSupplier="allSupplier" clearable multiple />
        </el-form-item>
        <el-form-item :label="$t('代理公司Agent')" v-show="showSearch">
          <supplierSelect v-model="queryParams.agentIdList"  :placeholder="$t('请选择代理公司')" company-type="1" :allSupplier="allSupplier" clearable multiple />
        </el-form-item>
        <el-form-item :label="$t('报关方式')" prop="dcCustomsType" v-show="showSearch">
          <el-select v-model="queryParams.dcCustomsType" :placeholder="$t('请选择报关方式')" clearable  multiple>
            <el-option v-for="type in this.getDictDatas(DICT_TYPE.BOX_SHIPPING_CUSTOMS_TYPE)" :key="type.value" :label="$l(type, 'label')" :value="type.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('报关公司')" v-show="showSearch">
          <supplierSelect v-model="queryParams.dcCompanyId" :companyType="'2'" :placeholder="$t('请选择报关公司')" :allSupplier="allSupplier" clearable  multiple />
        </el-form-item>
        <el-row>
          <el-form-item :label="$t('预计起飞时间')" prop="flyTime" v-show="showSearch">
            <el-date-picker type="datetimerange" :start-placeholder="$t('预计起飞开始日期')" :end-placeholder="$t('预计起飞结束日期')" value-format="yyyy-MM-dd HH:mm:ss" v-model="queryParams.flyBeginTime"></el-date-picker>
          </el-form-item>
          <el-form-item :label="$t('放行时间')" v-show="showSearch">
            <el-date-picker type="datetimerange" :start-placeholder="$t('放行开始日期')" :end-placeholder="$t('放行结束日期')" v-model="queryParams.dcPassBeginTime" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
          </el-form-item>
        </el-row>

      <!-- </el-row> -->
      <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="['shipment:box:create:air']">{{ $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="['shipment:box:export:air']">{{ $t('导出') }} </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table  v-loading="loading" :data="list">
      <el-table-column :label="$t('自编号')" align="center" prop="selfNo">
        <template slot-scope="scope">
          <a href="javascript:void(0)" @click="handleCommand(scope.row, 'detail')">{{ scope.row.selfNo }}</a>
        </template>
      </el-table-column>
      <el-table-column :label="$t('运输方式')" align="center" prop="transportType">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.ECW_TRANSPORT_TYPE" :value="scope.row.transportType" />
        </template>
      </el-table-column>

      <el-table-column :label="$t('出货渠道')" align="center" prop="shippingChannelId">
        <template slot-scope="scope">
          <span><!--{{ getShipChannelName(scope.row.shippingChannelId) }}-->
          {{$l(scope.row.channelRespVO, 'name')}}
          </span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('订单方数（分拣/已出）')" align="center" prop="">
        <template slot-scope="{row}">
          {{row.boxStatistics.volume}}/{{row.boxStatistics.loadVolume}}
        </template>
      </el-table-column>
      <el-table-column :label="$t('订单重量（分拣/已出）')" align="center" prop="weight">
        <template slot-scope="{row}">
          {{row.boxStatistics.weight}}/{{row.boxStatistics.loadWeight}}
        </template>
      </el-table-column>
      <el-table-column :label="$t('出仓方数（分拣/已出）')" align="center" prop="weight">
        <template slot-scope="{row}">
          {{row.boxStatistics.mergePlanVolume }}/{{row.boxStatistics.mergeRealVolume}}
        </template>
      </el-table-column>
      <el-table-column :label="$t('出仓重量（分拣/已出）')" align="center" prop="weight">
        <template slot-scope="{row}">
          {{row.boxStatistics.mergePlanWeight}}/{{row.boxStatistics.mergeRealWeight}}
        </template>
      </el-table-column>

      <el-table-column :label="$t('状态')" align="center" prop="shipmentStatusText" />

      <el-table-column :label="$t('提单状态')" align="center" prop="ladingBillStatus" width="180">
        <template slot-scope="scope">
          <span>{{ ladingBillStatusData[scope.row.ladingBillStatus] }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('日期')" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ new Date(scope.row.createTime).format('yyyy-MM-dd hh:mm:ss') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('操作')" align="center" class-name="small-padding fixed-width" width="200px">
        <template slot-scope="scope">
          <!-- <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)"
                     v-hasPermi="['shipment:box:query']">{{$t('查看')}}</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['shipment:box:update']">{{$t('修改')}}</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['shipment:box:delete']">{{$t('删除')}}</el-button> -->
          <el-dropdown trigger="click" @command="(command) => handleCommand(scope.row, command)" style="marginRight:10px;">
            <el-button type="primary"> {{ $t('操作') }}<i class="el-icon-arrow-down el-icon--right"></i> </el-button>
            <el-dropdown-menu  slot="dropdown">
              <el-dropdown-item command="edit" v-has-permi="['shipment:air:edit']" :disabled="scope.row.prStatus>21">{{$t('编辑')}}</el-dropdown-item>
              <el-dropdown-item command="air" v-has-permi="['shipment:air:action']">{{$t('操作')}}-{{$t('空运')}}</el-dropdown-item>
              <el-dropdown-item command="error" v-has-permi="['shipment:air:exception']">{{$t('异常登记')}}</el-dropdown-item>
              <el-dropdown-item command="cost" v-has-permi="['shipment:air:fee']">{{$t('费用登记')}}</el-dropdown-item>
              <el-dropdown-item command="batchMarkup" v-has-permi="['shipment:air:batchMarkup']">{{$t('批量加价')}}</el-dropdown-item>
              <el-dropdown-item command="editLadingBill" v-has-permi="['shipment:air:editLadingBill']">{{$t('编辑提货单')}}</el-dropdown-item>
<!--              <el-dropdown-item command="delete">{{$t('删除')}}</el-dropdown-item>-->

            </el-dropdown-menu>
          </el-dropdown>
          <el-dropdown trigger="click" @command="(command)=>handleCommand(scope.row, command)" v-hasPermi="['shipment:air:download:downloadPreloadGoodsList',
          'shipment:air:download:downloadLoadGoodsList','shipment:air:download:downloadReceivableList',
          'shipment:air:download:downloadAgentListFiles','shipment:air:download:downloadSoncapFiles',
          'shipment:air:download:zipDownload','shipment:air:download:downloadLadingCopy']">
            <el-button type="primary">
              {{$t('下载')}}<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="downloadPreloadGoodsList" v-hasPermi="['shipment:air:download:downloadPreloadGoodsList']">{{$t('预装单')}}</el-dropdown-item>
              <el-dropdown-item command="downloadReceivableList" v-hasPermi="['shipment:air:download:downloadReceivableList']">{{$t('应收汇总表')}}</el-dropdown-item>
              <el-dropdown-item command="downloadAgentListFiles" v-hasPermi="['shipment:air:download:downloadAgentListFiles']">agent list</el-dropdown-item>
              <el-dropdown-item command="downloadSoncapFiles" v-hasPermi="['shipment:air:download:downloadSoncapFiles']">soncap</el-dropdown-item>
              <el-dropdown-item command="zipDownload" v-hasPermi="['shipment:air:download:zipDownload']">{{$t('提货单')}}</el-dropdown-item>
              <el-dropdown-item command="downloadLadingCopy" v-hasPermi="['shipment:air:download:downloadLadingCopy']">{{$t('提单Copy')}}</el-dropdown-item>
              <el-dropdown-item command="downloadLoadGoods" v-hasPermi="['shipment:air:download:downloadLoadGoods']">{{$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.page" :limit.sync="queryParams.rows" @pagination="getList" />

    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogCfg.title" :visible.sync="dialogCfg.open" :width="dialogCfg.width" :fullscreen="dialogCfg.fullscreen" append-to-body class="shippingSea-dialog">
      <template v-if="dialogCfg.dialogType === 'edit' || dialogCfg.dialogType === 'add'">
        <editAirForm v-if="dialogCfg.open" @closeDialog="closeDialog" :shipmentObj="currRow" :warehouseList="warehouseList" :transportTypes="transportTypes" />
      </template>
      <template v-if="dialogCfg.dialogType === 'cost'">
        <costForm v-if="dialogCfg.open" @closeDialog="closeDialog" :shipmentObj="currRow" flag="air" />
      </template>
      <template v-if="dialogCfg.dialogType === 'error'">
        <regError v-if="dialogCfg.open" @closeDialog="closeDialog" :shipmentObj="currRow" :allUsers="allUsers" flag="air" />
      </template>
      <template v-if="dialogCfg.dialogType === 'editLadingBill'">
        <ladingBill v-if="dialogCfg.open" @closeDialog="closeDialog" :shipmentObj="currRow" :getCabinetName="getCabinetName" type="air" />
      </template>
      <template v-if="dialogCfg.dialogType === 'notice'">
        <div class="notice-dialog">
          <div class="notice-title">
            {{
              $t('您有{cnt}个待处理出货操作，请尽快前往处理', {
                cnt: noticeList.length
              })
            }}：
          </div>
          <el-table :data="noticeList" height="500px" border>
            <el-table-column :label="$t('自编号')" align="center" prop="selfNo" />
            <el-table-column :label="$t('类型')" align="center">
              <template slot-scope="scope">
                {{scope.row.noticeText}}
                <!--<dict-tag :type="DICT_TYPE.BOX_SHIPPING_NOTICE_TYPE" :value="String(scope.row.noticeType)" />-->
              </template>
            </el-table-column>
            <el-table-column :label="$t('预计时间')" align="center">
              <template slot-scope="scope">
                {{ formatDate(scope.row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column :label="$t('操作')" align="center" width="80">
              <template slot-scope="scope">
                <el-button type="text" @click="handleCommand(scope.row, 'handle')">{{ $t('处理') }}</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-row class="operate-button">
            <el-button type="primary" @click="closeDialog">{{ $t('关闭窗口') }}</el-button>
          </el-row>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  deletebox,
  getbox,
  getboxPage,
  exportboxExcel,
  getNoticeList,
  dealCustomsSplitNotify,
  exportPreloadGoodsList, downloadReceivableList, getAirNoticeList, zipDownload, downloadAirReceivableList
} from '@/api/ecw/box'
import { getLineInfo } from '@/api/ecw/boxAir'
import { getChannelList } from '@/api/ecw/channel'
import { downloadLoadGoods }  from '@/api/ecw/boxAir'
import { getWarehouseList } from '@/api/ecw/warehouse'
import costForm from './costForm.vue'
import regError from './regError.vue'
import editAirForm from './editAirForm.vue'
import dockSelect from "./shippingSea/nodePage/common/dockSelect.vue"
import supplierSelect from "./shippingSea/nodePage/common/supplierSelect.vue"
import {
  downloadFile,
  downloadFileByUrl,
  formatDate,
  constantDict,
} from "./shippingAir/utils";
import { getRegionList } from "@/api/ecw/order";
import { getDockPage } from "@/api/ecw/dock";
import { getSupplierPage } from "@/api/ecw/supplier";
import {getCabinetPage} from "@/api/ecw/cabinet";
import LadingBill from "@/views/ecw/box/ladingBill/index.vue";
import {listUser} from "@/api/system/user";

export default {
  name: 'EcwBoxIndexair',
  components: {
    LadingBill,
    costForm,
    regError,
    editAirForm,
    dockSelect,
    supplierSelect,
  },
  data() {
    return {
      AddressCity: [],
      AddressProvince: [],
      AddressTown: [],
      countryIdList: null,
      destCityIdList: null,
      destWarehouseIdList: null,
      // 选中数组
      ids: [],
      //目的国
      countryList: [],
      //目的城市
      cityList: [],
      //目的仓
      destWarehouseList: [],
      cabinetList:[],
      dateTypes: [
        { value: '1', label: this.$t('分拣时间') },
        { value: '7', label: this.$t('出仓时间') },
        { value: '3', label: this.$t('起飞时间') },
        { value: '4', label: this.$t('到港时间') },
        { value: '5', label: this.$t('清关时间') },
        { value: '6', label: this.$t('提货时间') }
      ],

      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 出货列表
      list: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      // 弹出类型
      dialogCfg: {
        title: '',
        dialogType: '',
        width: '600px',
        // 是否显示弹出层
        open: false,
        fullscreen: false
      },
      dateRangeCreateTime: [],
      transportTypes: [],
      // 查询参数
      queryParams: {
        page: 1,
        rows: 10,
        id: null,
        selfNo: null,
        cubNo: null,
        cabinetId: null,
        shipmentStatusAir: null,
        startWarehouseId: null,
        destWarehouseIdList: null,
        transportType: null
      },
      channelList: [],
      warehouseList: [],
      // 码头
      allDocks: [],
      // 供应商
      allSupplier: [],
      voyageData: constantDict.voyageData,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        shippingChannelId: [
          {
            required: true,
            message: this.$t('出货渠道不能为空'),
            trigger: 'blur'
          }
        ],
        startWarehouseId: [
          {
            required: true,
            message: this.$t('始发地不能为空'),
            trigger: 'blur'
          }
        ],
        destWarehouseIdList: [
          {
            required: true,
            message: this.$t('目的地不能为空'),
            trigger: 'blur'
          }
        ]
      },
      ladingBillStatusData: [
        this.$t("未完成"),
        this.$t("部分完成"),
        this.$t("已完成"),
      ],
      allUsers: [],
      makeBillNodeStatus: {
        '1':403,
        '2':407,
        '3':409,
        '4':410,
        '5':411,
        '6':412,
        '7':421,
        '8':421,
        '9':421,
        '10':426,
        '11':426,
        '12':428,
        '13':430,
        '14':435,
        '15':438,
      },
      destinationClearanceData: [
        {
          label: '我司清关',
          value: 1
        },
        {
          label: '合作方清关',
          value: 2
        },
        {
          label: '客户',
          value: 3
        },
      ],
      deliveryTypeData: [
        {
          label: '多票',
          value: 1
        },
        {
          label: '单票',
          value: 2
        }
      ]
    }
  },
  watch: {
    countryIdList: {
      //监听当前地区值的变化，于与上方地区值进行了双向绑定
      deep: true, //深度监听
      handler() {
        //每当值省份值改变时其下地区值进行清空
        this.AddressCity = []
        this.AddressTown = []
        this.destCityIdList = ""
        this.destWarehouseIdList = ""
        this.findByprovinceCode()
        if (this.countryIdList == "") {
          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.countryIdList != "" && this.destCityIdList == "" && this.destWarehouseIdList == "") {
          getRegionList(2, this.countryIdList)
            .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);
        //   });
      }
    },
    destCityIdList: {
      deep: true, //深度监听
      handler() {
        this.AddressTown = []
        this.destWarehouseIdList = ""
        this.findBycityCode()

        if (this.destCityIdList != "" && this.countryIdList != "" && this.destWarehouseIdList == "") {
          //获取当前城市值id，获取该城市下区域
          getRegionList(3, this.destCityIdList)
            .then(({ data }) => {
              this.AddressTown = data
            })
            .catch((error) => {
              console.log(error)
            })
        } else if (this.countryIdList == "" && this.destCityIdList == "" && this.destWarehouseIdList == "") {
          getRegionList(5, 5)
            .then(({ data }) => {
              this.AddressTown = data
            })
            .catch((error) => {
              console.log(error)
            })
        } else if (this.countryIdList != "" && this.destCityIdList == "" && this.destWarehouseIdList == "") {
          getRegionList(2, this.countryIdList)
            .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.destCityIdList!="" && this.destCityIdList=="" ){
        //   getRegionList(5, 5).then(({data}) => {
        // this.AddressTown = data;

        // }).catch(error => {
        //   console.log(error);
        // });
        // }
      }
    },
    destWarehouseIdList: {
      deep: true, //深度监听
      handler() {
        if (this.destCityIdList != "" && this.countryIdList != "" && this.destWarehouseIdList == "") {
          //获取当前城市值id，获取该城市下区域
          getRegionList(3, this.destCityIdList)
            .then(({ data }) => {
              this.AddressTown = data
            })
            .catch((error) => {
              console.log(error)
            })
        } else if (this.countryIdList != "" && this.destCityIdList == "" && this.destWarehouseIdList == "") {
          getRegionList(5, 5)
            .then(({ data }) => {
              this.AddressTown = data
            })
            .catch((error) => {
              console.log(error)
            })
        }
        //   else if(this.destCityIdList=="" && this.destWarehouseIdList==""){
        //     getRegionList(5, 5).then(({data}) => {
        //      this.AddressTown = data;
        // })
        //   .catch(error => {
        //     console.log(error);
        //   });
        //   }
      }
    }
  },
  computed: {
    getCabinetName() {
      return (cabinetId) => {
        for (let index in this.cabinetList) {
          let cabinetItem = this.cabinetList[index];
          if (cabinetItem.id == cabinetId) {
            return cabinetItem.name;
          }
        }
      };
    },
    exportWarehouseList() {
      return this.warehouseList.filter((item) => item.tradeType == '2' || item.type == '3')
    },
    importWarehouseList() {
      return this.warehouseList.filter((item) => item.tradeType == '1' || item.type == '3')
    },

    getShipChannelName() {
      return (shippingChannelId) => {
        for (let index in this.channelList) {
          let channelItem = this.channelList[index]
          if (channelItem.channelId == shippingChannelId) {
            return this.$l(channelItem, 'name')
          }
        }
        return '/'
      }
    }
  },
  created() {
    this.init()
    getCabinetPage({status:0}).then((response) => {
      this.cabinetList = response.data.list;
    });
    this.transportTypes = this.getDictDatas(
      this.DICT_TYPE.ECW_TRANSPORT_TYPE
    ).filter((item) => item.value == "3");console.log(this.getDictDatas(
      this.DICT_TYPE.ECW_TRANSPORT_TYPE
    ),'this.transportTypes')
    getWarehouseList().then((res) => (this.warehouseList = res.data))
    this.getList()
    this.getChannelList()
    this.queryNotice()
    // 用户
    listUser({ pageNo: "1", pageSize: "10000" }).then((res) => {
      const { data } = res;
      this.allUsers = data.list ?? [];
    });

  },
  methods: {
    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)
        })
      // 码头
      getDockPage({ pageNo: "1", pageSize: "10000" }).then((res) => {
        const { data } = res;
        this.allDocks = data.list;
      });
      // 供应商
      getSupplierPage({ pageNo: "1", pageSize: "10000" }).then((res) => {
        const { data } = res;
        this.allSupplier = data.list.map((item) => {
          if (item.companyType) {
            item.companyTypes = item.companyType.split(",");
          }
          return item;
        });
      });
    },
    findByprovinceCode() {
      //获取当前省份值id，获取该省份下城市 countryIdList provinceCode

      getRegionList(2, this.countryIdList)
        .then(({ data }) => {
          this.AddressCity = data
        })
        .catch((error) => {
          console.log(error)
        })
    },
    findBycityCode() {
      //获取当前城市值id，获取该城市下区域
      getRegionList(3, this.destCityIdList)
        .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)
        })
    },
    formatDate,
    getChannelList() {
      getChannelList().then((res) => (this.channelList = res.data))
    },
    queryNotice() {
      getAirNoticeList({
        transportTypeList: this.transportTypes.map((item) => item.value),
      }).then((res) => {
        const { data } = res;
        this.noticeList = data ?? [];
        if (data.length) {
          this.$set(this.dialogCfg, "title", this.$t("出货操作提醒"));
          this.$set(this.dialogCfg, "dialogType", "notice");
          this.$set(this.dialogCfg, "width", "650px");
          this.$set(this.dialogCfg, "open", true);
        }
      });
    },
    formatQuery() {
      let obj = {}
      //始发仓
      // if (this.startWarehouseId != null && this.startWarehouseId != "") {
      //   obj.startWarehouseIds = this.startWarehouseId
      // }
      //目的国
      if (this.countryIdList != null && this.countryIdList != "") {
        obj.countryIdList = this.countryIdList
      }
      //目的城市
      if (this.destCityIdList != null && this.destCityIdList != "") {
        obj.destCityIdList = this.destCityIdList
      }
      //目的仓
      if (this.destWarehouseIdList != null && this.destWarehouseIdList != "") {
        obj.destWarehouseIdList = this.destWarehouseIdList
      }
      return obj
    },
    /** 查询列表 */
    getList() {
      this.loading = true
      // 处理查询参数
      let params = { ...this.queryParams }
      params.transportType = 3
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, 'createTime')
      this.addBeginAndEndTimeNew(params, params.flyBeginTime, 'fly');// 预计起飞时间
      this.addBeginAndEndTimeNew(params, params.dcPassBeginTime, 'dcPass');// 放行时间
      // 执行查询
      getboxPage({...params, ...this.formatQuery()}).then((response) => {
        this.list = response.data.list
        this.total = response.data.total
        // var lineParams = []
        // this.list.forEach(item=>{
        //   let line = lineParams.findIndex(li=>li.startWarehouseId==item.startWarehouseId&&li.destWarehouseIdList==item.destWarehouseIdList&&li.transportType==item.transportType)
        //   if(line == -1){
        //     lineParams.push({startWarehouseId:item.startWarehouseId,destWarehouseIdList:item.destWarehouseIdList,transportType:item.transportType})
        //   }
        // })
        // getLineInfoList(lineParams)
        this.loading = false
      })
    },
    /** 取消按钮 */
    cancel() {
      this.open = false
      this.reset()
    },
    /* 关闭弹窗 */
    closeDialog(type) {
      this.$set(this.dialogCfg, "open", false);
      if (type === "add" || type === "edit") {
        this.getList();
      }
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        cabinetId: undefined,
        startWarehouseId: undefined,
        destWarehouseIdList: undefined,
        transportType: undefined
      }
      this.countryIdList = null;
      this.destCityIdList = null;
      this.destWarehouseIdList = null;
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {};
      this.dateRangeCreateTime = [];
      this.countryIdList = null;
      this.destCityIdList = null;
      this.destWarehouseIdList = null;
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$set(this.dialogCfg, 'title', this.$t('添加出货'))
      this.$set(this.dialogCfg, 'dialogType', 'add')
      this.$set(this.dialogCfg, 'width', '600px')
      this.$set(this.dialogCfg, 'fullscreen', false)
      this.$set(this.dialogCfg, 'open', true)
      this.currRow = {
        transportType: '3',
        destinationClearanceSelect: 1,
        destinationClearance: 1,
        deliveryType: 1
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const id = row.id;
      getbox(id).then((response) => {
        this.currRow = response.data;
        this.$set(this.dialogCfg, "title", this.$t("修改出货"));
        this.$set(this.dialogCfg, "dialogType", "edit");
        this.$set(this.dialogCfg, "width", "600px");
        this.$set(this.dialogCfg, "open", true);
        this.$set(this.dialogCfg, 'fullscreen', false);
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id
      this.$modal
        .confirm(this.$t('是否确认删除出货编号为{id}的数据项?', { id }))
        .then(function () {
          return deletebox(id)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess(this.$t('删除成功'))
        })
        .catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = { ...this.queryParams }
      params.pageNo = undefined
      params.pageSize = undefined
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, 'createTime')
      this.addBeginAndEndTimeNew(params, params.flyBeginTime, 'fly');// 预计起飞时间
      this.addBeginAndEndTimeNew(params, params.dcPassBeginTime, 'dcPass');// 放行时间
      // 执行导出
      this.$modal
        .confirm(this.$t('是否确认导出所有出货数据项?'))
        .then(() => {
          this.exportLoading = true
          return exportboxExcel({...params, ...this.formatQuery()})
        })
        .then((response) => {
          this.$download.excel(response, this.$t("空运管理") + ".xls");
          this.exportLoading = false
        })
        .catch(() => {})
    },
    /** 查看按钮操作 */
    async handleCommand(row, command) {
      console.log(command, row);
        switch (command) {
          case "detail":
            this.$router.push("/boxAir/query/" + row.id);
            break;
          case 'air':
            this.$router.push('/boxAir/shippingAir/' + row.id)
            break

          case 'edit':
            this.handleUpdate(row)
            break

          case 'delete':
            this.handleDelete(row);
            break;
          case "editLadingBill":
            let line = await getLineInfo({startWarehouseId: row.startWarehouseId,destWarehouseId: row.destWarehouseId,transportType:row.transportType})
            let makeBillNode = line.data.makeBillNode
            console.log(row,this.makeBillNodeStatus[makeBillNode])
            if(row.shipmentStatusAir<this.makeBillNodeStatus[makeBillNode]){
              this.$message.error(this.$t("此出货单状态未到提单节点"));
              return
            }
            const cabinetLabel = this.getCabinetName(row.cabinetId);
            const title = this.$t(
              "查看提单 {selfNo}",
              {
                selfNo: row.selfNo,
                cubNo: row.cubNo,
                cabinetLabel: cabinetLabel,
              }
            );
            this.$set(this.dialogCfg, "title", title);
            this.$set(this.dialogCfg, "fullscreen", true);
            break;
          case 'batchMarkup':
            this.$router.push('/boxAir/batch_markup?shipmentId=' + row.id)
            break
          case "downloadPreloadGoodsList":
            // downloadFile(
            //   command,
            //   {shipmentId: row.id},
            //   this.$t("预装单") + `(${row.selfNo}).xlsx`,
            //   "xlsx"
            // );
            this.exportExcel(exportPreloadGoodsList, { shipmentId: row.id }, this.$t("预装单") + `(${row.selfNo}).xlsx`)
            break;
          case "downloadLoadGoodsList":
            downloadFile(
              command,
              {shipmentId: row.id},
              this.$t("已装单") + `(${row.selfNo}).xlsx`,
              "xlsx"
            );
            break;
          case "downloadReceivableList":
            //下载空运应收款汇总单 lanbm 2024-05-25 添加注释
            this.exportExcel(
              downloadAirReceivableList,
              {shipmentId: row.id}
            );
            break;
          case "zipDownload":
            /*downloadFile(
              command,
              {shipmentId: row.id},
              this.$t("提货单") + `(${row.selfNo}).zip`,
              "zip"
            );*/
            this.exportExcel(zipDownload, { shipmentId: row.id }, this.$t("提货单") + `(${row.selfNo}).zip`)
            break;
          case "downloadAgentListFiles":
          case "downloadSoncapFiles":
          case "downloadLadingCopy":
            downloadFileByUrl(command, {shipmentId: row.id});
            break;
          case "downloadLoadGoods":
            if(row.tyStatus < 2112){
              this.$message.error('请先完成理货后，再下载已装单')
              return
            }
            this.exportExcel(downloadLoadGoods, { shipmentId: row.id }, this.$t("已装单") + `(${row.selfNo}).xls`)
            break;
          case "handle":
            const { noticeType } = row;
            if ([1, 2, 3, 4, 8, 14].includes(noticeType)) {
              this.$router.push("/boxAir/shippingAir/" + row.id);
            }
            // 10 是起飞异常，参考海运的起运异常6处理
            if ([5, 6, 7, 10].includes(noticeType)) {
              this.$router.push("/boxAir/query/" + row.id);
            }
            if([9, 12, 13].includes(noticeType)){
              await dealCustomsSplitNotify(row.notifyId)
            }
            this.closeDialog();
            break;
        }
        if (["editLadingBill", "cost", "error"].includes(command)) {
          this.currRow = row;
          this.$set(this.dialogCfg, "dialogType", command);
          this.$set(this.dialogCfg, "width", "600px");
          this.$set(this.dialogCfg, "open", true);
        }
    },
    // 通用导出函数
    exportExcel(func, params, fileName = null){
      this.exportLoading = true;
      func(params).then(res => {
        console.log({res})
        this.$message.success(this.$t('已加入导出队列，请稍后在下载日志中下载'))
        // this.$download.excel(res, fileName + '.xls');
      }).finally(() => {
        this.exportLoading = false
      })
    },
  }
}

</script>

<style lang="scss" scoped>
.notice-dialog {
  ::v-deep .notice-title {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 10px;
  }
  ::v-deep .operate-button {
    margin-top: 10px;
    text-align: center;
  }
}
</style>

