<template>
  <div class="app-container shipping-split-order">
    <el-card>
      <div slot="header" class="card-title">{{$t('拆单申请')}}-{{orderData.orderNo||''}}</div>
      <div class="btn-header">
        <span class="card-title">{{$t('原单信息')}}</span>
      </div>
      <el-descriptions :column="4">
        <el-descriptions-item :label="$t('唛头')">
          {{orderData.marks?orderData.marks:$t('无')}}
        </el-descriptions-item>
        <el-descriptions-item :label="$t('已实装箱数/总箱数')">
          <span>{{currRow.installNum||0}}/{{currRow.num||0}}</span>
        </el-descriptions-item>
        <el-descriptions-item :label="$t('订单状态')">
          {{orderData.status==99? $t('异常'):$t('正常')}}
        </el-descriptions-item>
        <el-descriptions-item :label="$t('送货日期')">
          {{orderData.deliveryDate}}
        </el-descriptions-item>
      </el-descriptions>
      <el-descriptions :column="4">
        <el-descriptions-item :label="$t('运输方式')">
          <dict-tag :type="DICT_TYPE.ECW_TRANSPORT_TYPE" :value="orderData.transportId" />
        </el-descriptions-item>
        <el-descriptions-item :label="$t('始发地')">
          {{orderData.logisticsInfoDto?$l(orderData.logisticsInfoDto, 'startTitle'):$t('无')}}
        </el-descriptions-item>
        <el-descriptions-item :label="$t('目的地')">
          {{orderData.logisticsInfoDto?$l(orderData.logisticsInfoDto, 'destTitle'):$t('无')}}
        </el-descriptions-item>
      </el-descriptions>
      <el-descriptions :column="4">
        <el-descriptions-item :label="$t('发货人姓名')">
          {{orderData.consignorVO?orderData.consignorVO.name||$t('无'):$t('无')}}
        </el-descriptions-item>
        <el-descriptions-item :label="$t('发货公司')">
          {{orderData.consignorVO?orderData.consignorVO.company||$t('无'):$t('无')}}
        </el-descriptions-item>
        <el-descriptions-item :label="$t('发货电话')">
          {{orderData.consignorVO?(orderData.consignorVO.phone?("+"+orderData.consignorVO.countryCode+orderData.consignorVO.phone):$t('无')):$t('无')}}
        </el-descriptions-item>
      </el-descriptions>
      <el-descriptions :column="4">
        <el-descriptions-item :label="$t('收货人姓名')">
          {{orderData.consigneeVO?orderData.consigneeVO.name||$t('无'):$t('无')}}
        </el-descriptions-item>
        <el-descriptions-item :label="$t('收货公司')">
          {{orderData.consigneeVO?orderData.consigneeVO.company||$t('无'):$t('无')}}
        </el-descriptions-item>
        <el-descriptions-item :label="$t('收货电话')">
          {{orderData.consigneeVO?orderData.consigneeVO.phone?"+"+orderData.consigneeVO.countryCode+orderData.consigneeVO.phone :$t('无'):$t('无')}}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <el-card class="card">
      <!-- 列表 -->
      <div slot="header" class="card-title">{{$t('货物信息')}}</div>
      <el-table id='table' v-loading="loading" border :data="orderData.orderItemVOList" :summary-method="getSummaries" show-summary>
        <el-table-column :label="$t('序号')" align="center" prop="id" type="index" width="60">
          <template slot-scope="scope">
            <span>{{scope.$index + 1}}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('品名')" align="center">
          <template slot-scope="scope">
            <el-row>{{scope.row.prodTitleZh}}</el-row>
            <el-row>{{scope.row.prodTitleEn}}</el-row>
          </template>
        </el-table-column>
        <el-table-column :label="$t('装柜货物属性')" align="center" width="600">
          <template slot-scope="scope">
            <el-row style="text-align:left;">
              <el-row>
                <span>{{$t('规格')}}：{{scope.row.warehouseInInfoVO ? scope.row.warehouseInInfoVO.boxGauge : ''}}</span>
              </el-row>
              <el-row>
                <span>{{$t('品牌')}}：
                  <dict-tag :type="DICT_TYPE.ECW_IS_BRAND" :value="scope.row.brandType" />
                </span>
                <span style="margin-left: 10px;">{{$t('箱数')}}：{{scope.row.warehouseInInfoVO ? scope.row.warehouseInInfoVO.cartonsNum : 0 }}</span>
                <span style="margin-left: 10px;">{{$t('体积')}}：{{scope.row.warehouseInInfoVO ? scope.row.warehouseInInfoVO.volume : 0 }}m³</span>
                <span style="margin-left: 10px;">{{$t('重量')}}：{{scope.row.warehouseInInfoVO ? scope.row.warehouseInInfoVO.weight : 0 }}kg</span>
              </el-row>
              <el-row>
                <span>{{$t('计划装柜')}}：{{planCabinet}}</span>
              </el-row>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column :label="$t('最后操作时间')" align="center">
          <template slot-scope="scope">
            <span>{{parseTime(scope.row.updateTime)}}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('状态')" align="center">
          {{orderData.abnormalState!=0?$t('异常'):$t('正常')}}
          <!-- <template slot-scope="scope">
            <dict-tag :type="DICT_TYPE.ORDER_STATUS" :value="scope.row.status" />
          </template> -->
        </el-table-column>
      </el-table>
    </el-card>

    <el-card class="card" v-if="splitData.id">
      <!-- 列表 -->
      <div slot="header" class="card-title">{{$t('拆单信息')}}</div>
      <div>
        <div class="btn-header">
          <div>
            <p class="card-info">
              <span class="card-title">
                {{splitData.orderNo}}
              </span>
              <span>{{orderData.logisticsInfoDto?$l(orderData.logisticsInfoDto, 'startTitle'):$t('无')}}</span>
              <span>{{$t('发往')}}：{{splitData.dstWarehouseName}}</span>
            </p>
          </div>
          <div>
            <el-button type="primary" :disabled="isAudit" @click="addShop">{{$t('放入')}}</el-button>
          </div>
        </div>
        <el-table border :data="splitData.orderSplitItemBackVOList">
          <el-table-column :label="$t('序号')" align="center" prop="id" type="index">
            <template slot-scope="scope">
              <span>{{scope.$index + 1}}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('品名')" align="center">
            <template slot-scope="scope">
              <el-row>{{scope.row.prodTitleZh}}</el-row>
              <el-row>{{scope.row.prodTitleEn}}</el-row>
            </template>
          </el-table-column>
          <el-table-column :label="$t('品牌')" align="center">
            <template slot-scope="scope">
              <dict-tag :type="DICT_TYPE.ECW_IS_BRAND" :value="scope.row.brandType" />
            </template>
          </el-table-column>
          <el-table-column :label="$t('体积')" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.volume}}m³</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('重量')" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.weight}}kg</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('箱数')" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.num}}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('计划装柜')" align="center">
            {{planCabinet}}
          </el-table-column>
          <el-table-column :label="$t('操作')" align="center">
            <template slot-scope="scope">
              <el-button size="mini" :disabled="isAudit" type="text" icon="el-icon-delete" @click="removeShop(scope.row.id)">{{$t('移出')}}</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <el-row style="marginTop:15px;">
      <work-flow xmlkey="split_order" v-model="selectedUsers"></work-flow>
    </el-row>

    <div slot="footer" class="card footer_btn">
      <el-button v-if="!isAudit" type="primary" @click="submitForm">{{$t('提交申请')}}</el-button>
      <el-button v-if="!isAudit" plain type="primary" @click="$emit('closeDialog2')">{{$t('取消')}}</el-button>
      <el-button v-if="isAudit" type="primary" @click="jumpReviewDetail">{{$t('审核中')}}</el-button>
      <el-button v-if="isAudit" plain type="primary" @click="cancelSplit">{{$t('取消审核')}}</el-button>
      <el-button v-if="isAudit" plain type="primary" @click="$emit('closeDialog2')">{{$t('返回')}}</el-button>
    </div>

    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="$t('放入品名')" :visible.sync="shopOpen" width="400px" append-to-body>
      <el-form ref="shopForm" :model="shopForm" :rules="shopRules" label-width="100px">
        <el-row>
          <el-form-item :label="$t('中文品名')+'：'" prop="zhId">
            <el-select v-model="shopForm.zhId" :placeholder="$t('请选择中文品名')" @change="changeProdTitleZh">
              <el-option v-for="item in orderItems" :label="item.prodTitleZh" :value="item.id" :key="item.id" :disabled="itemDisabled(item)"></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item :label="$t('英文品名')+'：'" prop="enId">
            <el-select v-model="shopForm.enId" :placeholder="$t('请选择英文品名')" @change="changeProdTitleEn">
              <el-option v-for="item in orderItems" :label="item.prodTitleEn" :value="item.id" :key="item.id" :disabled="itemDisabled(item)"></el-option>
            </el-select>
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item :label="$t('剩余箱数')+'：'">
                {{shopForm.num||0}}
              </el-form-item>
            </el-col>
            <el-col :span="12" v-show="isQuantity">
              <el-form-item :label="$t('剩余数量(个)')+'：'">
                {{shopForm.quantity||0}}
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item :label="$t('放入箱数')+'：'">
            {{shopForm.putNum||0}}
          </el-form-item>
          <!-- <el-form-item :label="$t('放入数量(个)')+'：'" prop="putQuantity" v-show="isQuantity">
            <el-input-number v-model="shopForm.putQuantity" controls-position="right" :min="0"></el-input-number>
          </el-form-item> -->
          <el-form-item :label="$t('备注信息')+'：'">
            <el-input v-model="shopForm.remarks"></el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="shopAdd">{{$t('确定')}}</el-button>
        <el-button @click="shopCancel">{{$t('取消')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getSplitList,
  quantitycheck,
  createSplitItem,
  deleteSplitItem,
} from "@/api/ecw/orderHandle";
import { getTradeCityList } from "@/api/ecw/region";
import WorkFlow from "@/components/WorkFlow";
import { getOrder } from "@/api/ecw/order";
import { serviceMsg, toReviewDetail } from "../../utils";
import { createApproval, approvalCancel, splitList } from "@/api/ecw/boxSea";
import Decimal from "decimal.js";

export default {
  name: "splitOrder",
  inheritAttrs: false,
  components: {
    WorkFlow,
  },
  props: {
    currRow: Object,
  },
  data() {
    return {
      orderData: {},
      splitData: {},
      detail: {},
      loading: false,
      selectedUsers: [],
      tradeCityList: [],
      planCabinet: "",

      shopOpen: false,
      orderItems: [],
      shopForm: {},
      // 表单校验
      shopRules: {
        zhId: [
          {
            required: true,
            message: this.$t("请选择中文品名"),
            trigger: "change",
          },
        ],
        enId: [
          {
            required: true,
            message: this.$t("请选择英文品名"),
            trigger: "change",
          },
        ],
      },
      queryParams: {
        orderId: 0,
        lang: 0,
      },
      isQuantity: false,
    };
  },
  created() {
    const { shipmentObj } = this.$attrs;
    this.planCabinet = `${shipmentObj.selfNo}-${this.currRow.sectionName}`;
    getTradeCityList().then((res) => (this.tradeCityList = res.data));
    this.queryParams.orderId = this.currRow.orderId;
    this.getOrderDetail();
    this.getSplit();
  },
  watch: {
    //监听table这个对象
    tableData: {
      // 立即监听
      immediate: true,
      handler() {
        this.$nextTick(() => {
          const tds = document.querySelectorAll(
            "#table .el-table__footer-wrapper tr>td"
          );
          // colSpan合并列
          tds[1].colSpan = 5;
          tds[1].style.textAlign = "left";
          tds[2].style.display = "none";
          tds[3].style.display = "none";
          tds[4].style.display = "none";
        });
      },
    },
  },
  computed: {
    isAudit() {
      const { shipmentObj } = this.$attrs;
      const { cabinetSplitInfo } = shipmentObj;
      if (cabinetSplitInfo) {
        /**
         * PROCESS(1, "处理中"),
         * APPROVE(2, "通过"),
         * REJECT(3, "不通过"),
         * CANCEL(4, "已取消");
         */
        const { approvalStatus } = cabinetSplitInfo;
        if (approvalStatus === 1) return true;
      }
      return false;
    },
  },
  methods: {
    /* 拆箱总数 */
    totalSplitNum() {
      let _total = 0;
      const { orderSplitItemBackVOList = [] } = this.splitData;
      orderSplitItemBackVOList.forEach((v) => {
        _total = Decimal.add(_total, Number(v.num)).toNumber();
      });
      return _total;
    },
    totalSplitQty() {
      let _total = 0;
      const { orderSplitItemBackVOList = [] } = this.splitData;
      orderSplitItemBackVOList.forEach((v) => {
        _total = Decimal.add(_total, Number(v.quantity)).toNumber();
      });
      return _total;
    },
    /* 打开拆单 */
    getSplit() {
      this.orderItems = this.currRow.goodsList ?? [];
      const { shipmentObj } = this.$attrs;
      splitList({
        orderId: this.currRow.orderId,
        shipmentId: shipmentObj.id,
      }).then((res) => {
        const data = res.data;
        // 取拆单项
        this.splitData = data.filter((item) => !item.isMaster)?.[0] ?? {};
      });
    },
    itemDisabled(data) {
      const { orderSplitItemBackVOList = [] } = this.splitData;
      const isExist = orderSplitItemBackVOList.find(
        (item) => item.orderItemId === data.orderItemId
      );
      return isExist ? true : false;
    },
    /* 查询拆单项 */
    querySplitGoods() {
      getSplitList({
        lang: 0,
        orderId: this.currRow.orderId,
        shipmentType: 1,
      }).then((res) => {
        const { orderSplitBackVOList } = res.data; // 取拆单项
        const list =
          orderSplitBackVOList.filter((item) => !item.isMaster)?.[0] ?? {};

        this.splitData.orderSplitItemBackVOList =
          list.orderSplitItemBackVOList ?? [];
      });
    },
    getOrderDetail() {
      this.loading = true;
      getOrder(this.queryParams.orderId).then((response) => {
        this.orderData = response.data;
        this.loading = false;
      });
    },
    getSummaries() {
      const sums = [];

      sums[0] = this.$t("小计");
      if (
        !this.orderData ||
        !this.orderData.orderItemVOList ||
        this.orderData.length == 0
      ) {
        return sums;
      }
      let orderSum = 0;
      let orderV = 0;
      let orderW = 0;
      let leviteSum = 0;
      let leviteV = 0;
      let leviteW = 0;
      this.orderData.orderItemVOList.forEach((column, index) => {
        orderSum = Decimal.add(orderSum, column.num ?? 0).toNumber();
        orderV = Decimal.add(orderV, column.volume ?? 0).toFixed(2);
        orderW = Decimal.add(orderW, column.weight ?? 0).toFixed(2);
        leviteSum = Decimal.add(
          leviteSum,
          column.warehouseInInfoVO?.cartonsNum ?? 0
        ).toNumber();
        leviteV = Decimal.add(
          leviteV,
          column.warehouseInInfoVO?.volume ?? 0
        ).toFixed(2);
        leviteW = Decimal.add(
          leviteW,
          column.warehouseInInfoVO?.weight ?? 0
        ).toFixed(2);
      });
      sums[1] = this.$t(
        "下单统计：{orderSum} 箱 {orderV} m³ {orderW} kg 入仓统计：{leviteSum} 箱 {leviteV} m³ {leviteW} kg",
        {
          orderSum,
          orderV,
          orderW,
          leviteSum,
          leviteV,
          leviteW,
        }
      );
      return sums;
    },
    importCityName(id) {
      let arr = this.tradeCityList.filter((item) => item.id == id);
      return arr.length > 0 ? this.$l(arr[0], "title") : this.$t("无");
    },
    submitForm() {
      const { shipmentObj } = this.$attrs;
      // 创建拆单审核
      createApproval({
        applyReason: this.$t("拆单审核"),
        approvalStatus: 0,
        approvalType: 8,
        copyUserId: this.selectedUsers,
        orderId: this.currRow.orderId,
        shipmentId: shipmentObj.id,
      }).then((res) => {
        serviceMsg(res, this).then((res) => {
          this.$emit("getBoxInfo");
          this.querySplitGoods();
        });
      });
    },
    addShop() {
      this.shopForm = {};
      this.shopOpen = true;
      this.isQuantity = false;
    },
    async changeProdTitleZh() {
      const item = this.setShopForm("zhId");
      this.shopForm.enId = item.id;
      this.shopForm = { ...this.shopForm };
      await this.getSelectData(item);
    },
    async changeProdTitleEn() {
      const item = this.setShopForm("enId");
      this.shopForm.zhId = item.id;
      this.shopForm = { ...this.shopForm };
      await this.getSelectData(item);
    },
    setShopForm(key) {
      let list = [];
      list = this.orderItems.filter((item) => item.id == this.shopForm[key]);

      const data = list[0];
      const itemNum = data.num ?? 0;
      const itemQty = data.quantity ?? 0;
      // 获取拆单项的总num
      const total = this.totalSplitNum();
      // 订单的剩余
      const orderNum = this.currRow.num - this.currRow.installNum;
      // 剩余可装
      const remainNum = Decimal.sub(orderNum, total).toNumber();

      this.shopForm.num = 0;
      this.shopForm.putNum = 0;
      // 剩余可装大于等于订单项剩余，显示订单剩余
      if (remainNum >= itemNum) {
        this.shopForm.num = remainNum;
        this.shopForm.putNum = itemNum;
      }
      // 订单剩余小于订单项剩余，显示订单项剩余
      if (remainNum < itemNum) {
        this.shopForm.num = this.shopForm.putNum = remainNum;
      }

      const totalQty = this.totalSplitQty();
      this.shopForm.quantity = 0;
      if (totalQty >= itemQty) {
        this.shopForm.quantity = totalQty;
      }
      if (totalQty < itemQty) {
        this.shopForm.quantity = itemQty;
      }

      this.shopForm.orderItemId = data.orderItemId;
      this.shopForm.putQuantity = Decimal.div(
        this.shopForm.quantity,
        this.shopForm.num
      ).toFixed(0);
      return data;
    },
    async getSelectData(item) {
      await quantitycheck({
        seaFreightVolume: item.seaFreightVolume,
        clearanceFreightVolume: item.clearanceFreightVolume,
      }).then((res) => {
        if (res.data) {
          this.isQuantity = true;
          this.shopRules.putQuantity = [
            {
              required: true,
              message: this.$t("请输入数量(个)"),
              trigger: "change",
            },
          ];
        } else {
          this.isQuantity = false;
          delete this.shopRules.putQuantity;
        }
      });
    },
    shopAdd() {
      this.$refs["shopForm"].validate((valid) => {
        if (valid) {
          // 输入箱数大于实装箱数
          const total = this.totalSplitNum();
          const canSplitNum = Decimal.sub(
            this.currRow.num,
            this.currRow.installNum
          ).toNumber();
          const remain = Decimal.sub(canSplitNum, total).toNumber();
          if (this.shopForm.num > remain) {
            this.$message.error(this.$t("放入箱数不能大于总箱数"));
            return;
          }
          if (this.shopForm.num === 0) {
            this.$message.error(this.$t("放入箱数不能为0"));
            return;
          }
          if (this.shopForm.putQuantity === 0 && this.isQuantity) {
            this.$message.error(this.$t("放入数量(个)不能为0"));
            return;
          }

          let params = {
            num: this.shopForm.putNum,
            quantity: this.shopForm.putQuantity,
            orderItemId: this.shopForm.orderItemId,
            orderSplitId: this.splitData.id,
            remarks: this.shopForm.remarks,
          };
          createSplitItem(params).then((res) => {
            this.$message.success(this.$t("放入成功"));
            this.querySplitGoods();
            this.$refs["shopForm"].resetFields();
          });
          this.shopOpen = false;
        }
      });
    },
    removeShop(id) {
      let that = this;
      that.$confirm(this.$t("是否移除货物吗?")).then(function () {
        deleteSplitItem(id).then((res) => {
          that.$message.success(that.$t("移除成功"));
          that.querySplitGoods();
        });
      });
    },
    cancelSplit() {
      const { shipmentObj } = this.$attrs;
      approvalCancel({
        applyReason: this.$t("取消审核"),
        id: shipmentObj["cabinetSplitInfo"].id,
        shipmentId: shipmentObj.id,
      }).then((res) => {
        serviceMsg(res, this).then(() => {
          this.$emit("getBoxInfo");
          this.querySplitGoods();
        });
      });
    },
    shopCancel() {
      this.$refs["shopForm"].resetFields();
      this.shopOpen = false;
      this.shopForm = {};
    },
    jumpReviewDetail() {
      const { cabinetSplitInfo } = this.$attrs.shipmentObj;
      toReviewDetail.apply(this, [cabinetSplitInfo.bpmProcessId]);
      this.$emit("closeDialog2", "close");
    },
  },
};
</script>

<style lang="scss">
.shipping-split-order {
  .card-title {
    font-size: 18px;
    font-weight: bold;
    margin-top: 10px;
  }
  .card-info {
    font-size: 16px;
    > span {
      margin-right: 10px;
    }
  }
  .card {
    margin-top: 20px;
  }
  .btn-header {
    width: 90%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 20px 0;
  }
  .red {
    color: #ff3430;
    font-size: 15px;
  }
  .footer_btn {
    padding-bottom: 60px;
  }
}
</style>
