<template>
  <div>
    <el-form ref="cusDeclarationForm" :rules="rules" :model="cusDeclarationObj" label-width="120px">
      <el-form-item label="单证要求">
        <template v-for="(item, index) in cusDeclarationObj.documentInfo">
          <dict-tag :type="DICT_TYPE.ECW_CUSTOMS_TYPE" :value="item" :key="index" />
        </template>
        <el-button type="primary" style="margin-left:10px;" @click="downloadVGM">{{getButtonLabel(cusDeclarationObj.documentInfo)}}</el-button>
      </el-form-item>
      <el-form-item label="柜重" prop="dcBoxWgt">
        <el-input v-model="cusDeclarationObj.dcBoxWgt" placeholder="请输入柜重" clearable />
      </el-form-item>
      <el-form-item label="货重" prop="dcGoodsWgt">
        <el-input v-model="cusDeclarationObj.dcGoodsWgt" placeholder="请输入货重" clearable />
      </el-form-item>
      <el-form-item label="VGM重量">
        <el-input v-model="cusDeclarationObj.dcVgmWgt" placeholder="请输入VGM重量" clearable />
      </el-form-item>
      <el-form-item label="报关方式" prop="dcCustomsType">
        <el-select v-model="cusDeclarationObj.dcCustomsType" placeholder="请选择报关方式">
          <el-option v-for="type in this.getDictDatas(DICT_TYPE.BOX_SHIPPING_CUSTOMS_TYPE)" :key="type.value" :label="type.label" :value="type.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="正常报关订单">
      </el-form-item>
      <el-form-item label="报关公司名称">
        <supplierSelect v-model="cusDeclarationObj.dcCompanyId" :companyType="'2'" placeholder="请选择报关公司名称" :allSupplier="this.$attrs.allSupplier" />
      </el-form-item>
      <el-form-item label="截关时间">
        <el-date-picker type="datetime" placeholder="请选择日期" v-model="cusDeclarationObj.dcCutOffTime" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="dcCustomsStatus">
        <el-radio-group v-model="cusDeclarationObj.dcCustomsStatus">
          <el-radio v-for="item in this.getDictDatas(DICT_TYPE.BOX_SHIPPING_DCCUSTOMS_STATUS)" :key="item.value" :label="item.value">{{item.label}}</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 查验 -->
      <div v-show="cusDeclarationObj.dcCustomsStatus === '3'">
        <el-form-item label="查验">
          <el-radio-group v-model="cusDeclarationObj.dcCheckStatus">
            <el-radio v-for="item in this.getDictDatas(DICT_TYPE.BOX_SHIPPING_CHECK_STATUS)" :key="item.value" :label="item.value">{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>

      <!-- 退场 -->
      <div v-show="cusDeclarationObj.dcCheckStatus === '1' || cusDeclarationObj.dcCheckStatus === '2'">
        <el-form-item label="查验时间">
          <el-date-picker type="datetime" placeholder="请选择日期" v-model="cusDeclarationObj.dcCheckTime" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
        </el-form-item>
        <el-form-item label="查验前图片">
          <ImageUpload :limit="1" :isShowTip=false v-model="cusDeclarationObj.dcCheckPreImg" />
        </el-form-item>
        <el-form-item label="新封条">
          <el-input v-model="cusDeclarationObj.dcStripSeal" placeholder="请输入新封条" clearable />
        </el-form-item>
      </div>

      <!-- 放行 -->
      <el-form-item label="放行时间" v-show="cusDeclarationObj.dcCustomsStatus === '2' || cusDeclarationObj.dcCheckStatus === '2'">
        <el-date-picker type="datetime" placeholder="请选择日期" v-model="cusDeclarationObj.dcPassTime" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
      </el-form-item>

      <el-form-item label="装箱单">
        <el-button type="primary">下载装箱单</el-button>
      </el-form-item>
      <el-form-item label="报关单">
        <el-button type="primary">下载所有报关单</el-button>
      </el-form-item>

    </el-form>
    <el-row class="operate-button">
      <el-button type="primary" @click="onSubmit(1)">保存</el-button>
      <el-button type="success" @click="onSubmit(2)">提交</el-button>
      <el-button @click="cancel">关闭</el-button>
      <el-button type="primary" @click="extraCost" v-show="cusDeclarationObj.dcCustomsStatus === '2' || cusDeclarationObj.dcCustomsStatus === '3'">额外费用</el-button>
    </el-row>

    <!-- 对话框 -->
    <el-dialog custom-class="shipping-dialog customsClearance" :title="dialogConfig.title" :visible.sync="dialogConfig.dialogVisible" width="700px" :modal-append-to-body=false append-to-body>
      <el-row>
        <el-row>
          <el-form label-width="100px">
            <el-form-item label="订单号" class="two-element">
              <el-input v-model="orderNo" placeholder="请输入订单号" clearable />
              <el-button type="primary" icon="el-icon-search" @click="searchOrder"></el-button>
            </el-form-item>
          </el-form>
        </el-row>
        <el-row>
          <el-table :data="costOrderList">
            <el-table-column label="订单号" align="center" prop="orderNo" />
            <el-table-column label="报关费用" align="center" prop="fee">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.fee" controls-position="right" :min="1"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button type="primary" size="small" @click="createExtraCost(scope.row)">确定</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
        <el-row class="cost-title">
          <div>额外费用订单</div>
          <div>
            <el-button size="small" @click="restCostList()">重置</el-button>
          </div>
        </el-row>
        <el-row>
          <el-table :data="costList">
            <el-table-column type="selection" width="55" />
            <el-table-column label="订单号" align="center" prop="orderNo" />
            <el-table-column label="报关费用" align="center" prop="fee" width="220px">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.fee" controls-position="right" :min="1"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button type="primary" size="small" @click="updateExtraCost(scope.row)">修改</el-button>
                <el-button size="small" @click="restCostList(scope.row)">重置</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import supplierSelect from "./common/supplierSelect.vue";
import {
  customsCreate,
  extraCostList,
  extraCostOrder,
  extraCostCreate,
  extraCostUpdate,
  approvalCreate,
} from "@/api/ecw/boxSea";
import { formatNumberString, formatDateStr, serviceMsg } from "../utils";
import ImageUpload from "@/components/ImageUpload";

/**
 * 报关
 */
export default {
  name: "cusDeclaration",
  inheritAttrs: false,
  components: { supplierSelect, ImageUpload },
  data() {
    return {
      // 报关对象
      cusDeclarationObj: {},
      // 校验
      rules: {
        dcBoxWgt: [{ required: true, message: "必填", trigger: "change" }],
        dcGoodsWgt: [{ required: true, message: "必填", trigger: "change" }],
        dcCustomsType: [{ required: true, message: "必填", trigger: "change" }],
        dcCustomsStatus: [{ required: true, message: "必填", trigger: "change" }],
      },
      // 弹窗配置
      dialogConfig: {
        title: "",
        dialogVisible: false,
      },
      // 订单号
      orderNo: "",
      // 订单列表
      costOrderList: [],
      // 额外费用列表
      costList: [],
    };
  },
  created() {
    const { currNode, shipmentObj } = this.$attrs;
    const { voName } = currNode;
    let oldData = {
      ...shipmentObj[voName],
      documentInfo: shipmentObj.documentInfo?.split(",") ?? [],
    };
    oldData = formatDateStr(oldData, [
      "dcCutOffTime",
      "dcCheckTime",
      "dcPassTime",
    ]);
    oldData = formatNumberString(oldData, [
      "dcCustomsType",
      "dcCustomsStatus",
      "dcCheckStatus",
    ]);
    this.cusDeclarationObj = oldData;
  },
  methods: {
    getButtonLabel(documentInfo = []) {
      const newList = Array.from(new Set(documentInfo));
      return newList.length > 2 ? "混合报关" : "VGM声明";
    },
    /** 提交 */
    onSubmit(operateType) {
      this.$refs["cusDeclarationForm"].validate((valid) => {
        if (valid) {
          customsCreate({
            ...this.cusDeclarationObj,
            shipmentId: this.$attrs.shipmentObj.id,
            operateType,
          }).then((res) => {
            // 查验
            const { dcCustomsStatus, dcCheckStatus } = this.cusDeclarationObj;
            if (dcCustomsStatus === "3") {
              // 退场/部分退场
              if (["1", "2"].includes(dcCheckStatus)) {
                approvalCreate({
                  approvalStatus: 0,
                  approvalType: dcCheckStatus === "1" ? 5 : 6, // 5报关全退，6报关部分退
                  shipmentId: this.$attrs.shipmentObj.id,
                }).then((res) => {
                  serviceMsg(res, this).then(() => {
                    this.cancel("submit");
                  });
                });
              }
            } else {
              serviceMsg(res, this).then(() => {
                this.cancel("submit");
              });
            }
          });
        }
      });
    },
    /* 查询订单号 */
    searchOrder() {
      if (!this.orderNo) {
        this.$message.error("请输入订单号");
        return;
      }
      extraCostOrder({
        shipmentId: this.$attrs.shipmentObj.id,
        orderNo: this.orderNo,
      }).then((res) => {
        this.costOrderList = [
          {
            orderNo: this.orderNo,
            orderId: res.data,
          },
        ];
        this.searchCostList(res.data);
      });
    },
    /* 查询额外费用订单 */
    searchCostList(orderId) {
      extraCostList({
        shipmentId: this.$attrs.shipmentObj.id,
        orderId: orderId,
      }).then((res) => {
        this.costList = res.data.map((item) => {
          return { originalFee: item.fee, ...item };
        });
      });
    },
    /* 创建额外费用 */
    createExtraCost(row) {
      if (!row.fee) {
        this.$message.error("请输入费用");
        return;
      }
      extraCostCreate({
        fee: row.fee,
        orderId: row.orderId,
        orderNo: row.orderNo,
        shipmentId: this.$attrs.shipmentObj.id,
      }).then((res) => {
        serviceMsg(res, this).then(() => {
          this.searchCostList(row.orderId);
        });
      });
    },
    /* 修改额外费用 */
    updateExtraCost(row) {
      if (!row.fee) {
        this.$message.error("请输入费用");
        return;
      }
      extraCostUpdate(row).then((res) => {
        serviceMsg(res, this).then(() => {
          this.searchCostList(row.orderId);
        });
      });
    },
    /* 重置 */
    restCostList(row) {
      this.costList = this.costList.map((item) => {
        if (row && row.id === item.id) {
          return {
            ...item,
            fee: item.originalFee,
          };
        }
        if (!row) {
          return {
            ...item,
            fee: item.originalFee,
          };
        }
        return item;
      });
    },
    /** 取消 */
    cancel(type) {
      this.$emit("closeDialog", type);
    },
    // 下载VGM
    downloadVGM() {
      window.open(
        "http://pdatest.groupage.cn//apivue/boxTrack/vgmExport?token=930b11a41d9ca06f306d157f336a5dcb&id=1752"
      );
    },
    // 额外费用
    extraCost() {
      const { shipmentObj } = this.$attrs;
      // 清空额外费用
      this.orderNo = "";
      this.costOrderList = [];
      this.costList = [];
      this.$set(this.dialogConfig, "title", `${shipmentObj.selfNo} 报关费用`);
      this.$set(this.dialogConfig, "dialogVisible", true);
    },
    // 计算VGM重量
    calcVGM(dcBoxWgt, dcGoodsWgt) {
      let dcBoxWgtTmp = 0,
        dcGoodsWgtTmp = 0;
      if (!Number.isNaN(Number(dcBoxWgt))) {
        dcBoxWgtTmp = Number(dcBoxWgt);
      }
      if (!Number.isNaN(Number(dcGoodsWgt))) {
        dcGoodsWgtTmp = Number(dcGoodsWgt);
      }
      this.$set(
        this.cusDeclarationObj,
        "dcVgmWgt",
        dcBoxWgtTmp + dcGoodsWgtTmp
      );
    },
  },
  watch: {
    "cusDeclarationObj.dcBoxWgt"(dcBoxWgt) {
      this.calcVGM(dcBoxWgt, this.cusDeclarationObj.dcGoodsWgt);
    },
    "cusDeclarationObj.dcGoodsWgt"(dcGoodsWgt) {
      this.calcVGM(this.cusDeclarationObj.dcBoxWgt, dcGoodsWgt);
    },
    "cusDeclarationObj.dcCustomsStatus"(val) {
      if (val !== "3") {
        this.$set(this.cusDeclarationObj, "dcCheckStatus", "");
      }
    },
  },
};
</script>

<style lang="scss">
.customsClearance {
  .cost-title {
    display: flex;
    align-items: center;
    margin: 20px 0;
    border-left: 5px solid gray;
    > div:first-child {
      margin-left: 10px;
    }
    > div:last-child {
      flex: 1;
      text-align: right;
    }
  }
}
</style>
