<template>
  <div class="app-container">
    <!-- 操作栏 -->
    <el-row :gutter="10" class="mb10">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['wms:incoming-receipt:export']"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-show="$route.name === 'IncomingReceipt'"
          type="primary"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="handleChange"
        >切换为录入模式</el-button>
      </el-col>
      <right-toolbar
        v-show="$route.name === 'IncomingReceipt'"
        :columns="columnsList"
        :show-search.sync="showSearch"
        @saveSetting="getColumnsList"
        @queryTable="getList"
      />
    </el-row>

    <!-- 列表 -->
    <AutoResizer :given-height="220">
      <template #default="{height}">
        <el-table
          v-if="columnsList.length > 0"
          v-loading="loading"
          :height="height"
          :data="list"
          show-summary
          :summary-method="getSummaries"
          border
        >
          <el-table-column
            v-if="columnsList[0].visible"
            :key="columnsList[0].key"
            label="物料批次"
            align="center"
            prop="materialLots"
            width="160"
            fixed="left"
            show-overflow-tooltip
          >
            <template v-slot="scope">
              <el-button
                size="mini"
                type="text"
                @click="handleToMaterialRegister(scope.row)"
              >{{ scope.row.materialLots }}</el-button>
            </template>
          </el-table-column>
          <el-table-column
            v-if="columnsList[1].visible"
            :key="columnsList[1].key"
            label="采购订单"
            align="center"
            prop="purchaseOrderNo"
            min-width="120"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[2].visible"
            :key="columnsList[2].key"
            label="物料编码"
            align="center"
            prop="materialNo"
            width="150"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[3].visible"
            :key="columnsList[3].key"
            label="物料名称"
            align="center"
            prop="materialName"
            width="150"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[4].visible"
            :key="columnsList[4].key"
            label="到货数量"
            width="100"
            sortable
            align="center"
            prop="receiptQty"
          />
          <el-table-column
            v-if="columnsList[5].visible"
            :key="columnsList[5].key"
            label="检验状态"
            align="center"
            prop="testStatus"
          >
            <template slot-scope="scope">
              <dict-tag :type="DICT_TYPE.WMS_TEST_STATUS" :value="scope.row.testStatus" />
            </template>
          </el-table-column>
          <el-table-column
            v-if="columnsList[20].visible"
            :key="Math.random()"
            label="审核状态"
            align="center"
            prop="auditStatus"
            width="100"
          >
            <template slot-scope="scope">
              <dict-tag :type="DICT_TYPE.WMS_AUDIT_STATUS" :value="scope.row.auditStatus" />
            </template>
          </el-table-column>
          <el-table-column
            v-if="columnsList[6].visible"
            :key="columnsList[6].key"
            label="单位"
            align="center"
            prop="unitCode"
          />
          <el-table-column
            v-if="columnsList[7].visible"
            :key="columnsList[7].key"
            label="供应商"
            align="center"
            prop="supplierName"
            width="160"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[8].visible"
            :key="columnsList[8].key"
            label="部门"
            align="center"
            prop="departmentName"
            width="160"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[9].visible"
            :key="columnsList[9].key"
            label="备注"
            align="center"
            prop="remark"
            width="120"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[10].visible"
            :key="columnsList[10].key"
            label="登记时间"
            align="center"
            prop="receiptTime"
            width="160"
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.receiptTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            v-if="columnsList[11].visible"
            :key="columnsList[11].key"
            label="检验时间"
            align="center"
            prop="auditTime"
            width="160"
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.auditTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            v-if="columnsList[12].visible"
            :key="columnsList[12].key"
            label="检验结果"
            align="center"
            prop="noPassType"
            width="160"
          >
            <template slot-scope="scope">
              <dict-tag :type="DICT_TYPE.WMS_NO_PASS_TYPE" :value="scope.row.noPassType" />
            </template>
          </el-table-column>
          <el-table-column
            v-if="columnsList[13].visible"
            :key="columnsList[13].key"
            label="生产日期"
            align="center"
            prop="produceDate"
            width="160"
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.produceDate) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            v-if="columnsList[14].visible"
            :key="columnsList[14].key"
            label="登记人"
            align="center"
            prop="receiptPerson"
          />
          <el-table-column
            v-if="columnsList[15].visible"
            :key="columnsList[15].key"
            label="规格"
            align="center"
            width="130"
            show-overflow-tooltip
            prop="size"
          />
          <el-table-column
            v-if="columnsList[16].visible"
            :key="columnsList[16].key"
            label="存储条件"
            align="center"
            prop="storageEnvironment"
            width="150"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[17].visible"
            :key="columnsList[17].key"
            label="送货批次"
            align="center"
            prop="deliverBatch"
            width="120"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[18].visible"
            :key="columnsList[18].key"
            label="采购数量"
            sortable
            width="100"
            align="center"
            prop="purchaseQty"
          />
          <el-table-column
            v-if="columnsList[19].visible"
            :key="columnsList[19].key"
            sortable
            label="累计已到货数量"
            align="center"
            prop="receiveQty"
            width="140"
          />

          <el-table-column
            v-if="registerOperateShow"
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            fixed="right"
            width="80"
          >
            <template slot-scope="scope">
              <el-button
                v-hasPermi="['wms:incoming-receipt:delete']"
                size="mini"
                type="text"
                icon="el-icon-delete"
                class="text-danger"
                @click="handleDelete(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </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 { getIncomingReceiptPage, deleteIncomingReceipt, exportIncomingReceiptExcel, getFiles } from '@/api/wms/incoming/register'
import { getFormColumnsList } from '@/api/system/saveColumns/index'
import { mapGetters } from 'vuex'
import { isArray } from 'min-dash'

export default {
  name: 'IncomingRegister',
  inject: ['paramsQuery'],
  data() {
    return {
      // 生产日期
      produceDate: '',
      // 遮罩层
      loading: true,
      sureLoading: false,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 是否显示来料登记操作列
      registerOperateShow: true,
      // 总条数
      total: 0,
      // WMS 入库业务-来料登记主列表
      list: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 高级查询参数
      advParams: {},
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        areaTest: null,
        materialLots: null,
        purchaseOrderNo: null,
        materialNo: null,
        receiptQty: null,
        testStatus: null,
        createTime: [],
        materialName: null
      },
      // 显示隐藏列参数
      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 },
        { key: 8, label: '部门', visible: true },
        { key: 9, label: '备注', visible: true },
        { key: 10, label: '登记时间', visible: true },
        { key: 11, label: '检验时间', visible: true },
        { key: 12, label: '检验结果', visible: true },
        { key: 13, label: '生产日期', visible: true },
        { key: 14, label: '登记人', visible: true },
        { key: 15, label: '规格', visible: true },
        { key: 16, label: '存储条件', visible: true },
        { key: 17, label: '送货批次', visible: true },
        { key: 18, label: '采购数量', visible: true },
        { key: 19, label: '累计已到货数量', visible: true },
        { key: 20, label: '审核状态', visible: true }
      ],
      // 显示隐藏持久化参数
      columnsList: []
    }
  },
  // 获取当前登录用户id
  computed: {
    ...mapGetters([
      'userId'
    ])
  },
  created() {
    // 获取显隐列列表
    this.getColumnsList()
    this.getList()
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true
      // 执行查询
      const params = {
        ...this.queryParams,
        ...this.paramsQuery,
        ...this.advParams
      }
      getIncomingReceiptPage(params).then(response => {
        this.list = response.data.list
        this.total = response.data.total
      }).finally(() => {
        this.loading = false
      })
    },
    /** 取消按钮 */
    cancel() {
      this.open = false
      this.toggle = !this.toggle
      this.reset()
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        areaTest: undefined,
        materialLots: undefined,
        purchaseOrderNo: undefined,
        materialNo: undefined,
        receiptQty: undefined,
        testStatus: undefined,
        produceDate: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 删除操作
    handleDelete(row) {
      const { id, materialNo } = row
      this.$modal.confirm('是否确认删除物料编码为"' + materialNo + '"的数据项?').then(function() {
        return deleteIncomingReceipt(id)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    // // 查看附件
    // handleViewAttachment(row) {
    //   const { id } = row
    //   getFiles(id).then(res => {
    //     this.$emit('uploadedFiles', res.data || [])
    //   })
    // },
    // 获取显示隐藏列
    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
        }
      }).finally(() => {
        this.$emit('columns', this.columnsList)
      })
    },
    // 小数点问题处理
    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 === 'receiptQty' || column.property === 'purchaseQty' || column.property === 'receiveQty') {
          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
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      const params = { ...this.queryParams }
      params.pageNo = undefined
      params.pageSize = undefined
      this.$modal.confirm('是否确认导出所有WMS 入库业务-来料登记主数据项?').then(() => {
        this.exportLoading = true
        return exportIncomingReceiptExcel(params)
      }).then(response => {
        this.$download.excel(response, `WMS 入库业务-来料登记主-${ new Date().toLocaleString()}.xls`)
        this.exportLoading = false
      }).catch(() => {})
    },
    // 切换模式
    handleChange() {
      this.$router.push({ path: '/entry-exit/purchase-out-in/material-regist-enter' })
    },
    handleToMaterialRegister(row) {
      this.$router.push({ path: '/entry-exit/purchase-out-in/material-regist-enter?materialLots=' + row.materialLots })
    }

  }
}
</script>
<style>

::v-deep.el-table .el-table__cell.gutter{
  display: none!important;
  width:0!important;
}
/* .el-table__fixed-right {
  right: 0!important;
} */
</style>
