<template>
  <div>
    <div>
      <p-card title="主要信息">
        <p-grid-form
          ref="formTarget"
          :items="gridItems"
          @submit="
            ($event, form) => {
              handleSubmit($event, form, 'formTarget')
            }
          "
        />
        <p-table
          ref="logTable"
          :columns="tableColumnsConfig"
          rowKey="lineId"
          :dataSource.sync="dataSource"
          :rowSelectFixed="true"
          :loading="tabLoding"
          :rowSelectType="false"
          :expandRowByClick="false"
          :hasRowCount="false"
          :scroll="{ x: true }"
          :expandedRowKeys="expandedRowKeys"
          @expand="expandedRowRender"
          :execute="false"
          :autoLoad="false"
        >
          <div slot="action" slot-scope="text">
            <a slot="action" style="margin: 0 5px" @click.stop="specifyLocation(text)">指定库位</a>
          </div>

          <p-table-edit-pro
            ref="detailTable"
            slot="expandedRowRender"
            :columns="detailColumns"
            rowKey="id"
            :dataSource.sync="newLocationData"
            :loading="tabLoding1"
            :scroll="{ x: 300, y: 200 }"
            :expandedRowKeys="goodsColumnsRowKeys"
            @expand="expandedItems"
            :showHeader="true"
            :rowSelectType="false"
            :pagination="false"
            :hasRowCount="false"
            :colorTransformRow="false"
            :hasRowSelectCheck="true"
            dragle
            auto-width
          >
            <!-- <div slot="pieceQuantity">
              <p-input slot="pieceQuantity" style="margin: 0 5px" @change="qtyChange"></p-input>
            </div> -->
            <div slot="operate" slot-scope="text">
              <a slot="operate" style="margin: 0 5px" @click.stop="deleteLocation(text)">删除</a>
            </div>
          </p-table-edit-pro>
        </p-table>
        <div slot="extra">
          <p-button type="primary" @click="extract"> 提取 </p-button>
          <p-button style="margin-left: 10px" type="primary" @click="save"> 生成损溢单 </p-button>
          <p-button style="margin-left: 10px" type="primary" @click="reject"> 损溢驳回 </p-button>
        </div>
      </p-card>
    </div>
    <div>
      <p-modal
        title="提取"
        :visible="visible"
        :enlargeable="false"
        :draggable="true"
        width="65%"
        :maskClosable="false"
        @ok="handleOk"
        @cancel="handleCancel"
      >
        <div>
          <p-table
            :columns="extractColumns"
            rowKey="billid"
            :expandRowByClick="false"
            :rowSelectFixed="true"
            :rowSelectType="1"
            :dataSource.sync="extractData"
            :hasRowSelectCheck="true"
            @selectChange="selectChange"
            dragle
            auto-width
            bordered
          >
          </p-table>
        </div>
      </p-modal>
    </div>
    <!-- 报损 -->
    <breakage-modal
      v-model="breakage"
      :detailData="detailData"
      :paramRowData="rowData"
      :paramData="inventoryData"
      :newLocation="newLocation"
      @change="breakageChange"
    ></breakage-modal>
    <!-- 报溢 -->
    <overflow-modal
      v-model="overflow"
      :detailData="overflowDetailData"
      :paramRowData="overflowRowData"
      :paramData="overflowInventoryData"
      @change="overflowChange"
    ></overflow-modal>
  </div>
</template>
<script>
import { setFormItems, tableColumns, extractColumns, detailColumns } from './js/config'
import { getList, genAdjust, reject } from './api/index'
import { sorter } from '../../utils/sort'
import breakageModal from './modal/breakageModal.vue'
import OverflowModal from './modal/overflowModal.vue'
import { locationModule } from './mixins/location'

export default {
  components: { breakageModal, OverflowModal },
  mixins: [locationModule],
  data() {
    return {
      dataSource: [],
      tabLoding: false,
      gridItems: setFormItems(this),
      rowSelectType: 2,
      tableColumnsConfig: null,
      visible: false,
      extractColumns: extractColumns,
      extractData: [],
      extractRow: null,
      newLocationData: [],
      detailColumns: detailColumns(this),
      tabLoding1: false,
      locationData: [],
      expandedRowKeys: [],
      selectedRowKeys1: [],
      goodsColumnsRowKeys: [],
      newLocation: [],
      tempLocation: [],
      flg: true,
      // columnsRowKeys: [],

      breakage: false,
      rowData: {}, //当前行
      inventoryData: [],
      detailData: [],

      overflow: false,
      overflowRowData: {},
      overflowDetailData: [],
      overflowInventoryData: [],

      locationRows: {}, //指定库位
    }
  },
  created() {
    let column = tableColumns(this)
    this.tableColumnsConfig = sorter(column)
    this.getWarehouse()
  },
  methods: {
    getWarehouse() {
      this.$nextTick(() => {
        var warehouse = this.$store.state.user.warehouse
        this.$refs.formTarget.form.setFieldsValue(warehouse)
      })
    },
    handleOk(e) {
      this.confirmLoading = true
      // 每次提取确认要确保明细表为[]
      this.newLocationData = []
      this.locationData = []
      if (!this.extractRow) {
        this.$message.warning('请选择数据！')
        return
      }
      var billid = this.extractRow[0].billid
      let params = {
        num: 'erp2wmsAdjustD',
        params: {
          billid: billid,
          status:'10',
        },
      }
      getList(params).then((res) => {
        if (!res.success) {
          this.$exception(res)
          return
        }
        this.visible = false
        this.confirmLoading = false
        //默认将实际数量为0
        res.data.forEach((t) => {
          t.pieceQuantity = 0
        })
        this.dataSource = res.data
        // 表单赋值
        this.$refs.formTarget.form.setFieldsValue({
          cargoOwnerId: res.data[0].cargoOwnerId,
          cargoOwnerCode: res.data[0].cargoOwnerCode,
          cargoOwnerName: res.data[0].cargoOwnerName,
          billdate: res.data[0].billdate,
          autoBillNum: res.data[0].autoBillNum,
        })
      })
    },
    //弹框关闭
    handleCancel(e) {
      this.visible = false
    },

    //查询事件
    handleSubmit(event, form) {
      event.preventDefault()
    },

    selectChange(selectedRowKeys, selectedRows) {
      this.extractRow = selectedRows
    },
    // 提取
    extract() {
      let warehouseId = this.$refs.formTarget.form.getFieldsValue().warehouseId
      if (!warehouseId) {
        this.$message.warning('请先选择仓库')
        return
      }
      let params = {
        num: 'erp2wmsAdjust',
        params: {
          warehouseId: warehouseId,
          status: '10',
          dataSource: '2',
        },
      }
      getList(params).then((res) => {
        if (!res.success) {
          this.$exception(res)
          return
        }
        // res.data.list.outGoodsCaseCode = ''
        this.extractData = res.data
        this.visible = true
      })
    },
    // 生成损溢单
    save() {
      // 先盘点明细有无数据
      if (this.newLocationData.length < 1 || this.locationData.length < 1) {
        this.$message.warning('暂无损溢单数据，请检查')
        return
      }
      let a = this.checkNumber(this.dataSource)
      if (!a) return
      var params = []
      //明细打开赋值到newLocationData ，否则locationData存值
      // if (this.newLocationData.length < 1) {
      //   params = this.locationData
      // } else {
      //   params = this.newLocationData
      // }
      params = this.locationData
      this.$confirm({
        content: this.$lang('是否确定保存?'),
        onOk: () => {
          return this.handleAdd(params)
        },
      })
    },
    //驳回
    reject() {
      var params = []
      if (this.newLocationData.length < 1) {
        params = this.locationData
      } else {
        params = this.newLocationData
      }
      if (params.length < 1) {
        this.$message.warning('暂无损溢单数据，请检查')
        return
      }

      this.$confirm({
        content: this.$lang('是否确定驳回?'),
        onOk: () => {
          return reject(params).then((res) => {
            if (!res.success) {
              this.$exception(res)
              return
            }
            this.$message.success('驳回成功！')
            this.reset()
          })
        },
      })
    },
    handleAdd(params) {
      return genAdjust(params).then((res) => {
        if (!res.success) {
          this.$exception(res)
          return
        }
        this.$message.success('保存成功！')
        this.$refs.logTable.reload()
        this.reset()
      })
    },
    // 清空
    reset() {
      this.$nextTick(() => {
        this.$refs.formTarget.form.resetFields()
        this.dataSource = []
        this.newLocationData = []
        this.locationData = []
        this.getWarehouse()
        this.locationRows = {}
      })
    },

    expandedItems(expanded, record) {},

    expandedRowRender(expanded, record) {
      if (expanded) {
        this.expandedRowKeys = [record.lineId]
        var rowkey = this.expandedRowKeys[0]
        //筛选id
        this.newLocationData = this.locationData.filter((item) => {
          return item.lineId === rowkey
        })
        //总数量计算
        var sum = 0
        var lineId = ''
        this.newLocationData.forEach((t) => {
          lineId = t.lineId
          sum += t.pieceQuantity
        })
        //总数量赋值到主表实际数量
        this.dataSource.find((t) => {
          if (lineId === t.lineId) {
            t.pieceQuantity = sum
          }
        })
      } else {
        this.expandedRowKeys = this.expandedRowKeys.filter((item) => {
          return item != record.lineId
        })
      }
    },
    //指定库位
    specifyLocation(text) {
      this.locationRows = text
      // this.locationData = this.detailData
      this.selectLocation(text)
    },
    //删除库位
    deleteLocation(text) {
      var num = 0
      var lineId = text.lineId
      this.$confirm({
        content: this.$lang('是否确定删除?'),
        onOk: () => {
          //根据id删除数组对象
          //明细表
          this.newLocationData = this.newLocationData.filter((item) => {
            return item.id != text.id
          })
          //暂存库位表
          this.locationData = this.locationData.filter((item) => {
            return item.id != text.id
          })
          //将累加总数给到主表总数量
          this.newLocationData.forEach((t) => {
            num += t.pieceQuantity
          })
          this.dataSource.find((t) => {
            if (lineId === t.lineId) {
              t.pieceQuantity = num
            }
          })
        },
      })
    },
    //实际数量
    qtyChange(record, value) {
      this.checkQty(record, value)
      // if (value > record.pieceQty) {
      //   this.$message.warning('当前实际数量大于库位库存数量，请检查')
      // }
      this.$nextTick(() => {
        var number = 0
        // 遍历数组，累加数量获取总数量
        this.newLocationData.forEach((tt) => {
          number += tt.pieceQuantity
        })
        var lineId = record.lineId
        //将累加总数给到主表总数量
        this.dataSource.find((t) => {
          if (lineId === t.lineId) {
            t.pieceQuantity = number
          }
        })
      })
    },
    breakageChange(val) {
      let flg = true
      let record = this.locationRows
      this.expandedRowRender(flg, record)
    },
    overflowChange(val) {
      let flg = true
      let record = this.locationRows
      this.expandedRowRender(flg, record)
    },
  },
}
</script>
<style lang="less" scoped>
/deep/.ant-card-body {
  padding: 12px 18px 18px 18px;
}
</style>