<template>
  <div>
    <div class="customer-head">
      <div class="customer-back">
        <el-button type="danger" style="border: none;background: none;color: red" icon="el-icon-arrow-left"
                   @click="backToList(0)">返回列表
        </el-button>
        <el-button v-if="detailData.id" type="danger" style="border: none;background: none;color: red" icon="el-icon-arrow-left"
                   @click="backToList(1)">返回审核列表
        </el-button>
      </div>
      <div class="add-customer-btn">
        <el-button class="el-button--small-yh" style="margin-right: 10px" type="primary" size="small" :disabled="form.status>0"
                   @click="confirmEdit" v-if="optionForm.disabled === true">编辑
        </el-button>
        <el-dropdown style="margin-right: 10px">
          <el-button type="primary" size="small">
            审核处理<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="pleaseCheck" :disabled="form.status>0">请核数据</el-dropdown-item>
            <el-dropdown-item @click.native="checkScheduleDialog = true,checkId = form.id" :disabled="!form.id">审核进度</el-dropdown-item>
            <el-dropdown-item @click.native="repealCancel" :disabled="form.status === 0 || !form.status"
                              v-if="!detailData.id">撤销请核
            </el-dropdown-item>
            <el-dropdown-item @click.native="checkDialog = true,checkData = detailData.check;" v-if="detailData.id">特殊审批
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-button class="el-button--small-yh" type="primary" size="small" :disabled="form.status>0"
                   @click="editCustomer">保存数据
        </el-button>
      </div>
    </div>
    <trade-card title="基础资料" style="margin-top: 50px">
      <avue-form :option="optionForm" v-model="form" ref="form">
        <template slot="corpId" slot-scope="scope">
          <crop-select v-model="form.corpId" @getCorpData="(row)=>{getGSData(row,['form','corpName'])}"
                       :disabled="scope.disabled"
                       corpType="KH"/>
        </template>
        <template slot="shippingCompany" slot-scope="scope">
          <crop-select v-model="form.shippingCompanyId"
                       @getCorpData="(row)=>{getGSData(row,['form','shippingCompany'])}" :disabled="scope.disabled"
                       corpType="GS"/>
        </template>
        <template slot="departureHarbor" slot-scope="scope">
          <port-info :disabled="scope.disabled" v-model="form.departureHarborId" type="id"
                     @balabalaTow="(val)=>{balabala(val,['form','departureHarbor'])}"/>
        </template>
        <template slot="objectiveHarbor" slot-scope="scope">
          <port-info :disabled="scope.disabled" v-model="form.objectiveHarborId" type="id"
                     @balabalaTow="(val)=>{balabala(val,['form','objectiveHarbor'])}"/>
        </template>
      </avue-form>
    </trade-card>
    <trade-card title="箱信息" @openClose="key++">
      <avue-crud
          :option="option"
          :data="dataList"
          v-model="formTwo"
          ref="crud"
          :key="key"
          :search.sync="xiangsearch"
          :page.sync="xiangpage"
          @search-change="xiangsearchChange"
          @on-load="xiangpagefun"
          @row-save="rowSave"
          @row-update="rowUpdate"
          @selection-change="selectionChange"
          @resetColumn="resetColumnTwo('crud','option','optionBack',237.1)"
          @saveColumn="saveColumnTwo('crud','option','optionBack',237.1)">
        <template slot-scope="{type,size,row,index,disabled}" slot="menu">
          <el-button icon="el-icon-share" :size="size" :disabled="disabled" :type="type"
                     @click="track(row)">箱轨迹
          </el-button>
          <el-button icon="el-icon-edit" :size="size" :disabled="disabled" :type="type"
                     @click="$refs.crud.rowEdit(row,index)">编辑
          </el-button>
          <el-button icon="el-icon-delete" :size="size" :disabled="disabled" :type="type"
                     @click="rowDel(row,index,'MX')">删除
          </el-button>
        </template>
        <template slot-scope="{ row }" slot="status">
          <span v-for="item in $refs.crud.DIC.status" :style="{color: item.colour}" v-if="item.dictKey == row.status">{{item.dictValue}}</span>
        </template>
        <template slot="menuLeft" slot-scope="scope">
          <el-button type="success" size="small" :disabled="option.disabled" @click="importBox">提取</el-button>
          <el-button :disabled="option.disabled" type="success" size="small" icon="el-icon-bottom" @click="importBoxTwo">导入</el-button>
          <el-button class="el-icon-download" type="info" size="small" :disabled="!form.id" @click="openReport">报表打印</el-button>
          <el-dropdown>
            <el-button type="primary" size="small" :disabled="selectionList.length === 0">
              起运港<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="statusUpdate('1','空箱离场')">空箱离场</el-dropdown-item>
              <el-dropdown-item @click.native="statusUpdate('1','重箱回场')">重箱回场</el-dropdown-item>
              <el-dropdown-item @click.native="statusUpdate('1','上船')">上船</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-dropdown>
            <el-button type="primary" size="small" :disabled="selectionList.length === 0">
              目的港<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="statusUpdate('2','重箱入场')">重箱入场</el-dropdown-item>
              <el-dropdown-item @click.native="statusUpdate('2','重箱出场')">重箱出场</el-dropdown-item>
              <el-dropdown-item @click.native="statusUpdate('2','空箱入场')">空箱入场</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button style="margin-left: 0" type="success" size="small"
                     :disabled=" storeUp || selectionList.length === 0"
                     @click="stockpiling()">堆存
          </el-button>
        </template>
        <template slot="addressForm" slot-scope="scope">
          <port-info v-model="formTwo.addressId" type="id" :disabled="scope.disabled"
                     @balabalaTow="(val)=>{balabala(val,['formTwo','address'])}"/>
        </template>
<!--        <template slot="boxMakingCompanyIdForm" slot-scope="scope">-->
<!--          <crop-select v-model="formTwo.boxMakingCompanyId" :disabled="scope.disabled" :refresh="false"-->
<!--                       @getCorpData="(row)=>{getGSData(row,['formTwo','boxMakingCompany'])}" corpType="GS"/>-->
<!--        </template>-->
      </avue-crud>
    </trade-card>
    <!--    报表-->
    <report-dialog
        :switchDialog="switchDialog"
        :reportId="form.id"
        reportName="出口装运"
        @onClose="onClose()"
    />
    <!--    费用信息组件-->
    <box-cost v-model="dataListTwo" :id="form.id" :codeValue="237.2" type="CK" activeName="first" ref="boxCost"
              url="/api/blade-box-tube/transportItemFees/remove" @resetTrigger="resetTrigger"></box-cost>
    <trade-card title="附件明细">
      <c-upload
          basic
          :data="tradingBoxFilesList"
          :disabled="disabled"
          deleteUrl="/api/blade-box-tube/transportFiles/remove"
          :enumerationValue="237.3"
          display
      />
    </trade-card>
    <el-dialog
        append-to-body
        title="审批进度"
        class="el-dialogDeep"
        :visible.sync="checkScheduleDialog"
        width="40%"
        :close-on-click-modal="false"
        :destroy-on-close="true"
        :close-on-press-escape="false"
        v-dialog-drag
    >
      <check-schedule
          :checkId="checkId"
          :batchNo="batchNo"
          @choceScheduleFun="choceScheduleFun"
      ></check-schedule>
    </el-dialog>
    <el-dialog title="导入箱档案" append-to-body :visible.sync="excelBox" width="555px" :close-on-click-modal="false"
               v-dialog-drag>
      <avue-form v-if="excelBox" :option="excelOption" v-model="excelForm" table-loading="excelLoading"
                 :upload-before="uploadBefore" :upload-after="uploadAfter">
        <template slot="excelTemplate">
          <el-button type="primary" @click="derivation">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
      <p style="text-align: center;color: #DC0505">
        温馨提示 第一次导入时请先下载模板
      </p>
    </el-dialog>
    <el-dialog
        title="导入箱信息"
        :visible.sync="importOpen"
        :append-to-body="true"
        :destroy-on-close="true"
        :close-on-click-modal="false"
        top="1vh"
        width="80%">
      <span>
        <box-information v-model="importList" :condition="form"></box-information>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="importOpen = false">取 消</el-button>
        <el-button type="primary" @click="confirmImport" :disabled="importList.length === 0">导 入</el-button>
      </span>
    </el-dialog>
    <el-dialog
        :title="title"
        :visible.sync="dialogVisible"
        :append-to-body="true"
        :destroy-on-close="true"
        :close-on-click-modal="false"
        v-if="dialogVisible"
        width="60%">
      <span>
        <avue-form v-if="title == '堆存'" :option="optionStateTwo" v-model="formState" ref="formState">
          <template slot="addressId" slot-scope="scope">
            <port-info v-model="formState.addressId" type="id" :disabled="scope.disabled"
                       @balabalaTow="(val)=>{balabala(val,['formState','address'])}"/>
          </template>
          <template slot="purchaseCompanyId" slot-scope="scope">
          <crop-select v-model="formState.purchaseCompanyId"
                       @getCorpData="(row)=>{getGSData(row,['formState','purchaseCompanyName'])}"
                       :disabled="scope.disabled"
                       corpType="KH"/>
        </template>
        </avue-form>
        <avue-form v-else :option="optionState" v-model="formState" ref="formState">
          <template slot="addressId" slot-scope="scope">
            <port-info v-model="formState.addressId" type="id" :disabled="scope.disabled"
                       @balabalaTow="(val)=>{balabala(val,['formState','address'])}"/>
          </template>
        </avue-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :disabled="disabledVisible" @click="confirmChange">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
        title="箱轨迹"
        :visible.sync="boxTrack"
        :append-to-body="true"
        :destroy-on-close="true"
        :close-on-click-modal="false"
        width="80%">
      <span>
        <avue-crud
            ref="crudTrack"
            :option="optionTrack"
            :data="dataTrackList"
            :search.sync="search"
            :page.sync="page"
            :table-loading="loading"
            @on-load="onLoadTrack"
            @search-change="searchChange"
            @row-update="rowUpdateTrack"
            @resetColumn="resetColumnTwo('crudTrack','optionTrack','optionTrackBack',237.4)"
            @saveColumn="saveColumnTwo('crudTrack','optionTrack','optionTrackBack',237.4)"
            v-model="formTrack">
          <template slot-scope="{type,size,row,index,disabled}" slot="menu">
            <el-button icon="el-icon-edit" :size="size" :disabled="disabled" :type="type"
                       @click="$refs.crudTrack.rowEdit(row,index)">编辑
            </el-button>
            <el-button icon="el-icon-delete" :size="size" :disabled="disabled" :type="type"
                       @click="rowDel(row,index,'GJ')">删除
            </el-button>
          </template>
        </avue-crud>
      </span>
    </el-dialog>
    <el-dialog append-to-body title="审批" class="el-dialogDeep" :visible.sync="checkDialog" width="50%"
               :close-on-click-modal="false" :destroy-on-close="true" :close-on-press-escape="false" v-dialog-drag>
      <check :checkData="checkData" :checkDetail="false" :idList="[]" @choceCheckFun="choceCheckFun">
      </check>
    </el-dialog>
  </div>
</template>

<script>
import {
    detail,
    submit,
    generateStack,
    tradingBoxItem,
    tradingBoxFees,
    pleaseCheck,
    repealCancel, statusUpdate, archivestrajectory, update, tradingBoxGJ, transportItemListfun, transportItemSubmitfun
} from "@/api/boxManagement/exportShipment/index.js";

import checkSchedule from "@/components/check/checkSchedule";
import {selectByName} from "@/api/boxManagement";
import {selectArchivesList} from "@/api/boxManagement/buyContainer";
import {dateFormat} from "@/util/date";
import {getToken} from "@/util/auth";
import reportDialog from "@/components/report-dialog/main.vue";

import check from "@/components/check/check";
import {getParities} from "@/api/basicData/customerInquiry";
import {detList} from "@/api/boxManagement/leaseIn";
export default {
  name: "detailsPage",
  props: {
    onLoad: Object,
    detailData: Object
  },
  components: {checkSchedule,reportDialog,check},
  data() {
    return {
        // 分页
        xiangpage: {
            pageSize: 20,
            currentPage: 1,
            total: 0,
            pageSizes: [10, 20, 30, 40, 50, 100, 200, 300, 400, 500]
        },
        xiangsearch:{},
      checkData: {},
      checkDialog: false,
      switchDialog: false,
      excelBox: false,
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24
          },
          {
            label: "模板上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "模板上传中，请稍等",
            span: 24,
            propsHttp: {
              res: "data"
            },
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: "/api/blade-box-tube/transport/import-transport-info"
          }
        ]
      },
      excelForm: {},
      key: 0,
      importList: [],
      title: '',
      storeUp:true,
      loading: false,
      disabledVisible: false,
      boxTrack: false,
      importOpen: false,
      dialogVisible: false,
      checkScheduleDialog: false,
      checkId: '',
      batchNo: '',
      breakConfiguration: {
        multipleChoices: false,
        multiple: false,
        disabled: false,
        searchShow: true,
        collapseTags: false,
        clearable: true,
        placeholder: "请点击右边按钮选择",
        dicData: []
      },
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0,
        pageSizes: [10, 20, 30, 40, 50, 100, 200, 300, 400, 500]
      },
      formState: {},
      form: {},
      formTwo: {},
      formTrack: {},
      search: {},
      optionTrack: {},
      optionTrackBack: {
        align: 'center',
        index: true,
        addBtnText: "录入明细",
        refreshBtn: false,
        addBtn: false,
        span: 8,
        searchMenuPosition: "right",
        searchSpan: 8,
        searchIcon: true,
        searchIndex: 2,
        addRowBtn: false,
        cellBtn: false,
        editBtn: false,
        delBtn: false,
        menuWidth: 200,
        dialogTop: 25,
        dialogWidth: "80%",
        column: [{
          label: '客户名称',
          prop: 'corpName',
          width: 170,
          search: true,
        },{
          label: '箱号',
          prop: 'code',
          width: 100,
          overHidden: true,
          remote: true,
          filterable: true,
          type: "select",
          dicUrl: "/api/blade-box-tube/archives/selectArchivesList?size=10&current=1&code={{key}}",
          props: {
            label: "code",
            value: "code"
          },
          disabled: true
        }, {
          label: '地点',
          prop: 'address',
          width: 200,
          overHidden: true,
          formProp: 'address',
          search: true
        }, {
          label: '日期',
          prop: 'newDate',
          search: true,
          searchProp: 'newDateList',
          overHidden: true,
          type: "date",
          searchRange: true,
          searchDefaultTime: ["00:00:00", "23:59:59"],
          format: "yyyy-MM-dd",
          valueFormat: "yyyy-MM-dd HH:mm:ss"
        }, {
          label: '业务类型',
          prop: 'status',
          width: 140
        }]
      },
      dataTrackList: [],
      formSearch: {},
      optionStateTwo: {
        menuBtn: false,
        span: 12,
        column: [{
          label: '堆存地点',
          prop: 'addressId',
          rules: [{
            required: true,
            message: " ",
            trigger: "blur"
          }]
        }, {
          label: '付费对象',
          prop: 'purchaseCompanyId',
          rules: [{
            required: true,
            message: " ",
            trigger: "blur"
          }]
        },{
          label: '堆存日期',
          prop: 'rentDate',
          width: 100,
          type: "date",
          format: "yyyy-MM-dd",
          valueFormat: "yyyy-MM-dd HH:mm:ss",
          rules: [{
            required: true,
            message: " ",
            trigger: "blur"
          }]
        }]
      },
      optionState: {
        menuBtn: false,
        span: 12,
        column: [{
          label: '地点',
          prop: 'addressId',
          rules: [{
            required: true,
            message: " ",
            trigger: "blur"
          }]
        }, {
          label: '最新日期',
          prop: 'date',
          width: 100,
          search: true,
          overHidden: true,
          type: "date",
          format: "yyyy-MM-dd",
          valueFormat: "yyyy-MM-dd HH:mm:ss",
          rules: [{
            required: true,
            message: " ",
            trigger: "blur"
          }]
        }]
      },
      optionForm: {
        menuBtn: false,
        span: 6,
        column: [{
          label: '系统号',
          prop: 'sysNo',
          disabled: true
        },{
          label: '箱数',
          prop: 'boxNumber',
          disabled: true
        },{
          label: '合同号',
          prop: 'contractNo'
        }, {
          label: '客户',
          prop: 'corpId',
          width: 100,
          search: true,
          overHidden: true,
          rules: [{
            required: true,
            message: " ",
            trigger: "blur"
          }]
        }, {
          label: '船公司',
          prop: 'shippingCompany',
          width: 100,
          search: true,
          overHidden: true,
          rules: [{
            required: true,
            message: " ",
            trigger: "blur"
          }]
        }, {
          label: '提单号',
          prop: 'billNo',
          width: 100,
          search: true,
          overHidden: true
        }, {
          label: '船名',
          prop: 'shipName',
          width: 100,
          search: true,
          overHidden: true
        }, {
          label: '航次',
          prop: 'voyageNumber',
          width: 100,
          search: true,
          overHidden: true
        }, {
          label: '开船日期',
          prop: 'sailDate',
          width: 100,
          search: true,
          overHidden: true,
          type: "date",
          format: "yyyy-MM-dd",
          valueFormat: "yyyy-MM-dd HH:mm:ss",
        }, {
          label: '起运港',
          prop: 'departureHarbor',
          width: 100,
          search: true,
          overHidden: true,
          rules: [{
            required: true,
            message: " ",
            trigger: "blur"
          }]
        }, {
          label: '目的港',
          prop: 'objectiveHarbor',
          width: 100,
          search: true,
          overHidden: true,
          rules: [{
            required: true,
            message: " ",
            trigger: "blur"
          }]
        }, {
          label: '合同生效日期',
          prop: 'effectiveDate',
          width: 100,
          search: true,
          overHidden: true,
          type: "date",
          format: "yyyy-MM-dd",
          valueFormat: "yyyy-MM-dd HH:mm:ss",
          labelWidth:100,
          rules: [{
            required: true,
            message: " ",
            trigger: "blur"
          }]
        }, {
          label: '合同失效日期',
          prop: 'expiryDate',
          width: 100,
          search: true,
          overHidden: true,
          type: "date",
          format: "yyyy-MM-dd",
          valueFormat: "yyyy-MM-dd HH:mm:ss",
          labelWidth:100,
          rules: [{
            required: true,
            message: " ",
            trigger: "blur"
          }]
        }, {
          label: '起租日期',
          prop: 'startingRentDate',
          width: 100,
          search: true,
          overHidden: true,
          type: "date",
          format: "yyyy-MM-dd",
          valueFormat: "yyyy-MM-dd HH:mm:ss",
          rules: [{
            required: true,
            message: " ",
            trigger: "blur"
          }]
        }, {
          label: '出场日期',
          prop: 'exitDate',
          width: 100,
          search: true,
          overHidden: true,
          type: "date",
          format: "yyyy-MM-dd",
          valueFormat: "yyyy-MM-dd HH:mm:ss",
        }, {
          label: '入场日期',
          prop: 'admissionDate',
          width: 100,
          search: true,
          overHidden: true,
          type: "date",
          format: "yyyy-MM-dd",
          valueFormat: "yyyy-MM-dd HH:mm:ss",
        }, {
          label: '租金合计',
          prop: 'totalAmount',
          disabled: true
        }, {
          label: '超期箱使合计',
          prop: 'overdueAmount',
          disabled: true
        }, {
          label: '备注',
          prop: 'remarks',
          type: 'textarea',
          minRows: 1,
          span: 12
        }]
      },
      option: {},
      optionBack: {
        align: 'center',
        index: true,
        dialogDrag: true,
        selection: true,
        addBtnText: "录入明细",
        refreshBtn: false,
        addBtn: true,
        span: 8,
          searchMenuSpan: 18,
        addRowBtn: false,
        cellBtn: false,
        editBtn: false,
        delBtn: false,
        menuWidth: 200,
        dialogTop: 25,
        height:500,
        dialogWidth: "80%",
        showSummary: true,
        sumColumnList: [{
          name: 'amount',
          type: 'sum',
          decimals: 2
        },{
          name: 'emptyWeight',
          type: 'sum',
          decimals: 2
        },{
          name: 'grossWeight',
          type: 'sum',
          decimals: 2
        },{
          name: 'tare',
          type: 'sum',
          decimals: 2
        },{
          name: 'overdueAmount',
          type: 'sum',
          decimals: 2
        },{
          name: 'loadingWeight',
          type: 'sum',
          decimals: 2
        },{
          name: 'volume',
          type: 'sum',
          decimals: 2
        }],
        column: [{
          label: '箱号',
          prop: 'code',
          width: 100,
          overHidden: true,
          remote: true,
          filterable: true,
            search: true,
          type: "select",
          dicUrl: "/api/blade-box-tube/archives/selectArchivesList?size=10&current=1&code={{key}}",
          props: {
            label: "code",
            value: "code"
          },
          rules: [{
            required: true,
            message: " ",
            trigger: "blur"
          }]
        }, {
          label: '状态',
          prop: 'status',
          width: 100,
          overHidden: true,
          filterable: true,
          type: 'select',
          dicUrl: "/api/blade-system/dict-biz/dictionary?code=box_access_status",
          props: {
            label: "dictValue",
            value: "dictKey"
          },
          disabled: true
        }, {
          label: '地点',
          prop: 'address',
          overHidden: true,
          width: 100,
          rules: [{
            required: true,
            message: " ",
            trigger: "blur"
          }]
        }, {
          label: '日期',
          prop: 'newDate',
          overHidden: true,
          width: 100,
          type: "date",
          format: "yyyy-MM-dd",
          valueFormat: "yyyy-MM-dd HH:mm:ss",
          rules: [{
            required: true,
            message: " ",
            trigger: "blur"
          }]
        }, {
          label: '箱类型',
          prop: 'boxTypeId',
          width: 100,
          overHidden: true,
          filterable: true,
          type: 'select',
          props: {
            label: 'name',
            value: 'id'
          },
          dicUrl: '/api/blade-client/container/listMessage',
          rules: [{
            required: true,
            message: " ",
            trigger: "blur"
          }]
        }, {
          label: '币别',
          prop: 'currency',
          width: 100,
          overHidden: true,
          filterable: true,
          type: "select",
          dicUrl: "/api/blade-system/dict-biz/dictionary?code=currency",
          props: {
            label: "dictValue",
            value: "dictKey"
          },
          rules: [{
            required: true,
            message: " ",
            trigger: "blur"
          }]
        }, {
          label: '租金收入',
          prop: 'amount',
          type: 'number',
          value:0,
          controls: false,
          overHidden: true,
          rules: [{
            required: true,
            message: " ",
            trigger: "blur"
          }]
        }, {
          label: '超期单价/天',
          prop: 'price',
          type: 'number',
          value:0,
          controls: false,
          overHidden: true,
          rules: [{
            required: true,
            message: " ",
            trigger: "blur"
          }]
        }, {
          label: '超期箱使收入',
          prop: 'overdueAmount',
          overHidden: true,
          disabled: true
        }, {
          label: '堆存状态',
          prop: 'stackingStatus',
          display:false,
          overHidden: true,
          width: 100
        }, {
          label: '堆存时间',
          prop: 'stackingDate',
          width: 100,
          overHidden: true,
          type: "date",
          display:false,
          format: "yyyy-MM-dd",
          valueFormat: "yyyy-MM-dd HH:mm:ss"
        }]
      },
      dataList: [],
      dataListTwo: [],
      tradingBoxFilesList: [],
      selectionList: [],
      disabled: false,
      costData: {}
    }
  },
  async created() {
    this.option = await this.getColumnData(this.getColumnName(237.1), this.optionBack);
    this.optionTrack = await this.getColumnData(this.getColumnName(237.4), this.optionTrackBack);
    this.option.selectable = (row, index) => {
      return row.id;
    }
    selectByName("租金").then(res => {
      this.costData = res.data.data
    })
    //下拉箱号带出对应信息
    this.findObject(this.option.column, "newDate").value = dateFormat(new Date(), "yyyy-MM-dd") + " 00:00:00"
    this.findObject(this.option.column, "code").change = ({value, column}) => {
      selectArchivesList({code: value}).then(res => {
        for (let item of res.data.data) {
          if (value == item.code) {
            this.formTwo = {
              boxTypeId: item.typeId,
              boxType: item.name,
              addressId:item.addressId,
              address:item.address
            }
          }
        }
      })
    }
    if (this.onLoad.id && this.detailData.id) {
      this.refresh(this.onLoad.id, true)
    }else if (this.onLoad.id){
      this.refresh(this.onLoad.id, true)
    }
    this.key++
  },
  activated() {
    this.key++
  },
  methods: {
    //堆存
    stockpiling() {
      this.title = "堆存"
      const date = new Date();
      this.formState.rentDate = dateFormat(date, "yyyy-MM-dd") + " 00:00:00"
      this.dialogVisible = true
    },
    //关闭审核
    choceCheckFun() {
      this.checkDialog = false;
    },
    // 报表
    openReport() {
      this.switchDialog = !this.switchDialog;
    },
    // 报表关闭
    onClose(val) {
      this.switchDialog = val;
    },
    confirmEdit() {
      if (this.form.status > 0) {
        //基础资料
        this.$set(this.optionForm, "disabled", true)
        //箱信息
        this.$set(this.option, "disabled", true)
        this.$set(this.option, "addBtn", false)
        this.$set(this.option, "menu", false)
        //费用信息
        this.$set(this.$refs.boxCost.option, "disabled", true)
        this.$set(this.$refs.boxCost.option, "addBtn", false)
        this.$set(this.$refs.boxCost.option, "menu", false)
        //附件和顶部按钮
        this.disabled = true
      } else {
        //基础资料
        this.$set(this.optionForm, "disabled", false)
        //箱信息
        this.$set(this.option, "disabled", false)
        this.$set(this.option, "addBtn", true)
        this.$set(this.option, "menu", true)
        //费用信息
        this.$set(this.$refs.boxCost.option, "disabled", false)
        this.$set(this.$refs.boxCost.option, "addBtn", true)
        this.$set(this.$refs.boxCost.option, "menu", true)
        //附件和顶部按钮
        this.disabled = false
      }
      this.key++
    },
    //打开箱档案导入
    importBox() {
      this.importOpen = true
    },
    derivation() {
      window.open(`/api/blade-box-tube/transport/export-transport-info?${this.website.tokenHeader}=${getToken()}`);
    },
    importBoxTwo() {
      this.findObject(this.excelOption.column, "excelFile").data = {
        corpId: this.form.corpId,
        corpName: this.form.corpName,
        billType: "CKZY"
      }
      this.excelBox = true
    },
    uploadBefore(file, done, loading) {
      loading = true;
      done();
    },
    uploadAfter(res, done, loading, column) {
      this.excelBox = false;
      if (typeof res.message === "string") return
      for (let item of this.dataList) {
        for (let li of res.transportItemList) {
          if (item.code === li.code) {
            return this.$message.error(`箱号：${item.code}重复！`);
          }
        }
      }
      this.dataList = this.dataList.concat(res.transportItemList)
      this.dataListTwo = this.dataListTwo.concat(res.transportItemFeesList)
      this.$message.success("导入成功！");
      loading = false;
      done();
    },
    //确认导入箱信息
    confirmImport() {
      const loading = this.$loading({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(255,255,255,0.7)'
      });
      for (let item in this.importList) {
        for (let li in this.dataList) {
          if (this.importList[item].code === this.dataList[li].code) {
            loading.close();
            return this.$message.error(`第${Number(Number(item) + 1)}行箱号和明细第${Number(Number(li) + 1)}行重复`);
          }
        }
      }
      this.importOpen = false
      for (let item of this.importList) {
        this.dataList.push({
          code: item.code,
          address: item.address,
          addressId: item.addressId,
          newDate: item.newDate,
          boxType: item.name,
          boxTypeId: item.typeId,
          currency: "CNY"
        })
        getParities({
          currency: "CNY",
          businesDate: dateFormat(new Date(), "yyyy-MM-dd") + " 00:00:00"
        }).then(res => {
          item.exchangeRate = res.data.data.receiptsParities
          this.dataListTwo.push({
            corpId: this.form.corpId,
            corpName: this.form.corpName,
            code: item.code,
            itemId: this.costData.id,
            itemName: this.costData.cname,
            currency: "CNY",
            price: item.amount,
            quantity: 1,
            autoGenerate: 1,
            feesType: 1,
            exchangeRate: item.exchangeRate || 1,
            amount: item.amount
          })
          loading.close();
        })
      }
      this.key++
    },
    confirmChange() {
      if (this.title == "堆存") {
        this.$refs["formState"].validate((valid, done) => {
          done()
          if (valid) {
            let data = {
              ...this.form,
              type: "DCF",
              source: "CKZY",
              ...this.formState,
              // tradingBoxItemsList: this.dataList,
              tradingBoxItemsList: this.selectionList,
            }
            console.log(this.formState)
            // data.tradingBoxItemsList.forEach(item=> delete item.id)
            delete data.id
            const loading = this.$loading({
              lock: true,
              text: '加载中',
              spinner: 'el-icon-loading',
              background: 'rgba(255,255,255,0.7)'
            });
            generateStack(data).then(res => {
              this.$message.success("生成堆存成功")
              this.dialogVisible = false
              this.disabledVisible = false
              this.formState = {}
              this.selectionList = []
              loading.close();
              this.refresh(this.form.id)
            }).catch(()=>{
              loading.close();
            })
          }
        })
      } else {
        let data = []
        for (let item of this.selectionList) {
          data.push(item.id)
        }
        this.$refs["formState"].validate((valid, done) => {
          done()
          if (valid) {
            this.disabledVisible = true
            statusUpdate({
              ...this.formState,
              ids: data.join(',')
            }).then(res => {
              this.$message.success("操作成功")
              this.dialogVisible = false
              this.disabledVisible = false
              this.formState = {}
              this.refresh(this.form.id)
            }).catch(() => {
              this.disabledVisible = false
            })
          }
        })
      }
    },
    statusUpdate(status, type) {
      if (this.form.id) {
        this.title = type
        if (status === '1'){
          if(type === "空箱离场"){
            this.formState = {
              type: type,
              status: status,
              transportId: this.form.id,
              addressId:this.form.departureHarborId,
              address:this.form.departureHarbor,
              date:dateFormat(new Date(), "yyyy-MM-dd") + " 00:00:00"
            }
          }else {
            this.formState = {
              type: type,
              status: status,
              transportId: this.form.id,
              date:dateFormat(new Date(), "yyyy-MM-dd") + " 00:00:00"
            }
          }
        }else {
          if(type === "空箱入场"){
            this.formState = {
              type: type,
              status: status,
              transportId: this.form.id,
              addressId:this.form.objectiveHarborId,
              address:this.form.objectiveHarbor,
              date:dateFormat(new Date(), "yyyy-MM-dd") + " 00:00:00"
            }
          }else {
            this.formState = {
              type: type,
              status: status,
              transportId: this.form.id,
              date:dateFormat(new Date(), "yyyy-MM-dd") + " 00:00:00"
            }
          }
        }
        this.dialogVisible = true
      } else {
        this.$message.error('请保存后操作')
      }
    },
    selectionChange(list) {
      this.selectionList = list
      for (let item of list){
        if (item.status == '空箱入场' && item.stockpilingStatus == '1'){
          this.storeUp = false
        }else {
          return this.storeUp = true
        }
      }
    },
    track(row) {
      // this.dataTrackList = row
      this.formSearch = row
      this.boxTrack = true
    },
    searchChange(params, done) {
      done();
      this.onLoadTrack(this.page, params)
    },
    onLoadTrack(page, params = {}) {
      params = {
        ...params,
        current: page.currentPage,
        size: page.pageSize,
        code: this.formSearch.code
      }
      this.loading = true
      archivestrajectory(params).then(res => {
        this.dataTrackList = res.data.data.records
        this.page.total = res.data.data.total
        this.loading = false
      }).finally(() => {
        this.loading = false
      })
    },
    // 明细删除
    rowDel(row, index, type) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
            if (type == "GJ") {
              if (row.id){
                tradingBoxGJ(row.id).then(res => {
                  if (res.data.success) {
                    this.$message.success("操作成功!");
                    this.dataTrackList.splice(index, 1);
                  }
                })
              }else {
                this.$message.success("操作成功!");
                this.dataTrackList.splice(index, 1);
              }
            } else {
              if (row.id) {
                tradingBoxItem(row.id).then(res => {
                  if (res.data.success) {
                    this.$message.success("操作成功!");
                    this.dataList.splice(index, 1);
                    if (this.dataListTwo.length > 0) {
                      for (let item in this.dataListTwo) {
                        if (this.dataListTwo[item].code == row.code) {
                          if (this.dataListTwo[item].autoGenerate == 1) {
                            if (this.dataListTwo[item].id) {
                              tradingBoxFees(this.dataListTwo[item].id).then(res => {
                                if (res.data.success) {
                                  this.dataListTwo.splice(index, 1);
                                }
                              });
                            } else {
                              this.dataListTwo.splice(Number(item), 1);
                            }
                          }
                        }
                      }
                    }
                  }
                });
              } else {
                this.dataList.splice(index, 1);
                this.$message.success("操作成功!");
                if (this.dataListTwo.length > 0) {
                  for (let item in this.dataListTwo) {
                    if (this.dataListTwo[item].code === row.code) {
                      if (this.dataListTwo[item].autoGenerate == 1) {
                        this.dataListTwo.splice(Number(item), 1);
                      }
                    }
                  }
                }
              }
            }
          }
      )
      ;
    },
    balabala(val, type) {
      if (val === null) {
        this[type[0]][type[1]] = ''
      } else {
        this[type[0]][type[1]] = val.name
      }
    },
    //撤销
    repealCancel() {
      this.$confirm("您确定撤回此次申请吗？", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        const data = {
          id: this.form.id,
          pageLabel: "出库装运",
          checkFlag: 1,
        }
        const loading = this.$loading({
          lock: true,
          text: '加载中',
          spinner: 'el-icon-loading',
          background: 'rgba(255,255,255,0.7)'
        });
        repealCancel(data).then(res => {
          loading.close();
          this.$message.success('撤回成功')
          this.refresh(this.form.id)
        })
      })
    },
    // 请核
    pleaseCheck() {
      // for (let item of this.dataList) {
      //   if (item.status !== "空箱入场") return this.$message.error("有未空箱入场的明细，禁止请核！")
      // }
      if (this.dataList.length === 0) {
        return this.$message.error("箱信息不能为空")
      }
      if (this.$refs.boxCost.dataList.length === 0) {
        return this.$message.error("费用信息不能为空")
      }else {
        for (let item of this.$refs.boxCost.dataList){
          if (!item.id){
            return this.$message.error("费用信息未保存")
          }
        }
      }
      this.$confirm("您确定提交请核申请吗?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$refs["form"].validate((valid, done) => {
          done()
          if (valid) {
            let data = {
              ...this.form,
              transportItemList: this.dataList,
              transportItemFeesList: this.dataListTwo,
              transportFilesList: this.tradingBoxFilesList,
              billType: "CKZY",
              checkFlag: 1
            }
            const loading = this.$loading({
              lock: true,
              text: '加载中',
              spinner: 'el-icon-loading',
              background: 'rgba(255,255,255,0.7)'
            });
            submit(data).then(res => {
              const data = {
                id: res.data.data.id,
                url: '/boxManagement/exportShipment/index',
                pageStatus: "this.$store.getters.domSaleStatus",
                pageLabel: "出口装运",
                checkFlag: 1,
              }
              pleaseCheck({
                ...data,
                billType: "CKZY"
              }).then(rest => {
                loading.close();
                this.$message.success('请核成功')
                this.refresh(res.data.data.id)
              }).catch(()=>{
                loading.close();
              })
            }).catch(()=>{
              loading.close();
            })
          }
        });
      })
    },
    //审核关闭
    choceScheduleFun() {
      this.checkScheduleDialog = false
    },
      // 明细详情
    refresh(id, type) {
      const loading = this.$loading({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(255,255,255,0.7)'
      });
      detail({id: id}).then(res => {
        this.form = res.data.data
        // this.dataList = res.data.data.transportItemList
        this.dataListTwo = res.data.data.transportItemFeesList
        this.tradingBoxFilesList = res.data.data.transportFilesList
        delete this.form.transportItemList
        delete this.form.transportItemFeesList
        delete this.form.transportFilesList
        this.$refs.boxCost.code = this.form.code
        loading.close();
        if (type) {
          //基础资料
          this.$set(this.optionForm, "disabled", true)
          //箱信息
          this.$set(this.option, "disabled", true)
          this.$set(this.option, "addBtn", false)
          this.$set(this.option, "menu", false)
          //费用信息
          this.$set(this.$refs.boxCost.option, "disabled", true)
          this.$set(this.$refs.boxCost.option, "addBtn", false)
          this.$set(this.$refs.boxCost.option, "menu", false)
          //附件和顶部按钮
          this.disabled = true
        }else {
          if (this.form.status > 0) {
            //基础资料
            this.$set(this.optionForm, "disabled", true)
            //箱信息
            this.$set(this.option, "disabled", true)
            this.$set(this.option, "addBtn", false)
            this.$set(this.option, "menu", false)
            //费用信息
            this.$set(this.$refs.boxCost.option, "disabled", true)
            this.$set(this.$refs.boxCost.option, "addBtn", false)
            this.$set(this.$refs.boxCost.option,"menu",false)
            //附件和顶部按钮
            this.disabled = true
          } else {
            //基础资料
            this.$set(this.optionForm, "disabled", false)
            //箱信息
            this.$set(this.option, "disabled", false)
            this.$set(this.option, "addBtn", true)
            this.$set(this.option, "menu", true)
            //费用信息
            this.$set(this.$refs.boxCost.option, "disabled", false)
            this.$set(this.$refs.boxCost.option, "addBtn", true)
            this.$set(this.$refs.boxCost.option, "menu", true)
            //附件和顶部按钮
            this.disabled = false
          }
        }
        this.key++
      })
    },
      xiangsearchChange(form,dome){
        this.page.currentPage = 1
          this.page.pageSize = 20

        this.xiangpagefun(this.page,form)
        dome()
      },
      // 获取箱信息数据
      xiangpagefun(page,params = {}){
          const idp = this.form.id?this.form.id:this.onLoad.id
          if (!idp) {
              return
          }
          this.loading = true
          transportItemListfun({
              ...params,
              current: page.currentPage,
              size: page.pageSize,
              pid:this.form.id?this.form.id:this.onLoad.id
          }).then(res=>{
              console.log(res,997)
              this.xiangpage.total = res.data.data.total
              this.dataList = res.data.data.records
              this.loading = false
          }).finally(() => {
              this.loading = false
          }).catch(()=>{
              this.loading = false
          })
      },

    //新增修改
    editCustomer() {
      this.$refs["form"].validate((valid, done) => {
        done()
        if (valid) {
          let data = {
            ...this.form,
            // transportItemList: this.dataList,
            // transportItemFeesList: this.dataListTwo,
            transportFilesList: this.tradingBoxFilesList,
            billType: "CKZY"
          }
          const loading = this.$loading({
            lock: true,
            text: '加载中',
            spinner: 'el-icon-loading',
            background: 'rgba(255,255,255,0.7)'
          });
          submit(data).then(res => {
            if (this.form.id) {
              this.$message.success("修改成功")
            } else {
              this.$message.success("新增成功")
            }
            loading.close();
            this.refresh(res.data.data.id)
          }).catch(()=>{
            loading.close();
          })
        }
      });
    },
      // 箱信息的添加
    rowSave(form, done, loading) {
      let result = this.dataList.some((item) => {
        if (item.code == form.code) {
          return true
        }
      })
      if (result === true) {
        this.$message.error("已存在此箱号");
        return loading();
      }
      form.boxType = form.$boxTypeId
      done(form)
      getParities({
        currency: form.currency,
        businesDate: dateFormat(new Date(), "yyyy-MM-dd") + " 00:00:00"
      }).then(res => {
        form.exchangeRate = res.data.data.receiptsParities
        this.dataListTwo.push({
          corpId: this.form.corpId,
          corpName: this.form.corpName,
          code: form.code,
          itemId: this.costData.id,
          itemName: this.costData.cname,
          currency: form.currency,
          price: form.amount,
          quantity: 1,
          autoGenerate: 1,
          feesType: 1,
          exchangeRate:form.exchangeRate || 1,
          amount: form.amount,
        })
      })

        this.transportItemSubmitfunfun(form)
    },
      // 箱轨迹的编辑
    rowUpdateTrack(form, index, done, loading) {
      update(form).then(res => {
        done()
        this.$message.success("操作成功")
        this.onLoadTrack(this.page, this.search)
      })
    },
      // 出口 进口箱信息的添加和编辑接口
      transportItemSubmitfunfun(form){
          transportItemSubmitfun({
              ...form,
              pid:this.form.id,
          }).then(res=>{
              this.$message.success("操作成功!");
              this.xiangpagefun(this.page)
          })
      },
      // 箱信息的编辑
    rowUpdate(form, index, done, loading) {
      if (!Number(form.price) || Number(form.price) < 0) {
        loading()
        return this.$message.error('超期单价/天,不能为0或不能为负')
      }
      form.boxType = form.$boxTypeId
      done(form)
      getParities({
        currency: form.currency,
        businesDate: dateFormat(new Date(), "yyyy-MM-dd") + " 00:00:00"
      }).then(res => {
        form.exchangeRate = res.data.data.receiptsParities
        if (this.dataListTwo.length > 0) {
          for (let item in this.dataListTwo) {
            if (this.dataListTwo[item].code == form.code) {
              if (this.dataListTwo[item].autoGenerate == 1) {
                console.log(form.exchangeRate)
                this.dataListTwo.splice(Number(item), 1, {
                  ...this.dataListTwo[item],
                  corpId: this.form.corpId,
                  corpName: this.form.corpName,
                  code: form.code,
                  currency: form.currency,
                  price: form.amount,
                  exchangeRate:form.exchangeRate || 1,
                  amount: form.amount
                })
                this.key++
              }
            }
          }
        }
      })

        this.transportItemSubmitfunfun(form)
    },
    getGSData(row, type) {
      this[type[0]][type[1]] = row.cname
    },
    backToList(type) {
      if (type == 0){
        if (this.detailData.id){
          this.$router.push({
            path: '/boxManagement/exportShipment/index'
          });
        }
        this.$emit("backToList",type);
      }else if (type == 1){
        this.$router.push({
          path: '/approveData/index'
        });
        this.$emit("backToList",type);
      }
    },
    //自定义列保存
    async saveColumnTwo(ref, option, optionBack, code) {
      /**
       * 已定义全局方法，直接使用，saveColumnData保存列数据方法,参数传值(表格名称，当前表格的option数据)
       * 已定义全局方法，直接使用，getColumnName方法用来获取枚举值，参数根据自己定义的code值获取中文名
       * 一定要执行异步操作，要等接口成功返回，才能执行下一行代码
       */
      const inSave = await this.saveColumnData(this.getColumnName(code), this[option]);
      if (inSave) {
        this.$message.success("保存成功");
        //关闭窗口
        this.$refs[ref].$refs.dialogColumn.columnBox = false;
      }
    },
    resetTrigger() {
      this.$nextTick(() => {
        this.$refs.crud.doLayout()
      })
      if (this.optionForm.disabled == true) {
        if (this.form.status > 0) {
          //基础资料
          this.$set(this.optionForm, "disabled", true)
          //箱信息
          this.$set(this.option, "disabled", true)
          this.$set(this.option, "addBtn", false)
          this.$set(this.option, "menu", false)
          //费用信息
          this.$set(this.$refs.boxCost.option, "disabled", true)
          this.$set(this.$refs.boxCost.option, "addBtn", false)
          this.$set(this.$refs.boxCost.option,"menu",false)
          //附件和顶部按钮
          this.disabled = true
        } else {
          //基础资料
          this.$set(this.optionForm, "disabled", false)
          //箱信息
          this.$set(this.option, "disabled", false)
          this.$set(this.option, "addBtn", true)
          this.$set(this.option, "menu", true)
          //费用信息
          this.$set(this.$refs.boxCost.option, "disabled", false)
          this.$set(this.$refs.boxCost.option, "addBtn", true)
          this.$set(this.$refs.boxCost.option, "menu", true)
          //附件和顶部按钮
          this.disabled = false
        }
      }else {
        //基础资料
        this.$set(this.optionForm, "disabled", false)
        //箱信息
        this.$set(this.option, "disabled", false)
        this.$set(this.option, "addBtn", true)
        this.$set(this.option, "menu", true)
        //费用信息
        this.$set(this.$refs.boxCost.option, "disabled", false)
        this.$set(this.$refs.boxCost.option, "addBtn", true)
        this.$set(this.$refs.boxCost.option, "menu", true)
        //附件和顶部按钮
        this.disabled = false
      }
      this.key++
    },
    //自定义列重置
    async resetColumnTwo(ref, option, optionBack, code) {
      this[option] = this[optionBack];
      const inSave = await this.delColumnData(this.getColumnName(code), this[optionBack]);
      if (inSave) {
        //下拉箱号带出对应信息
        this.findObject(this.option.column, "newDate").value = dateFormat(new Date(), "yyyy-MM-dd") + " 00:00:00"
        this.findObject(this.option.column, "code").change = ({value, column}) => {
          selectArchivesList({code: value}).then(res => {
            for (let item of res.data.data) {
              if (value == item.code) {
                this.formTwo = {
                  boxTypeId: item.typeId,
                  boxType: item.name,
                  addressId:item.addressId,
                  address:item.address
                }
              }
            }
          })
        }
        this.resetTrigger()
        this.$message.success("重置成功");
        this.$refs[ref].$refs.dialogColumn.columnBox = false;
      }
    }
  }
}
</script>

<style scoped>
::v-deep .el-form-item {
  margin-bottom: 8px;
}
</style>
