<template>
  <div>
    <bill-editor ref="detail" :list="detailtList" :defData="detailData" @ok="onOk"> </bill-editor>

    <split-bill
      v-model="splitVisible"
      :formItems="splitFormItems"
      :columns="splitColumns"
      :data="splitOriginItem"
      :splitedCallback="splitedCallback"
      :confirmLoading="confirmLoading"
      :error="splitError"
      @ok="handleSpliteOk"
    />
  </div>
</template>

<script>
import BillEditor from '../../../components/bill-editor'
import SplitBill from '../../components/splitBill'
import { detailConfig } from './config/detail'
import { splitFormItems } from './config/split/formitems'
import { splitColumns } from './config/split/columns'
import { addItems, querySubList, querySubList2, querySubList3, querySubList4, querySubList5, querySubList6, taskSplit, doException, getLocationType } from './api'
import { getCargoOwner } from '../../../utils'

export default {
  components: {
    'bill-editor': BillEditor,
    'split-bill': SplitBill,
  },

  data() {
    return {
      detailtList: null,
      detailData: null,
      visible: false,
      splitVisible: false,
      splitColumns: splitColumns,
      splitFormItems: splitFormItems,
      splitOriginItem: null,
      splitError: '',
      confirmLoading: false,
      selectedMainItem: null,
      L_type: null,
    }
  },

  created() {
    this.handleView()
  },
  mounted() {
    this.getL_Type()
  },
  methods: {
    // 货位限定regCode=INBOUND_IN_STOCK_LOCATOR_TYPE&warehouseId=
    getL_Type() {
      let _this = this
      // this.$nextTick(() => {
      //   let ref = this.queryRefFromName('main')
      // })
      let warehouse = this.$store.state.user.warehouse
      let params = { regCode: 'INBOUND_IN_STOCK_LOCATOR_TYPE', warehouseId: warehouse.warehouseId }
      return getLocationType(params).then((res) => {
        if (!res.success) {
          this.$exception(res)
          return
        }
        _this.L_type = res.data.regValue
        _this.handleView()
      })
    },

    queryRefFromName(name) {
      return this.$refs.detail.$refs[name][0]
    },

    onOk() {
      this.$nextTick(() => {
        let warehouse = this.$store.state.user.warehouse
        let ref = this.queryRefFromName('main')
        ref.$refs.form.form.setFieldsValue({
          warehouseId: warehouse.warehouseId,
          warehouseCode: warehouse.warehouseCode,
          warehouseName: warehouse.warehouseName,
        })
        this.getCargoOwnerFirst()
      })
    },

    handleView() {
      this.detailtList = detailConfig(this)
    },

    toShelf() {
      let ref = this.queryRefFromName('list')
      if (ref.selectedRowKeys.length === 0) {
        this.$message.warning(this.$lang('请先勾选需要上架的商品明细'))
        return
      }
      // let vals = ref.data.filter(tt => ref.selectedRowKeys.some(key => key == tt.taskId));
      let vals = ref.data.filter((tt) => ref.selectedRowKeys.some((key) => key == tt.taskId))
      //
      if (!vals.every((t) => !!t.warehouseLocatorName)) {
        this.$message.warning(this.$lang('勾选的上架商品明细需要填写实际货位'))
        return
      }
      let params = vals.map((t, i) => ({
        ...t,
        lineNum: i + 1,
        warehouseLocatorId: t.whLocator,
        rcvType: this.selectedMainItem.rcvType,
      }))
      this.$confirm({
        content: this.$lang('是否确定上架?'),
        onOk: () => {
          return this.handleAdd(params).then((res) => {
            this.queryRefFromName('main').reload()
            this.handleQuerySubList({ rcvHeaderId: ref.selectedRowKeys[0] }).then((res) => {
              ref.data = res
            })
          })
        },
      })
    },

    handleQuerySubList(params, name, postFun) {
      if (!postFun) {
        postFun = querySubList
      }
      this.$refs.detail.$refs[name][0].loading = true
      this.$refs.detail.$refs[name][0].selectedRowKeys = []
      return postFun(params).then((res) => {
        this.$refs.detail.$refs[name][0].loading = false
        if (!res.success) {
          this.$exception(res)
          return
        }
        if (!res.data.list) return []
        return res.data.list.map((item) => {
          return {
            ...item,
            taskId: item.taskInboundId,
            oddCaseQty: item.caseQty,
            oddPieceQty: item.oddPieceQty,
            pieceQty: item.pieceQty,
          }
        })
      })
    },

    showSplitBill(item) {
      this.splitOriginItem = item
      this.splitVisible = true
    },

    splitedCallback(item) {
      item.pieceQty = item.conversionRate * item.oddCaseQty + item.oddPieceQty
      item.qty = (item.pieceQty / item.conversionRate).toFixed(2)
    },

    handleSpliteOk(list) {
      let errList = []
      list.forEach((tt, i) => {
        if (tt.whAreaCategoryCode == 'ZJK' && +tt.oddPieceQty > 0) {
          // 整件库： 零散数必须为0.
          errList.push('第' + (i + 1) + '行: 库别类型为整件库时零散数必须为0')
        }
        if (tt.whAreaCategoryCode == 'LHK' && (+tt.oddCaseQty > 0 || +tt.oddPieceQty >= +tt.conversionRate)) {
          // 零货库：件数必须为0，且零散数不能大于包装含量
          errList.push('第' + (i + 1) + '行: 库别类型为零货库时件数必须为0，且零散数不能大于包装含量')
        }
      })
      if (errList.length > 0) {
        this.splitError = errList.join('<br/>')
        return
      }
      let nList = list.map((t, i) => ({
        ...this.splitOriginItem,
        ...t,
        taskInboundId: i == 0 ? this.splitOriginItem.taskInboundId : null,
      }))
      this.handleSplitBill(nList)
    },

    toErrorBill() {
      let ref = this.queryRefFromName('list')
      if (ref.selectedRowKeys.length === 0) {
        this.$message.warning(this.$lang('请先勾选'))
        return
      }
      this.$confirm({
        content: this.$lang('是否确定提交?'),
        onOk: () => {
          let params = ref.data.filter((t) => ref.selectedRowKeys.some((k) => k == t[ref.rowKey]))
          return this.handleErrorBill(params).then((res) => {
            if (!res) return
            ref.data = ref.data.filter((t) => !ref.selectedRowKeys.some((k) => k == t[ref.rowKey]))
            ref.selectedRowKeys = []
          })
        },
      })
    },

    handleAdd(params) {
      return addItems(params).then((res) => {
        if (!res.success) {
          this.$exception(res)
          return
        }
        this.$message.success(this.$lang('新增成功'))
        this.handleReset()
      })
    },

    handleReset() {
      this.detailData = null
    },

    handleSplitBill(params) {
      this.confirmLoading = true
      return taskSplit(params).then((res) => {
        if (!res.success) {
          this.$exception(res)
          return
        }
        this.$message.success(this.$lang('拆单成功'))
        this.splitVisible = false
        this.confirmLoading = false
        let ref1 = this.queryRefFromName('main')
        let ref2 = this.queryRefFromName('list')
        this.handleQuerySubList({ rcvHeaderId: ref1.selectedRowKeys[0] }).then((res) => {
          ref2.data = res
        })
      })
    },

    handleErrorBill(params) {
      return doException(params).then((res) => {
        if (!res.success) {
          this.$exception(res)
          return false
        }
        this.$message.success(this.$lang('操作成功'))
        return true
      })
    },
    //获取货主信息
    getCargoOwnerFirst() {
      getCargoOwner().then((res) => {
        if (!res.success) {
          this.$exception(res)
          return
        }
        this.$nextTick(() => {
          if (res.data.list.length > 0) {
          let ref = this.queryRefFromName('main')
          ref.$refs.form.form.setFieldsValue({
            cargoOwnerId: res.data.list[0].companyId,
            cargoOwnerCode: res.data.list[0].companyCode,
            cargoOwnerName: res.data.list[0].companyName,
          })
          }
        })
        // }
      })
    },
  },
}
</script>

<style></style>
