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

    <!-- 搜索工作栏 -->
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :model="queryParams"
      size="small"
      label-width="88px"
    >
      <QueryFormWrapper>
        <el-col :span="6">
          <el-form-item label="送货单号" prop="deliveryOrderNo">
            <el-input
              v-model="queryParams.deliveryOrderNo"
              placeholder="请输入送货单号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="送货单批次" prop="deliverBatch">
            <el-input
              v-model="queryParams.deliverBatch"
              placeholder="请输入送货单批次"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="供应商" prop="supplierCode">
            <el-input
              v-model="queryParams.supplierCode"
              placeholder="请输入供应商"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="queryParams.remark"
              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">
            <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:incoming-receipt-master:create']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['wms:incoming-receipt-master: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"
          border
          :height="height"
          :span-method="arraySpanMethod"
        >
          <el-table-column
            v-if="columnsList[0].visible"
            label="暂收单号"
            align="center"
            prop="deliveryOrderNo"
            width="150"
            fixed="left"
          >
            <template slot-scope="scope">
              <el-button type="text" @click="handleDetails(scope.row)">{{ scope.row.deliveryOrderNo }}</el-button>
            </template>
          </el-table-column>
          <el-table-column
            v-if="columnsList[1].visible"
            label="供应商"
            align="center"
            prop="supplierName"
            width="120"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[2].visible"
            label="采购订单"
            align="center"
            prop="purchaseOrderNo"
            width="130"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[3].visible"
            label="物料批次"
            align="center"
            prop="materialLots"
            width="150"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[4].visible"
            label="物料编码"
            align="center"
            prop="materialNo"
            width="130"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[5].visible"
            label="物料名称"
            align="center"
            prop="materialName"
            width="120"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[6].visible"
            label="到货数量"
            align="center"
            prop="receiptQty"
          />
          <el-table-column
            v-if="columnsList[7].visible"
            label="单位"
            align="center"
            prop="unitCode"
          />
          <el-table-column
            v-if="columnsList[8].visible"
            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[9].visible"
            label="创建人"
            align="center"
            prop="creator"
          />
          <el-table-column
            v-if="columnsList[10].visible"
            label="备注"
            align="center"
            prop="remark"
          />
          <el-table-column
            v-if="columnsList[11].visible"
            label="创建时间"
            align="center"
            prop="createTime"
            width="180"
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            fixed="right"
            width="100"
          >
            <template slot-scope="scope">
              <el-button
                v-hasPermi="['wms:incoming-receipt-master: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"
    />

    <!-- <ReceiptDetails ref="receiptDetails" @saveComplete="getList" /> -->
  </div>
</template>

<script>
import { createIncomingReceiptMaster, updateIncomingReceiptMaster, deleteIncomingReceiptMaster, getIncomingReceiptMaster, getIncomingReceiptMasterPage, exportIncomingReceiptMasterExcel } from '@/api/wms/incoming/temporaryReceipt'
// import ReceiptDetails from './components/ReceiptDetails.vue'
import { getFormColumnsList } from '@/api/system/saveColumns/index'
import { mapGetters } from 'vuex'
import { isArray } from 'min-dash'

export default {
  name: 'TemporaryReceipt',
  components: {
    // ReceiptDetails
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 来料暂收主列表
      list: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        deliveryOrderNo: null,
        deliverBatch: null,
        supplierCode: null,
        remark: null,
        createTime: []
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deliveryOrderNo: [{ required: true, message: '送货单号不能为空', trigger: 'blur' }]
      },
      // 显示隐藏列参数
      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 }
      ],
      // 显示隐藏持久化参数
      columnsList: []
    }
  },
  // 获取当前登录用户id
  computed: {
    ...mapGetters([
      'userId'
    ])
  },
  created() {
    // 获取显隐列列表
    this.getColumnsList()
    this.getList()
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true
      // 执行查询
      getIncomingReceiptMasterPage(this.queryParams).then(response => {
        this.list = response.data.list
        this.total = response.data.total
      }).finally(() => {
        this.loading = false
      })
    },
    /** 取消按钮 */
    cancel() {
      this.open = false
      this.reset()
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        deliveryOrderNo: undefined,
        deliverBatch: undefined,
        supplierCode: undefined,
        remark: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.$router.push({ path: '/incoming/temporary-receipt-detail' })
      // this.$refs.receiptDetails.open = true
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id
      getIncomingReceiptMaster(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改来料暂收主'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (!valid) {
          return
        }
        // 修改的提交
        if (this.form.id != null) {
          updateIncomingReceiptMaster(this.form).then(response => {
            this.$modal.msgSuccess('修改成功')
            this.open = false
            this.getList()
          })
          return
        }
        // 添加的提交
        createIncomingReceiptMaster(this.form).then(response => {
          this.$modal.msgSuccess('新增成功')
          this.open = false
          this.getList()
        })
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id
      this.$modal.confirm('是否确认删除来料暂收主编号为"' + id + '"的数据项?').then(function() {
        return deleteIncomingReceiptMaster(id)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      const params = { ...this.queryParams }
      params.pageNo = undefined
      params.pageSize = undefined
      this.$modal.confirm('是否确认导出所有来料暂收主数据项?').then(() => {
        this.exportLoading = true
        return exportIncomingReceiptMasterExcel(params)
      }).then(response => {
        this.$download.excel(response, '来料暂收主.xls')
        this.exportLoading = false
      }).catch(() => {})
    },
    // 表格行合并
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      const newData = this.list.map((item, index) => {
        const filterData = this.list.filter(ele => {
          return item.deliveryOrderNo === ele.deliveryOrderNo
        })
        const dataIndex = this.list.findIndex(eleIndex => {
          return item.deliveryOrderNo === eleIndex.deliveryOrderNo
        })
        if (index === dataIndex) {
          item.rowspan = filterData.length
        } else {
          item.rowspan = 0
        }
        return newData
      })
      if (columnIndex === 0) {
        return {
          rowspan: row.rowspan,
          colspan: 1
        }
      } else {
        return false
      }
    },
    // 来料暂收明细
    handleDetails(row) {
      const { masterId } = row
      this.$router.push({ path: '/entry-exit/purchase-out-in/temporary-receipt-detail', query: { masterId }})
    },
    // 获取显示隐藏列
    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)
      })
    }
  }
}
</script>
