<template>
  <div class="app-startUnloading">

    <!-- 自编号 -->
    <el-row class="number-area">
      <p class="label-font">自编号：</p>
      <p class="label-font">{{selfNo}}</p>
      <el-input v-model="labelNo" placeholder="请输入标签号"></el-input>
      <div>
        <el-button type="primary" @click="modifyBatchUnload">批量输入</el-button>
        <el-button type="primary" @click="modifyAllUnload">一键卸柜</el-button>
      </div>
    </el-row>

    <!-- 当前部分 -->
    <el-row class="number-area">
      <p class="label-font">当前部分：</p>
      <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>
        {{getSectionInfo}}
      </p>
    </el-row>

    <!-- 表格 -->
    <el-row class="table-area">
      <el-table v-loading="loading" :data="pageData.sectionOrderList" border max-height="500px">
        <el-table-column label="序号" type="index" align="center" width="50" />
        <el-table-column label="订单号" align="center" prop="orderNo">
          <template slot-scope="scope">
            {{ scope.row.orderNo }}
          </template>
        </el-table-column>
        <el-table-column label="商品信息" align="center" prop="goodsList">
          <template slot-scope="scope">
            <section class="table-goodList">
              <div v-for="(item, index) in scope.row.goodsList" :key="index" class="goodList-div">
                <p>{{index+1}}：{{item.prodTitleZh}}</p>
              </div>
            </section>
          </template>
        </el-table-column>
        <el-table-column label="实装箱数" align="center" prop="installNum" />
        <el-table-column label="卸柜箱数" align="center" prop="unloadNum" />
        <el-table-column label="清关状态" align="center" prop="">
          <template slot-scope="scope">{{clearStatus(scope.row)}}</template>
        </el-table-column>
        <el-table-column label="体积" align="center" prop="volume" />
        <el-table-column label="重量" align="center" prop="weight" />
        <el-table-column label="订单状态" align="center" prop="">
          <template slot-scope="scope">
            {{getOrderError(scope.row, 'orderStatus')}}
          </template>
        </el-table-column>
        <el-table-column label="异常状态" align="center" prop="">
          <template slot-scope="scope">
            <el-button v-if="scope.row.exceptionList" type="text" size="small" @click="handleError(scope.row)" icon="el-icon-edit">{{getOrderError(scope.row, 'errorStatus')}}</el-button>
          </template>
        </el-table-column>
        <el-table-column label="异常类型" align="center" prop="">
          <template slot-scope="scope">
            {{getUnloadError(scope.row.exceptionList)}}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="danger" size="small" @click="openError(scope.row)">异常</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>

    <!-- 总计 -->
    <el-row>
      <div class="label-font">
        <p>
          <span>总计：</span>
          <span>{{getTotlContent(pageData.totalStatistics)}}</span>
        </p>
      </div>
      <div class="label-font">
        <p>
          <span>已卸：</span>
          <span>{{getUnLoadNumCount}}</span>
        </p>
      </div>
    </el-row>

    <!-- 审核流程 -->
    <el-row class="process-area">
      <div class="process">
        <div>审批流程</div>
        <work-flow xmlkey="unload_container" v-model="selectedUsers"></work-flow>
      </div>
      <!-- 操作 -->
      <div v-if="!isUnderReview">
        <el-button type="success" @click="onSubmit">卸柜完成</el-button>
        <el-button plain type="primary" @click="$emit('closeStart')">返回</el-button>
      </div>
      <div v-if="isUnderReview">
        <el-button type="primary" @click="jumpReviewDetail">卸柜审核中</el-button>
        <el-button plain type="primary" @click="canclAudit">取消审核</el-button>
        <el-button plain type="primary" @click="$emit('closeStart')">返回</el-button>
      </div>
    </el-row>

    <!-- 对话框 -->
    <el-dialog custom-class="shipping-dialog" title="异常" :visible.sync="dialogVisible" width="600px" :modal-append-to-body=false append-to-body>
      <unloadingError v-if="dialogVisible" @closeDialog="closeDialog" v-bind="$attrs" :currRow="currRow" />
    </el-dialog>
  </div>
</template>

<script>
import unloadingError from "./unloadingError.vue";
import {
  loadGoodsList,
  batchUnload,
  allUnload,
  approvalCreate,
  approvalCancel,
  getSectionList,
} from "@/api/ecw/boxSea";
import { serviceMsg, getTotlContent, toReviewDetail } from "../../utils";
import WorkFlow from "@/components/WorkFlow";

/**
 * 开始卸柜
 */
export default {
  name: "startUnloading",
  inheritAttrs: false,
  components: { unloadingError, WorkFlow },
  data() {
    return {
      // 标签号
      labelNo: "",
      // 当前部分
      currPart: "",
      // loading
      loading: false,
      // 页面数据
      pageData: {},
      // 弹窗配置
      dialogVisible: false,
      // 自编号
      selfNo: this.$attrs.shipmentObj.selfNo,
      // 当前行
      currRow: {},
      // 部分
      sectionList: [],
      // 已选部分
      sectionId: "0",
      // 部分订单商品
      sectionObj: {
        secStatistics: {},
        sectionOrderList: [],
        totalStatistics: {},
      },
      selectedUsers: [],
    };
  },
  created() {
    this.getLoadGoodsList();
    // 部分
    getSectionList({ shipmentId: this.$attrs.shipmentObj.id }).then((res) => {
      this.sectionList = res.data.map((item, index) => {
        return {
          ...item,
          title: `第${index + 1}部分`,
        };
      });
    });
  },
  methods: {
    getTotlContent,
    /* 获取卸柜数据 */
    getLoadGoodsList() {
      this.loading = true;
      let params = {
        secId: this.sectionId,
        shipmentId: this.$attrs.shipmentObj.id,
      };
      loadGoodsList(params).then((res) => {
        const { data } = res;
        this.pageData = data;
        this.loading = false;
      });
    },
    /* 批量输入 */
    modifyBatchUnload() {
      if (!this.labelNo) {
        this.$message.error("请输入标签号");
        return;
      }
      batchUnload({
        orderNumCode: this.labelNo,
        shipmentId: this.$attrs.shipmentObj.id,
      }).then((res) => {
        serviceMsg(res, this).then((res) => {
          this.labelNo = "";
          this.getLoadGoodsList();
        });
      });
    },
    /* 一键卸柜 */
    modifyAllUnload() {
      this.$confirm("确认卸柜？", "提示", {
        type: "warning",
      })
        .then((_) => {
          allUnload({ shipmentId: this.$attrs.shipmentObj.id }).then((res) => {
            serviceMsg(res, this).then((res) => {
              this.getLoadGoodsList();
            });
          });
        })
        .catch((_) => {});
    },
    /** 提交 */
    onSubmit() {
      approvalCreate({
        shipmentId: this.$attrs.shipmentObj.id,
        approvalStatus: 0,
        approvalType: 3, // 卸柜
        copyUserId: this.selectedUsers,
      }).then((res) => {
        serviceMsg(res, this).then(() => {
          this.cancel();
        });
      });
    },
    /** 取消 */
    cancel() {
      this.$emit("closeStart", "submit");
    },
    /* 关闭弹窗 */
    closeDialog(type) {
      this.dialogVisible = false;
      if (type === "query") this.getLoadGoodsList();
    },
    /* 打开异常 */
    openError(row) {
      this.currRow = row;
      this.dialogVisible = true;
    },
    /* 清关状态 */
    clearStatus(row) {
      const { installNum, unloadNum } = row;
      if (installNum === unloadNum) {
        return "全部清关";
      }
      if (installNum >= unloadNum) {
        return "部分清关";
      }
      if (unloadNum === 0) {
        return "未清关";
      }
    },
    // 部分切换
    sectionChange() {
      this.getLoadGoodsList();
    },
    /* 取消审核 */
    canclAudit() {
      const { shipmentObj } = this.$attrs;
      approvalCancel({
        applyReason: "取消审核",
        id: shipmentObj["cabinetUnloadApprovalInfo"].id,
        shipmentId: shipmentObj.id,
      }).then((res) => {
        serviceMsg(res, this).then(() => {
          this.cancel();
        });
      });
    },
    // 获取异常类型
    getUnloadError(exceptionList = []) {
      const codes = this.getDictDatas(this.DICT_TYPE.ORDER_ERROR_TYPE);
      let errorLabels = [];
      exceptionList.forEach((item) => {
        const errObj = codes.find(
          (cItem) => cItem.value === item.orderExceptionType
        );
        if (errObj) errorLabels.push(errObj.label);
      });
      return errorLabels.join(",");
    },
    // 订单异常
    getOrderError(row, type) {
      if (row.exceptionList && row.exceptionList.length) {
        return type === "orderStatus" ? "卸柜异常" : "待处理";
      }
      return type === "orderStatus" ? "已到港" : "";
    },
    // 处理异常
    handleError(row) {
      this.$emit("closeStart", "close");
      this.$router.push({
        path: `/order/pending?id=${row.orderId}`,
      });
    },
    jumpReviewDetail() {
      const { cabinetUnloadApprovalInfo } = this.$attrs.shipmentObj;
      toReviewDetail.apply(this, [cabinetUnloadApprovalInfo.bpmProcessId]);
      this.$emit("closeStart", "close");
    },
  },
  computed: {
    /* 是否审核中 */
    isUnderReview() {
      const { currNode, shipmentObj } = this.$attrs;
      return shipmentObj[currNode.keyName] === 183 ? true : false;
    },
    // 部分信息
    getSectionInfo() {
      const { totalStatistics, secStatistics } = this.pageData;
      if (!this.sectionId) {
        return getTotlContent(totalStatistics);
      } else {
        return getTotlContent(secStatistics);
      }
    },
    /* 已卸总数 */
    getUnLoadNumCount() {
      let count = 0;
      if (this.pageData.sectionOrderList) {
        this.pageData.sectionOrderList.forEach((item) => {
          count = count + item.unloadNum;
        });
      }
      return count;
    },
  },
};
</script>

<style lang="scss" scoped>
.app-startUnloading {
  p {
    margin: 0;
    > span {
      margin-right: 5px;
    }
  }
  .el-row {
    margin-bottom: 15px;
  }
  .label-font {
    font-size: 16px;
    font-weight: bolder;
  }
  .number-area {
    display: flex;
    align-items: center;
    > * {
      margin-right: 10px;
    }
    > .el-input {
      width: 200px;
    }
  }
  .table-area {
    .table-goodList {
      .goodList-div {
        > p {
          text-align: left;
        }
        > p:last-child {
          > span {
            margin-right: 5px;
          }
        }
      }
    }
  }
}
</style>
