<template>
  <basic-container>
    <avue-crud
        :key="key"
        ref="crud"
        :option="option"
        :data="data"
        :search.sync="search"
        @on-load="onLoad"
        @search-reset="query={}"
        :page.sync="page"
        @search-change="searchChange"
        @search-criteria-switch="searchCriteriaSwitch"
        @resetColumn="resetColumn"
        @saveColumn="saveColumn"
        :summary-method="summaryMethod"
        @refresh-change="refreshChange">
      <template slot="itemId" slot-scope="{row,index}">
        {{ row.goodsName }}
      </template>
      <template slot="warehouseId" slot-scope="{row,index}">
        {{ row.warehouse }}
      </template>
      <template slot="corpNameSearch">
        <crop-select v-model="search.corpId" corpType="GYS" :refresh="false"></crop-select>
      </template>
      <template slot="purchaserSearch">
        <crop-select v-model="search.purchaserId" corpType="KH" :refresh="false"></crop-select>
      </template>
      <template slot="menuLeft">
        <el-button type="warning"
                   icon="el-icon-plus"
                   size="small"
                   @click="outExport()">导出
        </el-button>
      </template>
      <template slot="header">
        <el-table
            :data="commodityData"
            border
            size="small"
            @header-click="cellClick"
            style="width: 100%">
          <el-table-column
              v-for="(item,index) in commodityLabel"
              :key="index"
              :prop="item.prop"
              width="200"
              show-overflow-tooltip
              :label="item.label">
          </el-table-column>
        </el-table>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import {generalLedgerListByGoods, getList,generalLedgerTotal} from "@/api/purchasingManagement/inventoryAccount";
import {getToken} from "@/util/auth";
import {dateFormat} from "@/util/date";

export default {
  data() {
    return {
      key: 0,
      search: {},
      data: [],
      total: [],
      query: {},
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
        pageSizes: [10, 50, 100, 200, 300]
      },
      option: {},
      optionList: {
        align: 'center',
        stripe: true,
        index: true,
        menu: false,
        height: "auto",
        searchSpan: 8,
        searchIcon: true,
        searchIndex: 2,
        // highlightCurrentRow: true,
        addBtn: false,

        showSummary: true,
        summaryText: "合计",
        sumColumnList: [
          {
            name: 'sliceNumber',
            type: 'sum',
            decimals: 2
          },{
            name: 'balanceNumber',
            type: 'sum',
            decimals: 2
          },{
            name: 'balanceMoney',
            type: 'sum',
            decimals: 2
          }],
        column: [{
          label: '货权人',
          prop: 'purchaser',
          index: 18,
          width: 140,
          overHidden: true,
          search: true
        },{
          label: '品名',
          // searchProp: 'goodsName',
          prop: 'itemId',
          dicUrl: '/api/blade-client/goodsdesc/descListAll',
          props: {
            label: "cname",
            value: "id",
          },
          filterable: true,
          type: "select",
          overHidden: true,
          index: 1,
          search: true
        }, {
          label: '提单号',
          prop: 'morderNo',
          index: 19,
          search: true
        }, {
          label: '箱号',
          prop: 'containerNo',
          index: 6,
          width: 100,
          search: true
        }, {
          label: '仓库',
          prop: 'warehouseId',
          type: "tree",
          dicUrl: "/api/blade-client/storagetype/tree",
          index: 11,
          props: {
            "label": "title",
            "value": "value"
          },
          "checkStrictly": true,
          "showAllLevels": false,
          "emitPath": false,
          "width": 120,
          "searchSpan": 8,
          "overHidden": true,
          search: true
        }, {
          label: '捆包号',
          prop: 'billNo',
          index: 6,
          width: 100,
          search: true
        }, {
          label: '长',
          prop: 'length',
          index: 2,
          search: true
        }, {
          label: '厚',
          prop: 'thickness',
          index: 5,
          search: true
        }, {
          label: '等级',
          prop: 'grade',
          dicUrl: "/api/blade-system/dict-biz/dictionary?code=goods_grade",
          type: "select",
          props: {
            label: "dictValue",
            value: "dictKey"
          },
          dataType: "string",
          index: 14,
          search: true
        }, {
          label: '品牌',
          prop: 'itemType',
          index: 13,
          search: true
        }, {
          label: '车船号',
          prop: 'vehicleShipNumber',
          index: 17,
          search: true
        }, {
          label: '产地',
          prop: 'itemProp',
          index: 15,
          search: true
        }, {
          label: '供应商',
          prop: 'corpName',
          index: 16,
          width: 100,
          overHidden: true,
          search: true
        },{
          label: "入库日期",
          prop: "stockDate",
          type: "date",
          value: dateFormat(new Date(),'yyyy-MM-dd'),
          format: "yyyy-MM-dd",
          valueFormat: "yyyy-MM-dd",
          width: 100
        },{
          label: "出库日期",
          prop: "deliveryDate",
          type: "date",
          value: dateFormat(new Date(),'yyyy-MM-dd'),
          format: "yyyy-MM-dd",
          valueFormat: "yyyy-MM-dd",
          width: 100
        }, {
          label: '状态',
          index: 19,
          prop: 'status',
          dataType: "number",
          type: 'select',
          dicUrl: "/api/blade-system/dict-biz/dictionary?code=inventory_account",
          props: {
            label: "dictValue",
            value: "dictKey"
          }
        }, {
          label: '状态',
          prop: 'isIssue',
          type: 'select',
          index: 19,
          hide: true,
          showColumn: false,
          dicData: [{
            label: "在库",
            value: 3
          }, {
            label: "计划",
            value: 4
          }, {
            label: "待出库",
            value: 5
          }, {
            label: "已出库",
            value: 7
          }],
          search: true
        }, {
          label: '可用片数',
          prop: 'sliceNumber',
          index: 7
        }, {
          label: '可用库存',
          prop: 'balanceNumber',
          index: 8
        }, {
          label: '库存单价',
          prop: 'price',
          index: 9
        }, {
          label: '库存金额',
          prop: 'balanceMoney',
          index: 10
        }, {
          label: '库位',
          prop: 'storageName',
          index: 12
        }]
      },
      commodityLabel: [],
      commodityData: []
    }
  },
  async created() {
    generalLedgerListByGoods().then(res => {
      for (let item in res.data.data) {
        this.commodityLabel.push({label: res.data.data[item].cname, prop: item, id: res.data.data[item].id})
        this.commodityData[0] = {
          ...this.commodityData[0],
          [item]: `${res.data.data[item].sliceNumber?res.data.data[item].sliceNumber:0}片,${res.data.data[item].balanceNumber?res.data.data[item].balanceNumber:0}立方`
        }
      }
    })
    this.option = await this.getColumnData(this.getColumnName(200), this.optionList);
    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: {
    summaryMethod({ columns, data }){
      const sums = [];
      if (columns.length > 0) {
        columns.forEach((column, index) => {
          let prop=column.property
          if (['sliceNumber','balanceNumber','balanceMoney'].includes(prop) ) {
            if(prop=='sliceNumber'){
              sums[index]=this.total.sliceNumber
            }else if(prop=='balanceNumber'){
              sums[index]=this.total.balanceNumber
            }else if(prop=='balanceMoney'){
              sums[index]=this.total.balanceMoney
            }
          } else {
            sums[0] = '合计'
          }
        });
      }
      return sums;
    },
    cellClick(row, column, cell, event) {
      for (let item of this.commodityLabel) {
        if (row.label == item.label) {
          this.search.itemId = item.id
          this.onLoad(this.page, this.search)
        }
      }
    },
    onLoad(page, params = {}) {
      let queryParams = {
        size: page.pageSize,
        current: page.currentPage,
        ...Object.assign(params, this.search)
      }
      getList(queryParams).then(res => {
        this.data = res.data.data.records
        this.page.total = res.data.data.total
        this.option.height = window.innerHeight - 230;
        generalLedgerTotal(queryParams).then(res=>{
          this.total = res.data.data
        })
      })
    },
    //搜索
    searchChange(params, done) {
      let data = params
      if (params.arrivalTime) {
        data.beginArrivalTime = params.arrivalTime[0]
        data.endArrivalTime = params.arrivalTime[1]
      }
      if (params.createTime) {
        data.beginCrateTime = params.createTime[0]
        data.endCrateTime = params.createTime[1]
      }
      delete data.arrivalTime
      delete data.createTime
      this.query = data;
      this.onLoad(this.page, data)
      done();
    },
    // 获得高度
    searchCriteriaSwitch(type) {
      if (type) {
        this.option.height = this.option.height - 55
      } else {
        this.option.height = this.option.height + 55
      }
      this.$refs.crud.getTableHeight()
    },
    //自定义列保存
    async saveColumn() {
      /**
       * 已定义全局方法，直接使用，saveColumnData保存列数据方法,参数传值(表格名称，当前表格的option数据)
       * 已定义全局方法，直接使用，getColumnName方法用来获取枚举值，参数根据自己定义的code值获取中文名
       * 一定要执行异步操作，要等接口成功返回，才能执行下一行代码
       */
      const inSave = await this.saveColumnData(this.getColumnName(200), this.option);
      if (inSave) {
        this.$message.success("保存成功");
        //关闭窗口
        this.$refs.crud.$refs.dialogColumn.columnBox = false;
      }
    },
    //自定义列重置
    async resetColumn() {
      this.option = this.optionList;
      const inSave = await this.delColumnData(this.getColumnName(200), this.optionList);
      if (inSave) {
        this.$message.success("重置成功");
        this.$refs.crud.$refs.dialogColumn.columnBox = false;
      }
    },
    refreshChange() {
      this.onLoad(this.page, this.search);
    },
    //导出
    outExport() {
      this.$confirm('是否导出数据明细？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let queryParams = this.query
        const routeData = this.$router.resolve({
          path: '/api/trade-purchase/woodHarvestingCloud/generalLedgerExport',      //跳转目标窗口的地址
          query: {
            'Blade-Auth': getToken(),
            ...queryParams    //括号内是要传递给新窗口的参数
          }
        })
        window.open(routeData.href.slice(1, routeData.href.length));
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消' //
        });
      })
    },
  }
}
</script>

<style scoped>

</style>
