<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="saleOutNo">
            <el-input
              v-model="queryParams.saleOutNo"
              placeholder="请输入出货单号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="销售订单" prop="erpOrderNo" label-width="88px">
            <el-input
              v-model="queryParams.erpOrderNo"
              placeholder="请输入销售订单"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <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>
        <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="outStatus">
                      <DictSelect v-model="model.outStatus" placeholder="请选择出货状态" dict-type="WMS_ISSUE_STATUS" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="客户编码" prop="customerCode">
                      <el-input
                        v-model="model.customerCode"
                        placeholder="请输入客户编码"
                        clearable
                        @keyup.enter.native="handleQuery"
                      />
                    </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
          type="primary"
          plain
          icon="el-icon-plus"
          size="small"
          @click="handleAdd"
          v-if="false"
        >新增</el-button>
      </el-col>
      <right-toolbar
        :columns="columnsList"
        :show-search.sync="showSearch"
        @saveSetting="getColumnsList"
        @queryTable="getList"
      />
    </el-row>

    <!-- 列表 -->
    <AutoResizer :given-height="166">
      <template #default="{height}">
        <el-table
          v-if="columnsList.length > 0"
          ref="multipleTable"
          v-loading="loading"
          :data="list"
          :height="height"
          border
          :span-method="arraySpanMethod"
          @selection-change="tableSelected"
          @select="select"
          @select-all="selectAll"
        >
          <!-- <el-table-column
        type="selection"
        width="55"
        fixed="left"
        align="center"
      /> -->
          <el-table-column
            v-if="columnsList[0].visible"
            :key="columnsList[0].key"
            label="通知单号"
            align="center"
            prop="saleOutNo"
            min-width="160"
            fixed="left"
            show-overflow-tooltip
          >
            <!--<template slot-scope="scope">
              <el-button type="text" @click="handleToShipmentDetail(scope.row)">{{ scope.row.saleOutNo }}</el-button>
            </template>-->
          </el-table-column>
          <el-table-column
            v-if="columnsList[1].visible"
            :key="columnsList[1].key"
            label="销售订单"
            align="center"
            prop="erpOrderNo"
            min-width="120"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[2].visible"
            :key="columnsList[2].key"
            label="出库状态"
            align="center"
            prop="outStatus"
            width="120"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <dict-tag :type="DICT_TYPE.WMS_ISSUE_STATUS" :value="scope.row.outStatus" />
            </template>
          </el-table-column>
          <el-table-column
            v-if="columnsList[3].visible"
            :key="columnsList[3].key"
            label="物料编码"
            align="center"
            prop="materialNo"
            min-width="150"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[4].visible"
            :key="columnsList[4].key"
            label="物料名称"
            align="center"
            prop="materialName"
            min-width="140"
            show-overflow-tooltip
          />
          <!-- <el-table-column
            v-if="columnsList[5].visible"
            :key="Math.random()"
            label="物料批次"
            align="center"
            prop="materialLots"
            width="140"
            show-overflow-tooltip
          /> -->
          <el-table-column
            v-if="columnsList[6].visible"
            :key="columnsList[6].key"
            label="客户编码"
            align="center"
            prop="customerCode"
            width="150"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[7].visible"
            :key="columnsList[7].key"
            label="客户名称"
            align="center"
            prop="customerName"
            width="140"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[8].visible"
            :key="columnsList[8].key"
            label="总应出货量"
            align="center"
            prop="shouldDeliveredQty"
            width="100"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[9].visible"
            :key="columnsList[9].key"
            label="本次出货量"
            align="center"
            prop="deliveredQty"
            width="100"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[10].visible"
            :key="columnsList[10].key"
            label="出货时间"
            align="center"
            prop="deliveryTime"
            width="160"
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.deliveryTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            v-if="columnsList[11].visible"
            :key="columnsList[11].key"
            label="创建时间"
            align="center"
            prop="createTime"
            width="160"
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            v-if="columnsList[12].visible"
            :key="columnsList[12].key"
            label="创建人"
            align="center"
            prop="creator"
            width="100"
            show-overflow-tooltip
          />
          <el-table-column
            label="操作"
            align="center"
            width="80"
            show-overflow-tooltip
            fixed="right"
          >
            <template slot-scope="scope">
              <el-button
                v-hasPermi="['wms:sale-out-order:delete']"
                type="text"
                class="text-danger"
                icon="el-icon-delete"
                size="mini"
                @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 { getSaleOutOrderListPage, deleteSaleOut } from '@/api/wms/output/shipmentNotification'
import { getFormColumnsList } from '@/api/system/saveColumns/index'
import { mapGetters } from 'vuex'
import { isArray } from 'min-dash'
// 获取token
// const AccessTokenKey = 'ACCESS_TOKEN'

export default {
  name: 'ShipmentNotification',
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      synchronizationLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // ERP采购订单主列表
      list: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      ids: '',
      currentRows: [],
      tokens: '',
      baseUrl: '',
      reportId: '',
      // 高级查询参数
      advParams: {},
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        erpOrderId: null,
        erpOrderNo: null,
        erpOrderTime: [],
        billAmount: null,
        billType: null,
        taxAmount: null,
        totalAmount: null,
        supplierCode: null,
        documentType: null,
        status: null,
        sourceOrderNo: null,
        sourceOrderType: null,
        exchangeRate: null,
        erpMdtime: [],
        createTime: [],
        erpMark: 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 },
        { 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 }
      ],
      // 显示隐藏持久化参数
      columnsList: []
    }
  },
  // 获取当前登录用户id
  computed: {
    ...mapGetters([
      'userId'
    ])
  },
  created() {
    // 获取显隐列列表
    this.getColumnsList()
    this.getList()
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true
      // 执行查询
      const params = {
        ...this.queryParams,
        ...this.advParams
      }
      getSaleOutOrderListPage(params).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,
        erpOrderId: undefined,
        erpOrderNo: undefined,
        erpOrderTime: undefined,
        billAmount: undefined,
        billType: undefined,
        taxAmount: undefined,
        totalAmount: undefined,
        supplierCode: undefined,
        documentType: undefined,
        status: undefined,
        sourceOrderNo: undefined,
        sourceOrderType: undefined,
        exchangeRate: undefined,
        erpMdtime: undefined,
        erpMark: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.advParams = {}
      this.handleQuery()
    },

    /** 查看明细 */
    handleView(row) {
      const { id } = row
      this.$refs.purchaseDetail.queryParams.inStockId = id
      this.$refs.purchaseDetail.open = true
    },
    // 表格选中
    tableSelected(val) {
      this.currentRows = val
      const list = this.currentRows.map(item => item.deliveryOrderNo)
      this.ids = list.join(',')
    },
    select(selection, row) {
      if (selection.length > 1) {
        const del_row = selection.shift()
        this.$refs.multipleTable.toggleRowSelection(del_row, false)
      }
    },
    selectAll(selection) {
      if (selection.length > 1) {
        selection.length = 1
      }
    },
    // 合并
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      const newData = this.list.map((item, index) => {
        const filterData = this.list.filter(ele => {
          return item.saleOutNo === ele.saleOutNo
        })
        const dataIndex = this.list.findIndex(eleIndex => {
          return item.saleOutNo === eleIndex.saleOutNo
        })
        if (index === dataIndex) {
          item.rowspan = filterData.length
        } else {
          item.rowspan = 0
        }
        return newData
      })
      if (columnIndex === 0 || columnIndex === 1) {
        return {
          rowspan: row.rowspan,
          colspan: 1
        }
      } else {
        return false
      }
    },
    handlePrintSupplier() {
      if (this.currentRows.length <= 0) {
        this.$modal.msgWarning('请选择您要打印的单据!')
        return
      }
      const src = `${this.baseUrl}/jmreport/view/${this.reportId}?token=${this.tokens}&deliveryOrderNo=${this.ids}`
      this.$refs.issuePrinit.dialogVisible = true
      this.$refs.issuePrinit.title = '送货通知单'
      this.$refs.issuePrinit.src = src
    },
    // 送货通知单明细
    handleDiveryDetail(row) {
      const { deliveryOrderNo } = row
      this.$router.push({ path: '/orders/delivery-notice-details', query: { deliveryOrderNo }})
    },
    // 删除出货通知单
    handleDelete(row) {
      const { id, saleOutNo } = row
      const message = `是否确认删除物料编码为【${saleOutNo}】的出货通知单?`
      this.$modal.confirm(message).then(function() {
        return deleteSaleOut(id)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    // 高级查询
    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
        }
      })
    },
    // 查看/编辑出货单明细
    handleToShipmentDetail(row) {
      const { saleOutNo } = row
      this.$router.push({ path: '/entry-exit/sales-in-out/shipment-order-detial', query: { saleOutNo }})
    },
    // 新增出货明细
    handleAdd() {
      this.$router.push({ path: '/entry-exit/sales-in-out/shipment-order-detial' })
    }
  }
}
</script>
