<template>
  <basic-container>
    <avue-crud :option="option" :search.sync="search" v-model="form" :table-loading="loading" :data="dataList"
      ref="crud" :key="key" :before-open="beforeOpen" @on-load="onLoad" @row-save="rowSave"
      @row-update="(row, index, done, loading) => { rowSave(row, done, loading, index) }" @search-change="searchChange"
      :upload-delete="uploadDelete" :before-close="beforeClose" @row-del="rowDel" @refresh-change="refreshChange"
      @resetColumn="resetColumnTwo('crud', 'option', 'optionList', 234)"
      @saveColumn="saveColumnTwo('crud', 'option', 'optionList', 234)" :page.sync="page">
      <template slot-scope="{type,size,row,$index}" slot="menu">
        <el-button icon="el-icon-edit" :size="size" type="text" @click="$refs.crud.rowEdit(row, index)">查 看
        </el-button>
      </template>
      <tempalte slot="boxMakingCompanyForm">
        <dic-select v-model="form.boxMakingCompany" placeholder="造箱公司" key="id" label="cnName" res="records"
          url="/blade-los/bcorps/selectList?corpTypeName=箱东" :filterable="true" :remote="true" dataName="cnName"
          @selectChange="dicChange('boxMakingCompany', $event)"></dic-select>
      </tempalte>
      <template slot-scope="{type,size,row,index,disabled}" slot="code">
        <span class="el-button--text" style="cursor: pointer" @click="track(row)">{{ row.code }}</span>
      </template>
    </avue-crud>
    <el-dialog title="箱轨迹" :visible.sync="boxTrack" :append-to-body="true" :destroy-on-close="true"
      :close-on-click-modal="false" v-if="boxTrack" top="1vh" width="80%">
      <span>
        <avue-crud ref="crudTrack" :option="optionTrack" :data="dataTrackList" :search.sync="searchTwo"
          :page.sync="pageTwo" :table-loading="loadingTwo" @on-load="onLoadTrack" @search-change="searchChangeTwo"
          @row-update="rowUpdateTrack"
          @resetColumn="resetColumnTwo('crudTrack', 'optionTrack', 'optionTrackBack', 234.1)"
          @saveColumn="saveColumnTwo('crudTrack', 'optionTrack', 'optionTrackBack', 234.1)" v-model="formTrack">
          <template slot-scope="{type,size,row,index,disabled}" slot="code">
            <span class="el-button--text" style="cursor: pointer" @click="contractNoJump(row)">{{ row.code
            }}</span>
          </template>
          <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>
  </basic-container>
</template>

<script>
import { addUpdate, boxRemove, getList, remove, archivestrajectory, update } from "@/api/box/archives";
import { getToken } from "@/util/auth";
import { getAllBoxs } from "@/api/basicData/portinformation";
import dicSelect from "@/components/dicSelect/main";
import fa from "element-ui/src/locale/lang/fa";
export default {
  name: "archives",
  components: {
    dicSelect
  },
  data() {
    return {
      boxTrack: false,
      dataTrackList: [],
      searchTwo: {},
      formTrack: {},
      optionTrack: {},
      optionTrackBack: {
        align: 'center',
        index: true,
        menu: false,
        addBtnText: "录入明细",
        refreshBtn: false,
        addBtn: false,
        span: 8,
        searchMenuPosition: "right",
        searchSpan: 6,
        searchMenuSpan: 24,
        searchIcon: true,
        searchIndex: 3,
        addRowBtn: false,
        cellBtn: false,
        editBtn: false,
        delBtn: false,
        menuWidth: 200,
        dialogTop: 25,
        dialogWidth: "80%",
        column: [
          {
            label: '箱号',
            prop: 'code',
            overHidden: true,
            // search: true
          },
          {
            label: '放箱号',
            prop: 'containerNumber',
            overHidden: true,
          },
          {
            label: '箱型',
            prop: 'boxType',
            overHidden: true,
          },
          {
            label: '箱东',
            prop: 'boxEastName',
            overHidden: true,
          },
          {
            label: '放箱号类型',
            prop: 'boxCategory',
            overHidden: true,
          },
          {
            label: '箱动态',
            prop: 'boxDynamics',
            overHidden: true,
            search: true,
            type: 'select',
            dicUrl: "/api/blade-system/dict-biz/dictionary?code=boxDynamics",
            props: {
              label: "dictValue",
              value: "dictValue"
            },
          },
          {
            label: '动态日期',
            prop: 'newDate',
            overHidden: true,
          },
          {
            label: '港口',
            prop: 'portCname',
            overHidden: true,
            search: true,
            type: "select",
            filterable: true,
            remote: true,
            dicUrl: "/api/blade-los/bports/list?size=20&current=1&cnName={{key}}",
            props: {
              label: "cnName",
              value: "cnName",
              res: "data.records"
            }
          },
          {
            label: '场站',
            prop: 'stationCname',
            overHidden: true,
            search: true,
            type: "select",
            filterable: true,
            remote: true,
            dicUrl: "/api/blade-los/bcorps/selectList?corpTypeName=场站&cnName={{key}}",
            props: {
              label: "cnName",
              value: "cnName",
              res: "data.records"
            }
          },
          {
            label: '客户名称',
            prop: 'corpName',
            overHidden: true,
            search: true,
            type: "select",
            filterable: true,
            remote: true,
            dicUrl: "/api/blade-los/bcorps/selectList?size=20&current=1&cnName={{key}}",
            props: {
              label: "cnName",
              value: "cnName",
              res: "data.records"
            }
          },
          {
            label: '提单号',
            prop: 'mblno',
            overHidden: true,
          },
          {
            label: '船名',
            prop: 'shipCname',
            overHidden: true,
          },
          {
            label: '航次',
            prop: 'voyage',
            overHidden: true,
          },
          {
            label: 'ETD',
            prop: 'etd',
            overHidden: true,
          },
          {
            label: 'POL堆场',
            prop: 'polCyCname',
            overHidden: true,
          },
          {
            label: 'POL免箱使天数',
            prop: 'polFreeBoxUseDays',
            width: 110,
            overHidden: true,
          },
          {
            label: 'POL提前出场日期',
            prop: 'polPreAppearanceDate',
            width: 120,
            overHidden: true,
          },
          {
            label: 'POL场站空箱出场日期',
            prop: 'polStationEmptyContainerExitDate',
            width: 140,
            overHidden: true,
          },
          {
            label: 'POL还箱日期',
            prop: 'polReturnDate',
            width: 100,
            overHidden: true,
          },
          {
            label: 'POL超期箱使天数',
            prop: 'polOverdueBoxUseDays',
            width: 120,
            overHidden: true,
          },
          {
            label: 'ETA',
            prop: 'eta',
            overHidden: true,
          },
          {
            label: 'POD空箱还箱日期',
            prop: 'podEmptyContainerReturnDate',
            width: 120,
            overHidden: true,
          },
          {
            label: 'POD场站',
            prop: 'podStationCname',
            overHidden: true,
          },
          {
            label: 'POD免箱使天数',
            prop: 'podFreeBoxUseDays',
            width: 110,
            overHidden: true,
          },
          {
            label: 'POD箱使天数',
            prop: 'podBoxUseDays',
            width: 100,
            overHidden: true,
          }
        ]
      },
      excelBox: false,
      loading: false,
      search: {},
      form: {},
      excelForm: {},
      dataList: [],
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0,
        pageSizes: [10, 20, 30, 40, 50, 100, 200, 300, 400, 500]
      },
      key: 0,
      option: {},
      optionList: {
        index: true,
        dialogDrag: true,
        addBtn: false,
        delBtn: false,
        editBtn: false,
        saveBtn: false,
        cancelBtnText: '关闭',
        span: 8,
        border: true,
        height: "auto",
        searchMenuPosition: "right",
        align: "center",
        searchSpan: 6,
        searchMenuSpan: 24,
        searchIcon: true,
        searchIndex: 3,
        menuWidth: 80,
        highlightCurrentRow: true,
        dialogWidth: "70%",
        column: [{
          label: '合同号',
          prop: 'contractNo',
          width: 100,
          disabled: true,
          overHidden: true,
          search: true,
        }, {
          label: '箱号',
          prop: 'code',
          width: 100,
          overHidden: true,
          search: true,
          disabled: true,
        },
        {
          label: '箱型',
          prop: 'typeName',
          width: 100,
          overHidden: true,
          search: true,
          disabled: true,
          type: "select",
          filterable: true,
          remote: true,
          dicUrl: "/api/blade-los/bcntrtypes/list?status=0&current=1&size=20&cnName={{key}}",
          props: {
            label: "cnName",
            value: "cnName",
            res: "data.records"
          }
        }, {
          label: '港口',
          prop: 'addressCname',
          width: 100,
          overHidden: true,
          search: true,
          disabled: true,
          type: "select",
          filterable: true,
          remote: true,
          dicUrl: "/api/blade-los/bports/list?current=1&size=20&cnName={{key}}",
          props: {
            label: "cnName",
            value: "cnName",
            res: "data.records"
          }
        },
        {
          label: '放箱号',
          prop: 'containerNumber',
          width: 100,
          overHidden: true,
          disabled: true,
        },
        {
          label: '箱属',
          prop: 'boxBelongsTo',
          width: 100,
          overHidden: true,
          disabled: true,
        },
        {
          label: '放箱号类别',
          prop: 'boxType',
          width: 100,
          overHidden: true,
          disabled: true,
        },
        {
          label: '箱东',
          prop: 'originalBoxEast',
          width: 100,
          overHidden: true,
          disabled: true,
        },
        {
          label: '场站',
          prop: 'stationCname',
          width: 100,
          overHidden: true,
          disabled: true,
        },
        {
          label: '限制港口',
          prop: 'restrictedPortsName',
          width: 100,
          overHidden: true,
          disabled: true,
        },
        {
          label: '限制船公司',
          prop: 'restrictingShippingCompaniesName',
          width: 100,
          overHidden: true,
          disabled: true,
        },
        {
          label: '启用日期',
          prop: 'activationDate',
          width: 100,
          overHidden: true,
          disabled: true,
          type: "date",
          format: "yyyy-MM-dd",
          valueFormat: "yyyy-MM-dd HH:mm:ss"
        },
        {
          label: '动态日期',
          prop: 'newDate',
          width: 100,
          searchProp: 'newDateList',
          overHidden: true,
          search: true,
          disabled: 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: 'leasingCompany',
          width: 100,
          overHidden: true,
          search: true,
          disabled: true,
        },
        {
          label: '箱来源',
          prop: 'boxSource',
          width: 100,
          overHidden: true,
          disabled: true,
          search: true,
          filterable: true,
          type: 'select',
          dicUrl: "/api/blade-system/dict-biz/dictionary?code=box_source",
          props: {
            label: "dictValue",
            value: "dictKey"
          }
        },
        {
          label: '箱状态',
          prop: 'boxStatus',
          width: 100,
          overHidden: true,
          disabled: true,
          search: true,
          filterable: true,
          type: 'select',
          dicUrl: "/api/blade-system/dict-biz/dictionary?code=box_status",
          props: {
            label: "dictValue",
            value: "dictKey"
          }
        },
        {
          label: '租赁方式',
          prop: 'leaseMethod',
          width: 100,
          overHidden: true,
          filterable: true,
          type: 'select',
          disabled: true,
          dicUrl: "/api/blade-system/dict-biz/dictionary?code=lease_method",
          props: {
            label: "dictValue",
            value: "dictKey"
          }
        },
        {
          label: '空重(kg)',
          prop: 'emptyWeight',
          width: 100,
          overHidden: true,
          disabled: false,

        }, {
          label: '毛重(kg)',
          prop: 'gorssWeight',
          width: 100,
          overHidden: true,
          disabled: false,

        }, {
          label: '皮重(kg)',
          prop: 'tare',
          width: 100,
          overHidden: true,
          disabled: false,

        }, {
          label: '装载重量(kg)',
          prop: 'loadingWeight',
          width: 100,
          overHidden: true,
          disabled: false,
        }, {
          label: '容积(m³)',
          prop: 'volume',
          overHidden: true,
          disabled: false,
          width: 100
        }, {
          label: '空闲状态',
          width: 100,
          overHidden: true,
          disabled: true,
          search: true,
          filterable: true,
          prop: 'status',
          type: 'select',
          dicUrl: "/api/blade-system/dict-biz/dictionary?code=box_archives_status",
          props: {
            label: "dictValue",
            value: "dictKey"
          }
        }, {
          label: '造箱公司',
          prop: 'boxMakingCompany',
          disabled: false,
          width: 100,
          overHidden: true,
          search: true,
        }, {
          label: '造箱日期',
          prop: 'boxMakingDate',
          searchProp: 'boxMakingDateList',
          width: 100,
          overHidden: true,
          disabled: false,
          search: 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: 'leaseCommencementDate',
          searchProp: 'leaseCommencementDateList',
          width: 100,
          overHidden: true,
          search: true,
          type: "date",
          disabled: true,
          searchRange: true,
          searchDefaultTime: ["00:00:00", "23:59:59"],
          format: "yyyy-MM-dd",
          valueFormat: "yyyy-MM-dd HH:mm:ss"
        }, {
          label: '购入日期',
          prop: 'purchaseDate',
          width: 100,
          overHidden: true,
          type: "date",
          disabled: true,
          searchRange: true,
          searchDefaultTime: ["00:00:00", "23:59:59"],
          format: "yyyy-MM-dd",
          valueFormat: "yyyy-MM-dd HH:mm:ss"
        }, {
          label: '箱龄(月)',
          prop: 'boxAge',
          overHidden: true,
          disabled: false,
          width: 100,
        }, {
          label: '箱动态',
          prop: 'boxAccessStatus',
          overHidden: true,
          disabled: true,
          width: 100,
        }
        ]
      }
    }
  },
  async created() {
    this.option = await this.getColumnData(this.getColumnName(234), this.optionList);
    this.optionTrack = await this.getColumnData(this.getColumnName(234.1), this.optionTrackBack);
    this.key++
    let i = 0;
    this.option.column.forEach(item => {
      if (item.search) i++
    })
    if (i % 3 !== 0) {
      const num = 3 - Number(i % 3)
      this.option.searchMenuSpan = num * 8;
      this.option.searchMenuPosition = "right";
    }
  },
  methods: {
    dicChange(name, row) {
      if (name == 'typeName') {
        if (row) {
          this.form.typeId = row.id
        } else {
          this.form.typeId = null
          this.form.typeName = null
        }
      }
      if (name == 'purchaseCompanyName') {
        if (row) {
          this.form.boxMakingCompanyId = row.id
        } else {
          this.form.boxMakingCompanyId = null
          this.form.boxMakingCompany = null
        }
      }
    },
    // 箱轨迹里合同号跳转
    contractNoJump(row) {
      this.boxTrack = false
      if (row.status == '买箱') {
        this.$router.push({
          path: '/boxManagement/buyContainer/index?srcId=' + row.srcId
        });
      } else if (row.status == '卖箱') {
        this.$router.push({
          path: '/boxManagement/sellingContainers/index?srcId=' + row.srcId
        });
      } else if (row.status == '出口装运') {
        this.$router.push({
          path: '/boxManagement/exportShipment/index?srcId=' + row.srcId
        });
      } else if (row.status == '进口返程') {
        this.$router.push({
          path: '/boxManagement/importReturnTrip/index?srcId=' + row.srcId
        });
      } else if (row.status == '租入') {
        this.$router.push({
          path: '/boxManagement/leaseIn/index?srcId=' + row.srcId
        });
      } else if (row.status == '租出') {
        this.$router.push({
          path: '/boxManagement/leaseOut/index?srcId=' + row.srcId
        });
      } else { }

    },
    track(row) {
      // this.dataTrackList = row
      this.formSearch = row
      this.boxTrack = true
    },
    rowUpdateTrack(form, index, done, loading) {
      update(form).then(res => {
        done()
        this.$message.success("操作成功")
        this.onLoadTrack(this.pageTwo, this.searchTwo)
      })
    },
    //打开表单前
    beforeOpen(done, type) {
      if (type === "add") {
        this.findObject(this.option.column, "boxSource").value = this.$refs.crud.DIC.boxSource.length > 0 ? this.$refs.crud.DIC.boxSource[0].dictKey : ''
        this.findObject(this.option.column, "boxStatus").value = this.$refs.crud.DIC.boxStatus.length > 0 ? this.$refs.crud.DIC.boxStatus[0].dictKey : ''
      }
      done();
    },
    searchChangeTwo(params, done) {
      done();
      this.onLoadTrack(this.pageTwo, params)
    },
    onLoadTrack(page, params = {}) {
      params = {
        ...params,
        current: page.currentPage,
        size: page.pageSize,
        code: this.formSearch.code
      }
      this.loadingTwo = true
      archivestrajectory(params).then(res => {
        this.dataTrackList = res.data.data.records
        this.pageTwo.total = res.data.data.total
        this.loadingTwo = false
      }).finally(() => {
        this.loadingTwo = false
      })
    },
    //导出
    outExport() {
      this.$confirm('是否导出当前所有箱档案？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let queryParams = this.search
        const routeData = this.$router.resolve({
          path: '/api/blade-box-tube/archives/export-archives-out',      //跳转目标窗口的地址
          query: {
            'Blade-Auth': getToken(),
            ...queryParams    //括号内是要传递给新窗口的参数
          }
        })
        window.open(routeData.href.slice(1, routeData.href.length));
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消' //
        });
      })
    },
    derivation() {
      window.open(`/api/blade-box-tube/archives/export-archives-info?${this.website.tokenHeader}=${getToken()}`);
    },
    uploadBefore(file, done, loading) {
      loading = true;
      done();
    },
    uploadAfter(res, done, loading, column) {
      this.excelBox = false;
      this.$message.success("导入成功！");
      this.onLoad(this.page, this.search);
      loading = false;
      done();
    },
    balabala(val) {
      if (val === null) {
        this.form.address = ''
      } else {
        this.form.address = val.name
      }
    },
    getGSData(row) {
      this.form.leasingCompany = row.cname
    },
    //关闭弹窗前
    beforeClose(done, type) {
      this.onLoad(this.page, this.search)
      done()
    },
    //刷新
    refreshChange() {
      this.onLoad(this.page, this.search)
    },
    rowDel(form, index) {
      this.$confirm('此操作将永久删除该行, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        remove(form.id).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.onLoad(this.page, this.search)
        })
      }).catch(() => {
      });
    },
    uploadDelete(file, column) {
      return new Promise((resolve, reject) => {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (this.form.filesList[file.uid].id) {
            boxRemove(this.form.filesList[file.uid].id).then(res => {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              resolve();
            })
          } else {
            resolve();
          }
        }).catch(() => {
          reject();
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        })
      })
    },
    rowSave(form, done, loading, index) {
      done()
      addUpdate(form).then(res => {
        this.onLoad(this.page, this.search)
      })
    },
    searchChange(params, done) {
      done();
      this.onLoad(this.page, params)
    },
    onLoad(page, params = {}) {
      params = {
        ...params,
        current: page.currentPage,
        size: page.pageSize,
        ...Object.assign(params, this.search)
      }
      this.loading = true
      getList(params).then(res => {
        this.dataList = res.data.data.records
        this.page.total = res.data.data.total
        this.loading = false
      }).finally(() => {
        this.loading = false
      })
    },

    //自定义列保存
    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;
      }
    },
    //自定义列重置
    async resetColumnTwo(ref, option, optionBack, code) {
      this[option] = this[optionBack];
      const inSave = await this.delColumnData(this.getColumnName(code), this[optionBack]);
      if (inSave) {
        this.$message.success("重置成功");
        this.$refs[ref].$refs.dialogColumn.columnBox = false;
      }
    },
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-col-md-8 {
  width: 24.33333%;
}
</style>
