<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item :label="$t('自编号')" prop="selfNo">
        <el-input v-model="queryParams.selfNo" :placeholder="$t('请输入自编号')" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item :label="$t('柜号')" prop="cubNo">
        <el-input v-model="queryParams.cubNo" :placeholder="$t('请输入柜号')" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item :label="$t('柜型')" prop="cabinetId">
        <el-select v-model="queryParams.cabinetId" :placeholder="$t('请选择柜型')" clearable>
          <el-option v-for="item in cabinetList" :label="$l(item, 'name')" :value="item.id" :key="item.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item :label="$t('始发地')" prop="startWarehouseId">
        <el-select v-model="queryParams.startWarehouseId" :placeholder="$t('请选择始发地')" clearable>
          <el-option v-for="item in exportWarehouseList" :label="$l(item, 'title')" :value="item.id" :key="item.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item :label="$t('目的地')" prop="destWarehouseId">
        <el-select v-model="queryParams.destWarehouseId" :placeholder="$t('请选择目的地')" clearable>
          <el-option v-for="item in importWarehouseList" :label="$l(item, 'title')" :value="item.id" :key="item.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="" prop="dateType">
        <el-select v-model="queryParams.dateType" :placeholder="$t('请选择时间类型')" clearable size="small">
          <el-option v-for="item in dateTypes" :key="item.value" :label="$l(item, 'label')" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="" prop="dateRangeCreateTime">
        <el-date-picker v-model="queryParams.dateRangeCreateTime" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange" range-separator="-" :start-placeholder="$t('开始日期')" :end-placeholder="$t('结束日期')" clearable />
      </el-form-item>

      <el-form-item :label="$t('状态')" prop="boxStatus">
        <el-select v-model="queryParams.boxStatus" :placeholder="$t('请选择状态')" clearable size="small">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.BOX_SEA_AIR_SHIPMENT_STATUS)" :key="dict.value" :label="$l(dict, 'label')" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">{{$t('搜索')}}</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">{{$t('重置')}}</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['shipment:box:create:seaAir']">{{$t('出货安排')}}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading" v-hasPermi="['shipment:box:export:seaAir']">{{$t('导出')}}
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="list">
      <el-table-column :label="$t('自编号')" align="center" prop="selfNo">
        <template slot-scope="scope">
          <a href="javascript:void(0)" @click="handleCommand(scope.row, 'detail')">{{ scope.row.selfNo }}</a>
        </template>
      </el-table-column>
      <el-table-column :label="$t('柜号')" align="center" prop="cubNo" />
      <el-table-column :label="$t('柜型')" align="center" prop="cabinetId">
        <template slot-scope="scope">
          <span>{{ getCabinetName(scope.row.cabinetId) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('运输方式')" align="center" prop="transportType">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.ECW_TRANSPORT_TYPE" :value="scope.row.transportType" />
        </template>
      </el-table-column>

      <el-table-column :label="$t('出货渠道')" align="center" prop="shippingChannelId">
        <template slot-scope="scope">
          <span>{{ getShipChannelName(scope.row.shippingChannelId) }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('方数') + '(' + $t('预装') + '/' + $t('已装') + ')'" align="center" prop="squareNumber">
        <template slot-scope="{ row }">
          {{ row.boxStatistics.volume }}/{{ row.boxStatistics.loadVolume }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('重量')+'(' + $t('预装') + '/' + $t('已装' + ')')" align="center" prop="weight">
        <template slot-scope="{ row }">
          {{ row.boxStatistics.weight }}/{{ row.boxStatistics.loadWeight }}
        </template>
      </el-table-column>

      <el-table-column :label="$t('状态')" align="center" prop="shipmentStatusText" />

      <el-table-column :label="$t('日期')" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ new Date(scope.row.createTime).format('yyyy-MM-dd hh:mm:ss') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('操作')" align="center" class-name="small-padding fixed-width" width="200px">
        <template slot-scope="scope">
          <el-dropdown trigger="click" v-hasPermi="['shipment:seaAir:action:edit','shipment:seaAir:action:sea','shipment:seaAir:action:error','shipment:seaAir:action:cost','shipment:seaAir:action:delete','shipment:seaAir:action:editLadingBill']" @command="(command)=>handleCommand(scope.row, command)" style="marginRight:10px;">
            <el-button type="primary">
              {{$t('操作')}}<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :disabled="scope.row.ldStatus>=46" command="edit" v-hasPermi="['shipment:seaAir:action:edit']">{{$t('编辑')}}</el-dropdown-item>
              <el-dropdown-item  command="seaAir" v-hasPermi="['shipment:seaAir:action:seaAir']">{{$t('海空联运')}}</el-dropdown-item>
              <el-dropdown-item command="error" v-hasPermi="['shipment:seaAir:action:error']">{{$t('异常登记')}}</el-dropdown-item>
              <el-dropdown-item command="cost" v-hasPermi="['shipment:seaAir:action:cost']">{{$t('费用登记')}}</el-dropdown-item>
              <el-dropdown-item command="delete" v-hasPermi="['shipment:seaAir:action:delete']">{{$t('删除')}}</el-dropdown-item>
              <el-dropdown-item :disabled="scope.row.ldStatus<46" command="editLadingBill" v-hasPermi="['shipment:seaAir:action:editLadingBill']">{{$t('编辑提货单')}}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-dropdown trigger="click" @command="(command)=>handleCommand(scope.row, command)" v-hasPermi="['shipment:seaAir:download:downloadPreloadGoodsList','shipment:seaAir:download:downloadLoadGoodsList','shipment:seaAir:download:downloadReceivableList','shipment:seaAir:download:downloadAgentListFiles','shipment:seaAir:download:downloadSoncapFiles','shipment:seaAir:download:zipDownload','shipment:seaAir:download:downloadLadingCopy']">
            <el-button type="primary">
              {{$t('下载')}}<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="downloadPreloadGoodsList" v-hasPermi="['shipment:seaAir:download:downloadPreloadGoodsList']">{{$t('预装单')}}</el-dropdown-item>
              <el-dropdown-item command="downloadLoadGoodsList" v-hasPermi="['shipment:seaAir:download:downloadLoadGoodsList']">{{$t('已装单')}}</el-dropdown-item>
              <el-dropdown-item command="downloadReceivableList" v-hasPermi="['shipment:seaAir:download:downloadReceivableList']">{{$t('应收汇总表')}}</el-dropdown-item>
              <el-dropdown-item command="downloadAgentListFiles" v-hasPermi="['shipment:seaAir:download:downloadAgentListFiles']">agent list</el-dropdown-item>
              <el-dropdown-item command="downloadSoncapFiles" v-hasPermi="['shipment:seaAir:download:downloadSoncapFiles']">soncap</el-dropdown-item>
              <el-dropdown-item command="zipDownload" v-hasPermi="['shipment:seaAir:download:zipDownload']">{{$t('提货单')}}</el-dropdown-item>
              <el-dropdown-item command="downloadLadingCopy" v-hasPermi="['shipment:seaAir:download:downloadLadingCopy']">{{$t('提单Copy')}}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.rows" @pagination="getList" />

    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogCfg.title" :visible.sync="dialogCfg.open" :width="dialogCfg.width" :fullscreen="dialogCfg.fullscreen" append-to-body class="shippingSea-dialog">
      <template v-if="dialogCfg.dialogType === 'edit' || dialogCfg.dialogType === 'add'">
        <editForm v-if="dialogCfg.open" @closeDialog="closeDialog" :shipmentObj="currRow" :warehouseList="warehouseList" :transportTypes="transportTypes" :cabinetList="cabinetList" />
      </template>
      <template v-if="dialogCfg.dialogType === 'cost'">
        <costForm v-if="dialogCfg.open" @closeDialog="closeDialog" :shipmentObj="currRow" />
      </template>
      <template v-if="dialogCfg.dialogType === 'error'">
        <regError v-if="dialogCfg.open" @closeDialog="closeDialog" :shipmentObj="currRow" :allUsers="allUsers" />
      </template>
      <template v-if="dialogCfg.dialogType === 'editLadingBill'">
        <ladingBill v-if="dialogCfg.open" @closeDialog="closeDialog" :shipmentObj="currRow" :getCabinetName="getCabinetName" />
      </template>
      <template v-if="dialogCfg.dialogType === 'notice'">
        <div class="notice-dialog">
          <div class="notice-title">{{$t('您有{cnt}个待处理出货操作,请尽快前往处理', {cnt: noticeList.length})}}:</div>
          <el-table :data="noticeList" height="500px" border>
            <el-table-column :label="$t('自编号')" align="center" prop="selfNo" />
            <el-table-column :label="$t('类型')" align="center">
              <template slot-scope="scope">
                <dict-tag :type="DICT_TYPE.BOX_SHIPPING_NOTICE_TYPE" :value="String(scope.row.noticeType)" />
              </template>
            </el-table-column>
            <el-table-column :label="$t('预计时间')" align="center">
              <template slot-scope="scope">
                {{formatDate(scope.row.createTime)}}
              </template>
            </el-table-column>
            <el-table-column :label="$t('操作')" align="center" width="80">
              <template slot-scope="scope">
                <el-button type="text" @click="handleCommand(scope.row, 'handle')">{{$t('处理')}}</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-row class="operate-button">
            <el-button type="primary" @click="closeDialog">{{$t('关闭窗口')}}</el-button>
          </el-row>
        </div>

      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  deletebox,
  getbox,
  getboxPage,
  exportboxExcel,
  getNoticeList,
} from "@/api/ecw/box";
import {
  downloadFile,
  downloadFileByUrl,
  formatDate,
} from "./shippingSea/utils";
import { getCabinetPage } from "@/api/ecw/cabinet";
import { getChannelList } from "@/api/ecw/channel";
import { getWarehouseList } from "@/api/ecw/warehouse";
import costForm from "./costForm.vue";
import regError from "./regError.vue";
import editForm from "./editSeaAirForm.vue";
import ladingBill from "./ladingBill/index.vue";
import { listUser } from "@/api/system/user";

export default {
  name: "EcwBoxIndexseaair",
  components: {
    costForm,
    regError,
    editForm,
    ladingBill,
  },
  data() {
    return {
      dateTypes: [
        { value: "1", label: this.$t("预装时间") },
        { value: "2", label: this.$t("装柜时间") },
        { value: "3", label: this.$t("起运时间") },
        { value: "4", label: this.$t("到港时间") },
        { value: "5", label: this.$t("清关时间") },
        { value: "6", label: this.$t("卸柜时间") },
      ],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 出货列表
      list: [],
      // 弹出层标题
      // 弹出类型
      dialogCfg: {
        title: "",
        dialogType: "",
        width: "600px",
        // 是否显示弹出层
        open: false,
        fullscreen: false,
      },
      // 当前行
      currRow: {},
      dateRangeCreateTime: [],
      // 查询参数
      queryParams: {
        page: 1,
        rows: 10,
      },
      cabinetList: [],
      channelList: [],
      warehouseList: [],
      transportTypes: [],
      // 通知列表
      noticeList: [],
      allUsers: [],
    };
  },
  computed: {
    exportWarehouseList() {
      return this.warehouseList.filter(
        (item) => item.tradeType == "2" || item.type == "3"
      );
    },
    importWarehouseList() {
      return this.warehouseList.filter(
        (item) => item.tradeType == "1" || item.type == "3"
      );
    },
    getCabinetName() {
      return (cabinetId) => {
        for (let index in this.cabinetList) {
          let cabinetItem = this.cabinetList[index];
          if (cabinetItem.id == cabinetId) {
            return cabinetItem.name;
          }
        }
        return "/";
      };
    },

    getShipChannelName() {
      return (shippingChannelId) => {
        for (let index in this.channelList) {
          let channelItem = this.channelList[index];
          if (channelItem.channelId == shippingChannelId) {
            return this.$l(channelItem, "name");
          }
        }
        return "/";
      };
    },
  },
  created() {
    this.transportTypes = this.getDictDatas(
      this.DICT_TYPE.ECW_TRANSPORT_TYPE
    ).filter((item) => item.value == "4");
    getWarehouseList().then((res) => (this.warehouseList = res.data));
    getCabinetPage({status:0}).then((response) => {
      this.cabinetList = response.data.list;
    });
    this.getList();
    this.getChannelList();
    this.queryNotice();
    // 用户
    listUser({ pageNo: "1", pageSize: "10000" }).then((res) => {
      const { data } = res;
      this.allUsers = data.list ?? [];
    });
  },
  methods: {
    formatDate,
    getChannelList() {
      getChannelList().then((res) => (this.channelList = res.data));
    },
    queryNotice() {
      getNoticeList({
        transportTypeList: this.transportTypes.map((item) => item.value),
      }).then((res) => {
        const { data } = res;
        this.noticeList = data ?? [];
        if (data.length) {
          this.$set(this.dialogCfg, "title", this.$t("出货操作提醒"));
          this.$set(this.dialogCfg, "dialogType", "notice");
          this.$set(this.dialogCfg, "width", "650px");
          this.$set(this.dialogCfg, "open", true);
        }
      });
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 处理查询参数
      let params = { ...this.queryParams };
      params.transportType = 4;
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, "createTime");
      // 执行查询
      getboxPage(params).then((response) => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {};
      this.dateRangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    resetForm() {
      this.$refs["queryForm"].resetFields();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$set(this.dialogCfg, "title", this.$t("添加出货"));
      this.$set(this.dialogCfg, "dialogType", "add");
      this.$set(this.dialogCfg, "width", "600px");
      this.$set(this.dialogCfg, "fullscreen", false);
      this.$set(this.dialogCfg, "open", true);
      this.currRow = {
        transportType: "4",
      };
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const id = row.id;
      getbox(id).then((response) => {
        this.currRow = response.data;
        this.$set(this.dialogCfg, "title", this.$t("修改出货"));
        this.$set(this.dialogCfg, "dialogType", "edit");
        this.$set(this.dialogCfg, "width", "600px");
        this.$set(this.dialogCfg, "open", true);
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal
        .confirm(this.$t("是否确认删除出货编号为{id}的数据项?", { id }))
        .then(function () {
          return deletebox(id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess(this.$t("删除成功"));
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = { ...this.queryParams };
      params.page = undefined;
      params.pageSize = undefined;
      params.transportTypeList = ['4'];
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, "createTime");
      // 执行导出
      this.$modal
        .confirm(this.$t("是否确认导出所有出货数据项?"))
        .then(() => {
          this.exportLoading = true;
          return exportboxExcel(params);
        })
        .then((response) => {
          this.$download.excel(response, this.$t("海空联运") + ".xls");
          this.exportLoading = false;
        })
        .catch(() => {});
    },
    /* 关闭弹窗 */
    closeDialog(type) {
      this.$set(this.dialogCfg, "open", false);
      if (type === "add" || type === "edit") {
        this.getList();
      }
    },
    /** 查看按钮操作 */
    handleCommand(row, command) {
      this.$set(this.dialogCfg, "fullscreen", false);
      switch (command) {
        case "seaAir":
          this.$router.push("/boxSeaAir/shippingSeaAir/" + row.id);
          break;

        case "detail":
          this.$router.push("/boxSeaAir/query/" + row.id);
          break;

        case "edit":
          this.handleUpdate(row);
          break;

        case "delete":
          this.handleDelete(row);
          break;

        case "editLadingBill":
          const cabinetLabel = this.getCabinetName(row.cabinetId);
          const title = this.$t(
            "查看提单 {selfNo} 柜号:{cubNo} 柜型:{cabinetLabel}",
            {
              selfNo: row.selfNo,
              cubNo: row.cubNo,
              cabinetLabel: cabinetLabel,
            }
          );
          this.$set(this.dialogCfg, "title", title);
          this.$set(this.dialogCfg, "fullscreen", true);
          break;

        case "cost":
          this.$set(this.dialogCfg, "title", this.$t("费用登记"));
          break;

        case "error":
          this.$set(this.dialogCfg, "title", this.$t("异常登记"));
          break;

        case "downloadPreloadGoodsList":
          downloadFile(
            command,
            { shipmentId: row.id },
            this.$t("预装单") + `(${row.selfNo}).xlsx`,
            "xlsx"
          );
          break;
        case "downloadLoadGoodsList":
          downloadFile(
            command,
            { shipmentId: row.id },
            this.$t("已装单") + `(${row.selfNo}).xlsx`,
            "xlsx"
          );
          break;
        case "downloadReceivableList":
          downloadFile(
            command,
            { shipmentId: row.id },
            this.$t("应收汇总表") + `(${row.selfNo}).xlsx`,
            "xlsx"
          );
          break;
        case "zipDownload":
          downloadFile(
            command,
            { shipmentId: row.id },
            this.$t("提货单") + `(${row.selfNo}).zip`,
            "zip"
          );
          break;
        case "downloadAgentListFiles":
        case "downloadSoncapFiles":
        case "downloadLadingCopy":
          downloadFileByUrl(command, { shipmentId: row.id });
          break;
        case "handle":
          const { noticeType } = row;
          if ([1, 2, 3, 4, 8].includes(noticeType)) {
            this.$router.push("/boxSeaAir/shippingSeaAir/" + row.id);
          }
          if ([5, 6, 7].includes(noticeType)) {
            this.$router.push("/boxSeaAir/query/" + row.id);
          }
          this.closeDialog();
          break;
      }

      if (["editLadingBill", "cost", "error"].includes(command)) {
        this.currRow = row;
        this.currRow.bosType = "seaAir";
        this.$set(this.dialogCfg, "dialogType", command);
        this.$set(this.dialogCfg, "width", "600px");
        this.$set(this.dialogCfg, "open", true);
      }
    },
    /* 分页 */
    pageChange(page) {
      this.pageParam.page = page;
      this.getList();
    },
  },
};
</script>

<style lang="scss" scoped>
.notice-dialog {
  ::v-deep .notice-title {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 10px;
  }
  ::v-deep .operate-button {
    margin-top: 10px;
    text-align: center;
  }
}
</style>