<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-card>
      <div slot="header" class="card-title">拆单申请-{{orderData.orderNo||''}}</div>
      <div class="btn-header">
        <span class="card-title">原单信息</span>
        <div>
          <span v-if="orderData.status==99" class="red">异常无法拆单</span>
          <el-button v-else type="primary" @click="addSplit">新建拆单 </el-button>
        </div>
      </div>
      <el-descriptions :column="4">
        <el-descriptions-item label="唛头">
          {{orderData.marks?orderData.marks:'无'}}
        </el-descriptions-item>
        <el-descriptions-item label="已到箱数/总箱数">
          <span>{{orderData.sumNum||0}}/{{orderData.costVO?orderData.costVO.totalNum:0}}</span>
        </el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <!-- <dict-tag :type="DICT_TYPE.ORDER_STATUS" :value="orderData.status" /> -->
          {{orderData.status==99?'异常':'正常'}}
        </el-descriptions-item>
        <el-descriptions-item label="送货日期">
          {{orderData.consigneeVO?orderData.consigneeVO.deliveryDate:'无'}}
        </el-descriptions-item>
      </el-descriptions>
      <el-descriptions :column="4">
        <el-descriptions-item label="运输方式">
          <dict-tag :type="DICT_TYPE.ECW_TRANSPORT_TYPE" :value="orderData.transportId" />
        </el-descriptions-item>
        <el-descriptions-item label="始发地">
          {{orderData.logisticsInfoDto?orderData.logisticsInfoDto.startTitleZh:'无'}}
        </el-descriptions-item>
        <el-descriptions-item label="目的地">
          {{orderData.logisticsInfoDto?orderData.logisticsInfoDto.destTitleZh:'无'}}
        </el-descriptions-item>
      </el-descriptions>
      <el-descriptions :column="4">
        <el-descriptions-item label="发货人姓名">
          {{orderData.consignorVO?orderData.consignorVO.name||'无':'无'}}
        </el-descriptions-item>
        <el-descriptions-item label="发货公司">
          {{orderData.consignorVO?orderData.consignorVO.company||'无':'无'}}
        </el-descriptions-item>
        <el-descriptions-item label="发货电话">
          {{orderData.consignorVO?(orderData.consignorVO.phone?(orderData.consignorVO.countryCode+orderData.consignorVO.phone):'无'):'无'}}
        </el-descriptions-item>
      </el-descriptions>
      <el-descriptions :column="4">
        <el-descriptions-item label="收货人姓名">
          {{orderData.consigneeVO?orderData.consigneeVO.name||'无':'无'}}
        </el-descriptions-item>
        <el-descriptions-item label="收货公司">
          {{orderData.consigneeVO?orderData.consigneeVO.company||'无':'无'}}
        </el-descriptions-item>
        <el-descriptions-item label="收货电话">
          {{orderData.consigneeVO?(orderData.consigneeVO.phone?(orderData.consigneeVo.countryCode+orderData.consigneeVO.phone):'无'):'无'}}
        </el-descriptions-item>
      </el-descriptions>

    </el-card>
    <el-card class="card">
      <!-- 列表 -->
      <div slot="header" class="card-title">货物信息</div>
      <el-table id='table' v-loading="loading" border :data="orderData.orderItemVOList" :summary-method="getSummaries" show-summary>
        <el-table-column label="序号" 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="品名" 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="装柜货物属性" align="center" width="600">
          <template slot-scope="scope">
            <el-row>
              <span>规格：{{scope.row.boxGauge}}</span>
            </el-row>
            <el-row>
              <span>品牌：
                <dict-tag :type="DICT_TYPE.ECW_IS_BRAND" :value="scope.row.brandType" />
              </span>
              <span style="margin-left: 10px;">箱数：{{scope.row.warehouseInInfoVO ? scope.row.warehouseInInfoVO.cartonsNum : 0 }}</span>
              <span style="margin-left: 10px;">体积：{{scope.row.warehouseInInfoVO ? scope.row.warehouseInInfoVO.volume : 0 }}m³</span>
              <span style="margin-left: 10px;">重量：{{scope.row.warehouseInInfoVO ? scope.row.warehouseInInfoVO.weight : 0 }}kg</span>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="最后操作时间" align="center">
          <template slot-scope="scope">
            <span>{{parseTime(scope.row.updateTime)}}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <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.length>0">
      <!-- 列表 -->
      <div slot="header" class="card-title">拆单信息</div>
      <div v-for="(item, index) in splitData" :key="index">
        <div class="btn-header">
          <div>
            <p class="card-info">
              <span class="card-title">
                {{item.orderNo}}
              </span>
              <dict-tag :type="DICT_TYPE.ECW_TRANSPORT_TYPE" :value="item.transportId" />
              <span>发往：{{importCityName(item.dstWarehouseId)}}</span>
            </p>
          </div>
          <div>
            <el-button v-if="index==0" disabled type="primary" @click="addShop(index)">放入</el-button>
            <el-button v-if="index!=0" type="primary" @click="addShop(index)">放入</el-button>
            <el-button type="primary" plain @click="deleteSplit(item.id)">删除</el-button>
          </div>
        </div>
        <el-table border :data="item.orderSplitItemBackVOList">
          <el-table-column label="序号" align="center" prop="id" type="index">
            <template slot-scope="scope">
              <span>{{scope.$index + 1}}</span>
            </template>
          </el-table-column>
          <el-table-column label="品名" 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="品牌" 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="体积" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.volume}}m³</span>
            </template>
          </el-table-column>
          <el-table-column label="重量" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.weight}}m³</span>
            </template>
          </el-table-column>
          <el-table-column label="箱数" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.num}}</span>
            </template>
          </el-table-column>
          <el-table-column label="计划装柜" align="center">
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button v-if="index==0" disabled size="mini" type="text" icon="el-icon-delete" @click="removeShop(scope.row.id)">移出</el-button>
              <el-button v-else size="mini" type="text" icon="el-icon-delete" @click="removeShop(scope.row.id)">移出</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <work-flow xmlkey="split_order" v-model="selectedUsers"></work-flow>
    <div slot="footer" class="card footer_btn" v-if="orderData.status!=99">
      <el-button v-if="orderData.status!=19" type="primary" @click="submitForm">提交申请</el-button>
      <el-button v-if="orderData.status!=19" plain type="primary" @click="$emit('closeDialog')">取消</el-button>
      <el-button v-if="orderData.status==19" type="primary" disabled>审核中</el-button>
      <el-button v-if="orderData.status==19" plain type="primary" @click="cancelSplit">取消审核</el-button>
      <el-button v-if="orderData.status==19" plain type="primary" @click="$emit('closeDialog')">返回</el-button>
    </div>
    <!-- 对话框(添加 / 修改) -->
    <el-dialog title="新建拆单" :visible.sync="open" width="400px" append-to-body>
      <el-form ref="formSplit" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-form-item label="运输方式">
            <dict-selector :type="DICT_TYPE.ECW_TRANSPORT_TYPE" v-model="form.transportId" formatter="number" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="目的仓库:">
            <el-select v-model="form.destWarehouseId" placeholder="请选择目的仓库">
              <el-option v-for="item in importCityList" :label="item.titleZh" :value="item.id" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="出货渠道" v-if="getDictData(DICT_TYPE.ECW_TRANSPORT_TYPE, form.transportId).cssClass == 'channel'">
            <el-select v-model="form.channelId" placeholder="请选择出货渠道">
              <el-option :disabled="getDictData(DICT_TYPE.ECW_TRANSPORT_TYPE, form.transportId).cssClass != 'channel'" v-for="item in channelData" :key="item.channelId" :label="item.nameZh" :value="item.channelId" />
            </el-select>
          </el-form-item>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="haddleAdd">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 对话框(添加 / 修改) -->
    <el-dialog title="放入品名" :visible.sync="shopOpen" width="400px" append-to-body>
      <el-form ref="shopForm" :model="shopForm" :rules="shopRules" label-width="80px">
        <el-row>
          <el-form-item label="中文品名:">
            <el-select v-model="shopForm.prodTitleZh" placeholder="请选择中文品名" @change="changeProdTitleZh">
              <el-option v-for="item in orderData.orderItemVOList" :label="item.prodTitleZh" :value="item.prodTitleZh" :key="item.prodTitleZh"></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="英文品名:">
            <el-select v-model="shopForm.prodTitleEn" placeholder="请选择英文品名" @change="changeProdTitleEn">
              <el-option v-for="item in orderData.orderItemVOList" :label="item.prodTitleEn" :value="item.prodTitleEn" :key="item.prodTitleEn"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="剩余箱数:">
            {{shopForm.sum||0}}
          </el-form-item>
          <el-form-item label="放入箱数:">
            <el-input-number v-model="shopForm.num" controls-position="right" :min="1" :max="shopForm.sum"></el-input-number>
          </el-form-item>
          <el-form-item label="备注信息:">
            <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">确 定</el-button>
        <el-button @click="shopCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getDictData, getDictDatas } from "@/utils/dict";
import {
  getSplitList,
  splitApply,
  createSplit,
  cancelApply,
  createSplitItem,
  deleteSplitItem,
  deleteSplit,
} from "@/api/ecw/orderHandle";
import { getTradeCityList } from "@/api/ecw/region";
import { getChannelList } from "@/api/ecw/channel";
import WorkFlow from "@/components/WorkFlow";
import { getOrder } from "@/api/ecw/order";

export default {
  name: "splitOrder",
  components: {
    WorkFlow,
  },
  props: {
    currRow: Object,
  },
  data() {
    return {
      checked: false,
      orderData: {},
      splitData: [],
      splitIndex: 0,
      channelData: [],
      tradeCityList: [],
      multipleSelection: [],
      loading: false,
      open: false,
      form: {},
      selectedUsers: [],
      shopOpen: false,

      shopForm: {},
      // 表单校验
      rules: {
        transportId: [
          { required: true, message: "请选择运输方式", trigger: "change" },
        ],
        warehouseIds: [
          { required: true, message: "请选择目的仓库", trigger: "change" },
        ],
        channelId: [
          { required: true, message: "请选择出货渠道", trigger: "change" },
        ],
      },
      // 表单校验
      shopRules: {
        prodTitleZh: [
          { required: true, message: "请选择中文品名", trigger: "change" },
        ],
        prodTitleEn: [
          { required: true, message: "请选择英文品名", trigger: "change" },
        ],
      },
      queryParams: {
        orderId: 96,
        lang: 0,
      },
      query: {
        page: 1,
        rows: 20,
      },
      splitItemIndex: 0,
    };
  },
  created() {
    this.getChannel();
    getTradeCityList().then((res) => (this.tradeCityList = res.data));
    this.queryParams.orderId = this.currRow.orderId;
    this.getList();
    this.getOrder();
  },
  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: {
    getDictData() {
      return (type, value) => getDictData(type, value) || {};
    },
    getDictDatas() {
      return getDictDatas;
    },
    importCityList() {
      return this.tradeCityList.filter((item) => item.type == 1);
    },
  },
  methods: {
    getOrder() {
      this.loading = true;
      getOrder(this.queryParams.orderId).then((response) => {
        this.orderData = response.data;
        this.query.destWarehouseId =
          response.data.logisticsInfoDto.startWarehouseId;
        this.loading = false;
      });
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      getSplitList(this.queryParams).then((response) => {
        this.splitData = response.data;
        this.loading = false;
      });
    },
    getChannel() {
      getChannelList().then((res) => (this.channelData = res.data));
    },
    changeDest() {
      this.query.warehouseIds = this.form.destWarehouseId;
    },
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      if (rowIndex == this.orderData.orderItemVOList.length) {
        if (columnIndex === 1) {
          return [2, 3];
        } else if (columnIndex > 1) {
          return [0, 0];
        }
      }
    },
    getSummaries() {
      const sums = [];

      sums[0] = "小计";
      if (
        !this.orderData ||
        !this.orderData.orderItemVOList ||
        this.orderData.length == 0
      ) {
        return sums;
      }
      var orderSum = 0;
      var orderV = 0;
      var orderW = 0;
      var leviteSum = 0;
      var leviteV = 0;
      var leviteW = 0;
      this.orderData.orderItemVOList.forEach((column, index) => {
        orderSum += column.num ?? 0;
        orderV += column.volume ?? 0;
        orderW += column.weight ?? 0;
        leviteSum += column.warehouseInInfoVO?.cartonsNum ?? 0;
        leviteV += column.warehouseInInfoVO?.volume ?? 0;
        leviteW += column.warehouseInInfoVO?.weight ?? 0;
      });
      sums[1] =
        "下单统计：" +
        orderSum +
        " 箱 " +
        orderV +
        " m³ " +
        orderW +
        " kg " +
        " 入仓统计：" +
        leviteSum +
        " 箱 " +
        leviteV +
        " m³ " +
        leviteW +
        " kg";

      return sums;
    },

    importCityName(id) {
      var arr = this.tradeCityList.filter((item) => item.id == id);
      return arr.length > 0 ? arr[0].titleZh : "无";
    },
    submitForm() {
      var params = {
        orderId: this.queryParams.orderId,
        copyUserId: this.selectedUsers,
      };
      splitApply(params).then((res) => {
        this.$modal.msgSuccess("申请成功");
        that.getList();
      });
    },
    addShop(index) {
      this.splitItemIndex = index;
      this.shopOpen = true;
    },
    addSplit() {
      this.open = true;
    },
    changeProdTitleZh() {
      var list = [];
      list = this.orderData.orderItemVOList.filter(
        (item) => item.prodTitleZh == this.shopForm.prodTitleZh
      );
      this.shopForm.sum = list[0].num;
      this.shopForm.orderItemId = list[0].orderItemId;
      this.shopForm.prodTitleEn = list[0].prodTitleEn;
    },
    changeProdTitleEn() {
      var list = [];
      list = this.orderData.orderItemVOList.filter(
        (item) => item.prodTitleEn == this.shopForm.prodTitleEn
      );
      this.shopForm.sum = list[0].num;
      this.shopForm.prodTitleZh = list[0].prodTitleZh;
    },
    haddleAdd() {
      let that = this;
      if (!that.form.transportId) {
        that.$message.error("请选择运输方式");
      }
      if (!that.form.destWarehouseId) {
        that.$message.error("请选择目的仓库");
      }
      // if(!this.form.channelId){
      //   this.$modal.msgError("请选择出货渠道");
      // }
      var params = {
        dstWarehouseId: that.form.destWarehouseId,
        parentOrderId: that.orderData.orderId,
        parentOrderNo: that.orderData.orderNo,
        transportId: that.form.transportId,
      };
      createSplit(params).then((res) => {
        that.getList();
      });
      that.open = false;
    },
    cancel() {
      this.open = false;
      this.form = {};
    },
    shopAdd() {
      this.$refs["shopForm"].validate((valid) => {
        if (!valid) {
          return;
        }
      });
      var params = {
        num: this.shopForm.num,
        orderItemId: this.shopForm.orderItemId,
        orderSplitId: this.splitData[this.splitItemIndex].id,
        remarks: this.shopForm.remarks,
      };
      createSplitItem(params).then((res) => {
        this.$message.success("放入成功");
        this.getList();
        this.shopForm = {};
      });
      this.shopOpen = false;
    },
    removeShop(id) {
      let that = this;
      that.$confirm("是否移除货物吗?").then(function () {
        deleteSplitItem(id).then((res) => {
          that.$message.success("移除成功");
          that.getList();
        });
      });
    },
    cancelSplit() {
      let that = this;
      that.$confirm("是否取消审核吗?").then(function () {
        cancelApply({ orderId: that.queryParams.orderId }).then((res) => {
          that.$message.success("取消成功");
          that.getList();
        });
      });
    },
    shopCancel() {
      this.shopOpen = false;
      this.shopForm = {};
    },
    /** 删除按钮操作 */
    deleteSplit(id) {
      let that = this;
      that.$confirm("是否确认删除新拆的订单吗?").then(function () {
        deleteSplit(id).then((res) => {
          that.$message.success("删除成功");
          that.getList();
        });
      });
    },
  },
};
</script>
<style>
.card-title {
  font-size: 18px;
  font-weight: bold;
  margin-top: 10px;
}
.card-info {
  font-size: 16px;
}
.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>
