<template>
  <div class="shipping-tally">
    <el-row type="flex" style="margin-top: 15px; margin-bottom: 15px" justify="center">
      <el-col :xs="24" :sm="24" :md="24" :lg="20" :xl="22">
        <el-card>
          <el-descriptions :column="4" border>
            <el-descriptions-item :label="$t('自编号')">
              {{shipmentObj.selfNo}}
            </el-descriptions-item>
            <el-descriptions-item :label="$t('运输方式')">
              <dict-tag :type="DICT_TYPE.ECW_TRANSPORT_TYPE" :value="shipmentObj.transportType" />
            </el-descriptions-item>
            <el-descriptions-item :label="$t('始发地')">
              {{getCityName(shipmentObj.startWarehouseId)}}
            </el-descriptions-item>
            <el-descriptions-item :label="$t('目的地')">
              {{getCityName(shipmentObj.destWarehouseId)}}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <el-row style="margin-top: 15px">
          <el-row>
            <el-button size="small" type="primary" @click="()=>tallyClick('batch')">{{$t('批量理货')}}</el-button>
            <el-button size="small" type="primary" @click="()=>removeClick('batch')">{{$t('批量移出')}}</el-button>
          </el-row>
          <el-row style="margin-top: 5px">
            <el-table border :data="tallyList" @select="checkboxSelect" @select-all="checkboxSelect" max-height="600px">
              <el-table-column type="selection" align="center" width="55" fixed="left" />
              <el-table-column align="center" :label="$t('序号')" width="50" prop="tidanNum" />
              <el-table-column :label="$t('订单号')" align="center" prop="orderNo">
                <template slot-scope="scope">
                  <div>
                    {{scope.row.orderNo}}
                  </div>
                  <div style="color:blue;fontWeight:bold;">
                    {{ scope.row.isExternalWarehouse === 1 ? ('('+$t('外部仓')+')') : ''}}
                  </div>
                  <div style="color:red;fontWeight:bold;">
                    {{ scope.row.adjustToDestWarehouseId > 0 ? ('('+$t('调仓')+')') : ''}}
                  </div>
                </template>
              </el-table-column>
              <el-table-column :label="$t('商品信息')" width="250px" align="center" prop="">
                <template slot-scope="{row}">
                  {{$l(row,'prodTitle')}}
                </template>
              </el-table-column>
              <el-table-column :label="$t('备案')" align="center" prop="feeType">
                <template slot-scope="{row}">
                  <template v-if="row.brandName">{{row.brandName}}</template>
                  <dict-tag v-else :type="DICT_TYPE.ECW_IS_BRAND" :value="row.feeType" />
                </template>
              </el-table-column>
              <el-table-column :label="$t('报关方式')" align="center" prop="customsType">
                <template slot-scope="scope">
                  <div :class="scope.row.customsType !== 1 ? 'custom_type_red' : ''">
                    <dict-tag :type="DICT_TYPE.ECW_CUSTOMS_TYPE" :value="scope.row.customsType" />
                  </div>
                </template>
              </el-table-column>
              <el-table-column :label="$t('箱数')" align="center" prop="warehouseInInfo.cartonsNum">
                <template slot-scope="scope">
                  <el-link type="primary" @click.native="showWarehouseLogs(scope.row)">
                    {{scope.row.warehouseInInfo.cartonsNum}}
                  </el-link>
                  <div style="color:blue;fontWeight:bold;">
                    {{ scope.row.multiSpecification === true ? '(多规格)' : ''}}
                  </div>
                </template>
              </el-table-column>
              <el-table-column :label="$t('纸箱尺寸')" align="center" prop="warehouseInInfo.boxGauge">
              </el-table-column>
              <el-table-column :label="$t('体积')" align="center" prop="warehouseInInfo.volume">
              </el-table-column>
              <el-table-column :label="$t('重量')" align="center" prop="warehouseInInfo.weight">
              </el-table-column>
              <el-table-column :label="$t('数量(个)')" align="center" prop="quantity"></el-table-column>
              <el-table-column :label="$t('储位')" align="center" prop="positionNo" width="250px">
                <template slot-scope="scope">
                  {{notset(scope.row.positionNo)}}
                </template>
              </el-table-column>
              <el-table-column :label="$t('状态')" align="center" prop="tallyStatus">
                <template slot-scope="scope">
                  {{scope.row.tallyStatus === 1 ? $t('已理货') : $t('未理货')}}
                </template>
              </el-table-column>
              <el-table-column :label="$t('理货时间')" align="center" prop="tallyTime">
                <template slot-scope="scope">
                  {{formatDate(scope.row.tallyTime,'YYYY-MM-DD HH:mm:ss')}}
                </template>
              </el-table-column>
              <el-table-column :label="$t('操作')" align="center" width="160" class-name="small-padding fixed-width" fixed="right">
                <template slot-scope="scope">
                  <el-button type="text" size="small" @click="tallyClick('single',scope.row)">{{$t('理货')}}</el-button>
                  <el-button type="text" size="small" @click="removeClick('single',scope.row)">{{$t('移出')}}</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-row>
        </el-row>

        <el-row style="margin-top: 15px" class="operate-button">
          <el-button size="small" type="primary" @click="tallyFinish">{{$t('完成理货')}}</el-button>
          <el-button size="small" @click="cancel">{{$t('取消')}}</el-button>
        </el-row>
      </el-col>
    </el-row>
    <!-- 对话框 -->
    <el-dialog custom-class="shipping-dialog" :title="dialogConfig.title" :visible.sync="dialogConfig.dialogVisible" :fullscreen="dialogConfig.fullscreen" :width="dialogConfig.width" :modal-append-to-body=false append-to-body>
      <batchTally v-if="dialogConfig.dialogVisible" v-bind="$attrs" @closeDialog="closeDialog" :type="dialogConfig.type" :tallyRows="tallyRows" :shipmentObj="shipmentObj" />
    </el-dialog>
    <warehouse-detail :order="order" :orderItemId="showWarehouseInItemId" v-if="showWarehouseInItemId" @close="showWarehouseInItemId=null" />
  </div>
</template>

<script>
import batchTally from "./batchTally.vue";
import { getTallyList, tallyRemove, tallyCommit } from "@/api/ecw/boxSea";
import { formatDate, serviceMsg } from "../../utils";
import WarehouseDetail from "./warehouseDetail";
import { getOrder } from "@/api/ecw/order";

export default {
  name: "tally",
  inheritAttrs: false,
  components: {
    batchTally,
    WarehouseDetail,
  },
  props: {
    shipmentObj: Object,
  },
  data() {
    return {
      showWarehouseInItemId: null,
      order: null,
      tallyList: [],
      // 理货数据
      tallyRows: [],
      // 勾选行
      selectedRows: [],
      // 弹窗配置
      dialogConfig: {
        title: "",
        dialogVisible: false,
        width: "30%",
        type: "",
        fullscreen: false,
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 格式化日期
    formatDate,
    //去重
    notset(string){
      if(!string) return string
      let arr = string.split(',')
      arr = arr.filter((item,index)=>{return arr.indexOf(item)==index})
      return arr.toString()
    },
    // 查询理货列表
    getList() {
      getTallyList({ shipmentId: this.shipmentObj.id }).then((res) => {
        let list = [];
        res.data.forEach((item) => {
          item.orderItemList.forEach((oItem) => {
            let warehouseInInfo = {};
            if (oItem.warehouseInInfo) {
              warehouseInInfo = JSON.parse(oItem.warehouseInInfo ?? {});
            }

            list.push({
              ...oItem,
              warehouseInInfo,
              // multiSpecification: item.multiSpecification,
              positionNo: oItem.positionNo,
              tallyStatus: item.tallyStatus,
              tallyTime: item.tallyTime,
            });
          });
        });
        // let relist = []
        // list.forEach(l=>{
        //   let index = relist.findIndex(i=>i.orderId == l.orderId && i.positionNo == l.positionNo)
        //   if(index == -1){
        //     relist.push(l)
        //   }else{
        //     relist[index].warehouseInInfo.cartonsNum = parseInt(relist[index].warehouseInInfo.cartonsNum)+parseInt(l.warehouseInInfo.cartonsNum)
        //   }
        // })
        this.tallyList = list;
      });
    },
    // 选中
    checkboxSelect(selection) {
      this.selectedRows = selection;
    },
    // 理货点击
    tallyClick(type, data) {
      if (type === "batch") {
        if (this.selectedRows.length === 0) {
          this.$message.error(this.$t("请选择需要理货的订单"));
          return;
        }
        this.tallyRows = this.selectedRows;
        this.showDialog("batchTally");
      } else {
        this.tallyRows = [data];
        this.showDialog("singleTally");
      }
    },
    // 移出点击
    removeClick(type, data) {
      let orderNos = [],
        orderIds = [];
      if (type === "batch") {
        if (this.selectedRows.length === 0) {
          this.$message.error(this.$t("请选择需要移出的订单"));
          return;
        }
        orderNos = this.selectedRows.map((item) => item.orderNo);
        orderIds = this.selectedRows.map((item) => item.orderId);
      } else {
        orderNos = [data.orderNo];
        orderIds = [data.orderId];
      }

      let msgTitle = this.$t("您确定要将 {no} 移出 {selfNo} 吗?", {
        no: orderNos.join(","),
        selfNo: this.shipmentObj.selfNo,
      });

      this.$confirm(msgTitle, this.$t("提示"), {
        type: "warning",
      })
        .then((_) => {
          tallyRemove({
            orderIdLIst: orderIds,
            shipmentId: this.shipmentObj.id,
          }).then((res) => {
            serviceMsg(res, this).then(() => {
              this.getList();
            });
          });
        })
        .catch((_) => {});
    },
    // 关闭弹窗
    closeDialog(type) {
      this.$set(this.dialogConfig, "dialogVisible", false);
      if (type === "query") {
        this.getList();
      }
    },
    // 打开弹窗
    showDialog(type) {
      switch (type) {
        case "batchTally":
          this.$set(this.dialogConfig, "title", this.$t("批量理货"));
          this.$set(this.dialogConfig, "width", "500px");
          break;
        case "singleTally":
          this.$set(this.dialogConfig, "title", this.$t("理货确认"));
          this.$set(this.dialogConfig, "width", "500px");
          break;
      }
      this.$set(this.dialogConfig, "type", type);
      this.$set(this.dialogConfig, "dialogVisible", true);
    },
    /** 取消 */
    cancel(type) {
      this.$emit("closeDialog", type);
    },
    // 理货完成
    tallyFinish() {
      tallyCommit({ shipmentId: this.shipmentObj.id }).then((res) => {
        serviceMsg(res, this).then(() => {
          this.$emit("closeDialog", "submit");
        });
      });
    },
    // 显示入仓记录
    showWarehouseLogs(row) {
      getOrder(row.orderId).then((response) => {
        this.order = response.data;
        this.showWarehouseInItemId = row.orderItemId;
      });
    },
  },
  computed: {
    /* 获取仓库 */
    getCityName() {
      return (id) => {
        let arr = this.$attrs.warehouseList.filter((item) => item.id == id);
        return arr.length > 0 ? this.$l(arr[0], "title") : this.$t("无");
      };
    },
  },
};
</script>

<style lang="scss" scoped>
</style>