<!-- 功能库房拣货 -->
<template>
  <div class='functionTab2' ref='functionTab2'>
    <!-- 商品详情 -->
    <itemDetail ref='detailItem' :itemId='itemId' />

    <!-- 登录 -->
    <workerLogin :loginVisible='loginVisible' :isSupervisedData='isSupervisedData' @loginResult='loginResult'
                 @handleCancel='handleCancel'></workerLogin>
    <!-- 红冲 -->
    <modal-red :modal_visible.sync='modal_visible'
               :modal_columns='modal_columns'
               :modal_data='modal_data'
               :modalType='modalType'
               @modal_confirm='modal_confirm'
    >
    </modal-red>
    <!-- 绑定容器号 -->
    <p-modal title='绑定容器号'
             width='500px'
             :visible='visible_container'
             :enlargeable='true'
             :draggable='true'
             :getContainer='()=>$refs.functionTab2'
             centered
             @cancel='handleCancel'
             :footer='null'
    >
      <p-input ref='scan'
               size='large'
               v-model='containerCode'
               placeholder='请扫描容器码或输入后按回车绑定任务'
               @pressEnter='pressEnter'
               allowClear>
        <a-icon slot='prefix' type='scan' />
      </p-input>
    </p-modal>

    <p-modal title='任务确认'
             width='80%'
             :visible='visible'
             :enlargeable='true'
             :draggable='true'
             @ok='handleOk'
             @cancel='handleCancel'
    >
      <a-table
        :columns='columns2'
        :data-source='data2'
        :has-row-count='true'
        rowKey='pickOrderId'
        auto-width
        dragle
        :rowSelectType='false'
        :pagination='false'
        :loading='loading'
        bordered
      >
        <span slot='customTitle' style='color:#2b80ff;'> 确认已拣数量  <a-icon type='check' /></span>
      </a-table>
      <p-input placeholder='请输入工号' size='large' disabled v-model='search.operatorCode' style='margin-top:16px'>
        <span slot='suffix' style='color: #CCC;'>工号</span>
      </p-input>
    </p-modal>

    <header>
      <p-input placeholder='请输入工号' v-model='search.operatorCode' disabled />
      <p-input placeholder='请输入容器编号' v-model='search.containerCode' />
      <p-checkbox :checked='isPrint' @change='onCheckChange'> 自动打印</p-checkbox>
      <p-checkbox :checked='isConfirm' @change='onCheckConfirm'> 自动确认</p-checkbox>
      <p-button type='primary' icon='pull-request' @clickSync='askFor' :disabled='isDisabled'>索取</p-button>
      <p-button type='primary' icon='printer' @click='println'>打印</p-button>
      <p-button type='primary' icon='scan' @click='bindCon' :disabled='isBindContainer'>绑定容器</p-button>
    </header>


    <div style='margin-top: 16px; margin-bottom: 16px;'>
      <p-grid-form
        ref='search'
        :items='items21'
        @submit='hanlderSubmit'
      />
    </div>


    <!--  dragle 通过 header 拖拽列 -->
    <p-table
      ref='table'
      dragle
      auto-width
      rowSelectFixed
      :scroll='{x:true}'
      :columns='columns3'
      :data-source.sync='data'
      :has-row-count='true'
      :row-select-type='2'
      :selectedRowKeys.sync='selectedRowKeys'
      rowKey='pickTaskDId'
      hasRowSelectCheck
      @checkRow='checkRow'
      @dblclickRow='dblclickRow'
      @change='paginationChange'
      @select='tableSelect'
      :pagination='pagination'
      :loading='loading'
      bordered
    >
      <template slot='printStatus' slot-scope='text'> {{ text == '1' ? '已打印' : '未打印' }}</template>
      <template slot='status' slot-scope='text,rows,index'>
        {{ text | statusFilter }}
      </template>
      <template v-slot:operation='text,rows,index'>
        <a @click='checkItem(rows)'>详情</a>
      </template>

    </p-table>
  </div>
</template>

<script>
// 商品详情
import itemDetail from '@/views/kzyWMS/components/itemDetail'
import { sorter } from '@/views/kzyWMS/utils/sort.js'

import modalRed from '../../components/modal_red.vue'
import workerLogin from '@/views/kzyWMS/outBound/check/innerCheck/components/workerLogin.vue'
// 打印
import { toPrintServer, tempType } from '@/views/kzyWMS/utils/printServer.js'

// 设置默认仓库
import { setwarehouse } from '@/views/kzyWMS/SearchModal/mixins_warehouse.js'
import { items21, columns2, columns3, modal_columns } from '../../config/zeroStockPicking.js'
import {
  create_pickorder4,
  page_mixpicktaskall,
  picktask_confirm,
  picktask_confirm_red,
  picktask_bind_container_mix,
  picktask_print_paperslip,
  print_whole_labels,
  isSupervised
} from '../../config/api.js'
import { mapGetters } from 'vuex'

export default {
  components: { workerLogin, modalRed, itemDetail },
  mixins: [setwarehouse],
  filters: {
    statusFilter(value) {
      if (value === '0') return '待索取'
      if (value === '1') return '待确认'
      if (value === '2') return '待复核'
      if (value === '3') return '已完成'
      return ''
    }
  },
  data() {
    return {
      columns2: sorter(columns2),
      columns3: sorter(columns3),
      items21: items21(this),
      data: [],
      data2: [],
      selectedRowKeys: [],
      selectIds: [],
      type: [],
      values: null,
      itemId: null,
      visible: false,
      visible_container: false,
      confirmLoading: false,
      loading: false,
      isPrint: false, //自动打印
      isConfirm: false, //自动确认
      containerCode: '',//绑定容器编号
      isBindContainer: true, // 是否绑定容器（索取之后）
      search: {
        warehouseId: '',	//仓库id
        containerCode: '', //容器编号
        operatorCode: this.$store.getters.userInfo.employeeNo,	//搜索工号
        isPrint: 1, //自动打印 ,接口传参
        isConfirm: 0//自动确认,接口传参
      },
      loginVisible: false,
      isSupervisedData: {},
      selectedRows: [],	//
      isDisabled: false,
      modal_visible: false,	//红冲弹窗
      modal_columns,
      modal_data: [],
      modalType: 'orderPicking',
      red_params: {
        operatorCode: '',	//工号 {红冲解锁人登录工号}
        redQty: 0,	//冲红数量
        messageType: '',	//错误处理方式
        redReason: ''	//冲红原因
      },
      pagination: {
        total: 0,
        pageSize: 10, //每页中显示10条数据
        current: 1,
        showSizeChanger: true,
        pageSizeOptions: ['10', '15', '20'], //每页中显示的数据
        showTotal: total => `共有 ${total} 条数据` //分页中显示总的数据
      }
    }
  },
  methods: {
    getData(params) {
      params = {
        pageNum: this.pagination.current, // 当前页码
        pageSize: this.pagination.pageSize, // 每页数量
        ...params
      }
      this.loading = true
      page_mixpicktaskall(params).then((res) => {
        this.loading = false
        if (res.success) {
          this.data = res.data.list
          // 扫描监管码数据
          // this.$emit('emitData',[...this.data]);
          this.pagination.total = Number(res.data.totalCount)
          this.selectedRowKeys.length = 0
          this.selectedRows.length = 0
        } else {
          this.$exception(res)
          this.loading = false
        }
      })
        .then(() => {
          console.log('索取成功之后:')
          // 遍历是否有未绑定容器的记录，有先绑定容器
          let temp = this.data.find(item => (!item.containerCode || false))
          console.log('temp:', temp)  //结果 undefined
          if (temp) {
            this.isBindContainer = false
            // this.$message.warning('存在未绑定容器数据,请先绑定容器！');
            // this.visible_container = true;
          } else {
            this.isBindContainer = true
          }

        })
        .finally(() => {
          this.loading = false
        })
    },
    tableSelect(record, selected, selectedRows, nativeEvent) {
      //   this.selectedRows = selectedRows
    },
    // 绑定容器
    bindCon() {
      let _this = this
      this.visible_container = true
      this.$nextTick(() => {
        _this.$refs.scan.focus()
      })
    },
    // 索取按钮
    askFor() {
      this.isDisabled = true
      // this.$nextTick(()=>{
      this.$refs.search.form.validateFields((err, values) => {
        if (!err) {
          this.search.warehouseId = values.warehouseId
          let params = Object.assign(this.search, {
            isPrint: (this.search.isPrint ? 1 : 0),
            bldgId: this.$refs.search.form.getFieldsValue().bldgId,
            bldgCode: this.$refs.search.form.getFieldsValue().bldgCode
          })
          create_pickorder4(params).then(res => {
            if (res.success) {
              this.$message.success(`索取拣选单成功, 共${res.data.count}个任务`, 5)

              // 自动打印
              if (this.isPrint) {
                if (res.data.count) {
                  // this.selectIds =Array.from(new Set( this.data.map(item => {
                  // 	if(item.type == 1) {
                  // 		return item
                  // 	}
                  // }) ));
                  this.selectIds = Array.from(new Set(this.data.map(item => item.pickTaskDId)))

                  console.log('this.selectIds:', this.selectIds)
                  this.println()		//调用打印
                } else {
                  // this.$message.info('无自动打印数据！')
                }
              }


              this.getData({ pickTaskType: 3, type: 1, ...this.$refs.search.form.getFieldsValue() })
              setTimeout(() => {
                this.isDisabled = false
              }, 500)
            } else {
              this.$exception(res)
              this.isDisabled = false
            }
          })

          // 自动确认
          if (this.search.isConfirm) {
            this.visible = true
          }
        }
      })
      // })
    },
    // 勾选搜索自动打印
    onCheckChange(e) {
      // 同步:checked
      this.isPrint = e.target.checked
      // 转换到搜索参数
      this.search.isPrint = e.target.checked ? 1 : 0
      console.log(`checked = ${e.target.checked}`, this.search)
    },
    // 勾选搜索自动确认
    onCheckConfirm(e) {
      // 同步:checked
      this.isConfirm = e.target.checked
      // 转换到搜索参数
      this.search.isConfirm = e.target.checked ? 1 : 0
      console.log(`checked = ${e.target.checked}`, this.search)
    },

    paginationChange(pagination) {
      this.pagination = pagination
      this.pagination.pageNum = pagination.current
      this.getData({ type: 1, ...this.$refs.search.form.getFieldsValue() })
    },
    colChange({ name, value, index, label, record, modalRowData, config, vNode, options, moment, event }) {
      console.log('改变单元格数据：', name, value, index, label, record, modalRowData)
      this.data[index].pickQty = value
      console.log('行修改后：', this.data[index])
    },

    // 条件查询
    hanlderSubmit(event, form) {
      event.preventDefault()
      // console.log("getFieldsValue:",form.getFieldsValue());
      // this.getData(form.getFieldsValue())
      this.$refs.search.form.validateFields((err, values) => {
        if (!err) {
          console.log('验证通过: ', values)
          this.getData(values)
        }
      })
    },
    // 重置
    hanlderRest(event, form) {
      this.$refs.search.form.resetFields()
    },
    // 拣货确认前过滤data数据
    getData_modal(val) {
      let _this = this
      return new Promise(function(resolve, reject) {
        if (_this.data.length) {
          let temp = _this.data.map(item => {
            return {
              operatorCode: val,	// 拣选人工号
              pickQty: item.pickQty,		//已拣数量
              pickTaskDId: item.pickTaskDId	//拣选任务明细id
            }
          })
          return resolve(temp)
        } else {
          _this.$message.warning('暂无数据！')
        }
      })
    },
    // 弹出框确认
    handleOk(e) {
      if (this.selectedRows.length) {
        let params = this.selectedRows.map(item => {
          return {
            ...item,
            operatorCode: this.values.operatorCode,
            warehouseId: this.values.warehouseId,
            warehouseCode: this.values.warehouseCode,
            warehouseName: this.values.warehouseName,
            bldgId: this.values.bldgId,
            bldgCode: this.values.bldgCode,
            bldgName: this.values.bldgName,
            pickQty: item.qty - item.saleRedQty	//确认已拣数量,
          }
        })
        picktask_confirm(params).then(res => {
          if (res.success) {
            this.visible = false
            this.$message.success('确认成功')
            this.getData({ type: 1, ...this.$refs.search.form.getFieldsValue() })
            this.selectedRows.length = 0
          } else {
            this.$exception(res)
          }
        })
      } else {
        this.$message.warning('无数据')
      }
    },


    // 确认保存（搜索栏）
    confirmSave(event) {
      if (this.selectedRows.length) {
        this.selectedRows = this.selectedRows.map(item => {
          return {
            refBillId: item.pickTaskId,	//拣选任务主表id
            refBillLineId: item.pickTaskDId,	//拣选任务明细id
            ...item
          }
        })
        let temp = this.selectedRows.filter(item => item.isSupervise == 1)
        this.$refs.search.form.validateFields((err, values) => {
          if (!err) {
            // 必须填写容器
            let errIndex = -1
            if (!this.selectedRows.every((tt, ii) => {
              errIndex = ii
              return (!!tt.containerCode || tt.type == 1)
            })) {
              this.$message.warning('第' + (errIndex + 1) + '行，请输入容器编号')
              return
            }
            // //是否完成扫描监管码
            isSupervised(temp).then(res => {
              if (res.success) {
                if (!res.data && temp.length) {
                  this.$emit('emitData', this.selectedRows, true, true)
                } else {
                  this.values = values
                  this.$nextTick(() => {
                    this.data2 = [...this.selectedRows]
                    // if(this.search.autoConfirm){
                    this.visible = true
                    // }
                  })
                }
              }
            })
          }
        })
      } else {
        this.$message.warning('请选择数据！')
      }
    },

    // 红冲确认
    modal_confirm(red_data) {
      this.confirmLoading = true
      console.log('emit红冲确认', red_data)
      picktask_confirm_red(red_data).then(res2 => {
        if (res2.success) {
          this.confirmLoading = false
          this.visible = false
          this.$message.success('成功!')
          this.getData({ type: 1, ...this.$refs.search.form.getFieldsValue() })
        } else {
          this.$exception(res2)
          this.confirmLoading = false
        }
      }).finally(() => {
        this.confirmLoading = false
      })
    },
    // 登录成功后返回函数
    loginResult(bool, values) {
      // 解锁数量 登录工号
      this.red_params.operatorCode = values.workercode

      this.loginVisible = bool // 关闭登录窗
      this.modal_visible = true //打开冲红窗
      let _this = this
      this.$nextTick(() => {
        // 传入数据前 混入红冲参数 this.red_params 同时混入当前登录工号
        _this.selectedRows.map(item => {
          return Object.assign(item, _this.red_params, { warehouseId: (item.warehouseId || this.warehouse.warehouseId) })
        })
        // 红冲数据
        _this.modal_data = [..._this.selectedRows]
        console.log(_this.modal_data, 'modal_datamodal_datamodal_datamodal_data')

      })
    },
    // 数量解锁
    unlock() {
      if (this.selectedRows.length) {
        this.isSupervisedData = {
          warehouseId: this.$refs.search.form.getFieldsValue().warehouseId,
          specialWorkType: '整单拣货红冲'
        },
          // 遍历是否有未绑定容器的记录，有先绑定容器
          // let temp =	this.selectedRows.find(item=>item.containerCode==null);
          // console.log("temp:",temp);  //结果 undefined
          // if(temp){
          // 	this.$message.warning('存在未绑定容器数据,请先绑定容器！');
          // 	this.visible_container = true;
          // } else {
          this.loginVisible = true
        // }
      } else {
        this.$message.warning('请选择数据！')
      }
    },
    handleCancel(e) {
      console.log('Clicked cancel button')
      this.visible = false	//关闭确认弹窗
      this.loginVisible = false 	//关闭登录弹窗
      this.visible_container = false // 关闭绑定容器号
    },
    // 异步打印查询
    println_search() {
      let _this = this
      return new Promise((resolve, reject) => {
        this.$refs.search.form.validateFields((err, values) => {
          if (!err) {
            let params = {
              warehouseId: _this.$refs.search.form.getFieldsValue().warehouseId,
              // bldgId : _this.$refs.search.form.getFieldsValue().bldgId,
              // pickTaskType : "3",	//0-整件 1-零货 2-功能库房 3-整单
              type: this.type[0],   //0-拣货 1-补货
              pickTaskDIds: _this.selectIds
            }
            print_whole_labels(params).then(res => {
              if (res.success) {
                resolve(res.data[0].data)
              } else {
                _this.$message.warning(res.message)
                reject('打印数据查询失败！')
              }
            })
          }
        })
      })
    },
    // 打印
    println() {
      if (this.selectIds.length) {
        console.log(this.type, 'typetypetypetype')
        if (this.selectedRows.length != 1) {
          this.$message.error('只能选择一条数据打印')
          return
        }
        //筛选数据是否为补货数据
        // let flag = this.selectedRows.some(item => {
        //     return	item.type == 0
        // })
        // if(flag) {
        // 	this.$message.error('只能选择补货数据打印，拣选数据请到内复核打印')
        // 	return
        // }
        //判断是否为多种类型数据
        if (this.type.length > 1) {
          this.$message.warn('数据有多个打印任务类型,只能选择一种任务类型打印！')
          return false
        }
        this.println_search().then(res => {
          console.log('打印：', res)
          const warehouseId = this.$refs.search.form.getFieldsValue().warehouseId
          toPrintServer(
            res,
            warehouseId,
            this.type[0] ? tempType.zjbhbq : tempType.pick_tag,
            this.$refs.search.form.getFieldsValue().bldgId
          ).then(res => {
            if (!res.success) {
              this.$exception(res)
              return
            }
            this.$message.success(res.message)
          })
        })
        this.getData({ type: 1, ...this.$refs.search.form.getFieldsValue() })
      } else {
        this.$message.warning('请选择打印数据！')
      }
    },
    // 选择时的变化, 必须点到 checkbox 上或者'hasRowSelectCheck=true'点击行
    checkRow(selectedRowKeys, selectedRows) {
      // 选择pickOrderId，并去重
      this.selectIds = Array.from(new Set(selectedRows.map(item => item.pickTaskDId)))
      this.type = Array.from(new Set(selectedRows.map(item => item.type)))
      this.selectedRows = [...selectedRows]
      console.log(this.selectIds, selectedRows)
      this.$emit('emitData', this.selectedRows)

      // 如果选中记录容器号为空，则弹出绑定
      /* if(!selectedRows[0].containerCode){
        this.visible_container = true;
      } */

    },
    dblclickRow(event, activeID, rowRecord) {
      console.log('双击行', event, activeID, rowRecord)
      this.selectedRows.length = 0
      this.selectedRows.push(rowRecord)
      if (this.selectedRows[0].isSupervise) {
        this.$emit('emitData', this.selectedRows, true)
      } else {
        this.$message.warning('该单所有商品，无需扫描药品追溯码')
      }
    },
    // 绑定容器号
    // 请扫描容器条码绑定任务
    pressEnter(e) {
      this.$nextTick(() => {
        console.log('请扫描容器码绑定或输入后按回车绑定', e)
        if (this.containerCode) {
          this.$refs.search.form.validateFields((err, values) => {
            if (!err) {
              if (this.selectedRows.length) {
                let params = {
                  containerCode: this.containerCode,
                  ...this.$refs.search.form.getFieldsValue(),
                  pickOrderId: this.selectedRows[0].pickOrderId
                }
                picktask_bind_container_mix(params).then(res => {
                  if (res.success) {
                    this.$message.success(this.containerCode + '容器任务绑定成功')
                    this.getData({ type: 1, ...this.$refs.search.form.getFieldsValue() })
                    this.visible_container = false // 关闭绑定容器号
                  } else {
                    this.$exception(res)
                  }
                })
              } else {
                this.$message.warning('请选择数据！')
              }
            } else {
              this.$message.warning('参数有误！')
              this.visible_container = false // 关闭绑定容器号
            }
          })

        } else {
          this.$message.warning('容器编号为空！')
        }
      })

    },
    // 商品详情
    checkItem(item) {
      this.itemId = item.itemId
      this.$refs.detailItem.open()
    }

  }, //methods
  computed: {
    ...mapGetters(['userInfo', 'warehouse'])
  },
  mounted() {
    this.$refs.search.form.setFieldsValue({
      operatorCode: this.userInfo.employeeNo
    })
    // 	0：任务索取 1：任务确认
    // this.getData({type:1});
    this.$bus.$on('refreshData', v => {
      // 监管码后的刷新
      this.selectedRowKeys.length = 0
      this.selectedRows.length = 0
      this.getData({ type: 1, ...this.$refs.search.form.getFieldsValue() })
      // this.$refs.table.reload();
      console.log('功能库房拣货$bus.$on执行了。')
    })
  },
  // 给router-view加了个keep-alive导致组件缓存了，所以不会触发beforeDestory和destoryed
  beforeDestroy() {
    // 关闭监听
    this.$bus.$off('refreshData')
  },
  // 触发beforeDestory和destoryed
  beforeRouteLeave(to, from, next) {
    this.$destroy()
    next()
  }
}
</script>

<style scoped='scoped' lang='less'>
.functionTab2 {
  min-height: 410px;
  padding-left: 20px;
  padding-right: 20px;
  box-sizing: border-box;

  ::v-deep .ant-modal-body {
    text-align: center;
    padding: 2em 0;

    .ant-input-affix-wrapper {
      display: inline-block;
      width: 426px;

      .ant-input {
        height: 50px;
        line-height: 50px;
        border-radius: 2px;
        padding-left: 5em;
        font-size: 18px;
        font-weight: bold;
      }

      i.anticon {
        margin-left: 20px;
        color: #BABABA;
        font-size: 25px;
      }
    }
  }

  header {
    height: 68px;
    line-height: 68px;
    background: #FEFFE0;

    ::v-deep {
      // 工号
      .ant-input {
        width: 180px;
        height: 36px;
        border-radius: 2px;
        margin-left: 14px;
      }

      // 自动打印
      .ant-checkbox-wrapper {
        margin-left: 20px;

        > span:last-child {
          font-weight: bold;
          font-size: 14px;
          color: #323233;
          letter-spacing: 1px;
        }
      }

      .ant-btn-primary {
        margin-left: 20px;
        height: 36px;
      }
    }

  }

  ::v-deep {
    .className {
      .ant-table-column-title {
        color: #2b80ff;
      }
    }

    .ant-btn {
      border-radius: 2px;
    }

    .p-table-edit .ant-table-body {
      min-height: 0;
    }

    .p-table-edit .ant-table-body ~ .ant-table-placeholder {
      min-height: 150px;
    }
  }
}
</style>
