<template>
  <div>
    <div class="bg-in">
      <div>
        <el-form :model="deliveryForms" :rules="rules" ref="ruleForm" label-width="120px">
          <el-row>
            <el-col>
              <el-form-item label="预约类型:" prop="appointment_type">
                <el-select v-model="deliveryForms.appointment_type" :disabled="disabledType">
                  <el-option v-for="(item, index) in appointmentList" :key="index" :label="item.label"
                    :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="预约时间:" prop="" v-if="deliveryForms.appointment_type != 0">
                <el-date-picker v-model="deliveryForms.appointment_time" type="datetime" placeholder="选择日期时间"
                  :disabled="disabledType" value-format="yyyy-MM-dd HH:mm:ss" :picker-options="{
                    disabledDate(time) {
                      return (
                        time.getTime() <=
                        new Date(
                          new Date().getFullYear(),
                          new Date().getMonth(),
                          new Date().getDate()
                        ).getTime() -
                        86400000
                      );
                    },
                  }"></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-divider></el-divider>
          <div style="display: flex;">
            <div>
              <h3 style="margin-top: 0;">发货人信息:</h3>
              <el-row class="el-row">
                <el-col :span="12">
                  <el-form-item label="发货人姓名:" prop="sender.name">
                    {{ deliveryForms.sender.name }}
                    <!--   <el-input v-model="deliveryForms.sender.name" :minlength="1" :maxlength="20" placeholder="请输入发货人姓名"
                  :disabled="true"></el-input>  -->
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="手机号:" prop="sender.phone">
                    {{ deliveryForms.sender.phone }}
                    <!--  <el-input v-model="deliveryForms.sender.phone" :minlength="1" :maxlength="20" :disabled="true"
                  placeholder="请输入手机号"></el-input>  --> </el-form-item></el-col>
                <el-col :span="18">
                  <el-form-item label="发货地址:" prop="sender.address">
                    {{
                      fullSenderAddress
                    }}
                    <!-- <el-cascader size="large" :options="options" clearable :disabled="true" v-model="selectedOptions"
                  @change="sendHandleChange">
                </el-cascader>
                <el-input :disabled="true" v-model="deliveryForms.sender.address" placeholder="请输入"></el-input> -->
                  </el-form-item></el-col>
                <!--    <el-col :span="12">
              <el-form-item label="配送仓库:" prop="freight_price">
                <el-select>

                </el-select>
              </el-form-item></el-col
            >
            <el-col :span="12">
              <el-form-item label="物流公司:" prop="logistics_company_id">
                <el-select v-model="deliveryForms.logistics_company_id">

                </el-select>
              </el-form-item></el-col
            >
            <el-col :span="12">
              <el-form-item label="配送地址" prop="address">
                <el-input
                  v-model="deliveryForms.address"
                  :minlength="1"
                  :maxlength="20"
                  clearable
                  placeholder="请输入提货人"
                ></el-input> </el-form-item
            ></el-col> -->
              </el-row>
            </div>
            <div>
              <h3 style="margin-top: 0;">收货人信息:</h3>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="收货人姓名:" prop="receiver.name">
                    {{ deliveryForms.receiver.name }}
                    <!-- <el-input v-model="deliveryForms.receiver.name" :minlength="1" :maxlength="20" :disabled="true"
                  placeholder="请输入收货人姓名"></el-input> -->
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="手机号:" prop="receiver.phone">
                    {{ deliveryForms.receiver.phone }}
                    <!--  <el-input v-model="deliveryForms.receiver.phone" :minlength="1" :maxlength="20" :disabled="true"
                  placeholder="请输入手机号"></el-input>  --></el-form-item></el-col>
                <el-col :span="18">
                  <el-form-item label="配送地址:" prop="receiver.address">
                    {{
                      fullReceiverAddress
                    }}
                    <!--  <el-cascader size="large" :options="options" clearable :disabled="true" v-model="receiverOptions"
                  @change="receiverChange">
                </el-cascader>
                <el-input v-model="deliveryForms.receiver.address" size="medium" :disabled="true"
                  placeholder="请输入"></el-input> --> </el-form-item></el-col>
              </el-row>
            </div>
          </div>


          <!-- <el-divider></el-divider>
          <h3>商品信息:</h3>
          <el-table :data="product_list" border :cell-style="{ textAlign: 'center' }"
            :header-cell-style="{ textAlign: 'center' }" style="width: 100%">
            <el-table-column type="selection" width="40" align="center" />
            <el-table-column label="商品编号">
              <template slot-scope="scope">
                {{ scope.row.goods_vo.sn }}
              </template>
</el-table-column>
<el-table-column label="商品名称">
  <template slot-scope="scope">
                {{ scope.row.goods_vo.name }}
              </template>
</el-table-column>
<el-table-column label="sku">
  <template slot-scope="scope">
                {{ scope.row.product_vo.sku }}
              </template>
</el-table-column>
<el-table-column label="序列号" v-if="sn_code_list">
  <template slot-scope="scope">
                <span v-for="(item, index) in scope.row.sn_code_list" :key="item.id"><span v-if="index !== 0">，</span>{{
                  item.sn_code }}</span>
              </template>
</el-table-column>
<el-table-column label="规格型号">
  <template slot-scope="scope">
                {{ scope.row.product_vo.spec_name }}
              </template>
</el-table-column>
<el-table-column label="单位">
  <template slot-scope="scope">
                {{ scope.row.product_vo.unit }}
              </template>
</el-table-column>
<el-table-column label="订单数量">
  <template slot-scope="scope">
                {{ scope.row.num }}
              </template>
</el-table-column>
<el-table-column label="可用库存">
  <template slot-scope="scope">
                {{ scope.row.use_able_stock }}
              </template>
</el-table-column>
<el-table-column label="实际库存">
  <template slot-scope="scope">
                {{ scope.row.actual_stock }}
              </template>
</el-table-column>
</el-table> -->
          <el-divider></el-divider>
          <h3>商品明细</h3>
          <el-button class="button" size="mini" type="primary" @click="scanCode"
            v-if="deliveryForms.status == 'TO_BE_SEND'">扫码出库</el-button>
          <div style="width: 100%; display: block">
            <el-table border :data="goodsExchangeAddForm.product_list" :cell-style="{ textAlign: 'center' }"
              :header-cell-style="{ textAlign: 'center' }" style="width: 100%; margin-top: 20px">
              <el-table-column label="商品编号">
                <template slot-scope="scope">
                  <span>{{ scope.row.goods_vo.sn }}</span>
                </template>
              </el-table-column>
              <el-table-column label="商品名称">
                <template slot-scope="scope">
                  <span>{{ scope.row.goods_vo.name }}</span>
                </template>
              </el-table-column>
              <el-table-column label="sku">
                <template slot-scope="scope">
                  <span>{{ scope.row.product_vo.sku }}</span>
                </template>
              </el-table-column>
              <el-table-column label="库位号">
                <template slot-scope="scope">
                  <el-popover placement="right" trigger="click" v-if="scope.row.area_stock_list">
                    <div>
                      <p v-for="item in scope.row.area_stock_list" :key="item.id">{{ item.warehouse_area_name }}</p>
                    </div>
                    <span slot="reference" v-if="scope.row.area_stock_list.length!==0">{{ scope.row.area_stock_list[0].warehouse_area_name }}</span>
                  </el-popover>
                </template>
              </el-table-column>
              <el-table-column label="序列号" v-if="sn_code_list">
                <template slot-scope="scope">
                  <div class="sn-code-container">
                    <span v-for="item in scope.row.sn_code_list" :key="item.id">
                      <p>{{ item.sn_code }}</p>
                    </span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="product_vo.spec_name" label="规格型号">
              </el-table-column>
              <el-table-column label="单位">
                <template slot-scope="scope">
                  <span>{{ scope.row.product_vo.unit }}</span>
                </template>
              </el-table-column>
              <el-table-column label="出库数量">
                <template slot-scope="scope">
                  {{ scope.row.num }}
                  <!--  <el-input v-model="scope.row.out_num" type="number" :min="0" :maxlength="20"></el-input> -->
                </template>
              </el-table-column>
              <el-table-column label="订单数量">
                <template slot-scope="scope">
                  {{ scope.row.orderNum }}
                </template>
              </el-table-column>
              <el-table-column label="实际库存">
                <template slot-scope="scope">
                  <span>{{ scope.row.actual_stock }}</span>
                  <!-- <span>{{ scope.row.use_able_stock }}</span> -->
                </template>
              </el-table-column>
              <el-table-column width="200" label="操作" v-if="!disabledType">
                <template slot-scope="scope">
                  <!-- <el-button
                  size="mini"
                  @click="addSnCode(scope.row,scope.$index)"
                  >添加序列号</el-button
                > -->
                  <el-button size="mini" @click="
                    goodsExchangeAddForm.product_list.splice(scope.$index, 1)
                    ">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

          </div>

          <el-divider></el-divider>
          <h3></h3>
          <el-row>
            <el-col :span="8">
              <el-form-item label="物品总重量:" prop="total_weight">
                <el-input v-model.number="deliveryForms.total_weight" :minlength="1" :maxlength="20" type="number"
                  max="50" clearable :disabled="disabledType" placeholder="请输入物品总重量"><template
                    slot="append">KG</template></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="物品总体积:" prop="total_volume">
                <el-input v-model="deliveryForms.total_volume" :minlength="1" :maxlength="20" clearable
                  :disabled="disabledType" placeholder="请输入物品总体积"><template slot="append">m³</template></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="物品价格:" prop="declared_value">
                <el-input v-model="deliveryForms.declared_value" :minlength="1" :maxlength="20" clearable
                  :disabled="disabledType" placeholder="请输入物品价格"><template slot="append">元</template></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="备注:" prop="remark">
                <el-input v-model="deliveryForms.remark" type="textarea" clearable :disabled="disabledType"
                  :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入备注"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-divider></el-divider>
          <el-row :gutter="20" v-if="send_type !== 'EXPRESS_DELIVERY'">
            <el-col :span="8" :offset="6">
              <el-form-item label="物流单号:" prop="tracking_number" v-if="deliveryForms.send_type !== 'SELF_PICKUP'">
                <el-input v-model="kdnCode" :minlength="1" :maxlength="20" :disabled="true"
                  placeholder="请输入物流单号"></el-input>
                <el-button @click="obtainOrder" v-if="kdnCode == '' || kdnCode == undefined"
                  :disabled="btnType">获取单号</el-button>
              </el-form-item>
              <el-form-item label="自提单号:" prop="tracking_number" v-else>
                {{ deliveryForms.selfPickupNum }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" v-else>
            <el-col :span="8">
              <el-form-item label="快递公司:" prop="logistics_type">
                <el-select v-model="deliveryForms.logistics_type" clearable :disabled="disabledType">
                  <el-option v-for="(item, index) in expressList" :key="index" :label="item.name"
                    :value="item.code"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="物流单号:" prop="logistics_code">
                <el-input v-model="deliveryForms.logistics_code" :minlength="1" :maxlength="20" :disabled="disabledType"
                  placeholder="请输入物流单号"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="寄件人手机号:" prop="logistics_phone">
                <el-input v-model="deliveryForms.logistics_phone" :minlength="1" :maxlength="20"
                  :disabled="disabledType" placeholder="请输入寄件人手机号后四位"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div v-if="
        outType !== undefined &&
        (JSON.stringify(deliveryForms.create_order_fail) !== '{}' ||
          JSON.stringify(deliveryForms.create_order_success) !== '{}')
      ">
        <h3>物流状态:</h3>
        <div class="steps-wrap" v-if="JSON.stringify(deliveryForms.create_order_fail) !== '{}'">
          <el-steps class="steps" direction="vertical" process-status="finish">
            <el-step icon="el-icon-error" :title="deliveryForms.create_order_fail && deliveryForms.create_order_fail.orderStatus == 600
              ? '下单失败'
              : ''
              ">
              <div slot="description">
                <p class="row-remark">
                  {{ safeAccess(deliveryForms.create_order_fail, 'remark') }}
                </p>
                <div slot="description" v-if="deliveryForms.create_order_fail">
                  <p class="row-remark">
                    {{ deliveryForms.create_order_fail.remark }}
                  </p>
                  <p class="row-time" v-if="deliveryForms.create_order_fail.requestTime">
                    {{ (deliveryForms.create_order_fail.requestTime / 1000) | unixToDate }}
                  </p>
                </div>
              </div>
            </el-step>
          </el-steps>
        </div>
        <div class="steps-wrap" v-else>
          <el-steps class="steps" direction="vertical" process-status="finish" :active="activeStep">
            <el-step icon="el-icon-success"
              v-if="JSON.stringify(deliveryForms.sign_in) !== '{}' && deliveryForms.sign_in.orderStatus == 402"
              :title="deliveryForms.sign_in.orderStatus == 402 ? '退回' : ''">
              <div slot="description">
                <p class="row-remark">
                  订单号:{{ deliveryForms.create_order_success.orderCode }}
                </p>
                <p class="row-remark">
                  物流单号:{{ deliveryForms.create_order_success.channelOrderCode }}
                </p>
                <p class="row-remark">{{ deliveryForms.sign_in.remark }}</p>
                <p class="row-time">
                  {{ (deliveryForms.sign_in.requestTime / 1000) | unixToDate }}
                </p>
              </div>
            </el-step>
            <el-step icon="el-icon-success" v-if="JSON.stringify(deliveryForms.sign_in) !== '{}'"
              :title="deliveryForms.sign_in.orderStatus == 401 ? '签收' : ''">
              <div slot="description">
                <p class="row-remark">
                  订单号:{{ deliveryForms.create_order_success.orderCode }}
                </p>
                <p class="row-remark">
                  物流单号:{{ deliveryForms.create_order_success.channelOrderCode }}
                </p>
                <p class="row-remark">{{ deliveryForms.sign_in.remark }}</p>
                <p class="row-time">
                  {{ (deliveryForms.sign_in.requestTime / 1000) | unixToDate }}
                </p>
              </div>
            </el-step>
            <el-step icon="el-icon-success" v-if="JSON.stringify(deliveryForms.user_sending) !== '{}'" :title="deliveryForms.user_sending.orderStatus == 300 ? '配送中' : ''
              ">
              <div slot="description">
                <p class="row-remark">
                  订单号:{{ deliveryForms.create_order_success.orderCode }}
                </p>
                <p class="row-remark">
                  物流单号:{{ deliveryForms.create_order_success.channelOrderCode }}
                </p>
                <p class="row-remark">
                  快递员名称:{{ deliveryForms.user_arrives.courierInfo.courierName }}
                </p>
                <p class="row-remark">
                  快递员电话:{{ deliveryForms.user_arrives.courierInfo.courierMobile }}
                </p>
                <p class="row-remark">
                  {{ deliveryForms.user_sending.remark }}
                </p>
                <p class="row-time">
                  {{
                    (deliveryForms.user_sending.requestTime / 1000) | unixToDate
                  }}
                </p>
              </div>
            </el-step>
            <el-step icon="el-icon-success" v-if="JSON.stringify(deliveryForms.user_arrives) !== '{}'" :title="deliveryForms.user_arrives.orderStatus == 202 ? '已到店' : ''
              ">
              <div slot="description">
                <p class="row-remark">
                  订单号:{{ deliveryForms.create_order_success.orderCode }}
                </p>
                <p class="row-remark">
                  物流单号:{{ deliveryForms.create_order_success.channelOrderCode }}
                </p>
                <p class="row-remark">
                  {{ deliveryForms.user_arrives.remark }}
                </p>
                <p class="row-remark">
                  快递员名称:{{ deliveryForms.user_arrives.courierInfo.courierName }}
                </p>
                <p class="row-remark">
                  快递员电话:{{ deliveryForms.user_arrives.courierInfo.courierMobile }}
                </p>
                <p class="row-time">
                  {{
                    (deliveryForms.user_arrives.requestTime / 1000) | unixToDate
                  }}
                </p>
              </div>
            </el-step>
            <el-step icon="el-icon-success" v-if="JSON.stringify(deliveryForms.user_take_order) !== '{}'" :title="deliveryForms.user_take_order.orderStatus == 201 ? '已接单' : ''
              ">
              <div slot="description">
                <p class="row-remark">
                  订单号:{{ deliveryForms.create_order_success.orderCode }}
                </p>
                <p class="row-remark">
                  物流单号:{{ deliveryForms.create_order_success.channelOrderCode }}
                </p>
                <p class="row-remark">
                  {{ deliveryForms.user_take_order.remark }}
                </p>
                <p class="row-time">
                  {{
                    (deliveryForms.user_take_order.requestTime / 1000)
                    | unixToDate
                  }}
                </p>
              </div>
            </el-step>
            <el-step icon="el-icon-success" v-if="JSON.stringify(deliveryForms.create_order_success) !== '{}'" :title="deliveryForms.create_order_success.orderStatus == 100
              ? '待接单'
              : ''
              ">
              <div slot="description">
                <p class="row-remark">
                  订单号:{{ deliveryForms.create_order_success.orderCode }}
                </p>
                <p class="row-remark">
                  物流单号:{{ deliveryForms.create_order_success.channelOrderCode }}
                </p>
                <p class="row-remark">
                  {{ deliveryForms.create_order_success.remark }}
                </p>
                <p class="row-time">
                  {{
                    (deliveryForms.create_order_success.requestTime / 1000)
                    | unixToDate
                  }}
                </p>
              </div>
            </el-step>
            <el-step icon="el-icon-success" v-if="JSON.stringify(deliveryForms.cancel_order_kdn) !== '{}'" :title="deliveryForms.create_order_success.orderStatus == 500
              ? '拒绝接单'
              : ''
              ">
              <div slot="description">
                <p class="row-remark">
                  订单号:{{ deliveryForms.create_order_success.orderCode }}
                </p>
                <p class="row-remark">
                  物流单号:{{ deliveryForms.create_order_success.channelOrderCode }}
                </p>
                <p class="row-remark">
                  {{ deliveryForms.create_order_success.remark }}
                </p>
                <p class="row-time">
                  {{
                    (deliveryForms.create_order_success.requestTime / 1000)
                    | unixToDate
                  }}
                </p>
              </div>
            </el-step>
          </el-steps>
        </div>
      </div>
      <div v-if="send_type == 'EXPRESS_DELIVERY' && logistics.length !== 0">
        <h3>快递状态:</h3>
        <el-timeline :reverse="reverse">
          <el-timeline-item v-for="(activity, index) in logistics" :key="index" :timestamp="activity.AcceptTime">
            {{ activity.AcceptStation }}
          </el-timeline-item>
        </el-timeline>
      </div>
      <el-dialog title="扫码出库" :visible.sync="scanDialogVisible" width="30%" :close-on-click-modal="false">
        <el-form ref="scanGoodsForm" :model="scanGoodsForm" inline>
          <el-form-item label="sku" prop="bar_code">
            <el-input v-model="scanGoodsForm.bar_code" ref="input" @keyup.enter.native="toSearch()" :minlength="0"
              :maxlength="100"></el-input>
          </el-form-item>
          <el-form-item label="序列号" prop="sn_code">
            <el-input v-model="sn_code" ref="sn_input" @keyup.enter.native="toSnCode()" :minlength="0"
              :maxlength="100"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <!-- <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleRejectGoodsExchange()">确 定</el-button> -->
        </span>
      </el-dialog>
      <!--  <el-divider></el-divider>
      <el-form
        :model="deliveryForms"
        ref="deliveryForms"
        label-width="120px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="出库单号:" prop="name">
              <el-select v-model="deliveryForms.sn">

              </el-select>

            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单编号:" prop="sn">
              <el-select v-model="deliveryForms.order_sn_list">

              </el-select>
            </el-form-item></el-col
          >
          <el-col :span="12">
            <el-form-item label="配送方式:" prop="category_id">
              <el-select>

              </el-select>
            </el-form-item></el-col
          >
          <el-col :span="12">
            <el-form-item label="配送仓库:" prop="freight_price">
              <el-select>

              </el-select>
            </el-form-item></el-col
          >
          <el-col :span="12">
            <el-form-item label="物流公司:" prop="logistics_company_id">
              <el-select v-model="deliveryForms.logistics_company_id">

              </el-select>
            </el-form-item></el-col
          >
          <el-col :span="8" >
            <el-form-item label="配送地址" prop="address">
              <el-input
                v-model="deliveryForms.address"
                :minlength="1"
                :maxlength="20"
                clearable
                placeholder="请输入提货人"
              ></el-input>
              </el-form-item
          ></el-col>
        </el-row>
          <el-row  :gutter="20">
              <el-col :span="8" :offset="6">
              <el-form-item label="物流单号:" prop="tracking_number">
                <el-input
                  v-model="tracking_number"
                  :minlength="1"
                  :maxlength="20"
                  clearable
                  placeholder="请输入物流单号"
                ></el-input>
                <el-button>自动获取单号</el-button>
                </el-form-item
            ></el-col>
          </el-row>
      </el-form> -->
      <div class="footer" v-if="send_type !== 'EXPRESS_DELIVERY'">
        <!-- <el-button type="primary"> 获取全部单号 </el-button> -->
        <el-button type="primary" @click="saveErpWarehouseOut" :disabled="outType == 'check'"
          v-if="kdnCode !== '' || deliveryForms.send_type == 'SELF_PICKUP'">发货
        </el-button>
        <el-button @click="roBack2()">保存</el-button>
      </div>
      <div class="footer" v-else>
        <!-- <el-button type="primary"> 获取全部单号 </el-button> -->
        <el-button type="primary" @click="saveDelivery" :disabled="outType == 'check'">发货
        </el-button>
        <el-button @click="roBack2()">保存</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import * as API_BasicSetting from "@/api/basicSetting";
import * as API_order from "@/api/order";
import * as API_Setting from "@/api/setting";
import * as API_Auth from "@/api/auth";
import { RegExp } from "~/ui-utils";
import * as API_GoodsExchange from "@/api/goodsExchange";
import * as API_Express from '@/api/express'
import { Foundation } from "~/ui-utils";
import {
  provinceAndCityData,
  pcTextArr,
  regionData,
  pcaTextArr,
  codeToText,
} from "element-china-area-data";
import { mapGetters } from "vuex";

export default {
  name: "orderOutbound",
  data() {
    return {
      reverse: true,
      btnType: false,
      disabledType: false,
      // 列表loading状态
      loading: false,
      appointmentList: [
        {
          label: "立即单",
          value: 0,
        },
        {
          label: "预约上门",
          value: 1,
        },
      ],
      deptList: [],
      orderIds: "",
      orderOutboundInfo: {
        warehouse_consignee_id: "",
      },
      id: "",
      adminList: [],
      kdnCode: "",
      deliveryForms: {
        logistics_type: "",
        logistics_code: "",
        logistics_phone: "",
        send_type: '',
        selfPickupNum: '',
        remark: "",
        declared_value: "",
        total_volume: "",
        appointment_type: 0,
        total_weight: "",
        status: '',
        //发货人
        sender: {
          name: "",
          phone: "",
          address: "",
        },
        //收货人
        receiver: {
          name: "",
          phone: "",
          address: "",
        },
        //商品信息列表
        goods_list: [],
      },
      product_list: [],
      options: regionData,
      selectedOptions: [],
      receiverOptions: [],
      rules: {
        appointment_type: [
          { required: true, message: "请选择预约类型", trigger: "change" },
        ],
        appointment_time: [
          { required: true, message: "请选择上门时间", trigger: "blur" },
        ],
        logistics_type: [
          { required: true, message: "请选择快递公司", trigger: "change" },
        ],
        logistics_code: [
          { required: true, message: "请选填写快递单号", trigger: "blur" },
        ],
        logistics_phone: [
          { required: true, message: "请选输入寄件人手机号后四位", trigger: "blur" },
        ],
        sender: {
          name: [
            { required: true, message: "请输入发货人姓名", trigger: "blur" },
          ],

          phone: [
            this.MixinRequired("请输入手机号码！"),
            {
              validator: (rule, value, callback) => {
                if (!RegExp.mobile.test(value)) {
                  callback(new Error("手机号码格式有误！"));
                } else {
                  callback();
                }
              },
              trigger: ["change", "blur"],
            },
          ],
        },
        receiver: {
          name: [
            { required: true, message: "请输入收货人姓名", trigger: "blur" },
          ],
          phone: [
            this.MixinRequired("请输入手机号码！"),
            {
              validator: (rule, value, callback) => {
                if (!RegExp.mobile.test(value)) {
                  callback(new Error("手机号码格式有误！"));
                } else {
                  callback();
                }
              },
              trigger: ["change", "blur"],
            },
          ],
        },
        total_weight: [
          { required: true, message: "请输入物品总重量", trigger: "blur" },
          /**/ {
            type: "number",
            min: 0,
            max: 50,
            message: "物品总重量不能超过50kg",
            trigger: "blur",
          },
        ],
        total_volume: [
          { required: true, message: "请输入物品总体积", trigger: "blur" },
        ],
        declared_value: [
          { required: true, message: "请输入物品价格", trigger: "blur" },
        ],
      },
      outType: "",
      send_address: "",
      receive_address: "",
      detailData: [], // 物流详情
      /* nameToCodeMap:{} */
      sn_code: "",
      sku: "",
      sn_code_list: [],
      index: "",
      scanDialogVisible: false,
      goodsExchangeAddForm: {
        product_list: [],
        type: "",
      },
      scanGoodsForm: {},
      send_type: '',
      expressList: [],//物流公司列表
      logistics: [],
    };
  },
  watch: {
    $route: {
      immediate: true,
      handler(newVal) {
        if (this.$route.name === "orderOutboundAdd") {
          /* this.id = this.$route.params.id;
          this.GET_WarehouseOutDetail(); */
        } else {
          this.orderIds = this.$route.params.orderIds;
          /* this.GET_WarehouseOutPreview(); */
        }
      },
    },
  },
  computed: {
    ...mapGetters(["user"]),

    activeStep() {
      // 定义步骤数组，每个元素对应一个步骤的条件
      const steps = [
        this.deliveryForms.sign_in && this.deliveryForms.sign_in.orderStatus === 402,
        this.deliveryForms.sign_in && this.deliveryForms.sign_in.orderStatus === 401,
        this.deliveryForms.user_sending && this.deliveryForms.user_sending.orderStatus === 300,
        this.deliveryForms.user_arrives && this.deliveryForms.user_arrives.orderStatus === 202,
        this.deliveryForms.user_take_order && this.deliveryForms.user_take_order.orderStatus === 201,
        this.deliveryForms.create_order_success && this.deliveryForms.create_order_success.orderStatus === 100
      ];

      // 找出最后一个为真的步骤的索引
      for (let i = steps.length - 1; i >= 0; i--) {
        if (steps[i]) return i;
      }

      // 如果没有任何步骤是激活的，返回-1或者你可以选择返回0显示第一步
      return -1;
    },
    fullSenderAddress() {
      console.log(this.deliveryForms.sender);
      const { province_name, city_name, area_name, address } = this.deliveryForms.sender;
      return [province_name, city_name, area_name, address].filter(Boolean).join("");
    },
    fullReceiverAddress() {
      console.log(this.deliveryForms.receiver);
      const { province_name, city_name, area_name, address } = this.deliveryForms.receiver;
      return [province_name, city_name, area_name, address].filter(Boolean).join("");
    }
  },
  mounted() {
    /**/ this.id = this.$route.params.id;
    this.send_type = this.$route.params.send_type
    this.GET_WarehouseOutDetail();
    this.GET_AdministratorList();
    this.GET_ExpressList()
    this.outType = this.$route.params.type;
    /* this.generateMap(regionData); */
  },
  methods: {
    /* 扫sku */
    toSearch() {
      API_GoodsExchange.getProduct(
        this.deliveryForms.warehouse_id,
        this.scanGoodsForm.bar_code.replace(/\s+/g, '')
      ).then((res) => {
        res.sn_code_list = []
        this.sku = res.product_vo.sku;
        // 查找当前商品是否已存在于列表中
        const indexs = this.goodsExchangeAddForm.product_list.findIndex((el) => {
          return (
            el.goods_id === res.goods_id &&
            el.product_id === res.product_id &&
            el.product_vo.sku === res.product_vo.sku
          );
        });
        // 如果商品不存在，则添加到列表
        if (indexs === -1) {
          // 检查是否有相同商品在product_list中
          const existingProduct = this.product_list.find(el => (
            el.goods_id === res.goods_id &&
            el.product_id === res.product_id &&
            el.product_vo.sku === res.product_vo.sku
          ));

          if (!existingProduct) {
            this.$message.error('订单内没有该商品，请重新录入');
            this.$nextTick(() => {
              this.$refs.input.focus();
            });
            return; // 退出函数，不继续执行
          }
          this.index = this.goodsExchangeAddForm.product_list.length
          this.goodsExchangeAddForm.product_list.push(res);
        } else {
          this.index = indexs
        }
        if (res.product_vo.have_sn) {
          this.$nextTick(() => {
            this.$refs.sn_input.focus();
          });
        } else {
          if (this.goodsExchangeAddForm.product_list[this.index].num >= this.goodsExchangeAddForm.product_list[this.index].orderNum) return this.$message.warning('录入完成,请录入下一条!')
          this.goodsExchangeAddForm.product_list[this.index].num += 1
          /*  this.scanDialogVisible = false; */
        }
      });
    },
    // 扫码出库
    scanCode() {
      this.scanDialogVisible = true;
      this.$nextTick(() => {
        this.$refs.input.focus();
      });
    },
    //扫序列号goodsExchangeAddForm.product_list[this.index].sn_code_list
    toSnCode() {
      if (this.sku == '') return this.$message.error('请录入正确的sku')
      API_GoodsExchange.getSnCode("out", this.sku, this.sn_code.replace(/\s+/g, '')).then((res) => {
        this.sn_code = "";
        // 假设res是一个对象，我们根据res的某个属性（如sn）来检查重复
        let exists = this.goodsExchangeAddForm.product_list[
          this.index
        ].sn_code_list.find(
          (item) => item.sn_code === res.sn_code && item.sku === res.sku
        );
        if (!exists) {
          API_GoodsExchange.skuRedis({
            send_order_id: this.id, item_id: this.goodsExchangeAddForm.product_list[
              this.index
            ].id, sku: res
          }).then(response => {
            this.goodsExchangeAddForm.product_list[this.index].sn_code_list.push(
              res
            );
          })
        }
        this.goodsExchangeAddForm.product_list[this.index].num = this.goodsExchangeAddForm.product_list[this.index].sn_code_list.length
        const indexs = this.product_list.findIndex((el) => {
          return (
            el.goods_id === res.goods_id &&
            el.product_id === res.product_id &&
            el.product_vo.sku === res.sku
          );
        });
        this.goodsExchangeAddForm.product_list[this.index].id = this.product_list[indexs].id
        if (this.goodsExchangeAddForm.product_list[this.index].num == this.product_list[indexs].num) {
          this.scanGoodsForm.bar_code = "";
          return this.$message.warning('录入完成,请录入下一条!')
          /*  this.scanDialogVisible = false; */
        } else {
          this.scanGoodsForm.bar_code = "";
          this.$nextTick(() => {
            this.$refs.input.focus();
          });
        }

      });
    },
    addSnCode(row, index) {
      this.sku = row.product_vo.sku;
      this.index = index;
      this.snCodeVisible = true;
    },


    safeAccess(obj, key) {
      return obj ? obj[key] : '';
    },
    /* 收获地址 */
    receiverChange(val) {
      this.deliveryForms.receiver.province_name =
        codeToText[this.receiverOptions[0]];
      this.deliveryForms.receiver.city_name =
        codeToText[this.receiverOptions[1]];
      this.deliveryForms.receiver.area_name =
        codeToText[this.receiverOptions[2]];
      this.receive_address = val.join(",");
    },
    /* 发货地址 */
    sendHandleChange(val) {
      this.deliveryForms.sender.province_name =
        codeToText[this.selectedOptions[0]];
      this.deliveryForms.sender.city_name = codeToText[this.selectedOptions[1]];
      this.deliveryForms.sender.area_name = codeToText[this.selectedOptions[2]];
      this.send_address = val.join(",");
    },

    obtainOrder() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          this.btnType = true;
          const params = this.MixinClone(this.deliveryForms);
          if (params.receiver.city_name === '市辖区') {
            params.receiver.city_name = params.receiver.province_name;
          }
          if (params.sender.city_name === '市辖区') {
            params.sender.city_name = params.sender.province_name;
          }
          //发货详细地址
          params.receiver.province_city_area_address =
            params.receiver.province_name +
            params.receiver.city_name +
            params.receiver.area_name +
            params.receiver.address;
          //收货详细地址
          params.sender.province_city_area_address =
            params.sender.province_name +
            params.sender.city_name +
            params.sender.area_name +
            params.sender.address;
          //商品信息
          const item = {};
          this.product_list.map((el) => {
            item.goods_name = el.goods_vo.name;
            /* item.goods_price = el.product_vo.price; */
            item.quantity = el.orderNum;
            item.unit = el.product_vo.unit;
            return params.goods_list.push(item);
          });
          params.goods_num = this.product_list.reduce(
            (sum, e) => sum + Number(e.orderNum || 0),
            0
          );
          params.total_weight = Number(params.total_weight);
          params.total_volume = Number(params.total_volume);
          params.declared_value = Number(params.declared_value);
          //地址
          params.send_address = this.send_address;
          params.receive_address = this.receive_address;
          params.order_code = this.id;
          API_order.getKdShip(this.id, params).then((res) => {
            this.kdnCode = res;
            this.btnType = false;
          }).catch(() => { this.btnType = false; })
        } else {
          this.$message.error("表单填写有误，请检查")
          return false;
        }
      });
    },

    //获取地址
    handleChange(value) { },
    /** 获取人员列表 */
    GET_AdministratorList() {
      API_Auth.getAdministratorList({
        page_no: 1,
        page_size: 9999,
        user_state: 0,
      }).then((response) => {
        this.adminList = response.data;
      });
    },
    //发货
    saveErpWarehouseOut() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          this.btnType = true;
          const params = this.MixinClone(this.deliveryForms);
          //发货详细地址
          params.receiver.province_city_area_address =
            params.receiver.province_name +
            params.receiver.city_name +
            params.receiver.area_name +
            params.receiver.address;
          //收货详细地址
          params.sender.province_city_area_address =
            params.sender.province_name +
            params.sender.city_name +
            params.sender.area_name +
            params.sender.address;
          //商品信息
          const item = {};
          this.product_list.map((el) => {
            item.goods_name = el.goods_vo.name;
            /* item.goods_price = el.product_vo.price; */
            item.quantity = el.num;
            item.unit = el.product_vo.unit;
            return params.goods_list.push(item);
          });
          params.goods_num = this.product_list.reduce(
            (sum, e) => sum + Number(e.orderNum || 0),
            0
          );
          params.total_weight = Number(params.total_weight);
          params.total_volume = Number(params.total_volume);
          params.declared_value = Number(params.declared_value);
          //地址
          params.send_address = this.send_address;
          params.receive_address = this.receive_address;
          params.order_code = this.id;
          if (this.goodsExchangeAddForm.product_list.length == 0) {
            return this.$message.error("请录入出库商品")
          }
          params.order_item_vos = this.goodsExchangeAddForm.product_list
          API_order.outOrderSend(this.id, params).then((res) => {
            this.$router.push({ name: "sendOrder" });
          });
        } else {
          console.log(this.deliveryForms);
          this.$message.error("表单填写有误，请检查")
          return false;
        }
      });
    },
    //快递发货
    saveDelivery() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          this.btnType = true;
          const params = this.MixinClone(this.deliveryForms);
          //发货详细地址
          params.receiver.province_city_area_address =
            params.receiver.province_name +
            params.receiver.city_name +
            params.receiver.area_name +
            params.receiver.address;
          //收货详细地址
          params.sender.province_city_area_address =
            params.sender.province_name +
            params.sender.city_name +
            params.sender.area_name +
            params.sender.address;
          //商品信息
          const item = {};
          this.product_list.map((el) => {
            item.goods_name = el.goods_vo.name;
            /* item.goods_price = el.product_vo.price; */
            item.quantity = el.num;
            item.unit = el.product_vo.unit;
            return params.goods_list.push(item);
          });
          params.goods_num = this.product_list.reduce(
            (sum, e) => sum + Number(e.orderNum || 0),
            0
          );
          params.total_weight = Number(params.total_weight);
          params.total_volume = Number(params.total_volume);
          params.declared_value = Number(params.declared_value);
          //地址
          params.send_address = this.send_address;
          params.receive_address = this.receive_address;
          params.order_code = this.id;
          if (this.goodsExchangeAddForm.product_list.length == 0) {
            return this.$message.error("请录入出库商品")
          }
          params.order_item_vos = this.goodsExchangeAddForm.product_list
          API_order.outOrderSend(this.id, params).then((res) => {
            this.$router.push({ name: "sendOrder" });
          });
          API_order.queryLogistics({ shipper_code: params.logistics_type, logistic_code: params.logistics_code, customer_name: params.logistics_phone }).then(res => {
          })
        } else {
          console.log(this.deliveryForms);
          this.$message.error("表单填写有误，请检查")
          return false;
        }
      });
    },
    // 选择批次
    async handleSelectWarehouseEntryBatch(items) {
      const goodsData = await this.$EnwarehouseEntryBatch({
        goodsApi: "admin/erp/warehouseEntryBatch",
        selectedIds: items.batch_list
          ? items.batch_list.map((item) => item.id)
          : [],
        purchasePlanApiParams: {
          warehouse_id: this.orderOutboundInfo.warehouse_id,
          product_id: items.product_id,
        },
        showWarehouseSearch: false,
      });
      items.batch_list = goodsData.purchasePlans.map((item) => {
        item.batch_id = item.id;
        item.batch_sn = item.sn;
        return item;
      });
    },
    roBack2() {
      this.btnType = true;
      const params = this.MixinClone(this.deliveryForms);
      //发货详细地址
      params.receiver.province_city_area_address =
        params.receiver.province_name +
        params.receiver.city_name +
        params.receiver.area_name +
        params.receiver.address;
      //收货详细地址
      params.sender.province_city_area_address =
        params.sender.province_name +
        params.sender.city_name +
        params.sender.area_name +
        params.sender.address;
      //商品信息
      const item = {};
      this.product_list.map((el) => {
        item.goods_name = el.goods_vo.name;
        /* item.goods_price = el.product_vo.price; */
        item.quantity = el.num;
        item.unit = el.product_vo.unit;
        return params.goods_list.push(item);
      });
      params.goods_num = this.product_list.reduce(
        (sum, e) => sum + Number(e.num || 0),
        0
      );
      params.total_weight = Number(params.total_weight);
      params.total_volume = Number(params.total_volume);
      params.declared_value = Number(params.declared_value);
      //地址
      params.send_address = this.send_address;
      params.receive_address = this.receive_address;
      params.order_code = this.id;
      params.order_item_vos = this.goodsExchangeAddForm.product_list
      API_order.saveOrderSend(this.id, params).then((res) => {
        this.$router.push({ name: "sendOrder" });
      });
      /*  const { callback } = this.$route.params;
       if (typeof callback === "function") callback();
       this.$store.dispatch("delCurrentViews", {
         view: this.$route,
         $router: this.$router,
       });
       this.$router.push({ name: "warehouseOut" }); */


    },
    roBack() {
      const { callback } = this.$route.params;
      if (typeof callback === "function") callback();
      this.$store.dispatch("delCurrentViews", {
        view: this.$route,
        $router: this.$router,
      });
      this.$router.push({ name: "order" });
    },
    /** 获取发货单详情*/
    GET_WarehouseOutDetail() {
      API_order.getSendOrderDetail(this.id).then((res) => {
        res.product_list = res.order_item_vos;
        this.product_list = res.order_item_vos;
        this.deliveryForms.send_type = res.order_vo.send_type
        this.deliveryForms.selfPickupNum = res.self_pickup_num
        if (res.warehouse_vo && res.warehouse_vo.ware_pro_city_area) {
          this.selectedOptions = res.warehouse_vo.ware_pro_city_area.split(",");
        }
        if (res.order_vo && res.order_vo.province_city_area) {
          this.receiverOptions = res.order_vo.province_city_area.split(",");
        }
        if (this.outType !== undefined || res.kdn_order_code !== undefined) {
          this.goodsExchangeAddForm.product_list = res.order_item_vos
          this.disabledType = true;
          this.deliveryForms.appointment_type = res.appointment_type;
          this.deliveryForms.appointment_time = res.appointment_time;
          this.deliveryForms.sender.name = res.sender_name;
          this.deliveryForms.sender.phone = res.sender_phone;
          this.deliveryForms.sender.address = res.sender_address;
          this.deliveryForms.receiver.name = res.receiver_name;
          this.deliveryForms.receiver.phone = res.receiver_phone;
          this.deliveryForms.receiver.address = res.receiver_address;
          this.deliveryForms.total_volume = res.total_volume;
          this.deliveryForms.declared_value = res.order_vo.real_price;
          this.deliveryForms.remark = res.remark;
          this.kdnCode = res.kdn_order_code;
          if (
            JSON.stringify(res.create_order_fail) == "{}" ||
            JSON.stringify(res.create_order_success) == "{}" ||
            JSON.stringify(res.user_take_order) == "{}" ||
            JSON.stringify(res.user_arrives) == "{}" ||
            JSON.stringify(res.user_sending) == "{}" ||
            JSON.stringify(res.order_fee) == "{}" ||
            JSON.stringify(res.sign_in) == "{}"
          ) {
            this.deliveryForms.sign_in = res.sign_in;
            this.deliveryForms.create_order_fail = res.create_order_fail;
            this.deliveryForms.create_order_success = res.create_order_success;
            this.deliveryForms.user_take_order = res.user_take_order;
            this.deliveryForms.user_arrives = res.user_arrives;
            this.deliveryForms.user_sending = res.user_sending;
            this.deliveryForms.order_fee = res.order_fee;
          }
        } else {
          const params = this.deliveryForms
          params.sender.name = res.warehouse_vo.user_name;
          params.sender.phone = res.warehouse_vo.phone;
          //this.selectedOptions = res.warehouse_vo.ware_pro_city_area.split(",")
          params.sender.province_name =
            codeToText[this.selectedOptions[0]];
          params.sender.city_name = codeToText[this.selectedOptions[1]];
          params.sender.area_name = codeToText[this.selectedOptions[2]];
          params.sender.address = res.warehouse_vo.warehouse_address;
          params.receiver.name = res.order_vo.customer_name;
          params.receiver.phone = res.order_vo.customer_phone;
          //this.receiverOptions = res.order_vo.province_city_area.split(",");
          params.receiver.province_name =
            codeToText[this.receiverOptions[0]];
          params.receiver.city_name =
            codeToText[this.receiverOptions[1]];
          params.receiver.area_name =
            codeToText[this.receiverOptions[2]];
          params.receiver.address = res.order_vo.address;

        }
        /* 获取缓存数据 */
        API_GoodsExchange.skuRedis({ send_order_id: this.id, type: 'enter' }).then(response => {
          res.order_item_vos.map((el) => {
            el.orderNum = el.num
            if (res.kdn_order_code == undefined || res.kdn_order_code == '') {
              el.num = 0
            }
            Object.keys(response).map(item => {
              if (el.id == item) {
                el.sn_code_list = response[item]
                el.num = el.sn_code_list.length
              }
            })
            if (!el.sn_code_list) {
              el.sn_code_list = []
            } else {
              el.num = el.sn_code_list.length
            }
            this.deliveryForms.total_weight = Number(
              el.product_vo.weight * el.num
            );
            console.log(el.orderNum);
          });
        })
        this.deliveryForms.status = res.status
        this.deliveryForms.warehouse_id = res.warehouse_id
        this.deliveryForms.declared_value = Number(res.order_vo.real_price);
        this.goodsExchangeAddForm.product_list = res.order_item_vos
        if (this.send_type == 'EXPRESS_DELIVERY') {
          this.deliveryForms.logistics_type = res.logistics_type
          this.deliveryForms.logistics_code = res.logistics_code
          this.deliveryForms.logistics_phone = res.logistics_phone
        }
        if (this.send_type == 'EXPRESS_DELIVERY' && res.logistics.length !== 0) {
          this.logistics = res.logistics
        }
      });
    },
    /** 出库前预览 */
    GET_WarehouseOutPreview() {
      API_order.getWarehouseOutPreview({ order_id_list: this.orderIds }).then(
        (response) => {
          this.dept_id = response.dept_id;
          this.orderOutboundInfo = response;
          this.orderOutboundInfo.out_time = new Date().getTime();
          this.$set(
            this.orderOutboundInfo,
            "warehouse_consignee_id",
            this.user.uid
          );
        }
      );
    },
    /** 获取物流公司列表 */
    GET_ExpressList() {
      API_Express.getExpressList(this.params).then(response => {
        this.expressList = response.data
      })
    }
  },
};
</script>
<style type="text/scss" lang="scss" scoped>
/deep/.el-card {
  margin-top: 30px;
}

.el-row {
  // border-bottom: 1px solid #ebeef5;
  position: relative;
}

.el-col {
  position: relative;

  &:not(:first-child)::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    // width: 1px;
    height: 100%;
    background-color: #ebeef5;
  }
}

/deep/ .el-card__body {
  margin: 10px;
  padding: 0;
  border: 1px solid #ebeef5;
  border-bottom: 0;
  font-size: 12px;
}

.bg-in {
  background-color: #fff;
  margin: 10px;
  padding: 20px 55px 55px;
}

.flex {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 20px;

  div {
    flex: 1;
    color: #909399;
    font-size: 15px;
  }
}

.font {
  color: #606266;
  padding: 0 12px 0 0;
}

.order-item {
  margin-top: 30px;
}

.sn-code-container {
  max-height: 100px;
  /* 设置最大高度，超过这个高度将显示滚动条 */
  overflow-y: auto;
  /* 垂直方向上溢出时显示滚动条 */
}

.footer {
  width: 100%;
  padding: 10px;
  bottom: 0px;
  text-align: center;
  z-index: 999;
  margin-top: 30px;
}

.el-form-item {
  margin-bottom: 15px
}

/deep/ .el-form-item__content {
  display: flex;
  align-items: center;

  .el-input {
    width: 300px;
  }
}

/* 覆盖步骤条的数字为圆点 */
/deep/.el-steps__icon {
  background-color: #409eff;
  /* 蓝色背景 */
  color: #409eff;
  /* 蓝色文字，与背景同色，使数字不可见 */
}

/* 调整圆点的大小 */
/deep/.el-steps__icon-inner {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: white;
  /* 白色圆点 */
  transform: translate(-50%, -50%);
  position: absolute;
  top: 50%;
  left: 50%;
}

/deep/.el-divider--horizontal {
  margin: 15px 0;
}
</style>
