<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-row>
        <el-form
          v-if="!btnDisableState"
          ref="form"
          :model="form"
          :rules="rules"
          size="mini"
          align="left"
        >
          <el-col :span="6">
            <el-form-item label="单号" prop="allotOrderNo" label-width="80px">
              <el-input
                v-model="form.allotOrderNo"
                placeholder="保存时自动生成"
                disabled
                size="mini"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="调拨方式" prop="allotMode" label-width="120px">
              <DictSelect v-model="form.allotMode" placeholder="请选择调拨方式" dict-type="WMS_ALLOT_MODE" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发料人" prop="creator" label-width="80px">
              <el-input v-model="form.creator" disabled size="mini" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发料时间" prop="createTime" label-width="120px">
              <el-input :value="form.createTime?new Date(form.createTime).toLocaleString():'-'" disabled size="mini" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="签收人" prop="signEmployee" label-width="80px">
              <el-input v-model="form.signEmployee" disabled size="mini" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="签收时间" prop="signTime" label-width="120px">
              <el-input :value="form.signTime?new Date(form.signTime).toLocaleString():'-'" disabled size="mini" />
            </el-form-item>
          </el-col>
        </el-form>
        <el-descriptions
          v-else
          :column="3"
          style="width: 100%;"
          border
        >
          <el-descriptions-item label="单号">
            {{ form.allotOrderNo }}
          </el-descriptions-item>
          <el-descriptions-item label="调拨方式">{{ form.allotMode }}</el-descriptions-item>
          <el-descriptions-item label="发料人">{{ form.creator? form.creator: '-' }}</el-descriptions-item>
          <el-descriptions-item label="发料时间">
            {{ form.createTime?new Date(form.createTime).toLocaleString():'-' }}
          </el-descriptions-item>
          <el-descriptions-item label="签收人">{{ form.signEmployee? form.signEmployee: '-' }}</el-descriptions-item>
          <el-descriptions-item label="签收时间">
            {{ form.signTime?new Date(form.signTime).toLocaleString():'-' }}
          </el-descriptions-item>
        </el-descriptions>
      </el-row>
    </el-card>
    <!--  :body-style="{ height: '900px' }" -->
    <el-card class="box-form">
      <el-row>
        <el-form
          ref="form2"
          :model="form"
          size="mini"
          align="left"
          @submit.native.prevent
        >
          <el-col :span="6">
            <el-form-item label="标签码" prop="qrCode" label-width="80px">
              <el-input
                v-model="form.qrCode"
                :disabled="btnDisableState"
                clearable
                size="mini"
                @keyup.enter.native="handleScanQrCode"
              />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <div style="display: inline-block;" />
          </el-col>
          <el-col :span="1">
            <el-button
              v-if="!btnDisableState"
              size="mini"
              type="success"
              @click="handleSaveData"
            >保存</el-button>
          </el-col>
          <el-col :span="1">
            <el-button
              v-if="btnDisableState"
              size="mini"
              type="primary"
              @click="handleSign"
            >签收</el-button>
          </el-col>
          <el-col :span="1">
            <el-button
              size="mini"
              @click="handleBackRoute"
            >返回</el-button>
          </el-col>
        </el-form>
      </el-row>
      <div class="tooltip-title">
        <span>⁖ </span>
        <span>物料列表</span>
      </div>
      <vxe-table
        ref="xTable"
        border
        show-overflow
        auto-resize
        keep-source
        highlight-current-row
        :height="tableHeight"
        :row-config="{height: '30'}"
        :column-config="{ resizable: true }"
        :data="form.detail"
        :edit-config="{
          trigger: 'click',
          mode: 'row',
          icon: 'vxe-icon-edit',
          showStatus: false,
        }"
      >
        <!-- :edit-rules="validRules" -->
        <vxe-column type="checkbox" width="50" />
        <vxe-column
          type="seq"
          title="序号"
          align="center"
          width="60"
        />
        <vxe-column
          field="materialNo"
          title="物料编码"
          align="center"
          min-width="120"
        >
          <template #default="{ row }">
            <span>{{ row.materialNo }}</span>
          </template>
        </vxe-column>
        <vxe-column
          field="batchNumber"
          title="物料条码"
          align="center"
          min-width="180"
        >
          <template #default="{ row }">
            <span>{{ row.batchNumber }}</span>
          </template>
        </vxe-column>
        <vxe-column
          field="qty"
          title="数量"
          align="center"
          min-width="110"
        >
          <template #default="{ row }">
            <span>{{ row.qty }}</span>
          </template>
        </vxe-column>
        <vxe-column
          field="wmsStockName"
          title="来源仓库"
          align="center"
          min-width="110"
        >
          <template #default="{ row }">
            <span>{{ row.wmsStockName }}</span>
          </template>
        </vxe-column>
        <vxe-column
          field="newWmsStockName"
          title="目标仓库"
          align="center"
          min-width="110"
        >
          <template #default="{ row }">
            <span>{{ row.newWmsStockName }}</span>
          </template>
        </vxe-column>
      </vxe-table>
    </el-card>
    <SignScan ref="signScan" @complete="handleGetStockAllotMasterDetail" />
  </div>
</template>
<script>
import { stockAllotInfoByQrCode, saveStockAllotMaster, getStockAllotMasterDetail } from '@/api/wms/output/backFlushMaterial'
export default {
  components: {
    SignScan: () => import('../components/SignScan.vue')
  },
  data() {
    return {
      // 行数
      rowNum: 1,
      // 行数据
      rowData: null,
      loading: false,
      tableHeight: 300,
      tableData: [],
      materialList: [],
      // 复制行dialog
      dialogCopyVisible: false,
      auditEvent: null,
      btnDisableState: false,
      form: {
        qrCode: '',
        code: '',
        description: '',
        allotOrderNo: '',
        allotMode: '',
        size: '',
        auditTime: '',
        auditComment: '',
        routingMasterId: '',
        processRouteVersion: '',
        detail: []
      },
      // 表单校验
      rules: {
        allotMode: [{ required: true, message: '调拨方式不能为空', trigger: 'blur' }]
      }
    }
  },
  async created() {
    this.btnDisableState = !!this.$route.query.view
    this.handleGetStockAllotMasterDetail()
  },
  mounted() {
    window.addEventListener('resize', () => {
      this.trendsHeight()
    })
    this.trendsHeight()
  },
  methods: {
    // 备料签收
    handleSign() {
      this.$refs.signScan.signId = this.form?.id
      this.$refs.signScan.codeOpen = true
    },
    handleScanQrCode() {
      stockAllotInfoByQrCode({ qrCode: this.form.qrCode })
        .then(({ code, data, msg }) => {
          if (code === 0) {
            console.log(data)
            data?.forEach(ret => {
              this.form.detail.push({ ...ret, qty: ret?.receiptQty })
            })
          }
        })
    },
    // 设置动态高度
    trendsHeight: function() {
      this.tableHeight = window.innerHeight - this.$refs.xTable.$el.offsetTop - 95
    },
    // 获取表单数据及列表数据
    handleGetStockAllotMasterDetail() {
      if (this.$route.query?.allotOrderNo) {
        getStockAllotMasterDetail(this.$route.query?.allotOrderNo)
          .then(({ code, data, msg }) => {
            if (code === 0) {
              const formData = JSON.parse(JSON.stringify(data)) ?? {}
              Object.assign(this.form, formData)
            }
          })
      }
    },
    handleSaveData() {
      const $table = this.$refs.xTable
      const { tableData } = $table.getTableData()
      const submitParams = {
        allotMode: this.form.allotMode,
        allotOrderNo: this.form.allotOrderNo,
        detail: []
      }
      tableData.forEach(ret => {
        submitParams.detail.push({
          materialNo: ret.materialNo,
          batchNumber: ret.batchNumber,
          qty: ret.qty,
          wmsStockId: ret.wmsStockId,
          newWmsStockId: ret.newWmsStockId
        })
        ret?.id ? submitParams.detail.push(ret.id) : ''
      })
      this.form?.id ? submitParams.id = this.form.id : ''

      // 表单校验
      this.$refs['form'].validate(async(valid) => {
        if (valid) {
          // 校验成功
          saveStockAllotMaster(submitParams)
            .then(({ code, data, msg }) => {
              if (code === 0) {
                this.form.id = data
                this.$message.success('保存成功！')
                this.$router.push({ path: '/entry-exit/product-out-in/backFlushMaterial/Info?opert=edit&id=' + data })
                // this.handleGetStockAllotMasterDetail()
              }
            })
            .catch((err) => {
              console.log(err)
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    async handleRemoveRow() {
      const $table = this.$refs.xTable
      const selectCurrentRow = $table.getCheckboxRecords()
      if (selectCurrentRow.length) {
        for (let x = 0; x < selectCurrentRow.length; x++) {
          // 用户录入的删除
          // $table.removeCheckboxRow(selectCurrentRow[x])
        }
      } else {
        this.$message.warning('请选择要删除的行')
      }
    },
    handleBackRoute() {
      this.$router.push('/entry-exit/product-out-in/backFlushMaterial/list')
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-form-item--small.el-form-item {
  margin-bottom: 4px !important;
}

.box-card {
  flex: 1;
  background-color: rgb(255, 255, 255);
  .header-operation {
    display: flex;
    justify-content: space-between;
    & > div:nth-of-type(2) {
      width: 200px;
      min-width: 160px;
    }
  }
}
.box-form {
  margin: 1px 0 0 0;
}
.tooltip-title {
  font-size: 14px;
  font-weight: bold;
  line-height: 32px;
  span:nth-of-type(1) {
    color: red;
  }
}
.flex-center {
  display: flex;
  align-items: center;
}
.app-container {
  margin: 4px;
  padding: 0;
  overflow-y: hidden;
  height: calc(100vh - 95px);
}

::v-deep .el-form-item {
  margin-bottom: 8px !important;
}
::v-deep .el-tabs__item {
  height: 30px !important;
  line-height: 30px !important;
  padding: 0 15px !important;
}
::v-deep .el-tabs--border-card > .el-tabs__content {
  padding: 2px !important;
}
::v-deep .pagination-container {
  margin: 0;
  padding: 0;
}
::v-deep .el-card__body {
  padding: 4px;
}
</style>
