<template>
  <div>
    <avue-crud
        :option="option"
        :search.sync="search"
        v-model="form"
        :table-loading="loading"
        :data="dataList"
        ref="crud"
        :key="key"
        @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"
        @selection-change="selectionChange"
        @refresh-change="refreshChange"
        @resetColumn="resetColumnTwo('crud','option','optionList',238)"
        @saveColumn="saveColumnTwo('crud','option','optionList',238)"
        :page.sync="page">
<!--      <template slot-scope="scope" slot="menuLeft">-->
<!--        <el-button type="success" size="small" icon="el-icon-bottom" @click="excelBox = true">导入-->
<!--        </el-button>-->
<!--        <el-button type="warning"-->
<!--                   icon="el-icon-download"-->
<!--                   size="small"-->
<!--                   @click="outExport">导出-->
<!--        </el-button>-->
<!--      </template>-->
      <template slot="leasingCompanyIdForm">
        <crop-select v-model="form.leasingCompanyId" @getCorpData="getGSData" corpType="GS"/>
      </template>
      <template slot="addressIdForm">
        <port-info v-model="form.addressId" type="id" @balabalaTow="balabala"/>
      </template>
      <template slot="addressIdSearch">
        <port-info v-model="search.addressId" type="id"/>
      </template>
      <template slot="addressId" slot-scope="{row}">
        {{ row.address }}
      </template>
      <template slot="leasingCompanyIdSearch">
        <crop-select v-model="search.leasingCompanyId" corpType="KH"/>
      </template>
      <template slot="leasingCompanyId" slot-scope="{row}">
        {{ row.leasingCompany }}
      </template>
    </avue-crud>
<!--    <el-dialog title="导入客户" append-to-body :visible.sync="excelBox" width="555px" :close-on-click-modal="false"-->
<!--               v-dialog-drag>-->
<!--      <avue-form :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&#45;&#45;right"></i>-->
<!--          </el-button>-->
<!--        </template>-->
<!--      </avue-form>-->
<!--      <p style="text-align: center;color: #DC0505">-->
<!--        温馨提示 第一次导入时请先下载模板-->
<!--      </p>-->
<!--    </el-dialog>-->
  </div>
</template>

<script>
import {addUpdate, boxRemove, getList, remove} from "@/api/box/archives";
import {getToken} from "@/util/auth";
import {getAllBoxs} from "@/api/basicData/portinformation";

export default {
  name: "archives",
  data() {
    return {
      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]
      },
      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/archives/import-descParts-info"
          }
        ]
      },
      key: 0,
      option: {},
      optionList: {
        index: true,
        span: 8,
        border: true,
        selection: true,
        reserveSelection: true,
        searchMenuPosition: "right",
        align: "center",
        menu:false,
        addBtn:false,
        searchSpan: 8,
        searchIcon: true,
        searchIndex: 2,
        highlightCurrentRow: true,
        dialogWidth: "70%",
        column: [{
          label: '合同号',
          prop: 'contractNo',
          width: 100,
          overHidden: true,
          search: true,
        }, {
          label: '箱号',
          prop: 'code',
          width: 100,
          overHidden: true,
          search: true,
        }, {
          label: '箱类型',
          prop: 'typeId',
          width: 100,
          overHidden: true,
          search: true,
          filterable: true,
          type: 'select',
          dataType: 'number',
          props: {
            label: 'name',
            value: 'id'
          },
          dicUrl: '/api/blade-client/container/listMessage'
        }, {
          label: '最新地点',
          prop: 'addressId',
          width: 100,
          overHidden: true,
          search: true,
        }, {
          label: '最新日期',
          prop: 'newDate',
          width: 100,
          searchProp: 'newDateList',
          overHidden: true,
          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: 'leasingCompanyId',
          width: 100,
          overHidden: true,
          search: true,
        }, {
          label: '箱来源',
          prop: 'boxSource',
          width: 100,
          overHidden: 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,
          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',
          dicUrl: "/api/blade-system/dict-biz/dictionary?code=lease_method",
          props: {
            label: "dictValue",
            value: "dictKey"
          }
        }, {
          label: '空重(kg)',
          prop: 'emptyWeight',
          width: 100,
          overHidden: true,
          type: 'number',
          controls: false,
        }, {
          label: '毛重(kg)',
          prop: 'gorssWeight',
          width: 100,
          overHidden: true,
          type: 'number',
          controls: false,
        }, {
          label: '皮重(kg)',
          prop: 'tare',
          width: 100,
          overHidden: true,
          type: 'number',
          controls: false,
        }, {
          label: '装载重量(kg)',
          prop: 'loadingWeight',
          width: 100,
          overHidden: true,
          type: 'number',
          controls: false,
        }, {
          label: '容积(m³)',
          prop: 'volume',
          type: 'number',
          controls: false,
          overHidden: true,
          width: 100
        }, {
          label: '状态',
          width: 100,
          overHidden: 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',
          width: 100,
          overHidden: true,
          search: true,
        }, {
          label: '造箱日期',
          prop: 'boxMakingDate',
          searchProp: 'boxMakingDateList',
          width: 100,
          overHidden: true,
          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",
          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",
          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,
          width: 100,
        }, {
          label: '照片',
          prop: 'filesList',
          width: 200,
          overHidden: true,
          type: 'upload',
          span: 24,
          listType: 'picture-card',
          tip: '只能上传jpg/png文件，且不超过500kb',
          propsHttp: {
            url: 'link',
            name: 'originalName',
            res: 'data'
          },
          action: '/api/blade-resource/oss/endpoint/put-file'
        }]
      }
    }
  },
  model: {
    prop: "listData",
    event: "callBack"
  },
  props: {
    listData: {
      type: Array,
      default: function () {
        return [];
      }
    }
  },
  async created() {
    this.option = await this.getColumnData(this.getColumnName(238), this.optionList);
    this.key++
    this.findObject(this.option.column, "typeId").change = ({value, column}) => {
      getAllBoxs().then(res => {
        for (let item of res.data.data){
          if (value == item.id){
            this.form.name = item.name
          }
        }
      })
    }
    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: {
    //导出
    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) {
      done();
      loading = true;
    },
    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)
    },
    selectionChange(list){
      this.$emit("callBack", list);
    },
    rowDel(form, index) {
      this.$confirm('此操作将永久删除该行, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        remove(form.id).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })
      }).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,
        status:"待使用",
        ...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 scoped>

</style>
