<template>
  <div class="app-container">

    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item :label="$t('编号')">
        <el-input
          v-model.trim="noParam.value"
          :placeholder="$t('请输入快递号、包裹号、订单号')"
          clearable
          class="w-200"
          @input="replaceSpace(noParam, 'value')"
          @keyup.enter.native="handleQuery">
          <template slot="prepend">
            <dict-selector :type="DICT_TYPE.ORDER_QUERY_NO_FIELD" defaultable v-model="noParam.key"/>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="发货人" prop="customerNumber">
        <el-input v-model="queryParams.customerKey" placeholder="请输入发货人手机号、客户编号" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="发货人名称" prop="customerNumber">
        <el-input v-model="queryParams.customerName" placeholder="请输入客户名称" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item :label="$t('客户经理')">
        <user-selector manage v-model="queryParams.salesmanIds" multiple clearable @change="handleQuery"
                       :prepend="{ id: 0, nickname: $t('未分配客户经理') }" class="w-200"/>
      </el-form-item>
      <el-form-item :label="$t('包裹状态')" prop="statusList">
        <dict-selector :type="DICT_TYPE.CONS_STATUS" multiple v-model="queryParams.statusList" @keyup.enter.native="handleQuery"  clearable @change="handleQuery" class="w-200" />
      </el-form-item>
      <el-form-item :label="$t('在仓时间')" v-show="showSearch">
        <el-input type="number" v-model.trim="pickRatio.value" :placeholder="$t('请输入数字')" clearable @keyup.enter.native="handleQuery" class="w-200">
          <template slot="prepend">
            <dict-selector :type="DICT_TYPE.PICK_RATIO_FIELD" defaultable v-model="pickRatio.key" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item :label="$t('集运仓')">
        <el-select v-model="queryParams.wareId" :placeholder="$t('请选择仓库')" filterable>
          <el-option v-for="warehouse in this.warehouseList" :key="warehouse.id" :label="$l(warehouse,'title')"
                     :value="warehouse.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('运输方式')" prop="transportId">
        <dict-selector :type="DICT_TYPE.ECW_TRANSPORT_TYPE" v-model="queryParams.transportId" class="w-200"/>
      </el-form-item>
      <el-form-item :label="$t('目的国')" prop="consigneeCountryId">
        <el-select v-model="queryParams.consigneeCountryId" :label="queryParams.consigneeCountryId"
                   :placeholder="$t('请选择目的国')" clearable @change="handleQuery" class="w-200">
          <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">
        <el-select v-model="queryParams.consigneeCityId" :placeholder="$t('请选择目的城市')" style="width: 200px"
                   clearable @change="handleQuery" class="w-200">
          <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="channelIds">
        <selector clearable :options="channelList" :label-field="$l('name')" value-field="channelId" v-model="queryParams.channelIds" multiple class="w-200"></selector>
      </el-form-item>
      <el-form-item :label="$t('验货服务')" prop="needInspect" v-show="showSearch">
        <dict-selector v-model="queryParams.needInspect" :type="DICT_TYPE.YES_OR_NO" fomatter="bool" clearable @change="handleQuery" class="w-200" />
      </el-form-item>
      <el-form-item :label="$t('验货状态')" prop="inspectStatus" v-show="showSearch">
        <dict-selector v-model="queryParams.inspectStatus" :type="DICT_TYPE.CONS_INSPECT_STATUS" fomatter="bool" clearable @change="handleQuery" class="w-200" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</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:cons:create']">新增</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:cons:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleEdit">单个预报</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-plus" size="mini" @click="handleEditMore">多个预报</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleBatchSignOff">批量签收</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-plus" size="mini" @click="handleBatchConsEdit">批量更新货运信息
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-plus" size="mini" @click="handleTransfer">转运</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-plus" size="mini">批量申请费用</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" fixed></el-table-column>
      <el-table-column label="快递单号" align="center" prop="expressNo">
        <template slot-scope="scope">
          <router-link
            :to="{
              path: '/cons/detail',
              query: { consId: scope.row.id }
            }"
            class="link-type"
          >
            <span>{{ scope.row.expressNo }}</span>
          </router-link>
          <div
            style="display: flex;flex-wrap: wrap"
            v-if="scope.row.hasErrors || scope.row.hasReturnStatus || scope.row.returnStatus===0 || scope.row.hasExitApproval || scope.row.hasAddApproval || scope.row.isOverLimit"
          >
            <el-button
              size="mini"
              style="margin-left: 2px;margin-bottom:2px;"
              type="danger"
              circle
              v-if="scope.row.hasErrors"
            >{{ $t('异') }}</el-button>
            <el-button
              size="mini"
              style="margin-left: 2px;margin-bottom:2px;"
              type="danger"
              circle
              v-if="scope.row.isFollowOverTime"
            >{{ $t('跟') }}</el-button>
            <el-button
              size="mini"
              style="margin-left: 2px;margin-bottom:2px;"
              type="danger"
              circle
              v-if="scope.row.hasReturnStatus || scope.row.returnStatus===0"
            >{{ $t('退') }}</el-button>
            <el-button
              size="mini"
              style="margin-left: 2px;margin-bottom:2px;"
              type="danger"
              circle
              v-if="scope.row.hasExitApproval"
            >{{ $t('撤') }}</el-button>
            <el-button
              size="mini"
              style="margin-left: 2px;margin-bottom:2px;"
              type="danger"
              circle
              v-if="scope.row.hasAddApproval"
            >{{ $t('加') }}</el-button>
            <el-button
              size="mini"
              style="margin-left: 2px;margin-bottom:2px;"
              type="danger"
              circle
              v-if="scope.row.isOverLimit"
            >{{ $t('超') }}</el-button>
            <el-button
              size="mini"
              style="margin-left: 2px;margin-bottom:2px;"
              type="danger"
              circle
              v-if="scope.row.consSpecialNeeds&&scope.row.consSpecialNeeds.length>0"
              v-for="(item, index) in specialRendering(scope.row.consSpecialNeeds)"
              :key="index"
            >{{ item.symbol }}</el-button
            >
          </div>
        </template>
      </el-table-column>
      <el-table-column label="客户" align="center">
        <template slot-scope="scope">
          <router-link :to="`/customer/query/${scope.row.customerId}`" class="link-type">
          {{ scope.row.customerName }}({{ scope.row.customerNumber }})
          </router-link>
        </template>
      </el-table-column>
      >
      <el-table-column :label="$t('运输方式')" align="center">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.ECW_TRANSPORT_TYPE" :value="scope.row.transportId"/>
        </template>
      </el-table-column>
      <el-table-column :label="$t('在仓时长')" align="center" prop="inWarehouseDays">
        <template slot-scope="scope">
          <span :style="{ color: scope.row.isOverTime ? 'red' : '' }">
            {{ scope.row.inWarehouseDays }}
          </span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('动态')" align="center">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.CONS_BUSINESS_NODE" :value="scope.row.businessNode"/>
        </template>
      </el-table-column>
      <el-table-column :label="$t('最新跟进状态')" align="center">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.ECW_CONS_FOLLOWUP_STATUS" :value="scope.row.followStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="最新跟进时间" align="center">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.followTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最新跟进备注" align="center" prop="followContent"/>
      <el-table-column label="箱数" align="center" prop="sumQuantity"/>
      <el-table-column label="填单商品" align="center">
        <template slot-scope="scope">
          <span v-html="getGoodsName(scope.row.consItemVOList)"></span>
        </template>
      </el-table-column>
      <el-table-column label="验货数据" align="center">
        <template slot-scope="scope">
           <span :style="{ color: scope.row.isOverLimit ? 'red' : '' }">
              {{ getInspectionInfo(scope.row.consItemList, scope.row.inspectStatus) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="货值(RMB)" align="center" prop="worth"/>
      <!--      <el-table-column label="预计到仓时间" align="center" prop="watEtime" width="180">-->
      <!--        <template slot-scope="scope">-->
      <!--          <span>{{ parseTime(scope.row.watEtime) }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="签收时间" align="center" prop="signedTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.signedTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="签收图片" align="center" prop="mediaUrl" width="180">
        <template slot-scope="scope">
          <a v-if="scope.row.signed==1"  :style="{ color: 'blue' }" @click="showSignImage(scope.row.mediaUrl)">{{ $t("签收图片") }}</a>
        </template>
      </el-table-column>
      <el-table-column label="签收备注" align="center" prop="signedRemarks"/>
      <el-table-column label="始发仓" align="center">
        <template slot-scope="scope">
          {{ isChinese ? scope.row.startTitleZh : scope.row.startTitleEn }}
        </template>
      </el-table-column>
      <el-table-column label="目的仓" align="center">
        <template slot-scope="scope">
          {{ isChinese ? scope.row.destTitleZh : scope.row.destTitleEn }}
        </template>
      </el-table-column>
      <el-table-column
        prop="tansportType"
        :label="$t('出货渠道')"
        align="center"
        width="100"
      >
        <template slot-scope="{ row }">
          <div>
            {{ channelName(row.channelId) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('验货')" align="center">
        <template slot-scope="scope">
          <template v-if="scope.row.inspectStatus===null">
            {{ $t('未申请') }}
          </template>
          <template v-else>
            <dict-tag :type="DICT_TYPE.CONS_INSPECT_STATUS" :value="scope.row.inspectStatus"/>
          </template>
        </template>
      </el-table-column>
      <el-table-column :label="$t('包裹状态')" align="center">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.CONS_STATUS" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="关联订单号" align="center" prop="orderNo">
        <template slot-scope="scope">
          <a href="javascript:void(0);"  @click="jumpOrderDetail(scope.row)">{{ scope.row.orderNo }}</a>
        </template>
      </el-table-column>
      <el-table-column :label="$t('订单状态')" align="center">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.ORDER_STATUS" :value="scope.row.orderStatus"/>
        </template>
      </el-table-column>
      <el-table-column :label="$t('退仓处理状态')" align="center">
        <template slot-scope="scope">
          {{ scope.row.returnStatus === null ? '' : scope.row.returnStatus === 0 ? $t('未处理') : $t('已处理') }}
        </template>
      </el-table-column>
      <el-table-column label="包裹号" align="center" prop="consNum"/>
      <el-table-column label="包裹备注" align="center" prop="remarks"/>
      <el-table-column label="" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-dropdown>
            <el-button type="text">{{ $t("操作") }}</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item  v-if="isEditable(scope.row)" @click.native="handleUpdate(scope.row)">修改
              </el-dropdown-item>
              <el-dropdown-item  size="mini" type="text" v-if="scope.row.status==1"  @click.native="handleDelete(scope.row)">删除
              </el-dropdown-item>
              <el-dropdown-item  v-if="cancleInspect(scope.row)" @click.native="handleInspectEdit(scope.row)">
                {{ $t('验货撤销') }}
              </el-dropdown-item>
              <el-dropdown-item  v-if="scope.row.orderNo==null&&!scope.row.hasAddApproval&&!scope.row.hasExitApproval&&(scope.row.needInspect==0||(scope.row.needInspect==1&&(scope.row.inspectStatus==0&&scope.row.inspectStatus==4)))" @click.native="handleInspect(scope.row)">
                {{ $t('验货') }}
              </el-dropdown-item>
              <el-dropdown-item  @click.native="transmutation(scope.row)">{{ $t('转异') }}
              </el-dropdown-item>
              <el-dropdown-item  @click.native="copyCons(scope.row)">{{ $t('复制') }}
              </el-dropdown-item>
              <el-dropdown-item  @click.native="specialNeedsCons(scope.row)">{{ $t('特需') }}
              </el-dropdown-item>
              <el-dropdown-item  @click.native="specialNeedsConsLook(scope.row)">
                {{ $t('特需查看') }}
              </el-dropdown-item>
              <el-dropdown-item v-if="scope.row.status!=2&&!scope.row.hasAddApproval&&!scope.row.hasExitApproval"  @click.native="feeApplication(scope.row)">
                {{ $t('费用申请') }}
              </el-dropdown-item>
              <el-dropdown-item  @click.native="consFollowup(scope.row)">{{ $t('跟进') }}
              </el-dropdown-item>
              <el-dropdown-item  @click.native="exceptionHandling(scope.row)">{{$t('处理异常')}}</el-dropdown-item>
              <el-dropdown-item
                         @click.native="
                        showExit = true
                        consId = scope.row.id
                      "
                         v-hasPermi="['ecw:order:warehouse_exit']"
              >{{ $t("撤出包裹") }}
              </el-dropdown-item>
              <el-dropdown-item
                         @click.native="
                        showAdd = true
                        consId = scope.row.id
                      "
                         v-hasPermi="['ecw:order:warehouse_exit']"
              >{{ $t("追加包裹") }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-dropdown>
            <el-button type="text">{{ $t("仓库") }}</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-if="scope.row.status===0"  @click.native="handleSign(scope.row)">签收
              </el-dropdown-item>
              <!-- 退仓 -->
              <el-dropdown-item
                v-if="scope.row.status===2&&!scope.row.hasAddApproval"
                @click.native="
                        show = true
                        consId = scope.row.id
                      "
                v-hasPermi="['ecw:order:warehouse_exit']"
              >{{ $t("退仓") }}
              </el-dropdown-item>
              <el-dropdown-item
                v-if="!scope.row.hasExitApproval"
                @click.native="
                        show = true
                        consId = scope.row.id
                      "
                v-hasPermi="['ecw:order:warehouse_exit']"
              >{{ $t("取消退仓") }}
              </el-dropdown-item>
              <el-dropdown-item
                v-if="scope.row.status===2&&!scope.row.hasAddApproval"
                @click.native="
                        showReturnWarehouse = true
                        consId = scope.row.id
                      "
                v-hasPermi="['ecw:order:warehouse_exit']"
              >{{ $t("处理退仓") }}
              </el-dropdown-item>
              <el-dropdown-item
                @click.native="
                        openAdd = true
                        addForm.consNum = scope.row.consNum
                      "
                v-hasPermi="['ecw:order:warehouse_exit']"
              >{{ $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.row"
                @pagination="getList"/>

    <el-dialog :title="inspectTitle" :visible.sync="openInspect" width="500px" append-to-body>
      <div style="margin-bottom: 5px">{{ $t('备注:') }}</div>
      <el-input v-model="inspectRemark" type="textarea" :rows="3" placeholder="请输入"/>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleInspectSubmit">确 定</el-button>
        <el-button @click="openInspect = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="inspectTitle" :visible.sync="openInspectExit" width="500px" append-to-body>
      <div style="margin-bottom: 5px">{{ $t('备注:') }}</div>
      <el-input v-model="inspectRemark" type="textarea" :rows="3" placeholder="请输入"/>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleInspectExitSubmit">确 定</el-button>
        <el-button @click="openInspectExit = false">取 消</el-button>
      </div>
    </el-dialog>
    <!--订单追加-->
    <el-dialog :title="$t('包裹追加申请')" :visible.sync="openAdd" width="500px" append-to-body>
      <el-form ref="addForm" :model="addForm" :rules="rules" label-width="80px">
          <el-form-item label="包裹编号:">
            <template>
              {{addForm.consNum}}
            </template>
          </el-form-item>
          <el-form-item label="订单编号:">
            <el-input style="width: 70%;margin-right: 5px" v-model="addForm.orderId"></el-input><el-button type="primary"  @click="showAddForOrder = true">添加</el-button>
          </el-form-item>
        <el-form-item label="订单状态:">
          <template slot-scope="scope">
            <dict-tag :type="DICT_TYPE.ORDER_STATUS" :value="addForm.orderStatus"/>
          </template>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="" prop="customerId">
          <el-input v-model="form.customerId" placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="客户编号" prop="customerNumber">
          <el-input v-model="form.customerNumber" placeholder="请输入客户编号"/>
        </el-form-item>
        <el-form-item label="运输方式，来自字典的值" prop="transportId">
          <el-input v-model="form.transportId" placeholder="请输入运输方式，来自字典的值"/>
        </el-form-item>
        <el-form-item label="订单ID，关联订单表" prop="orderId">
          <el-input v-model="form.orderId" placeholder="请输入订单ID，关联订单表"/>
        </el-form-item>
        <el-form-item label="平台ID，关联平台表数据，为后面系统对接预留字段" prop="platformId">
          <el-input v-model="form.platformId" placeholder="请输入平台ID，关联平台表数据，为后面系统对接预留字段"/>
        </el-form-item>
        <el-form-item label="平台订单号" prop="platformOrderSn">
          <el-input v-model="form.platformOrderSn" placeholder="请输入平台订单号"/>
        </el-form-item>
        <el-form-item label="包裹状态，来自字典表，cons_status" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="1">请选择字典生成</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="快递公司ID，对应快递公司表" prop="expressId">
          <el-input v-model="form.expressId" placeholder="请输入快递公司ID，对应快递公司表"/>
        </el-form-item>
        <el-form-item label="快递单号" prop="expressNo">
          <el-input v-model="form.expressNo" placeholder="请输入快递单号"/>
        </el-form-item>
        <el-form-item label="仓库ID" prop="wareId">
          <el-input v-model="form.wareId" placeholder="请输入仓库ID"/>
        </el-form-item>
        <el-form-item label="货值" prop="worth">
          <el-input v-model="form.worth" placeholder="请输入货值"/>
        </el-form-item>
        <el-form-item label="货值单位，默认为3，人民币" prop="worthCurrency">
          <el-input v-model="form.worthCurrency" placeholder="请输入货值单位，默认为3，人民币"/>
        </el-form-item>
        <el-form-item label="预计到仓时间" prop="watEtime">
          <el-date-picker clearable v-model="form.watEtime" type="date" value-format="yyyy-MM-dd"
                          placeholder="选择预计到仓时间"/>
        </el-form-item>
        <el-form-item label="" prop="watTime">
          <el-date-picker clearable v-model="form.watTime" type="date" value-format="yyyy-MM-dd" placeholder="选择"/>
        </el-form-item>
        <el-form-item label="是否被签收,0未签收，1已签收" prop="signed">
          <el-radio-group v-model="form.signed">
            <el-radio label="1">请选择字典生成</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="签收时间" prop="signedTime">
          <el-date-picker clearable v-model="form.signedTime" type="date" value-format="yyyy-MM-dd"
                          placeholder="选择签收时间"/>
        </el-form-item>
        <el-form-item label="签收备注" prop="signedRemarks">
          <el-input v-model="form.signedRemarks" placeholder="请输入签收备注"/>
        </el-form-item>
        <el-form-item label="数量" prop="sumQuantity">
          <el-input v-model="form.sumQuantity" placeholder="请输入数量"/>
        </el-form-item>
        <el-form-item
          label="区分包裹是由谁创建的，关联字典表 cons_op_source，可区分为后台创建、客户web端、客户app端、客户H5端、仓库创建及其他，默认为1 客户app端"
          prop="opSource">
          <el-input v-model="form.opSource"
                    placeholder="请输入区分包裹是由谁创建的，关联字典表 cons_op_source，可区分为后台创建、客户web端、客户app端、客户H5端、仓库创建及其他，默认为1 客户app端"/>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="$t('签收图片')" :visible.sync="mvShow" :before-close="closeMv" :close-on-click-modal="false">
      <image-and-video-upload readonly :fileSize="50" :isShowTip="true" :value="this.mediaUrl" ></image-and-video-upload>
    </el-dialog>
    <Transmutation :showException.sync="showException" :id="id" @determine="getList"></Transmutation>
    <SpecialNeedsCons :showSpecialNeedsCons.sync="showSpecialNeedsCons" :currency="JSON.stringify(currencyList)"
                      :consId="id" :consNum="consNum" @determine="getList"></SpecialNeedsCons>
    <SpecialNeedsConsLook :showSpecialNeedsConsLook.sync="showSpecialNeedsConsLook" :consNum="consNum"
                          :consId="id"></SpecialNeedsConsLook>
    <fee-application-cons v-if="feeApplicationBol" :consId="id" :currencys="JSON.stringify(currencyList)"
                          :dialog-visible.sync="feeApplicationBol " @refresh="getList"></fee-application-cons>
    <ConsFollowupEdit :showConsFollowupEdit.sync="showConsFollowupEdit" :consId="id"
                      @determine="getList"></ConsFollowupEdit>
    <batch-sign-off :showConsBatchSignOff.sync="showConsBatchSignOff" @determine="getList"
                    :consIds="consIds"></batch-sign-off>
    <batch-cons-edit :showConsBatchEdit.sync="showConsBatchEdit" @determine="getList"
                     :consIds="consIds"></batch-cons-edit>
    <cons-withdrawal v-if="show" :dialog-visible="show"  :consId="consId"></cons-withdrawal>
    <cons-withdrawal-exit v-if="showExit" :dialog-visible="showExit"  :consId="consId"></cons-withdrawal-exit>
    <cons-withdrawal-deal v-if="showReturnWarehouse" :dialog-visible="showReturnWarehouse"  :consId="consId" ></cons-withdrawal-deal>
    <add-for-order v-if="showAddForOrder" :dialog-visible="showAddForOrder"  :consId="consId"></add-for-order>
  </div>
</template>

<script>
import {createCons, deleteCons, exportConsExcel, getCons, getConsPage, updateCons, updateInspect} from "@/api/ecw/cons";
import Transmutation from "@/views/ecw/cons/components/Transmutation.vue"
import addForOrder from "@/views/ecw/cons/addForOrder.vue"
import Template from "@/views/cms/template/index.vue";
import UserSelector from "@/components/UserSelector/index.vue";
import {getWarehouseList} from "@/api/ecw/warehouse";
import {getRegionList} from "@/api/ecw/order";
import SpecialNeedsCons from "@/views/ecw/cons/components/SpecialNeedsCons.vue"
import SpecialNeedsConsLook from "@/views/ecw/cons/components/SpecialNeedsConsLook.vue"

import {getCurrencyList} from "@/api/ecw/currency"
import FeeApplicationCons from "@/views/ecw/cons/components/FeeApplicationCons.vue"
import {getChannelList} from "@/api/ecw/channel";
import ConsFollowupEdit from "@/views/ecw/consFollowup/components/ConsFollowupEdit.vue"
import BatchSignOff from "@/views/ecw/cons/batchSignOff.vue";
import BatchConsEdit from "@/views/ecw/cons/batchConsEdit.vue";
import ConsWithdrawal from "@/views/ecw/cons/consWithdrawal.vue";
import ConsWithdrawalExit from "@/views/ecw/cons/consWithdrawalExit.vue";
import ConsWithdrawalDeal from "@/views/ecw/cons/consWithdrawalDeal.vue";
import {DICT_TYPE} from "@/utils/dict";
import {arrryToKeyedObjectBy} from "@/utils";
import Selector from "@/components/Selector/index.vue";
import Label from "@/views/cms/label/index.vue";
import ImageAndVideoUpload from "@/components/ImageAndVideoUpload/index.vue";

export default {
  name: "Cons",
  components: {
    addForOrder,
    ImageAndVideoUpload,
    Label,
    Selector,
    ConsWithdrawal,
    ConsWithdrawalExit,
    UserSelector,
    Transmutation,
    Template,
    FeeApplicationCons,
    SpecialNeedsConsLook,
    ConsFollowupEdit,
    SpecialNeedsCons,
    BatchSignOff,
    BatchConsEdit,
    ConsWithdrawalDeal
  },
  data() {
    return {
      pickRatio: {
        key: "eqPickRatio",
        value: ""
      },
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      show: false,
      showExit: false,
      showAdd: false,
      showReturnWarehouse: false,
      showAddForOrder: false,
      consId: undefined,
      // 总条数
      total: 0,
      // 集运包裹主列表
      list: [],
      channelList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openAdd: false,
      // 编号搜索条件
      noParam: {
        key: "numberKey",
        value: ""
      },
      consIds: [],
      inspectTitle:null,
      inspectRemark:'',
      inspectConsId:null,
      openInspect:false,
      openInspectExit:false,
      consList: [],
      dateRangeWatEtime: [],
      warehouseList: [],
      AddressProvince: [],
      AddressCity: [],
      dateRangeWatTime: [],
      dateRangeSignedTime: [],
      dateRangeCreateTime: [],
      // 查询参数
      queryParams: {
        page: 1,
        row: 10,
        customerId: null,
        customerNumber: null,
        transportId: null,
        orderId: null,
        platformId: null,
        platformOrderSn: null,
        status: null,
        expressId: null,
        expressNo: null,
        wareId: null,
        worth: null,
        worthCurrency: null,
        signed: null,
        signedRemarks: null,
        sumQuantity: null,
        opSource: null,
        remarks: null,
      },
      // 表单参数
      form: {
        transportId: null,
      },
      // 追加表单参数
      addForm: {
        orderId: null,
        orderStatus: null,
      },
      // 表单校验
      rules: {
        signed: [{required: true, message: "是否被签收,0未签收，1已签收不能为空", trigger: "blur"}],
      },
      showException: false,
      showSpecialNeedsCons: false,
      showSpecialNeedsConsLook: false,
      showConsFollowupEdit: false,
      showConsBatchSignOff: false,
      showConsBatchEdit: false,
      id: null,
      currencyList: [],
      consNum: null,
      feeApplicationBol: false,
      mvShow:false,
      mediaUrl:null
    };
  },
  created() {
    this.getChannelList()
    this.getList();
    getChannelList().then((res) => (this.channelList = res.data))
    getWarehouseList().then((r) => {
      this.warehouseList = r.data.filter(map => map.isConsService === 1);
    });
    this.getAddressProvince()
    this.getAddressCity()
    getCurrencyList().then((res) => (this.currencyList = res.data))
  },
  computed: {
    // 渠道用id做键值
    keyedChannel(){
      return arrryToKeyedObjectBy(this.channelList, 'channelId')
    },
    // 根据渠道id获取渠道名
    channelName() {
      return (id) => {
        return id !== null && this.keyedChannel[id] ? this.keyedChannel[id].nameZh : null;
      };
    },
    isChinese() {
      return this.$i18n.locale === "zh_CN";
    },
    combinedQueryParams() {
      console.log(this.queryParams)
      let queryParams = {...this.queryParams}
      if (this.noParam.value) {
        queryParams[this.noParam.key] = this.noParam.value
      }
      return queryParams
    },
  },
  watch: {
    'queryParams.consigneeCountryId': {
      deep: true, //深度监听
      handler() {
        if (this.queryParams.consigneeCountryId != "") {
          this.findByprovinceCode()
        }
      }
    },
  },
  methods: {
    handleInspectSubmit(){
      const param= {};
      param.inspectStatus=1
      param.needInspect=1
      param.id=this.inspectConsId
      param.inspectRemark=this.inspectRemark
      updateInspect(param).then((res) => {
        if (res.code === 0){
          this.$modal.msgSuccess("申请成功");
          this.openInspect = false;
          this.getList();
        }
      })
    },
    handleInspectExitSubmit(){
      const param= {};
      param.inspectStatus=1
      param.needInspect=4
      param.id=this.inspectConsId
      param.inspectRemark=this.inspectRemark
      updateInspect(param).then((res) => {
        if (res.code === 0){
          this.$modal.msgSuccess("撤销成功");
          this.openInspectExit = false;
          this.getList();
        }
      })
    },
    isEditable(item){
      debugger
      if (item.status===1){
        return true;
      }else if (item.status===2&&!item.hasAddApproval&&!item.hasExitApproval){
        return true;
      }else {
        return false
      }
    },
    showSignImage(val){
      if (val) {
        this.mediaUrl = val
      }
      this.mvShow = true
    },
    closeMv(){
      this.mediaUrl = null
      this.mvShow = false
    },
    specialRendering(val) {
      console.log("val", val);
      if (val !== undefined && val!==null &&val.length>0) {

        // let i = val.split(",");
        let i = val.map(item => item.needStatus).join(",");
        return this.getDictDatas(this.DICT_TYPE.CONS_SPECIAL_NEEDS_STATUS)
          .filter((e) => {
            return i.indexOf(e.value) > -1;
          })
          .map((item) => {
            // 打字开头的用最后一个字，否则取第一个字
            item.symbol =
              item.label[0] == "打"
                ? item.label[item.label.length - 1]
                : item.label[0];
            return item;
          });
      }
    },
    /* 跳转订单详情 */
    jumpOrderDetail(row) {
      this.$router.push({
        path: "/order/detail",
        query: { orderId: row.orderId },
      });
    },
    handleSelectionChange(val) {
      this.consIds = val.map((i) => i.id)
      this.consList = val;
    },
    getChannelList() {
      getChannelList().then((res) => (this.channelList = res.data))
    },
    getAddressProvince() {
      getRegionList(1, 1).then(({data}) => {
        this.AddressProvince = data
      })
    },
    getAddressCity() {
      getRegionList(4, 4).then(({data}) => {
        this.AddressCity = data
      })
    },
    findByprovinceCode() {
      if (this.queryParams.consigneeCountryId != null && this.queryParams.consigneeCountryId != "") {
        //获取当前省份值id，获取该省份下城市 destCountryId provinceCode
        getRegionList(2, this.queryParams.consigneeCountryId).then(({data}) => {
          this.AddressCity = data
        })
      }
    },
    // 自动去除空格
    replaceSpace(obj, field) {
      obj[field] = obj[field].replace(/\s+/g, "")
    },
    getGoodsName(val) {
      if (val==null || val.length === 0) {
        return null
      } else {
        return val.map((item, index) => `${index + 1}.${item.prodName}*${item.quantity}`).join('<br>');
      }
    },
    getInspectionInfo(val, status) {
      if (!val||(status && status !== 2)) {
        return null
      }
      let inspectionNums = 0;
      let inspectionUnit;
      let inspectionQuantitys = 0;
      let inspectionVolumes = 0;
      let inspectionWeights = 0;
      val.forEach(item => {
        inspectionUnit = item.inspectionUnit;
        inspectionNums += item.inspectionNum;
        inspectionQuantitys += item.inspectionQuantity;
        inspectionVolumes += item.inspectionVolume;
        inspectionWeights += item.inspectionWeight;
      });
      return `${inspectionQuantitys}${inspectionUnit ? inspectionUnit : this.$t('箱')} ${inspectionVolumes}m³ ${inspectionWeights}kg ${inspectionNums}件`;
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 处理查询参数
      let params = {...this.combinedQueryParams};
      console.log(params)
      this.addBeginAndEndTime(params, this.dateRangeWatEtime, 'watEtime');
      this.addBeginAndEndTime(params, this.dateRangeWatTime, 'watTime');
      this.addBeginAndEndTime(params, this.dateRangeSignedTime, 'signedTime');
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, 'createTime');
      // 执行查询
      getConsPage(params).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        customerId: undefined,
        customerNumber: undefined,
        transportId: undefined,
        orderId: undefined,
        platformId: undefined,
        platformOrderSn: undefined,
        status: undefined,
        expressId: undefined,
        expressNo: undefined,
        wareId: undefined,
        worth: undefined,
        worthCurrency: undefined,
        watEtime: undefined,
        watTime: undefined,
        signed: undefined,
        signer: undefined,
        signedTime: undefined,
        signedRemarks: undefined,
        sumQuantity: undefined,
        opSource: undefined,
        remarks: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRangeWatEtime = [];
      this.dateRangeWatTime = [];
      this.dateRangeSignedTime = [];
      this.dateRangeCreateTime = [];
      this.noParam.value = ""
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleEditMore() {
      this.$router.push("/cons/cons/create-more")
    },
    handleEdit() {
      this.$router.push("/cons/cons/create")
    },
    handleBatchSignOff() {
      if (!this.consIds.length) {
        return this.$message.error(this.$t('最少选择一个包裹'))
      }
      const hasSigned = this.consList.some(item => item.signed);
      if (hasSigned) {
        return this.$message.error(this.$t('已签收包裹不允许操作，请检查'));
      }
      this.showConsBatchSignOff = true;

    },
    handleBatchConsEdit() {
      if (!this.consIds.length) {
        return this.$message.error(this.$t('最少选择一个包裹'))
      }
      //如果状态不是代签收或已签收但无在途追加 signed=0 代签收 signed=1 已签收 hasAddApproval 是否存在追加 使用some
      if (!this.consList.every(item =>
        item.status === 0 ||
        (item.status === 1 && !item.hasAddApproval)
      )) {
        return this.$message.error(this.$t('包裹不允许操作，请检查'));
      }

      this.showConsBatchEdit = true;
    },
    handleTransfer() {
      if (!this.consIds.length) {
        return this.$message.error(this.$t('最少选择一个包裹'))
      }
      // 查找第一个不符合条件的包裹
      const invalidItem = this.consList.find(item =>
        // 条件逻辑：允许转运的条件（取反后检测非法项）
        !(item.status === 1 && !item.hasReturnStatus && !item.hasExitApproval && !item.hasAddApproval)
      );
      if (invalidItem) {
        return this.$message.error(
          this.$t('{consNum}不允许转运，请检查！', { consNum: invalidItem.consNum })
        );
      }
      // 2. 防御空数组
      if (!this.consList?.length) return
      // 新增客户ID非空校验（在所有校验前优先检查）
      const hasEmptyCustomer = this.consList.some(item => !item.customerId)
      if (hasEmptyCustomer) {
        return this.$message.error(this.$t('客户不能为空'))
      }
      // 3. 定义需要校验的字段及中文映射
      const VALIDATION_FIELDS = [
        'customerId',
        'transportId',
        'departureId',
        'consigneeCountryId',
        'consigneeCityId',
        'warehouseLineId',
        'channelId'
      ]
      const FIELD_NAMES = {
        customerId: this.$t('客户'),
        transportId: this.$t('运输方式'),
        departureId: this.$t('发货地'),
        consigneeCountryId: this.$t('收件国家'),
        consigneeCityId: this.$t('收件城市'),
        warehouseLineId: this.$t('仓库线路'),
        channelId: this.$t('渠道')
      }

      // 4. 动态基准值校验逻辑
      for (const field of VALIDATION_FIELDS) {
        // 4.1 动态获取第一个非空基准值
        let baseValue = null
        for (const item of this.consList) {
          if (item[field] != null) {
            baseValue = item[field]
            break
          }
        }

        // 4.2 全空字段跳过检查
        if (baseValue === null) continue

        // 4.3 检查所有非空值是否一致
        const inconsistentItem = this.consList.find(item =>
          item[field] != null && item[field] !== baseValue
        )

        if (inconsistentItem) {
          return this.$message.error(
            this.$t('所有包裹的 {field} 必须一致', { field: FIELD_NAMES[field] })
          )
        }
      }
      this.$router.push({
        path: "/order/create",
        query: {
          consIds: this.consIds.join(","),
        }
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加集运包裹主";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const id = row.id;
      this.$router.push({
        path: "/cons/edit",
        query: {
          id: id,
        }
      });
    },
    /** 修改按钮操作 */
    handleInspect(row) {
      const id = row.id;
      this.inspectConsId=id
      this.inspectTitle=row.consNum+"-"+row.customerNumber+"-"+this.$t("验货申请")
      this.openInspect=true
    },
    cancleInspect(item){
      return item.inspectStatus===1
    },
    handleInspectEdit(row) {
      const id = row.id;
      this.inspectConsId=id
      this.inspectTitle=row.consNum+"-"+row.customerNumber+"-"+this.$t("验货撤销")
      this.openInspectExit=true
    },
    /** 签收按钮操作 */
    handleSign(row) {
      const id = row.id;
      this.$router.push({
        path: "/cons/sign",
        query: {
          id: id,
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        // 修改的提交
        if (this.form.id != null) {
          updateCons(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createCons(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除集运包裹主编号为"' + id + '"的数据项?').then(function () {
        return deleteCons(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams};
      params.page = undefined;
      params.row = undefined;
      this.addBeginAndEndTime(params, this.dateRangeWatEtime, 'watEtime');
      this.addBeginAndEndTime(params, this.dateRangeWatTime, 'watTime');
      this.addBeginAndEndTime(params, this.dateRangeSignedTime, 'signedTime');
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, 'createTime');
      // 执行导出
      this.$modal.confirm('是否确认导出所有集运包裹主数据项?').then(() => {
        this.exportLoading = true;
        return exportConsExcel(params);
      }).then(response => {
        this.$download.excel(response, '${table.classComment}.xls');
        this.exportLoading = false;
      }).catch(() => {
      });
    },
    //转异
    transmutation(row) {
      this.id = row.id
      this.showException = true
    },
    //复制
    copyCons(row) {
      const id = row.id
      this.$router.push({
        path: "/cons/edit",
        query: {
          copy: 1,
          id: id
        }
      });
    },
    //特需
    specialNeedsCons(row) {
      this.id = row.id
      this.consNum = row.consNum
      this.showSpecialNeedsCons = true
    },
    //特需查看
    specialNeedsConsLook(row) {
      this.id = row.id
      this.consNum = row.consNum
      this.showSpecialNeedsConsLook = true
    },
    //费用申请
    feeApplication(row) {
      this.id = row.id
      this.consNum = row.consNum
      this.feeApplicationBol = true
    },
    //跟进记录
    consFollowup(row) {
      this.id = row.id
      this.showConsFollowupEdit = true
    },
    //异常
    exceptionHandling(row) {
      this.$router.push({
        path: "./consException?id=" + row.id
      })
    }
  }
};
</script>
