<template>
  <div class="app-container shipping-detail">
    <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">
        <div style="display: flex; justify-content: space-between;align-items: flex-end;">
          <h2>出货详情</h2>
          <div>
            <el-button size="small" @click="handleCommand('edit')">编辑</el-button>
            <el-button size="small" @click="handleCommand('router')">操作</el-button>
            <el-button type="primary" size="small" @click="handleCommand('error')">异常登记</el-button>
            <el-button type="primary" size="small" @click="handleCommand('cost')">费用登记</el-button>
            <el-button type="danger" size="small" @click="handleCommand('delete')">删除</el-button>
          </div>
        </div>
        <el-card style="margin-top: 15px">
          <el-descriptions :column="4" border>
            <el-descriptions-item label="自编号">
              {{shipmentObj.selfNo}}
            </el-descriptions-item>
            <el-descriptions-item label="运输方式">
              <dict-tag :type="DICT_TYPE.ECW_TRANSPORT_TYPE" :value="shipmentObj.transportType" />
            </el-descriptions-item>
            <!-- <el-descriptions-item label="出货渠道">
              {{getShipChannelName(shipmentObj.shippingChannelId)}}
            </el-descriptions-item> -->
            <el-descriptions-item label="柜型">
              {{getCabinetLabel(shipmentObj.cabinetId)}}
            </el-descriptions-item>
            <el-descriptions-item label="状态">
              {{getBoxStatus(shipmentObj)}}
            </el-descriptions-item>
            <el-descriptions-item label="总计">
              {{getBoxSum(shipmentObj.boxStatistics)}}
            </el-descriptions-item>
            <el-descriptions-item label="始发地">
              {{getCityName(shipmentObj.startWarehouseId)}}
            </el-descriptions-item>
            <el-descriptions-item label="目的地">
              {{getCityName(shipmentObj.destWarehouseId)}}
            </el-descriptions-item>
            <el-descriptions-item label="SO NO">
              {{shipmentObj.bookSeaInfo ? shipmentObj.bookSeaInfo.sono : '' }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <el-tabs style="margin-top: 15px" type="border-card" value="detail">
          <el-tab-pane label="明细" name="detail">
            <div class="detail-pane">
              <div>当前部分：</div>
              <el-select placeholder="请选择" v-model="sectionId" @change="sectionChange">
                <el-option key="0" label="全部" value="0"></el-option>
                <el-option v-for="item in sectionList" :key="item.id" :label="item.title" :value="item.id"></el-option>
              </el-select>
              <p class="box-weight">
                {{getSectionInfo}}
              </p>
              <div class="document-status">
                <p>单证状态：</p>
                <template v-for="(item, index) in getDocStatus(sectionObj.sectionOrderList)">
                  <dict-tag :type="DICT_TYPE.ECW_CUSTOMS_TYPE" :value="item" :key="index" />
                </template>
              </div>
            </div>
            <el-table :data="sectionObj.sectionOrderList" style="width: 100%" border>
              <el-table-column type="index" align="center" label="序号" width="50" />
              <el-table-column prop="orderNo" label="订单号" align="center">
                <template v-slot="scope">
                  <a href="javascript:void(0)" @click="jumpOrderDetail(scope.row)">{{ scope.row.orderNo }}</a>
                </template>
              </el-table-column>
              <el-table-column prop="goodsList" label="货物信息" width="250px" align="center">
                <template v-slot="{row}">
                  <section>
                    <div v-for="(item, index) in row.goodsList" :key="index">
                      {{index+1}}：{{item.prodTitleZh}}
                    </div>
                  </section>
                </template>
              </el-table-column>
              <el-table-column prop="num" label="计划箱数" align="center"></el-table-column>
              <el-table-column prop="installNum" label="实装箱数" align="center"></el-table-column>
              <el-table-column prop="unloadNum" label="卸柜箱数" align="center"></el-table-column>
              <el-table-column prop="destWarehouseName" label="提货点" align="center"></el-table-column>
              <el-table-column prop="volume" label="体积" align="center"></el-table-column>
              <el-table-column prop="weight" label="重量" align="center"></el-table-column>
              <el-table-column prop="totalWorth" label="货值" align="center"></el-table-column>
              <el-table-column prop="customsType" label="报关方式" align="center">
                <template slot-scope="scope">
                  <div :class="scope.row.customsType !== 1 ? 'customsType-red' : ''">
                    <dict-tag :type="DICT_TYPE.ECW_CUSTOMS_TYPE" :value="scope.row.customsType" />
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="customsFee" label="报关费用" align="center"></el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="状态" name="status">
            <div v-for="(item, index) in logList" :key="item.id" :class="`shipping-status ${index === 0 ? 'curr-status' : '' }`">
              <div class="status-line"></div>
              <div class="status-number">{{logList.length - index}}</div>
              <div class="status-info">
                <div>{{item.titleZh}}</div>
                <div>
                  <p>{{formatDate(item.createTime)}}</p>
                  <p>{{item.operator}}</p>
                </div>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="费用" name="fee">
            <el-table :data="costList" style="width: 100%" border>
              <el-table-column type="index" align="center" label="序号" width="50" />
              <el-table-column prop="costType" label="费用类型" align="center">
                <template slot-scope="scope">
                  <dict-tag :type="DICT_TYPE.FEE_TYPE" :value="scope.row.costType" />
                </template>
              </el-table-column>
              <el-table-column prop="supplierId" label="供应商" align="center">
                <template slot-scope="scope">
                  {{getSupplier(scope.row.supplierId)}}
                </template>
              </el-table-column>
              <el-table-column prop="price" label="金额" align="center"></el-table-column>
              <el-table-column prop="" label="实付金额" align="center"></el-table-column>
              <el-table-column prop="" label="实付日期" align="center"></el-table-column>
              <el-table-column prop="" label="操作" align="center">
                <template slot-scope="scope">
                  <el-button type="primary" size="small" @click="editCostClick(scope.row)" style="marginRight:10px;">编辑</el-button>
                  <el-popconfirm title="确定是否删除" @confirm="deleteCostClick(scope.row)">
                    <el-button type="danger" size="small" slot="reference">删除</el-button>
                  </el-popconfirm>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="异常" name="error">
            <el-table :data="errorList" style="width: 100%" border>
              <el-table-column type="index" align="center" label="序号" width="50" />
              <el-table-column prop="opStep" label="操作步骤" align="center">
                <template slot-scope="scope">
                  <dict-tag :type="DICT_TYPE.BOX_SHIPPING_PROCESS" :value="scope.row.opStep" />
                </template>
              </el-table-column>
              <el-table-column prop="billAbnId" label="异常" align="center">
                <template slot-scope="scope">
                  <dict-tag :type="DICT_TYPE.BOX_SHIPPING_TICKET_EXCEPTION" :value="scope.row.opStep" />
                </template>
              </el-table-column>
              <el-table-column prop="abnDetail" label="异常详情" align="center" width="800"></el-table-column>
              <el-table-column prop="" label="异常时间" align="center">
                <template slot-scope="scope">
                  <span v-if="scope.row.abnStartTime">{{formatDate(scope.row.abnStartTime)}} - </span>
                  <span v-if="scope.row.abnEndTime">{{formatDate(scope.row.abnEndTime)}}</span>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="表单" name="download">
            <el-table :data="[]" style="width: 50%">
              <el-table-column prop="" label="文件类型"> </el-table-column>
              <el-table-column prop="" label="下载链接"> </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>

    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogConfig.title" :visible.sync="dialogConfig.visible" :width="dialogConfig.width" append-to-body class="shippingSea-dialog">
      <template v-if="dialogConfig.type === 'edit'">
        <editForm v-if="dialogConfig.visible" @closeDialog="closeDialog" :shipmentObj="shipmentObj" :warehouseList="warehouseList" :transportTypes="transportTypes" :cabinetList="cabinetList" />
      </template>
      <template v-if="dialogConfig.type === 'cost'">
        <costForm v-if="dialogConfig.visible" @closeDialog="closeDialog" :shipmentObj="shipmentObj" :costDetail="costDetail" />
      </template>
      <template v-if="dialogConfig.type === 'error'">
        <regError v-if="dialogConfig.visible" @closeDialog="closeDialog" :shipmentObj="shipmentObj" />
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  getbox,
  getLogList,
  getCostList,
  getAbnormalList,
  deleteCost,
  deletebox,
} from "@/api/ecw/box";
import { getChannelList } from "@/api/ecw/channel";
import { getCabinetPage } from "@/api/ecw/cabinet";
import { getWarehouseList } from "@/api/ecw/warehouse";
import {
  getSeaStatus,
  getStatusName,
  getTotlContent,
  formatDate,
  serviceMsg,
} from "./shippingSea/utils";
import { getSectionList, boxGoodsDetail } from "@/api/ecw/boxSea";
import { getSupplierPage } from "@/api/ecw/supplier";
import costForm from "./costForm.vue";
import regError from "./regError.vue";
import editForm from "./editForm.vue";

export default {
  name: "boxDetail",
  props: {
    shipmentId: String,
  },
  components: {
    costForm,
    regError,
    editForm,
  },
  created() {
    this.transportTypes = this.getDictDatas(
      this.DICT_TYPE.ECW_TRANSPORT_TYPE
    ).filter((item) => item.value == "1" || item.value == "2");
    this.initData();
    this.queryAllData();
  },
  data() {
    return {
      // 出货对象
      shipmentObj: {},
      // 渠道
      channelList: [],
      // 柜型
      cabinetList: [],
      // 仓库
      warehouseList: [],
      // 供应商
      allSupplier: [],
      // 部分list
      sectionList: [],
      // 单证数组
      docStatus: [],
      // 操作日志
      logList: [],
      // 费用
      costList: [],
      // 异常
      errorList: [],
      // 部分订单商品
      sectionObj: {
        secStatistics: {},
        sectionOrderList: [],
        totalStatistics: {},
      },
      // 部分ID
      sectionId: "0",
      // 弹窗配置
      dialogConfig: {
        visible: false,
        title: "",
        width: "600px",
        type: "",
      },
      // 运输方式
      transportTypes: [],
      // 费用详情
      costDetail: {},
    };
  },
  methods: {
    // 初始化字典数据
    initData() {
      // 查询渠道
      getChannelList().then((res) => (this.channelList = res.data));
      // 查询柜型
      getCabinetPage(null).then(
        (response) => (this.cabinetList = response.data.list)
      );
      // 仓库
      getWarehouseList().then((r) => {
        this.warehouseList = r.data;
      });
      // 供应商
      getSupplierPage({ pageNo: "1", pageSize: "10000" }).then((res) => {
        const { data } = res;
        this.allSupplier = data.list;
      });
    },
    // 查询详情页所有数据
    queryAllData() {
      let param = { shipmentId: this.shipmentId };
      // 查询出货信息
      this.getBoxDetail();
      // 部分
      getSectionList(param).then((res) => {
        this.sectionList = res.data.map((item, index) => {
          return {
            ...item,
            title: `第${index + 1}部分`,
          };
        });
      });
      // 明细
      this.getBoxGoodsDetail();
      // 状态
      getLogList(param).then((res) => {
        this.logList = res.data;
      });
      // 费用
      this.getCost();
      // 异常
      getAbnormalList(param).then((res) => {
        this.errorList = res.data;
      });
      //表单
    },
    // 出货信息
    getBoxDetail() {
      getbox(this.shipmentId).then((res) => {
        const { data } = res;
        this.shipmentObj = data ?? {};
      });
    },
    // 获取费用
    getCost() {
      getCostList({ shipmentId: this.shipmentId }).then((res) => {
        this.costList = res.data;
      });
    },
    // 部分切换
    sectionChange() {
      this.getBoxGoodsDetail();
    },
    // 获取部分详情以及物品
    getBoxGoodsDetail() {
      boxGoodsDetail({
        shipmentId: this.shipmentId,
        secId: this.sectionId,
      }).then((res) => {
        this.sectionObj = res.data;
      });
    },
    // 供应商
    getSupplier(id) {
      let arr = this.allSupplier.find((item) => item.id == id) ?? {};
      return arr.companyZh ?? "";
    },
    editCostClick(row) {
      this.costDetail = row;
      this.handleCommand("cost");
    },
    deleteCostClick(row) {
      deleteCost(row.id).then((res) => {
        serviceMsg(res, this).then((res) => {
          this.getCost();
        });
      });
    },
    /* 跳转订单详情 */
    jumpOrderDetail(row) {
      this.$router.push({
        path: "/order/detail",
        query: { orderId: row.orderId },
      });
    },
    // 事件执行
    handleCommand(type) {
      switch (type) {
        case "edit":
          this.$set(this.dialogConfig, "visible", true);
          this.$set(this.dialogConfig, "title", "修改出货");
          this.$set(this.dialogConfig, "type", "edit");
          break;

        case "router":
          this.$router.push("/boxSea/shippingSea/" + this.shipmentId);
          break;

        case "cost":
          this.$set(this.dialogConfig, "visible", true);
          this.$set(this.dialogConfig, "title", "费用登记");
          this.$set(this.dialogConfig, "type", "cost");
          break;
        case "error":
          this.$set(this.dialogConfig, "visible", true);
          this.$set(this.dialogConfig, "title", "异常登记");
          this.$set(this.dialogConfig, "type", "error");
          break;
        case "delete":
          this.$modal
            .confirm(
              `是否确认删除出货编号为 ${this.shipmentObj.selfNo} 的数据项?`
            )
            .then(() => {
              return deletebox(this.shipmentId);
            })
            .then((res) => {
              serviceMsg(res, this).then((res) => {
                // 获取当前path
                const currPath = this.$router.currentRoute.path;
                // 根据path获取view
                const view = this.visitedViews.find(
                  (item) => item.path === currPath
                );
                if (view) {
                  this.$store.dispatch("tagsView/delView", view);
                  this.$router.push("/shipment/boxSea");
                }
              });
            })
            .catch(() => {});
          break;
      }
    },
    // 关闭弹框
    closeDialog(type) {
      this.$set(this.dialogConfig, "visible", false);
      if (type === "edit") {
        this.getBoxDetail();
      }
      if (type === "cost") {
        this.getCost();
      }
      if (type === "error") {
        getAbnormalList({ shipmentId: this.shipmentId }).then((res) => {
          this.errorList = res.data;
        });
      }
    },
    formatDate,
  },
  computed: {
    visitedViews() {
      return this.$store.state.tagsView.visitedViews;
    },
    // 单证状态
    getDocStatus() {
      return (list = []) => {
        // 获取类型
        let customsTypes = list.map((item) => item.customsType);
        // 去重
        return Array.from(new Set(customsTypes));
      };
    },
    /* 渠道 */
    getShipChannelName() {
      return (shippingChannelId) => {
        for (const channelItem of this.channelList) {
          if (channelItem.channelId == shippingChannelId) {
            return channelItem.nameZh;
          }
        }
      };
    },
    /* 获取柜型 */
    getCabinetLabel() {
      return (cabinetId) => {
        for (const cabinetItem of this.cabinetList) {
          if (cabinetItem.id == cabinetId) {
            return cabinetItem.name;
          }
        }
      };
    },
    /* 状态 */
    getBoxStatus() {
      return (shippingVO) => {
        return getStatusName(getSeaStatus(shippingVO));
      };
    },
    /* 总计 */
    getBoxSum() {
      return (boxStatistics) => {
        if (boxStatistics) {
          return `${boxStatistics.num ?? 0}箱 ${boxStatistics.volume ?? 0}m3 ${
            boxStatistics.weight ?? 0
          }kg`;
        }
        return;
      };
    },
    /* 获取仓库 */
    getCityName() {
      return (id) => {
        let arr = this.warehouseList.filter((item) => item.id == id);
        return arr.length > 0 ? arr[0].titleZh : "无";
      };
    },
    // 部分信息
    getSectionInfo() {
      const { totalStatistics, secStatistics } = this.sectionObj;
      if (!this.sectionId) {
        return getTotlContent(totalStatistics);
      } else {
        return getTotlContent(secStatistics);
      }
    },
  },
};
</script>

<style lang="scss">
.shipping-detail {
  .detail-pane {
    display: flex;
    align-items: center;
    margin-bottom: 5px;
    .box-weight {
      margin-left: 10px;
    }
    .document-status {
      flex: 1;
      justify-content: flex-end;
      display: flex;
      align-items: center;
      > span {
        margin-right: 10px;
      }
    }
  }
  .el-table__body {
    .customsType-red {
      color: red;
    }
  }
  .shipping-status {
    position: relative;
    display: flex;
    .status-line {
      width: 1px;
      height: calc(100% - 35px);
      background-color: #e8eaec;
      position: absolute;
      left: 13px;
      top: 30px;
    }
    .status-number {
      width: 26px;
      height: 26px;
      border: 1px solid #ccc;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .status-info {
      color: #999;
      margin-left: 20px;
      > :first-child {
        font-size: 14px;
        font-weight: bolder;
        line-height: 26px;
      }
      > :last-child {
        line-height: 26px;
        display: flex;
        > p {
          margin: 0;
          margin-right: 10px;
        }
      }
    }

    &.curr-status {
      .status-number {
        color: #fff;
        background-color: #2d8cf0;
        border-color: #2d8cf0;
      }
      .status-info {
        color: #666;
      }
    }
  }
}
</style>
