<template>
  <view>
    <view class="cu-bar bg-white search">
      <view class="search-form round">
        <scanlistener
        v-if="showScanlistener"
        suffixIcon="scan"
        :placeholder="$t('请扫描条形码')"
        v-model="keyword"
        @iconClick="scanCode"
        @confirm="search"
        @submit="keyword=$event; search()"
        style="width: 100%"
        ></scanlistener>
      </view>
    </view>

    <view class="bg-white">
      <form>
        <view class="cu-form-group">
          <view class="title">{{$t('国家')}}:</view>
          <picker @change="selectCountry" :value="countrySelected" :range="countryList">
            <view class="picker">{{ countryList[countrySelected] }}</view>
          </picker>
        </view>
        <view class="cu-form-group">
          <view class="title">{{$t('目的地')}}:</view>
          <picker @change="selectDestination" :value="destinationSelected" :range="destinationList">
            <view class="picker">{{ destinationList[destinationSelected] }}</view>
          </picker>
        </view>
        <view class="cu-form-group">
          <view class="title">{{$t('出货渠道')}}:</view>
          <picker @change="selectChannel" :value="channelSelected" :range="channelList">
            <view class="picker">{{ channelList[channelSelected] }}</view>
          </picker>
        </view>
        <view class="cu-form-group">
          <view class="title">{{$t('备案')}}:</view>
          <picker @change="selectRecord" :value="productRecord" :range="recordList" :range-key="isChinese ? 'label' : 'labelEn'">
            <view class="picker">{{ recordList[productRecord] ? (isChinese ?  recordList[productRecord].label : recordList[productRecord].labelEn) : "" }}</view>
          </picker>
        </view>
        <view class="cu-form-group">
          <view class="title">{{$t('品名')}}:</view>
          <input class="text-right" :placeholder="$t('品名')" v-model="itemName" />
        </view>
        <view class="cu-form-group">
          <view class="title">{{$t('箱数')}}:</view>
          <input class="text-right" :placeholder="$t('箱数')" type="number" v-model="num" />
        </view>
        <view class="cu-form-group">
          <view class="title">{{$t('方数')}}:</view>
          <input class="text-right" :placeholder="$t('方数')" type="digit" v-model="volume" />
        </view>
        <view class="cu-form-group">
          <view class="title">{{$t('重量')}}:</view>
          <input class="text-right" :placeholder="$t('重量')" type="digit" v-model="weight" />
        </view>
        <view class="cu-form-group">
          <view class="title">{{$t('入仓时间')}}:</view>
        </view>
        <view class="cu-form-group no-border">
          <uni-datetime-picker type="date" :border=false :value="rucangTimeStart" @change="selectBeginDate" :placeholder="$t('开始时间')">
          </uni-datetime-picker>
          <uni-datetime-picker type="date" :border=false :value="rucangTimeEnd" @change="selectEndDate" :placeholder="$t('结束时间')">
          </uni-datetime-picker>
        </view>
        <view class="padding-sm top-line">
          <button class="cu-btn block bg-blue margin-tb-sm lg" @click="search">{{$t('搜索')}}</button>
        </view>
      </form>
    </view>

    <view v-for="(order, orderKey) in orderList" :key="'order-' + orderKey">
      <view class="cu-bar bg-white solid-bottom margin-top">
        <view class="action">
          <text class="text-bold text-black">{{$t('订单号')}}：</text>
          <text>{{ order.orderNo }}</text>
        </view>
        <view class="action">
          <!-- <template v-if="order.transfer_status == 1 && order.transfer_order">
            <button class="cu-btn bg-red" @tap="transferWarehousesShow(true, order.id,order)" :disabled="order.pre_no_status==1">预装</button>
          </template>
          <template v-else>
            <button class="cu-btn bg-red" @tap="showPatchTo(true, order.id,order)" data-target="gridModal" :disabled="order.pre_no_status==1">预装</button>
          </template> -->
          <button class="cu-btn bg-blue" @tap="preload(order)" data-target="gridModal" :disabled="order.status === 11">{{$t('预装')}}</button>
        </view>
      </view>
      <!-- <view class="pre_tips solid-bottom" v-if="order.pre_tips">
        {{ order.pre_tips }}
      </view> -->
      <view class="cu-list menu bottom-line">
        <view class="cu-item">
          <view class="content">
            <text>{{$t('唛头')}}：</text>
            <text>{{ order.marks }}</text>
          </view>
          <view class="content">
            <text>{{$t('出货渠道')}}：</text>
            <text>{{ showChannelName(order.channelId) }}</text>
          </view>
        </view>
        <view class="cu-item">
          <view class="content">
            <text>{{$t('可出特性')}}：</text>
            <text>{{ order.attrNameList ? order.attrNameList.filter(v => v).join(',') : '' }}</text>
          </view>
        </view>
      </view>
      <!--231119要求增加清关和始发仓 https://zentao.test.jdshangmen.com/bug-view-5347.html-->
      <view class="cu-list menu bottom-line" style="margin-top: 0;">
        <view class="cu-item">
          <view class="content">
            <text>{{$t('入仓时间')}}：</text>
            <text>{{ formatDate(order.rucangTime) }}</text>
          </view>
          <view class="content">
            <text>{{$t('清关')}}：</text>
            <text>
              {{[,$t('我司'), $t('客户')][order.portDestCustomsClear]}}
            </text>
          </view>
        </view>
      </view>
      <view class="cu-list menu bottom-line" style="margin-top: 0;">
        <view class="cu-item">
          <view class="content">
            <text>{{$t('始发仓')}}：</text>
            <text>{{ order.startWarehouseName }}</text>
          </view>
          <view class="content">
            <text>{{$t('发往')}}：</text>
            <text>{{ order.destWarehouseName }}</text>
          </view>
        </view>
      </view>
      <view class="flex text-center text-black bg-white text-bold padding-sm fontSize30">
        <view class="flex-sub">{{$t('品名')}}</view>
        <view class="flex-sub">{{$t('备案')}}</view>
        <view class="flex-sub">{{$t('箱数')}}</view>
        <view class="flex-sub">{{$t('体积')}}</view>
        <view class="flex-sub">{{$t('重量')}}</view>
      </view>
      <view class="flex text-center bg-white padding-sm fontSize30" v-for="(v, goodsKey) in order.boxOrderItemList" :key="'goods-' + goodsKey">
        <view class="flex-sub">{{ $lang.locale=='zh-Hans'?v.prodTitleZh:v.prodTitleEn }}</view>
        <view class="flex-sub">
          <!-- <dict-tag :type="DICT_TYPE.PRODUCT_RECORD_ATTRIBUTE" :value="order.productRecord" /> -->
          <template>{{v.brandName}}</template>{{ $t('（') }}
          <dict-tag :type="DICT_TYPE.BRAND_CUSTOMER_CHARGING_MODEL" :value="v.feeType" />{{ $t('）') }}
        </view>
        <view class="flex-sub">{{ v.num }}</view>
        <view class="flex-sub">{{ v.volume }} CBM</view>
        <view class="flex-sub">{{ v.weight }} Kg</view>
      </view>
    </view>
    <uniLoadMore :status="status" :icon-size="16" :content-text="contentText" />

    <!-- 预装位置弹窗 -->
    <!--<view class="cu-modal" :class="pathToModal ? 'show' : ''" style="z-index: 900;">
      <view class="cu-dialog">
        <view class="cu-bar bg-white justify-end bottom-line">
          <view class="content">{{$t('预装位置')}}</view>
        </view>
        <view class="cu-form-group">
          <view class="title">{{$t('位置')}}:</view>
          <picker @change="selectPathTo" :value="pathToSelected" :range="pathToList" range-key="title">
            <view class="picker">{{ pathToList[pathToSelected] ? pathToList[pathToSelected].title : $t("请选择") }}</view>
          </picker>
        </view>
        <view class="cu-bar bg-white justify-end top-line">
          <view class="action">
            <button class="cu-btn bg-green" @tap="preload">{{$t('确认')}}</button>
            <button class="cu-btn bg-grey margin-left" @tap="showPatchTo(false)">{{$t('取消')}}</button>
          </view>
        </view>
      </view>
    </view>-->
    <!-- 批量密码弹窗 -->
    <view class="cu-modal" :class="batchPwModal ? 'show' : ''" style="z-index: 900;">
      <view class="cu-dialog">
        <view class="cu-bar bg-white justify-end bottom-line">
          <view class="content title-bolder">{{$t('装柜补单')}}</view>
        </view>
        <view class="cu-form-group">
          <text class="title">{{$t('密码')}}:</text>
          <input class="text-right" :placeholder="$t('请输入密码')" type="text" password="true" v-model="batchLoadPassword" />
        </view>
        <view class="cu-bar bg-white justify-end top-line">
          <view class="action">
            <button class="cu-btn bg-green" @tap="submitPreload">{{$t('确认')}}</button>
            <button class="cu-btn bg-grey margin-left" @tap="showBatchPassword(false)">{{$t('取消')}}</button>
          </view>
        </view>
      </view>
    </view>

    <view class="cu-modal" :class="showPatch ? 'show' : ''" style="z-index: 900;">
      <view class="cu-dialog">
        <view class="cu-bar bg-white justify-end bottom-line">
          <view class="content"></view>
        </view>
        <view class="cu-form-group">
          <view class="">{{ popupMessage }}</view>
        </view>
        <view class="cu-bar bg-white justify-end top-line">
          <view class="action">
            <button class="cu-btn bg-green" @tap="handlePatch(false)">{{$t('预装关联单')}}</button>
            <button class="cu-btn bb-green margin-left" @tap="handlePatch(true)">{{$t('仅当前订单')}}</button>
            <button class="cu-btn bg-grey margin-left" @tap="showPatch = false">{{$t('取消')}}</button>
          </view>
        </view>
      </view>
    </view>

    <!-- 订单调仓弹窗 -->
    <!-- <transfer-warehouses ref="transferWarehouses" :shipmentId='shipmentId' @submit="transferWarehousesSubmit"></transfer-warehouses> -->
  </view>
</template>

<script>
import * as types from "../../store/mutations-types.js";
import { uniLoadMore } from "@dcloudio/uni-ui";
import util from "../../util/util.js";
import { defaultPageSize } from "../../util/config.js";
import {getCounty, getWarehouseList} from "../../api/api.js";
import { getCabinet, getLoadingDetail, validatePwd } from "../loading/api";
import {  createGoods } from "./api";
import dayjs from "dayjs";
import { createAir, getChannelList, preloadPageAir } from "@/pages/mergePkg/api";
import { DICT_TYPE } from "@/util/dict";
import { getAirShipmentByShipmentId } from "@/pages/airWarehouseOut/api";

export default {
  name: "patch",
  components: {
    uniLoadMore,
    // transferWarehouses,
  },
  data() {
    return {
      //国家列表
      countryList: [],
      countryObjectList: [],
      countrySelected: 0,
      showPatch: false,
      popupMessage: '',
      /* 发货ID */
      shipmentId: "",
      destWarehouseId: "", // 目的地
      isTally: 0,
      // loadDetail: {},
      status: "more",
      contentText: {
        contentdown: this.$t("上拉加载更多"),
        contentrefresh: this.$t("加载中"),
        contentnomore: this.$t("没有更多"),
      },
      /* 目的地 */
      destinationSelected: 0,
      destinationList: [this.$t("全部")],
      destinationValueList: [0],
      destinationObjectList: [],
      /* 备案 */
      productRecord: 0,
      batchPwModal: false,
      batchLoadPassword: "",
      recordList: [],
      /* 查询条件 */
      itemName: "",
      keyword: "",
      volume: "",
      weight: "",
      num: "",
      rucangTimeStart: "",
      rucangTimeEnd: "",
      page: 1,
      /* 列表 */
      orderList: [],
      /* 选中订单 */
      orderSelected: null,
      /* 预装位置 */
      pathToModal: false,
      pathToList: [],
      pathToSelected: 0,
      channelObjectList: [],
      // 选择的渠道
      channelSelected: 0,
      // 备选渠道列表
      channelList: [],
      // 出货信息
      shipment: null
    };
  },
  created() {
    this.recordList = [
      {
        label: this.$t("全部"),
        labelEn: this.$t("全部"),
        value: "all",
      },
    ].concat(this.getDictDatas(this.DICT_TYPE.BRAND_CUSTOMER_CHARGING_MODEL));
  },
  computed: {
    DICT_TYPE() {
      return DICT_TYPE
    },
    isChinese(){
      return uni.getLocale() === 'zh-Hans'
    },
    // 根据渠道ID显示渠道
    showChannelName(){
      return channelId => {
        return this.$l(this.channelObjectList.find(item => item.channelId === channelId), 'name')
      }
    }
  },
  methods: {
    //获取国家
    async getCountry() {
      this.countryObjectList = [{id: '', titleZh: '全部', titleEn: 'All'}, ...await getCounty({treeType: 1})]
      this.countryList = this.countryObjectList.map(e => this.$lang.locale === 'zh-Hans' ? e.titleZh : e.titleEn)
    },
    // 获取渠道
    async getChannel(){
      this.channelObjectList = [{id: '', nameZh: '全部', nameEn: 'All'}, ...await getChannelList()]
      this.channelList = this.channelObjectList.map(e => this.$lang.locale === 'zh-Hans' ? e.nameZh : e.nameEn)
    },
    handlePatch(singleLoad) {
      let params = {
        isCover: 1,
        orderId: this.orderSelected.orderId,
        orderItemIdList: this.orderSelected.boxOrderItemList.map(
          (data) => data.orderItemId
        ),
        secId: this.pathToList[this.pathToSelected].id,
        shipmentId: this.shipmentId,
        isTally: this.isTally,
      };
      createAir({ ...params, relationStatus: 2, singleLoad }).then((res) => {
        this.showPatch = false
        this.$store.dispatch(types.SHOW_TOAST, {
          msg: this.$t("预装成功"),
        });
        // 预装成功后清空搜索框，刷新数据
        this.keyword = "";
        setTimeout(() => {
          this.showPatchTo(false);
          this.search();
        }, 100);
      })
    },
    formatDate: util.formatDate,
    selectCountry(e){
      this.countrySelected = e.detail.value
      this.destinationSelected = 0
      this.destinationList = [this.$lang.locale === 'zh-Hans' ? '全部' : 'All']
      this.destinationValueList = [0]
      this.destinationObjectList.forEach(e => {
        if(e.guojia === this.countryObjectList[this.countrySelected].id) {
          this.destinationValueList.push(e.id)
          this.destinationList.push(this.$lang.locale === 'zh-Hans' ? e.titleZh : e.titleEn)
        }
      })
    },
    /* 目的地 */
    selectDestination(e) {
      this.destinationSelected = e.detail.value;
    },
    /*渠道*/
    selectChannel(e){
      this.channelSelected = e.detail.value
    },
    /* 备案 */
    selectRecord(e) {
      this.productRecord = e.detail.value;
    },
    /* 入仓开始时间 */
    selectBeginDate(e) {
      this.rucangTimeStart = e;
    },
    /* 入仓结束时间 */
    selectEndDate(e) {
      this.rucangTimeEnd = e;
    },
    /* 显示批量输入密码 */
    showBatchPassword(show) {
      this.batchPwModal = show;
    },
    /* 预装 */
    showPatchTo(show, row) {
      this.pathToModal = show;
      this.orderSelected = row;
    },
    // 订单调仓弹窗
    /* transferWarehousesShow(show, id, order) {
      let callbackData = { id, order };
      if (show) {
        this.$refs.transferWarehouses.show(
          true,
          order.transfer_order,
          order.errorMsg,
          callbackData
        );
      }
    }, */
    // 订单调仓成功后
    /* transferWarehousesSubmit(callbackData) {
      this.showPatchTo(true, callbackData.id, callbackData.order);
    }, */
    /* 部分选中 */
    selectPathTo(e) {
      this.pathToSelected = e.detail.value;
    },
    scanCode() {
      uni.scanCode({
        success: (res) => {
          this.keyword = res.result;
          this.search();
        },
      });
    },
    /* 搜索 */
    search() {
      setTimeout(() => {
        this.keyword = util.getQrCode(this.keyword);
        this.keyword = util.delLastPartNum(this.keyword); //去掉箱号
        this.page = 1;
        this.getData();
      }, 100);
    },
    /* 装柜信息 */
    getLoadDetail() {
      if (this.shipmentId) {
        getLoadingDetail({ shipmentId: this.shipmentId }).then((data) => {
          // 部分
          const { loadDetail = [] } = data;
          loadDetail.forEach((v, k) => {
            this.pathToList.push({
              title: this.$t("第{k}部分", { k: k + 1 }),
              id: v.id,
            });
          });
        });
        // 目的地
        this.destinationList = [this.$t("全部")];
        this.destinationValueList = [0];
        getWarehouseList()
          .then((warehouseList) => {
            // let destinationSelected = undefined
            // 只要目的地的仓
            warehouseList
              .filter((item) => item.tradeType == "1" || item.type == "3")
              .forEach((v, k) => {
                this.destinationList.push( this.$lang.locale=='zh-Hans' ? v.titleZh : v.titleEn);
                this.destinationValueList.push(v.id);
                this.destinationObjectList.push(v);
                // if (String(v.id) === this.destWarehouseId) {
                //   destinationSelected =
                //     this.destinationValueList.findIndex(
                //       (id) => String(id) === this.destWarehouseId
                //     );
                // }
              });

              this.countrySelected = this.countryObjectList.findIndex(e => e.id === this.destinationObjectList[this.destinationSelected].guojia)
              this.selectCountry({detail: {value: this.countrySelected}})
              // this.destinationSelected = destinationSelected
          })
          .finally(() => {
            this.getData();
          });
      }
    },
    /* 查询待预装 */
    getData() {
      const destinationValue =
        this.destinationValueList[this.destinationSelected];
      let condition = {
        shipmentId: this.shipmentId,
        destWarehouseIdList: destinationValue === 0 ? [] : [destinationValue],
        productRecord: this.recordList[this.productRecord].value === "all" ? "" : this.recordList[this.productRecord].value,
        itemName: this.itemName,
        rucangTimeStart: this.rucangTimeStart
          ? dayjs(this.rucangTimeStart).format("YYYY-MM-DD 00:00:00")
          : this.rucangTimeStart,
        rucangTimeEnd: this.rucangTimeEnd
          ? dayjs(this.rucangTimeEnd).format("YYYY-MM-DD 23:59:59")
          : this.rucangTimeEnd,
        pageNo: this.page,
        pageSize: defaultPageSize,
        orderNo: this.keyword,
        volume: this.volume,
        weight: this.weight,
        num: this.num,
        destCountryId: this.countryObjectList[this.countrySelected]?.id,
        channelId: this.channelObjectList[this.channelSelected]?.id,
        startWarehouseId: this.shipment?.startWarehouseId
      };
      // 过去空值
      Object.keys(condition).forEach((key) => {
        if (condition[key] === "" || condition[key] === undefined) {
          delete condition[key];
        }
      });
      preloadPageAir(condition).then((data) => {
        const dataList = data.dataList || [];
        if (this.page == 1) this.orderList = [];

        if (dataList.list && dataList.list.length > 0) {
          this.orderList = this.orderList.concat(dataList.list);
          if (dataList.list.length >= defaultPageSize) {
            this.status = "more";
          } else {
            this.status = "noMore";
          }
        } else this.status = "noMore";

        uni.stopPullDownRefresh();
      });
    },
    /* 预装确认 */
    preload(order) {
      this.orderSelected = order
      this.batchPwModal = true;
      // 去掉密码输入
      // this.submitPreload();
    },
    isPass() {
      return validatePwd({ busiType: 6, pwd: this.batchLoadPassword });
    },
    /* 提交预装 */
    async submitPreload() {
      this.showBatchPassword(false);
      const correct = await this.isPass();
      if (!correct) {
        return uni.showToast({
          title: this.$t("密码错误"),
          icon: "error",
        });
      }
      this.batchLoadPassword = "";
      createAir({
        isCover: 1,
        orderId: this.orderSelected.orderId,
        orderItemIdList: this.orderSelected.boxOrderItemList.map(
          (data) => data.orderItemId
        ),
        secId: this.pathToList[this.pathToSelected].id,
        shipmentId: this.shipmentId,
        isTally: this.isTally,
      }).then((data) => {
        if(data !== null && data?.data !== null) {
          this.$store.dispatch(types.SHOW_TOAST, {
            msg: this.$t("预装成功"),
          });
          // 预装成功后清空搜索框，刷新数据
          this.keyword = "";
          setTimeout(() => {
            this.showPatchTo(false);
            this.search();
          }, 100);
        } else {
            this.popupMessage = data?.msg.replace(/<br>/g, '') + this.$t('，是否需要一起预装?')
            this.showPatch = true
        }
      });
    },
    /* 关闭弹框 */
    showConfirmPassword(show) {
      this.confirmPwModal = show;
    },
    /* 关闭弹框 */
    showConfirm(show) {
      this.confirmModal = show;
    },
    getShipment(){
      return getCabinet(this.shipmentId).then(res => {
        this.shipment = res
      })
    }
  },
  onPullDownRefresh() {
    this.page = 1;
    this.getData();
  },
  onReachBottom() {
    if (this.status == "more") {
      this.status = "loading";
      this.page++;
      this.getData();
    }
  },
  onLoad: async function (option) {
    uni.setNavigationBarTitle({
      title: this.$t("未预装订单列表"),
    });
    if ("id" in option) {
      this.shipmentId = option.id;
      this.destWarehouseId = option.destWarehouseId;
      this.isTally = option.isTally;
      // 查询出货详情
      await this.getShipment()
      await this.getCountry()
      await this.getChannel()
      this.getLoadDetail();
    }
  },
};
</script>

<style lang="scss" scoped>
.content .item {
  padding: 0 5px 0 5px;
}
.fontSize30 {
  font-size: 30upx;
}
.pre_tips {
  background-color: #ffffff;
  padding: 30upx;
}
.no-border {
  border: none;
}
.search-form.round {
  ::v-deep .uni-easyinput__content {
    border-radius: 20px;
    padding-right: 10px;
    background: rgba($color: #fff, $alpha: 0.5) !important;
    border: none;
  }
}
</style>
