<template>
  <div>
    <detail-page
      :tableColumns="columns"
      :title="title"
      :tableRemoteUrl="tableRemoteUrl"
      :tableRowKey="tableRowKey"
      :btnOptions="btnOptions"
      :queryStatus="false"
      :tableAutoLoad="false"
      :items="items"
      :ajaxId="ajaxId"
      @savePlan="savePlan"
      @savePlanAll="savePlanAll"
      @downtep="downtep"
      @importExcel="importExcel"
      @selectChange="selectChange"
      ref="detial"
    >
    </detail-page>
  </div>
</template>

<script>
import { getBusiness } from '@/views/kzyWMS/api/business' // 系统参数接口
import DetailPage from '../components/searchTable'
import { toPrintServer, tempType } from '@/views/kzyWMS/utils/printServer.js'
// import { detailConfig } from './config/planCheck'
// import { invcheckAdd } from '../api/api'
import { downLoadFromJar } from '../api/api.js'
import API from '../api/default'
import { remote } from '../api/remote'
import {
  genWarehouseAuthSearchModal,
  genBldgSearchModal,
  genWarehouseRoomSearchModal,
  genCargoownerAuthSearchModal
} from '../../SearchModal'
// inv_stockcheck_h_checkgroup2
import { SERVICE_DATA_API_BASE } from '@/config/serviceSettings'
import { getCargoOwner } from '../../utils/index'
let warehouseId = ''
let bldgId = ''
let warehouseRoomId = ''
let warehouseAreaId = ''
let warehouseLocatorId = ''
const items = function(that) {
  return [
    ...genWarehouseAuthSearchModal(
      1,
      true,
      false,
      null,
      function(modalRowData, form) {
        if (modalRowData) {
          warehouseId = modalRowData[0].warehouseId ? modalRowData[0].warehouseId : modalRowData[0].companyId
        } else {
          form.setFieldsValue({
            bldgId: '',
            bldgName: '',
            warehouseRoomId: '',
            warehouseRoomName: '',
            warehouseAreaId: '',
            warehouseAreaName: '',
            warehouseLocatorId: '',
            warehouseLocatorName: ''
          })
          warehouseId = ''
          bldgId = ''
          warehouseRoomId = ''
          warehouseAreaId = ''
          warehouseLocatorId = ''
        }
      },
      { span: 8 }
    ),
    ...genBldgSearchModal(
      1,
      false,
      false,
      function(res, remoteParams) {
        remoteParams.params.warehouseId = warehouseId // 添加仓库id查询
        return remoteParams
      },
      function(modalRowData, form) {
        if (modalRowData) {
          bldgId = modalRowData[0].bldgId
        } else {
          bldgId = ''
          warehouseRoomId = ''
          warehouseAreaId = ''
          warehouseLocatorId = ''
          form.setFieldsValue({
            warehouseRoomId: '',
            warehouseRoomName: '',
            warehouseAreaId: '',
            warehouseAreaName: '',
            warehouseLocatorId: '',
            warehouseLocatorName: ''
          })
        }
      },
      { span: 8 }
    ),
    ...genWarehouseRoomSearchModal(
      1,
      false,
      false,
      function(res, remoteParams) {
        remoteParams.params.warehouseId = warehouseId // 添加仓库id查询
        remoteParams.params.bldgId = bldgId // 添加建筑物id查询
        return remoteParams
      },
      function(modalRowData, form) {
        if (modalRowData) {
          warehouseRoomId = modalRowData[0].warehouseRoomId
        } else {
          warehouseRoomId = ''
          form.setFieldsValue({
            warehouseAreaId: '',
            warehouseAreaName: '',
            warehouseLocatorId: '',
            warehouseLocatorName: ''
          })
          warehouseAreaId = ''
          warehouseLocatorId = ''
        }
      },
      { span: 8 }
    ),
    {
      type: 'select',
      name: 'warehouseAreaCategory',
      label: '库别',
      value: '',
      span: 8,
      ...remote('wms_storeroom')
      // options: [
      //   { label: '零货库', value: '零货库' },
      //   { label: '整件库', value: '整件库' },
      //   { label: '退货库', value: '退货库' },
      //   { label: '不合格库', value: '不合格库' }
      // ]
    },
    ...genCargoownerAuthSearchModal(1, true, false, null, null, { span: 8 }),
    // {
    //   type: 'select',
    //   name: 'checkWay',
    //   label: '盘点方式',
    //   allowClear: false,
    //   span: 8,
    //   required: true,
    //   defaultValueIndex: 0,
    //   value: '',
    //   ...remote('inv_stockcheck_h_checkgroup2'),
    //   on: {
    //     change(value, label, options, form) {
    //       console.log(form.getFieldsValue())
    //       console.log(value)
    //     }
    //   }
    // },
    { type: 'input', name: 'warehouseAreaId', label: '库区ID', hidden: true },
    {
      type: 'search',
      name: 'warehouseAreaName',
      label: '库区',
      targetValueKey: 'warehouseAreaName',
      destroyOnClose: true,
      targetClick: true,
      span: 8,
      value: '',
      toolBar: {
        items: [
          {
            type: 'input',
            name: 'warehouseAreaName',
            label: '库区名称',
            span: 8,
            value: ''
          },
          {
            type: 'input',
            name: 'warehouseAreaCode',
            label: '库区编码',
            span: 8,
            value: ''
          }
        ]
      },
      tableConfig: {
        rowKey: 'warehouseAreaId',
        rowSelectType: 1,
        hasRowSelectCheck: true,
        columns: [
          { dataIndex: 'warehouseAreaName', title: '库区名称', key: 'warehouseAreaName' },
          { dataIndex: 'warehouseAreaCode', title: '库区编码', key: 'warehouseAreaCode' },
          { dataIndex: 'warehouseAreaId', title: '库区ID', key: 'warehouseAreaId' }
        ],
        remoteBefore(res, remoteParams) {
          console.log(arguments, '66666666')
          remoteParams.params.warehouseId = warehouseId // 添加仓库id查询
          remoteParams.params.bldgId = bldgId // 添加建筑物查询
          remoteParams.params.warehouseRoomId = warehouseRoomId // 添加库房查询
        }
      },
      value: '',
      remoteUrl: API.wmsWhArea,
      on: {
        ok(event, value, rowData, form) {
          form.setFieldsValue({
            warehouseAreaId: rowData[0].warehouseAreaId
          })
          warehouseAreaId = rowData[0].warehouseAreaId
        },
        change(event, value, options, form) {
          if (!value) {
            form.setFieldsValue({ warehouseAreaId: '' })
            warehouseAreaId = ''
          }
          form.setFieldsValue({
            warehouseLocatorId: '',
            warehouseLocatorName: ''
          })
          warehouseLocatorId = ''
        }
      }
    },
    { type: 'input', name: 'warehouseLocatorId', label: '货位ID', hidden: true },
    {
      type: 'search',
      name: 'warehouseLocatorName',
      label: '货位',
      targetValueKey: 'warehouseLocatorName',
      destroyOnClose: true,
      targetClick: true,
      span: 8,
      value: '',
      toolBar: {
        items: [
          {
            type: 'input',
            name: 'warehouseLocatorName',
            label: '货位名称',
            span: 8,
            value: ''
          },
          {
            type: 'input',
            name: 'warehouseLocatorCode',
            label: '货位编码',
            span: 8,
            value: ''
          }
        ]
      },
      tableConfig: {
        rowKey: 'warehouseLocatorId',
        rowSelectType: 1,
        hasRowSelectCheck: true,
        columns: [
          { dataIndex: 'warehouseLocatorName', title: '货位名称', key: 'warehouseLocatorName' },
          { dataIndex: 'warehouseLocatorCode', title: '货位编码', key: 'warehouseLocatorCode' },
          { dataIndex: 'warehouseLocatorId', title: '货位ID', key: 'warehouseLocatorId' }
        ],
        remoteBefore(res, remoteParams) {
          console.log(arguments, '66666666')
          if (remoteParams.params) {
            remoteParams.params.warehouseId = warehouseId // 添加仓库id查询
            remoteParams.params.bldgId = bldgId // 添加建筑物查询
            remoteParams.params.warehouseRoomId = warehouseRoomId // 添加库房查询
            remoteParams.params.warehouseAreaId = warehouseAreaId // 添加库区查询
          } else {
            remoteParams.params = {
              warehouseId: warehouseId,
              bldgId: bldgId,
              warehouseRoomId: warehouseRoomId,
              warehouseAreaId: warehouseAreaId
            }
          }
        }
      },
      value: '',
      remoteUrl: API.locatorWHPage,
      on: {
        ok(event, value, rowData, form) {
          form.setFieldsValue({
            warehouseLocatorId: rowData[0].warehouseLocatorId
          })
        },
        change(event, value, options, form) {
          if (!value) {
            form.setFieldsValue({ warehouseLocatorId: '' })
          }
        }
      }
    },
    {
      type: 'select',
      name: 'checkType',
      label: '盘点类型',
      allowClear: false,
      span: 8,
      required: true,
      defaultValueIndex: 3,
      value: '1',
      // ...remote('inv_stockcheck_type'),
      options: [
        {
          value: '1',
          label: '货位'
        }
      ]
    },

    // {
    //   type: 'row',
    //   label: '日期',
    //   span: 8,
    //   list: [
    //     {
    //       type: 'date',
    //       name: 'startDate',
    //       placeholder: '请输入开始日期',
    //       disabled: true,
    //       value: '',
    //       format: 'YYYY-MM-DD'
    //     },
    //     {
    //       type: 'date',
    //       name: 'endDate',
    //       disabled: true,
    //       placeholder: '请输入结束日期',
    //       format: 'YYYY-MM-DD',
    //       value: ''
    //     }
    //   ]
    // },

    // {
    //   type: 'select',
    //   name: 'platStatus1',
    //   label: '区域编号',
    //   value: '01',
    //   options: [
    //     { label: '01', value: '01' },
    //     { label: '02', value: '02' },
    //     { label: '03', value: '03' },
    //     { label: '04', value: '04' }
    //   ]
    // },
    // {
    //   type: 'row',
    //   label: '货位区间',
    //   list: [
    //     {
    //       type: 'input',
    //       name: 'start',
    //       placeholder: '请输入货位',
    //       value: '',
    //       style: 'padding-right:5px;'
    //     },
    //     {
    //       type: 'input',
    //       name: 'end',
    //       placeholder: '请输入货位',
    //       value: ''
    //     }
    //   ]
    // },
    {
      type: 'input',
      span: 8,
      name: 'itemCode',
      label: '商品编号'
    },
    {
      span: 8,
      type: 'buttonGroup',
      options: [
        {
          value: '查询',
          icon: 'search',
          btnType: 'primary',
          style: 'margin-left:30px;margin-right:10px;',
          htmlType: 'submit',
          on: {
            click: (event, form) => {
              form.validateFields((error, values) => {
                if (!error) {
                  that.$refs.detial.reload(values)
                }
              })
            }
          }
        },
        {
          value: '重置',
          name: 'ccz',
          icon: 'redo',
          on: {
            click(event, form) {
              form.resetFields()
            }
          }
        }
      ]
    }
  ]
}
const columns = function(self) {
  return [
    { dataIndex: 'warehouseName', title: '仓库名称', key: 'warehouseName' },
    { dataIndex: 'cargoOwnerName', title: '货主名称', key: 'cargoOwnerName', width: 150 },
    { dataIndex: 'warehouseAreaName', title: '库区', key: 'warehouseAreaName' },
    { dataIndex: 'warehouseLocatorName', title: '货位名称', key: 'warehouseLocatorName' },
    // { dataIndex: 'warehouseLocatorCode', title: '货位编码', key: 'warehouseLocatorCode' },
    // { dataIndex: 'code1', title: '区域编号', key: 'code1' },
    { dataIndex: 'oddCaseQuantity', title: '库存整件数', key: 'oddCaseQuantity' },
    { dataIndex: 'oddPieceQuantity', title: '库存零散数', key: 'oddPieceQuantity' },
    { dataIndex: 'quantity', title: '库存总数量', key: 'quantity' },
    { dataIndex: 'rcvQuantity', title: '入库已分配', key: 'rcvQuantity' },
    { dataIndex: 'outQuantity', title: '出库已分配', key: 'outQuantity' },
    { dataIndex: 'manufacturerLotNum', title: '批号', key: 'manufacturerLotNum' },
    { dataIndex: 'batchNum', title: '批次号', key: 'batchNum' },
    { dataIndex: 'itemCode', title: '商品编号', key: 'itemCode' },
    { dataIndex: 'itemName', title: '商品名称', key: 'itemName' },
    { dataIndex: 'specification', title: '商品规格', key: 'specification' },
    { dataIndex: 'uom', title: '包装单位', key: 'uom' },
    { dataIndex: 'caseConversionRate', title: '包装数量', key: 'caseConversionRate' },
    { dataIndex: 'manufacturerName', title: '生产厂家', key: 'manufacturerName' },
    { dataIndex: 'batchProductionDate', title: '生产日期', key: 'batchProductionDate' },
    { dataIndex: 'batchExpiredDate', title: '有效期', key: 'batchExpiredDate' },
    { dataIndex: 'bldgName', title: '建筑物', key: 'bldgName' },
    { dataIndex: 'warehouseRoomName', title: '库房', key: 'warehouseRoomName' },
    { dataIndex: 'warehouseAreaCategory', title: '库别', key: 'warehouseAreaCategory' }
  ]
}

export default {
  components: { DetailPage },
  data() {
    return {
      businessData: null,
      items: items(this),
      columns: columns(this),
      title: '库存批次打印',
      tableRowKey: 'id',
      selectedRowKeys: [],
      selectedRows: [],
      ajaxId: 'item-instock-list',
      tableRemoteUrl: {
        url: SERVICE_DATA_API_BASE + '/search/page',
        method: 'post',
        headers: {
          'Content-Type': 'application/JSON'
        }
      },
      btnOptions: [
        {
          name: '打印',
          icon: '',
          action: 'savePlan'
        }
        // {
        //   name: '下载模板',
        //   icon: '',
        //   action: 'downtep'
        // },
        // {
        //   name: '导入',
        //   icon: '',
        //   uploadtype: 'upload',
        //   action: 'importExcel'
        // }
        // {
        //   name: '全部生成计划',
        //   icon: '',
        //   action: 'savePlanAll'
        // }
        // {
        //   name: '打印设置',
        //   icon: 'delete',
        //   action: 'delAll'
        // }
      ]
    }
  },
  created() {
    getBusiness().then(res => {
      this.businessData = res // 系统参数
      //   this.handleView()
    })
    console.log(this.$store.getters)
    this.getAuthBycargoOwner()
  },
  mounted() {
    warehouseId = this.$store.state.user.warehouse.warehouseIdg
    this.$refs.detial.$refs.forms.form.setFieldsValue({
      warehouseId: this.$store.state.user.warehouse.warehouseId,
      warehouseName: this.$store.state.user.warehouse.warehouseName
    })
    if (this.businessData != 'int') {
      this.btnOptions.push({
        name: '下载模板',
        icon: '',
        action: 'downtep'
      })
      this.btnOptions.push({
        name: '导入',
        icon: '',
        uploadtype: 'upload',
        action: 'importExcel'
      })
    }
  },
  methods: {
    //下载模板
    async downtep() {
      let res = await downLoadFromJar()
      let blob = new Blob([res])
      let downloadElement = document.createElement('a')
      let href = window.URL.createObjectURL(blob) //创建下载的链接
      downloadElement.href = href
      downloadElement.download = '期初库存导入模板.xlsx' //下载后文件名
      document.body.appendChild(downloadElement)
      downloadElement.click() //点击下载
      document.body.removeChild(downloadElement) //下载完成移除元素
      window.URL.revokeObjectURL(href) //释放掉blob对象
    },
    //导入
    importExcel(info) {
      console.log(info)
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        this.$message.success(`${info.file.name} 文件上传成功`)
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} 文件上传失败`)
      }
    },
    async getAuthBycargoOwner() {
      await getCargoOwner().then(res => {
        if (res.success) {
          this.$nextTick(() => {
            this.$refs.detial.$refs.forms.form.setFieldsValue({
              cargoOwnerId: res.data.list[0].companyId,
              cargoOwnerName: res.data.list[0].companyName,
              cargoOwnerCode: res.data.list[0].companyCode
            })
          })
        }
        if (!res.success) {
          this.$exception(res)
          return
        }
      })
    },
    savePlan() {
      console.log(333)
      // console.log(this.$refs.detial.$refs.forms.form.getFieldsValue(), '333333')
      // // 生成计划
      // if (this.selectedRowKeys.length < 1) return this.$message.warn('请选择盘点商品!')
      // if (!this.$refs.detial.$refs.forms.form.getFieldsValue().warehouseId) return this.$message.warn('请选择仓库!')
      // if (!this.$refs.detial.$refs.forms.form.getFieldsValue().cargoOwnerId) return this.$message.warn('请选择货主!')
      // if (!this.$refs.detial.$refs.forms.form.getFieldsValue().checkWay) return this.$message.warn('请选择盘点方式!')
      // if (!this.$refs.detial.$refs.forms.form.getFieldsValue().checkType) return this.$message.warn('请选择盘点类型!')
      // let arrList = []
      // this.selectedRows.map((res, index) => {
      //   let item = {}
      //   item.batchExpiredDate = res.batchExpiredDate
      //   item.batchId = res.batchId
      //   item.batchNum = res.batchNum
      //   item.cargoOwnerId = res.cargoOwnerId
      //   item.caseQuantityAccount = res.oddCaseQuantity
      //   item.conversionRate = res.caseConversionRate
      //   item.itemId = res.itemId
      //   item.stockStatus = res.status
      //   item.lineNum = index
      //   item.oddQuantityAccount = res.oddPieceQuantity
      //   item.pieceQuantityAccount = res.quantity
      //   item.productionDate = res.batchProductionDate
      //   item.uom = res.uom
      //   item.warehouseId = res.warehouseId
      //   item.whLocatorId = res.locatorId
      //   item.manufacturerLotNum = res.manufacturerLotNum
      //   arrList.push(item)
      // })
      if (this.selectedRows.length < 1) {
        this.$message.error('请至少勾选一条数据')
        return
      }
      let blankLocator = 0
      this.selectedRows.forEach(item => {
        if (item.quantity == 0) {
          blankLocator++
        }
      })
      const params = [
        {
          head: {
            enterpriseName: this.$store.getters.userInfo.enterpriseName,
            blankLocator: blankLocator,
            printUser: this.$store.getters.userInfo.employeeName,
            warehouseName: this.$refs.detial.$refs.forms.form.getFieldsValue().warehouseName
          },
          table: this.selectedRows
        }
      ]
      const printParms = {
        consignorId: this.$refs.detial.$refs.forms.form.getFieldsValue().cargoOwnerId
      }
      const warehouseId = this.$refs.detial.$refs.forms.form.getFieldsValue().warehouseId
      toPrintServer(params, warehouseId, tempType.kcpc, printParms).then(res => {
        if (!res.success) {
          this.$exception(res)
          return
        }
        this.$message.success(res.message)
      })
      // this.invcheckAdd(arrList)
    },
    savePlanAll() {
      // 全部生成计划
      let that = this
      this.$confirm({
        title: '',
        content: '是否全部生成计划?',
        onOk() {
          that.$message.warn('接口待开发！')
        },
        onCancel() {}
      })
    },
    // invcheckAdd(arrList) {
    //   console.log(arrList)
    //   // 生成盘点
    //   let params = {
    //     checkMethod: this.$refs.detial.$refs.forms.form.getFieldsValue().checkWay,
    //     checkType: this.$refs.detial.$refs.forms.form.getFieldsValue().checkType,
    //     invCheckDVOList: arrList
    //   }
    //   invcheckAdd(params).then(res => {
    //     console.log(res)
    //     if (res.success) {
    //       this.$message.success('生成盘点计划成功！')
    //     } else {
    //       this.$exception(res)
    //     }
    //   })
    // },
    selectChange(selectedRowKeys, selectedRows) {
      // 勾选框
      console.log(selectedRowKeys, selectedRows, 'selectedRowKeys, selectedRows')
      this.selectedRows = selectedRows
      this.selectedRowKeys = selectedRowKeys
    }
  }
}
</script>

<style></style>
