<template>
  <div class="app-container">

    <!-- 搜索工作栏 -->
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :model="queryParams"
      size="small"
      label-width="68px"
    >
      <QueryFormWrapper>
        <el-col :span="8">
          <el-form-item label="存货编码" prop="materialNo">
            <el-input
              v-model="queryParams.materialNo"
              placeholder="请输入存货编码"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="存货名称" prop="materialName">
            <el-input
              v-model="queryParams.materialName"
              placeholder="请输入存货名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="单据号" prop="warehousingOrderNo">
            <el-input
              v-model="queryParams.warehousingOrderNo"
              placeholder="请输入单据号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <div slot="right">
          <el-form-item label-width="0" class="text-right" style="word">
            <EasyAdvancedQuery class="mr10" label-width="98px" @advQuery="advQuery">
              <template #default="{model}">
                <el-row :gutter="10" type="flex">
                  <el-col :span="12">
                    <el-form-item label="仓库" prop="wmsStockId">
                      <StockSelect
                        v-model="queryParams.wmsStockId"
                        filterable
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="生产单号" prop="workOrderNo">
                      <el-input
                        v-model="queryParams.workOrderNo"
                        placeholder="请输入生产单号"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="创建时间" prop="createTime">
                      <el-date-picker
                        v-model="queryParams.createTime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        type="daterange"
                        range-separator="-"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        :default-time="['00:00:00', '23:59:59']"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </template>
            </EasyAdvancedQuery>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </div>
      </QueryFormWrapper>

    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <!-- <el-button
          v-hasPermi="['wms:inventory-general:export']"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
        >导出</el-button> -->
      </el-col>
      <right-toolbar
        :columns="columnsList"
        :show-search.sync="showSearch"
        @saveSetting="getColumnsList"
        @queryTable="getList"
      />
    </el-row>

    <!-- 列表 -->
    <AutoResizer :given-height="177">
      <template #default="{height}">
        <el-table
          v-if="columnsList.length > 0"
          v-loading="loading"
          :data="list"
          :height="height"
          border
          :summary-method="getSummaries"
          show-summary
        >
          <el-table-column
            v-if="columnsList[2].visible"
            :key="Math.random()"
            label="单据号"
            align="center"
            prop="warehousingOrderNo"
            min-width="160"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[6].visible"
            :key="Math.random()"
            label="日期/制单时间"
            align="center"
            prop="createTime"
            min-width="160"
            show-overflow-tooltip
          >
            <template slot-scope="{ row }">
              <span>{{ parseTime(row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            :key="Math.random()"
            label="工票号"
            align="center"
            prop="erpWorkOrderNo"
            min-width="140"
            show-overflow-tooltip
          />
          <el-table-column
            :key="Math.random()"
            label="生产单号"
            align="center"
            prop="workOrderNoNew"
            min-width="140"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[4].visible"
            :key="Math.random()"
            label="仓库编码"
            align="center"
            prop="stockCode"
            min-width="110"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[4].visible"
            :key="Math.random()"
            label="仓库名称"
            align="center"
            prop="wmsStockId"
            min-width="110"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[5].visible"
            :key="Math.random()"
            label="收发类别"
            align="center"
            prop="inOutType"
            min-width="130"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[5].visible"
            :key="Math.random()"
            label="部门名称"
            align="center"
            prop="departmentName"
            min-width="130"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[0].visible"
            :key="Math.random()"
            label="存货编码"
            align="center"
            prop="materialNo"
            fixed="left"
            min-width="110"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[1].visible"
            :key="Math.random()"
            label="存货名称"
            align="center"
            prop="materialName"
            min-width="110"
            show-overflow-tooltip
          />
          <el-table-column
            :key="Math.random()"
            label="存货规格型号"
            align="center"
            prop="size"
            min-width="110"
            show-overflow-tooltip
          />
          <el-table-column
            :key="Math.random()"
            label="单位"
            align="center"
            prop="unitName"
            min-width="110"
            show-overflow-tooltip
          />
          <el-table-column
            :key="Math.random()"
            label="数量"
            align="center"
            prop="inQty"
            min-width="110"
            show-overflow-tooltip
          />
          <el-table-column
            :key="Math.random()"
            label="批号"
            align="center"
            prop="outputLot"
            min-width="110"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[6].visible"
            :key="Math.random()"
            label="生产日期"
            align="center"
            prop="produceDate"
            min-width="160"
            show-overflow-tooltip
          >
            <template slot-scope="{ row }">
              <span>{{ parseTime(row.produceDate) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            :key="Math.random()"
            label="制单人"
            align="center"
            prop="creator"
            min-width="110"
            show-overflow-tooltip
          />
          <el-table-column
            :key="Math.random()"
            label="审核人"
            align="center"
            prop="auditor"
            min-width="110"
            show-overflow-tooltip
          />
          <el-table-column
            :key="Math.random()"
            label="审核日期"
            align="center"
            prop="auditTime"
            min-width="110"
            show-overflow-tooltip
          />
        </el-table>
      </template>
    </AutoResizer>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { getIncomingProduceStockedDetailPage } from '@/api/wms/inquirePurchase/documentList'

import StockSelect from '../../incoming/wareHousing/components/StockSelect.vue'
import { getFormColumnsList } from '@/api/system/saveColumns/index'
import { mapGetters } from 'vuex'
import { isArray } from 'min-dash'

export default {
  name: 'FinishedProductReceipt',
  components: {
    StockSelect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库存总账列表
      list: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 高级查询参数
      advParams: {},
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        materialNo: null,
        materialName: null,
        warehousingOrderNo: null,
        workOrderNo: null,
        createTime: [],
        wmsStockId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      // 显示隐藏列参数
      columns: [
        { key: 0, label: '存货编码', visible: true },
        { key: 1, label: '存货名称', visible: true },
        { key: 2, label: '存货类别', visible: true },
        { key: 3, label: '库存状态', visible: true },
        { key: 4, label: '规格型号', visible: true },
        { key: 5, label: '存储条件', visible: true },
        { key: 6, label: '库存单位', visible: true },
        { key: 7, label: '库存量', visible: true }
      ],
      // 显示隐藏持久化参数
      columnsList: []
    }
  },
  // 获取当前登录用户id
  computed: {
    ...mapGetters([
      'userId'
    ])
  },
  created() {
    // 获取显隐列列表
    this.getColumnsList()
    this.getList()
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true
      // 执行查询
      const params = { ...this.queryParams, ...this.advParams }
      getIncomingProduceStockedDetailPage(params).then(response => {
        this.list = response.data.list
        this.total = response.data.total
      }).finally(() => {
        this.loading = false
      })
    },
    /** 表单重置 */
    reset() {
      this.form = {
        pageNo: 1,
        pageSize: 10,
        materialNo: null,
        materialName: null,
        warehousingOrderNo: null,
        workOrderNo: null,
        createTime: [],
        wmsStockId: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.advParams = {}
      this.handleQuery()
    },
    // 小数处理
    getHandleNumber(val) {
      return Math.round((parseFloat(val) * 100000000)) / 100000000
    },
    // 表尾计算
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计'
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (column.property === 'inQty') {
          sums[index] = values.reduce((acc, cur) => {
            const value = Number(cur)
            if (!isNaN(value)) {
              return this.getHandleNumber(acc + cur)
            } else {
              return acc
            }
          }, 0)
          sums[index]
        }
      })
      return sums
    },
    // 高级查询
    advQuery(advQueryParams) {
      this.advParams = advQueryParams
      this.handleQuery()
    },
    // 获取显示隐藏列
    getColumnsList() {
      const { componentName } = this.$route.meta || null
      const params = {
        userId: this.userId,
        vueForm: componentName
      }
      getFormColumnsList(params).then(res => {
        if (isArray(res.data)) {
          this.columnsList = res.data.length === 0 ? this.columns : res.data
          // 对比默认数据和接口数据，将缺失的列添加到接口数据中
          this.columnsList = this.columns.reduce((acc, defaultColumn) => {
            const found = res.data.find(apiColumn => apiColumn.key === defaultColumn.key)
            if (!found) {
              acc.push({ ...defaultColumn, vueForm: componentName, userId: this.userId, id: null })
            }
            return acc
          }, res.data)
        } else {
          this.columnsList = this.columns
        }
      }).catch((err) => {
        if (err) {
          this.columnsList = this.columns
        }
      })
    }
  }
}
</script>
