<template>
  <div class="supplementOrder">
    <el-card>
      <!-- 内容区 -->
      <el-row class="content-area">

        <!-- 左侧 -->
        <el-col :span="6" class="left-area">
          <el-row>
            <el-button type="primary" @click="addPart">{{$t('新增')}}</el-button>
            <el-button type="danger" @click="deletePart">{{$t('删除')}}</el-button>
          </el-row>
          <el-scrollbar style="height:calc(100% - 40px)">
            <el-row v-for="item in partList" :key="item.id" class="title-info" :class="item.id === partData.id ? 'selected' : ''">
              <div @click="partClick(item)">
                <p>{{item.title}}</p>
              </div>
              <el-collapse-transition>
                <div v-if="item.fold === false ? true : false">
                  <div v-for="(secGoog, index) in item.sectionOrderList" :key="index" class="part-secGoog">
                    <p>{{secGoog.orderNo}}</p>
                    <p>{{secGoog.prodTitleZh}}</p>
                    <div>
                      <i class="el-icon-delete" @click="deleteOrder(secGoog)"></i>
                    </div>
                  </div>
                </div>
              </el-collapse-transition>
              <div class="part-secGoog">
                <template>
                  {{getTotlContent(item.secStatistics)}}
                </template>
              </div>
            </el-row>
          </el-scrollbar>
        </el-col>

        <!-- 右侧 -->
        <el-col :span="18" class="right-area">

          <el-row class="right-title">
            <div>{{$t('货物筛选')}}</div>
            <div>{{$t('当前装柜')}}：{{partData.title}}</div>
            <div>{{$t('可预装方数')}}：{{unloadStatistics.volume}}m³，{{$t('重量')}}：{{unloadStatistics.weight}}Kg</div>
          </el-row>

          <!-- 搜索工作栏 -->
          <el-row>
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
              <el-form-item :label="$t('始发地')">
                <p>{{importCityName(queryParams.startWarehouseId)}}</p>
              </el-form-item>
              <el-form-item :label="$t('目的地')" prop="destination">
                <el-select v-model="queryParams.destWarehouseIdList" :placeholder="$t('请选择目的地')" multiple>
                  <el-option v-for="item in importWarehouseList" :label="item.titleZh" :value="item.id" :key="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item :label="$t('订单号')" prop="orderNo">
                <el-input v-model="queryParams.orderNo" :placeholder="$t('请输入订单号')" clearable />
              </el-form-item>

              <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="queryAllData">{{$t('搜索')}}</el-button>
              </el-form-item>
            </el-form>
          </el-row>

          <!-- 表格 -->
          <el-scrollbar style="height:calc(100% - 164px)">
            <el-row v-for="(item, index) in toBePreList" :key="index" class="toBePre-table">
              <el-row class="table-title">
                <div>{{item.orderNo}}</div>
                <div>{{$t('发往')}}：{{item.destWarehouseName}}</div>
                <div :class="item.customsType !== 1 ? 'custom_type_red' : ''">
                  <dict-tag :type="DICT_TYPE.ECW_CUSTOMS_TYPE" :value="item.customsType" />
                </div>
                <div>{{$t('入仓时间')}}：{{formatDate(item.rucangTime)}}</div>
                <div>
                  <el-button type="text" @click="handleGoods('all', item)">[{{$t('全部预装')}}]</el-button>
                  <el-button type="text" @click="foldTable(index, item)">[{{item.fold ? $t('展开') : $t('收起')}}]</el-button>
                </div>
              </el-row>
              <el-collapse-transition>
                <div v-show="!item.fold">
                  <el-table v-loading="loading" :data="item.boxOrderItemList" border>
                    <el-table-column :label="$t('序号')" type="index" align="center" width="50" />
                    <el-table-column :label="$t('品名')" align="center" prop="" min-width="500">
                      <template slot-scope="{row}">
                        {{$l(row,'prodTitle')}}
                      </template>
                    </el-table-column>
                    <el-table-column :label="$t('品牌')" align="center" prop="brandType" width="120">
                      <template slot-scope="scope">
                        <template v-if="scope.row.brandName">{{scope.row.brandName}}</template>
                        <dict-tag v-else :type="DICT_TYPE.ECW_IS_BRAND" :value="scope.row.feeType" />
                      </template>
                    </el-table-column>
                    <el-table-column :label="$t('箱数')" align="center" prop="num" width="120" />
                    <el-table-column :label="$t('体积')" align="center" prop="volume" width="120">
                      <template slot-scope="scope">
                        <p v-if="scope.row.volume">{{getTotlContent(scope.row,['volume'])}}</p>
                      </template>
                    </el-table-column>
                    <el-table-column :label="$t('重量')" align="center" prop="weight" width="120">
                      <template slot-scope="scope">
                        <p v-if="scope.row.weight">{{getTotlContent(scope.row,['weight'])}}</p>
                      </template>
                    </el-table-column>
                    <!-- <el-table-column :label="$t('预装柜')"
                                     align="center"
                                     prop=""
                                     width="120">{{ $t('无返回') }}</el-table-column> -->
                    <el-table-column :label="$t('操作')" align="center" class-name="small-padding fixed-width" width="100">
                      <template slot-scope="scope">
                        <el-button type="text" size="small" @click="handleGoods('singele',scope.row)">{{$t('预装')}}</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </el-collapse-transition>
            </el-row>
          </el-scrollbar>

          <!-- 分页 -->
          <el-pagination background layout="prev, pager, next" :page-size="pageParam.pageSize" :total="total" @current-change="pageChange" v-show="total > 0"></el-pagination>
        </el-col>

      </el-row>
    </el-card>
    <el-row>
      <el-col :span="6" class="totle-info">
        <div>
          <p>{{$t('总计')}}：</p>
          <p>{{sumStatistics(partList)}}</p>
        </div>
        <div>
          <p>{{$t('容量')}}：</p>
          <p>{{calcCapacity}}</p>
        </div>
      </el-col>
    </el-row>
    <el-row class="button-area">
      <el-button type="primary" @click="handlerFinish">{{$t('完成')}}</el-button>
    </el-row>
  </div>
</template>

<script>
import {
  loadSecGoodsList,
  preloadPage,
  createSection,
  deleteSection,
  createGoods,
  remove,
} from "@/api/ecw/boxSea";
import {
  formatDate,
  getTotlContent,
  serviceMsg,
  getCapacity,
  sumStatistics,
} from "../../utils";
/**
 * 补单
 */
export default {
  name: "supplementOrder",
  inheritAttrs: false,
  data() {
    return {
      // 二维码/条码编号
      cabinetNo: "",
      // 表格数据
      listData: [],
      // 选中部分
      partData: {},
      // 部分列表
      partList: [],
      // 部分统计
      loadStatistics: {},
      // 查询参数
      queryParams: {
        startWarehouseId: this.$attrs.shipmentObj.startWarehouseId,
      },
      pageParam: { pageNo: 1, pageSize: 10 },
      // 待预装
      toBePreList: [],
      total: 0,
      loading: false,
      unloadStatistics: {},
    };
  },
  created() {
    this.queryAllData();
  },
  methods: {
    /* 查询已预装 */
    getSecGoods() {
      loadSecGoodsList({ shipmentId: this.$attrs.shipmentObj.id }).then(
        (res) => {
          this.partList = res.data.map((item, index) => {
            item.fold = true;
            if (
              Object.keys(this.partData).length &&
              this.partData.id === item.id
            ) {
              item.fold = false;
            }
            return {
              ...item,
              title: this.$t("第{index}部分", { index: index + 1 }),
            };
          });

          if (this.partList.length && !Object.keys(this.partData).length) {
            this.partList[0].fold = false;
            this.partData = this.partList[0];
          }
        }
      );
    },
    /* 查询待预装 */
    getPreLoad() {
      this.loading = true;
      // 处理查询参数
      let params = {
        ...this.queryParams,
      };
      preloadPage({ ...params, ...this.pageParam }).then((res) => {
        const { data } = res;
        this.toBePreList = data.dataList?.list ?? [];
        this.total = data.dataList?.total ?? 0;
        this.unloadStatistics = data.unloadStatistics ?? {};
        this.loading = false;
      });
    },
    /* 删除订单 */
    deleteOrder(data) {
      let params = {
        secId: this.partData.id,
        shipmentId: this.$attrs.shipmentObj.id,
        orderId: data.orderId,
      };
      remove(params).then((res) => {
        serviceMsg(res, this).then(() => {
          this.getSecGoods();
        });
      }).catch((res) => {
        if (res.code === 666) {
              this.$confirm(res.msg+this.$t('是否需要一起移出?'), this.$t("提示"), {
                dangerouslyUseHTMLString: true,
                distinguishCancelAndClose: true,
                confirmButtonText: '确定移出',
                cancelButtonText: '仅移出当前订单'
              })
                .then((_) => {
                  remove({ ...params, deleteType: 2 }).then((res) => {
                    serviceMsg(res, this).then(() => {
                      this.getSecGoods();
                    });
                  });
                })
                .catch(action => {
                  if(action =='cancel'){
                    remove({ ...params, deleteType: 1 }).then((res) => {
                      serviceMsg(res, this).then(() => {
                        this.getSecGoods();
                      });
                    });
                  }
                });
            }
      });
    },
    /** 预装 */
    handleGoods(type, item) {
      let params = {
        secId: this.partData.id,
        shipmentId: this.$attrs.shipmentObj.id,
        orderId: item.orderId,
        isCover: 1
      };
      if (type === "all") {
        params.orderItemIdList = item.boxOrderItemList.map(
          (data) => data.orderItemId
        );
      } else {
        params.orderItemIdList = [item.orderItemId];
      }
      createGoods(params)
          .then((res) => {
            const { data } = res;
            if (data.relationMsg) {
              const msg = data.relationMsg.replaceAll(",", "，");
              this.$confirm(msg, this.$t("提示"), {
                dangerouslyUseHTMLString: true,
                type: "warning",
              })
                .then((_) => {
                  loadRelationOrder(data).then((res) => {
                    serviceMsg(res, this).then(() => {
                      this.queryAllData();
                    });
                  });
                })
                .catch((_) => {
                  this.queryAllData();
                });
            } else {
              serviceMsg(res, this).then(() => {
                this.queryAllData();
              });
            }
          })
          .catch((res) => {
            if (res.code === 555) {
              const msg = res.msg && res.msg.replaceAll(",", "，");
              this.$confirm(msg, this.$t("提示"), {
                dangerouslyUseHTMLString: true,
                type: "warning",
              })
                .then((_) => {
                  createGoods({ ...params, relationStatus: 1 }).then((res) => {
                    serviceMsg(res, this).then(() => {
                      this.queryAllData();
                    });
                  });
                })
                .catch((_) => {
                  this.queryAllData();
                });
            }
            
            if (res.code === 566) {
              this.$confirm(res.msg+this.$t('是否需要一起预装?'), this.$t("提示"), {
                dangerouslyUseHTMLString: true,
                distinguishCancelAndClose: true,
                confirmButtonText: '预装关联单',
                cancelButtonText: '仅当前订单'
              })
                .then((_) => {
                  createGoods({ ...params, relationStatus: 2, singleLoad: false }).then((res) => {
                    serviceMsg(res, this).then(() => {
                      this.queryAllData();
                    });
                  });
                })
                .catch((action) => {
                  if(action =='cancel'){
                    createGoods({ ...params, relationStatus: 2, singleLoad: true }).then((res) => {
                      serviceMsg(res, this).then(() => {
                        this.queryAllData();
                      });
                    });
                  }
                });
            }
          });
    },
    /* 增加部分 */
    addPart() {
      createSection({
        shipmentId: this.$attrs.shipmentObj.id,
        isCover: 1,
      }).then((res) => {
        serviceMsg(res, this).then(() => {
          this.getSecGoods();
        });
      });
    },
    /* 删除部分 */
    deletePart() {
      this.$confirm(
        this.$t("确认删除该部分及其已预装订单？"),
        this.$t("提示"),
        {
          type: "warning",
        }
      )
        .then((_) => {
          let params = {
            id: this.partData.id,
            deleteType: 2
          };
          deleteSection(params).then((res) => {
            serviceMsg(res, this).then(() => {
              this.partData = {};
              this.getSecGoods();
            });
          });
        })
        .catch((_) => {});
    },
    /* 部分点击 */
    partClick(item) {
      item.fold = !item.fold;
      this.partData = item;
      let copyList = [...this.partList];
      copyList = copyList.map((cItem) => {
        cItem.fold = true;
        if (item.id === cItem.id) {
          cItem.fold = false;
          return cItem;
        }
      });
      this.$set(this.partList, copyList);
    },
    /* 获取城市 */
    importCityName(id) {
      var arr = this.$attrs.warehouseList.filter((item) => item.id == id);
      return arr.length > 0 ? this.$l(arr[0], "title") : this.$t("无");
    },
    /* 待预装订单分页 */
    pageChange(page) {
      this.pageParam.pageNo = page;
      this.getPreLoad();
    },
    /* 折叠 */
    foldTable(index, item) {
      item.fold = !item.fold;
      this.$set(this.toBePreList, index, item);
    },
    /* 查询所有数据 */
    queryAllData() {
      this.getSecGoods();
      this.pageParam.pageNo = 1;
      this.getPreLoad();
    },
    /* 完成 */
    handlerFinish() {
      this.$confirm(this.$t("确定执行操作？"), this.$t("提示"), {
        type: "warning",
      })
        .then((_) => {
          this.$emit("supplementFinish");
        })
        .catch((_) => {});
    },
    formatDate,
    getTotlContent,
    sumStatistics,
  },
  computed: {
    /** 目的地 */
    importWarehouseList() {
      return this.$attrs.warehouseList.filter(
        (item) => item.tradeType == "1" || item.type == "3"
      );
    },
    /* 容量 */
    calcCapacity() {
      const { cabinetRespVO } = this.$attrs.shipmentObj;
      return getCapacity(cabinetRespVO);
    },
  },
};
</script>

<style lang="scss">
.supplementOrder {
  display: flex;
  flex-direction: column;
  p {
    margin: 0;
  }
  .el-card__body {
    height: 100%;
  }
  .content-area {
    display: flex;
    height: 100%;
    .left-area {
      border-right: 3px solid #e6ebf5;
      .el-scrollbar__view {
        padding-right: 10px;
      }
      .title-info {
        margin-top: 10px;
        height: auto;

        &.selected {
          > div:first-child {
            background-color: #4f9cdd;
            color: #fff;
          }
        }

        > div:first-child {
          font-size: 16px;
          background-color: #f2f2f2;
          line-height: 30px;
          text-align: center;
          cursor: pointer;
        }
        .part-secGoog {
          margin-top: 5px;
          display: flex;
          align-items: center;
          > p {
            margin-right: 10px;
            color: #4f9cdd;
          }
          > div {
            flex: 1;
            text-align: right;
            > i {
              cursor: pointer;
              color: red;
            }
          }
        }
      }
    }
    .right-area {
      padding-left: 10px;
      .right-title {
        display: flex;
        align-items: center;
        margin-bottom: 10px;
        font-size: 16px;
        > div:first-child {
          font-size: 18px;
        }
        > div:first-child + div {
          margin-left: 20px;
        }
        > div:last-child {
          flex: 1;
          text-align: right;
          font-size: 18px;
          color: red;
        }
      }
      .table-title {
        display: flex;
        align-items: center;
        line-height: 30px;
        background-color: #4f9cdd;
        color: #fff;
        > div {
          margin-left: 10px;
        }
        > div:last-child {
          flex: 1;
          display: flex;
          justify-content: flex-end;
          > .el-button--text {
            color: #fff;
          }
          > .el-button--text:last-child {
            margin-right: 10px;
          }
        }
      }
      .el-pagination {
        margin-top: 10px;
        padding: 0;
        text-align: right;
      }

      .toBePre-table {
        margin-bottom: 10px;
      }
    }
  }
  .totle-info {
    font-size: 20px;
    margin-top: 15px;
    > div {
      display: flex;
      margin-bottom: 5px;
    }
  }
  .button-area {
    text-align: center;
  }
}
</style>
