<template>
  <div class="preinstall">
    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="入仓时间" prop="rucangtime">
        <el-date-picker v-model="queryParams.rucangtime" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item label="始发地" prop="startWarehouseId">
        <el-select v-model="queryParams.startWarehouseId" placeholder="请选择始发地" clearable size="small">
          <el-option v-for="item in exportWarehouseList" :label="item.titleZh" :value="item.id" :key="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="目的地" prop="destWarehouseIdList">
        <el-select v-model="queryParams.destWarehouseIdList" placeholder="请选择目的地" 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="状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择状态" clearable size="small">
          <el-option v-for="item in stateOps" :label="item.label" :value="item.value" :key="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="备案" prop="productRecord">
        <el-select v-model="queryParams.productRecord" placeholder="请选择备案" clearable size="small">
          <el-option v-for="item in filingOps" :label="item.label" :value="item.value" :key="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="报关方式" prop="customsType">
        <el-select v-model="queryParams.customsType" placeholder="请选择报关方式" clearable size="small">
          <el-option v-for="item in declarationMethodOps" :label="item.label" :value="item.value" :key="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="订单号" prop="toBePreOrderNo">
        <el-input v-model="queryParams.orderNo" placeholder="请输入订单号码" clearable />
      </el-form-item>
      <el-form-item label="已预装单号" prop="preOrderNo">
        <el-input v-model="queryParams.preOrderNo" placeholder="请输入已预装单号" clearable />
      </el-form-item>
      <el-form-item label="品名" prop="itemName">
        <el-input v-model="queryParams.itemName" placeholder="请输入品名" clearable />
      </el-form-item>
      <el-form-item label="重货比" prop="weightRatioMax">
        <el-input v-model="queryParams.weightRatioMax" placeholder="请输入 大" clearable />
      </el-form-item>
      <el-form-item label="" prop="weightRatioMin">
        <el-input v-model="queryParams.weightRatioMin" placeholder="请输入 小" clearable />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery('pre')">搜索已预装订单</el-button>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery('toBePre')">搜索待预装订单</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="handleQuery('toBePre')"></right-toolbar>
    </el-row>

    <!-- 表格 -->
    <el-card style="margin-top: 15px" class="preinstall-card">
      <el-row class="preinstall-title">
        <div>
          <p>自编号：</p>
          <p>{{shipmentObj.selfNo}}</p>
        </div>
        <div>
          <p>柜号：</p>
          <p>{{shipmentObj.cubNo}}</p>
        </div>
        <div>
          <p>容量：</p>
          <p>无返回</p>
        </div>
        <div>
          <p>始发地：</p>
          <p>{{importCityName(shipmentObj.startWarehouseId)}}</p>
        </div>
        <div>
          <p>目的地：</p>
          <p>{{importCityName(shipmentObj.destWarehouseId)}}</p>
        </div>
      </el-row>
      <el-row class="preinstall-table">
        <!-- 已预装订单 -->
        <el-col :span="12">
          <el-row class="preinstall-title">
            <div class="table-label">已预装订单</div>
            <div>
              <p>总计：</p>
              <p>无返回</p>
            </div>
            <div class="red-label">
              <p>可预装方数：</p>
              <p>无返回</p>
            </div>
            <div class="red-label">
              <p>重量：</p>
              <p>无返回</p>
            </div>
            <div class="table-button">
              <el-button type="success" size="small" @click="addPart">增加</el-button>
            </div>
          </el-row>
          <el-scrollbar style="height:calc(100% - 43px)">
            <el-row v-for="(part, index) in preList" :key="index" class="pre-part">
              <el-row class="preinstall-title">
                <div class="pre-part-info">
                  <p>第{{index+1}}部分</p>
                  <p>
                    <span>{{part.secStatistics ? part.secStatistics.num : 0}}箱</span>
                    <span>{{part.secStatistics ? part.secStatistics.volume : 0}}m³</span>
                    <span>{{part.secStatistics ? part.secStatistics.weight : 0}}kg</span>
                  </p>
                </div>
                <div class="table-button">
                  <el-button type="danger" size="small" @click="deletePart(part)">删除部分</el-button>
                  <el-button type="danger" size="small" @click="deleteOrder('selected', part)">删除订单</el-button>
                  <el-button type="primary" size="small" @click="foldTable(index, part)">{{part.fold ? '展开' : '收起'}}</el-button>
                </div>
              </el-row>
              <el-collapse-transition>
                <div v-show="!part.fold">
                  <el-table v-loading="preLoading" border :data="part.sectionGoodsList" @select="(selection)=>checkboxSelect(selection, part)" @select-all="(selection)=>checkboxSelect(selection, part)">
                    <el-table-column type="selection" align="center" width="55" fixed="left" />
                    <el-table-column label="订单号" align="center" prop="orderNo" width="120" />
                    <el-table-column label="目的地" align="center" prop="destWarehouseName" width="120" />
                    <el-table-column label="入仓时间" align="center" prop="rucangtime" width="120" />
                    <el-table-column label="品名" align="center" prop="prodTitleZh" width="120" />
                    <el-table-column label="箱数" align="center" prop="num" />
                    <el-table-column label="体积/重量/重货比" align="center" width="140" prop="volumeWeight">
                      <template slot-scope="scope">
                        <p v-if="scope.row.volume">{{scope.row.volume}}m³</p>
                        <p v-if="scope.row.weight">{{scope.row.weight}}kg</p>
                      </template>
                    </el-table-column>
                    <el-table-column label="报关方式" align="center" prop="customsType" width="120">
                      <template slot-scope="scope">
                        <dict-tag :type="DICT_TYPE.ECW_CUSTOMS_TYPE" :value="scope.row.customsType" />
                      </template>
                    </el-table-column>
                    <el-table-column label="备案" align="center" prop="productRecord" width="100">
                      <template slot-scope="scope">
                        <dict-tag :type="DICT_TYPE.PRODUCT_RECORD_ATTRIBUTE" :value="scope.row.productRecord" />
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width" fixed="right">
                      <template slot-scope="scope">
                        <el-dropdown trigger="click" @command="(command)=>handleGoods('singele',scope.row,command)">
                          <el-button type="primary" size="small" icon="el-icon-edit-outline" circle></el-button>
                          <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item :command="bPart" v-for="(bPart, index) in preList" :key="bPart.id" v-show="bPart.id !== part.id">第{{index+1}}部分</el-dropdown-item>
                          </el-dropdown-menu>
                        </el-dropdown>
                        <el-button type="danger" size="small" icon="el-icon-minus" circle style="margin-left:10px;" @click="deleteOrder('row',scope.row)"></el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </el-collapse-transition>
            </el-row>
          </el-scrollbar>
        </el-col>
        <!-- 待预装订单 -->
        <el-col :span="12">
          <el-row class="preinstall-title">
            <div class="table-label red-label">待预装订单</div>
            <div class="preinstall-title preinstalled">
              <div class="red-label">
                <p>筛选后待预装数量：</p>
                <p>无返回</p>
              </div>
              <div class="red-label">
                <p>方数：</p>
                <p>无返回</p>
              </div>
              <div class="red-label">
                <p>重量：</p>
                <p>无返回</p>
              </div>
            </div>
          </el-row>
          <el-pagination background layout="prev, pager, next" :page-size="pageParam.pageSize" :total="total" @current-change="pageChange" v-show="total > 0"></el-pagination>
          <el-scrollbar style="height:calc(100% - 75px)">
            <el-row v-for="(item, index) in toBePreList" :key="index" class="tobePre-row">
              <el-row class="preinstall-title order-title">
                <div>
                  <p>{{item.orderNo}}</p>
                </div>
                <div>
                  <p>发往：</p>
                  <p>{{item.destWarehouseName}}</p>
                </div>
                <div>
                  <p>
                    <dict-tag :type="DICT_TYPE.ECW_CUSTOMS_TYPE" :value="item.customsType" />
                  </p>
                </div>
                <div>
                  <p>入仓时间：</p>
                  <p>{{item.rucangtime}}</p>
                </div>
                <div>
                  <p>重货比：</p>
                  <p>{{item.weightRatio}}</p>
                </div>
                <div class="table-button">
                  <el-dropdown trigger="click" @command="(command)=>handleGoods('all',item,command)">
                    <el-button type="success" size="small">预装全部</el-button>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item :command="part" v-for="(part, index) in preList" :key="part.id">第{{index+1}}部分</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </div>
              </el-row>
              <el-table v-loading="toBePreLoading" :data="item.orderItemList" border show-summary :summary-method="getSummaries">
                <el-table-column type="index" align="center" label="序号" width="50" />
                <el-table-column label="品名" align="center" prop="prodTitleZh" />
                <el-table-column label="备案" align="center" prop="brandType">
                  <template slot-scope="scope">
                    <dict-tag :type="DICT_TYPE.PRODUCT_RECORD_ATTRIBUTE" :value="scope.row.brandType" />
                  </template>
                </el-table-column>
                <el-table-column label="箱数" align="center" prop="num" />
                <el-table-column label="体积/重量" align="center" prop="volumeWeight">
                  <template slot-scope="scope">
                    <p v-if="scope.row.volume">{{scope.row.volume}}m³</p>
                    <p v-if="scope.row.weight">{{scope.row.weight}}kg</p>
                  </template>
                </el-table-column>
                <el-table-column label="报关方式" align="center" prop="" />
                <el-table-column label="包装类型" align="center" prop="" />
                <el-table-column label="材质" align="center" prop="material" />
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                  <template slot-scope="scope">
                    <el-dropdown trigger="click" @command="(command)=>handleGoods('singele',scope.row,command)">
                      <el-button type="primary" size="small">预装</el-button>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item :command="part" v-for="(part, index) in preList" :key="part.id">第{{index+1}}部分</el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </template>
                </el-table-column>
              </el-table>
            </el-row>
          </el-scrollbar>
        </el-col>
      </el-row>
    </el-card>

    <!-- 操作员 -->
    <el-row style="margin-top: 15px">
      <el-row>
        <el-form ref="operatorForm" :model="operatorData" size="small" :inline="true" label-width="120px" :rules="rules">
          <el-form-item label="目的地操作员" prop="noticeUser">
            <userSelect v-model="operatorData.noticeUser" placeholder="请选择目的地操作员" :allUsers="this.$attrs.allUsers" size="small" />
          </el-form-item>
        </el-form>
      </el-row>
      <el-row style="margin-top: 10px">
        <el-button type="primary" @click="onSubmit">提交申请</el-button>
      </el-row>
    </el-row>
  </div>
</template>

<script>
import { DICT_TYPE } from "@/utils/dict";
import {
  secGoodsList,
  preloadPage,
  createSection,
  deleteSection,
  serviceMsg,
  createGoods,
  deleteGoods,
  approvalCreate,
} from "@/api/ecw/boxSea";
import userSelect from "./common/userSelect.vue";

/**
 * 预装
 */
export default {
  name: "preinstall",
  inheritAttrs: false,
  components: { userSelect },
  data() {
    return {
      // 状态
      stateOps: [
        { value: "1", label: "拆单" },
        { value: "2", label: "关联单" },
      ],
      // 备案
      filingOps: this.getDictDatas(DICT_TYPE.COMMISSION_PRODUCT_APPROVAL),
      // 报关方式
      declarationMethodOps: this.getDictDatas(DICT_TYPE.ECW_CUSTOMS_TYPE),
      // 查询标识
      type: "",
      // 已预装 遮罩层
      preLoading: false,
      preList: [],
      // 选中行
      selectedRows: {},

      // 待预装
      toBePreLoading: false,
      toBePreList: [],
      total: 0,

      // 显示搜索条件
      showSearch: true,

      // 查询参数
      queryParams: {},
      pageParam: { pageNo: 1, pageSize: 10 },
      // 目的地操作员
      operatorData: {},
      // 校验
      rules: {
        noticeUser: [{ required: true, message: "必填", trigger: "change" }],
      },
      // 出货信息
      shipmentObj: this.$attrs.shipmentObj,
    };
  },
  computed: {
    /** 始发地 */
    exportWarehouseList() {
      return this.$attrs.warehouseList.filter(
        (item) => item.tradeType == "2" || item.type == "3"
      );
    },
    /** 目的地 */
    importWarehouseList() {
      return this.$attrs.warehouseList.filter(
        (item) => item.tradeType == "1" || item.type == "3"
      );
    },
  },
  created() {
    // 查询待预装
    this.handleQuery("toBePre");
  },
  methods: {
    /* 获取城市 */
    importCityName(id) {
      var arr = this.$attrs.warehouseList.filter((item) => item.id == id);
      return arr.length > 0 ? arr[0].titleZh : "无";
    },
    /* 选中行 */
    checkboxSelect(selection, part) {
      this.selectedRows[part.id] = selection;
    },
    /* 查询已预装 */
    getSecGoods() {
      this.preLoading = true;
      // 处理查询参数
      let params = { ...this.queryParams };
      // 已预装单号
      params.orderNo = params.preOrderNo;
      params.shipmentId = this.shipmentObj.id;
      secGoodsList(params).then((res) => {
        this.preList = res.data;
        this.preLoading = false;
      });
    },
    /* 查询待预装 */
    getPreLoad() {
      this.toBePreLoading = true;
      // 处理查询参数
      let params = { ...this.queryParams };
      // 订单号
      params.orderNo = params.toBePreOrderNo;
      preloadPage({ ...params, ...this.pageParam }).then((res) => {
        this.toBePreList = res.data.list;
        this.total = res.data.total;
        this.toBePreLoading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery(type) {
      this.pageParam.pageNo = 1;
      if (type === "pre") {
        this.getSecGoods();
      } else {
        this.getPreLoad();
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
    },
    /** 提交 */
    onSubmit() {
      this.$refs["operatorForm"].validate((valid) => {
        if (valid) {
          approvalCreate({
            ...this.operatorData,
            shipmentId: this.$attrs.shipmentObj.id,
            approvalStatus: 0,
            approvalType: 1,
          }).then((res) => {
            serviceMsg(res, this).then(() => {
              this.$emit("closeDialog", "submit");
            });
          });
        }
      });
    },
    /* 统计列 */
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (column.property === "brandType") {
          sums[index] = "合计";
          return;
        }
        if (column.property === "num") {
          sums[index] = this.calcSum(column.property, data) ?? 0;
        }
        if (column.property === "volumeWeight") {
          const volume = this.calcSum("volume", data);
          const weight = this.calcSum("weight", data);
          sums[index] = `${volume ?? 0}m³ ${weight ?? 0}kg`;
        }
      });

      return sums;
    },
    /* 计算总和 */
    calcSum(key, data) {
      const values = data.map((item) => Number(item[key]));
      if (!values.every((value) => isNaN(value))) {
        return values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!isNaN(value)) {
            return prev + curr;
          } else {
            return prev;
          }
        }, 0);
      }
    },
    /* 待预装订单分页 */
    pageChange(page) {
      this.pageParam.pageNo = page;
      this.getPreLoad();
    },
    /* 折叠 */
    foldTable(index, part) {
      part.fold = !part.fold;
      this.$set(this.preList, index, part);
    },
    /* 增加部分 */
    addPart() {
      createSection({ shipmentId: this.shipmentObj.id }).then((res) => {
        serviceMsg(res, this).then(() => {
          this.getSecGoods();
        });
      });
    },
    /* 删除部分 */
    deletePart(part) {
      this.$confirm("确认删除该部分及其已预装订单？", "提示", {
        type: "warning",
      })
        .then((_) => {
          deleteSection(part.id).then((res) => {
            serviceMsg(res, this).then(() => {
              this.getSecGoods();
            });
          });
        })
        .catch((_) => {});
    },
    /** 预装 */
    handleGoods(type, item, part) {
      let params = {
        secId: part.id,
        shipmentId: this.shipmentObj.id,
        orderId: item.orderId,
      };
      if (type === "all") {
        params.orderItemIdList = item.orderItemList.map(
          (data) => data.orderItemId
        );
      } else {
        params.orderItemIdList = [item.orderItemId];
      }
      createGoods(params).then((res) => {
        serviceMsg(res, this).then(() => {
          this.queryAllData();
        });
      });
    },
    /* 删除订单 */
    deleteOrder(type, data) {
      let ids = [];
      if (type === "selected") {
        const rows = this.selectedRows[data.id] ?? [];
        if (!rows.length) {
          this.$message.warning("请选择订单");
          return;
        }
        ids = rows.map((item) => item.orderItemId);
      }

      if (type === "row") {
        ids.push(data.orderItemId);
      }

      deleteGoods(ids).then((res) => {
        serviceMsg(res, this).then(() => {
          this.queryAllData();
        });
      });
    },
    /* 查询所有数据 */
    queryAllData() {
      this.getSecGoods();
      this.pageParam.pageNo = 1;
      this.getPreLoad();
    },
  },
};
</script>

<style lang="scss">
.preinstall {
  display: flex;
  flex-direction: column;

  p {
    margin: 0;
  }
  .preinstall-title {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    padding: 0 10px;

    &.preinstalled {
      flex: 1;
      display: flex;
      justify-content: flex-end;
      > div {
        display: flex;
      }
    }

    &.order-title {
      margin-bottom: 0px;
      background-color: #e6ebf5;
      height: 45px;
    }

    > div {
      display: flex;
      margin-right: 10px;
    }

    .table-label {
      font-size: 16px;
      font-weight: bolder;
    }
    .red-label {
      color: red;
    }
    .table-button {
      flex: 1;
      margin: 0;
      display: flex;
      justify-content: flex-end;
    }
  }
  .preinstall-table {
    display: flex;
    height: calc(100% - 30px);
    > div {
      border: 1px solid #e6ebf5;
      padding: 10px 0px;
    }
    > div:first-child {
      margin-right: 10px;
    }
  }

  .pre-part {
    margin-bottom: 10px;
    margin-right: 10px;
    .pre-part-info {
      font-weight: bolder;
      > p:first-child {
        color: #13ce66;
        margin-right: 10px;
      }
      > p:last-child {
        > span {
          margin-right: 5px;
        }
      }
    }
  }

  .preinstall-card {
    .el-card__body {
      height: 100%;

      .tobePre-row {
        margin-top: 10px;
      }
    }
  }
}
</style>
