<template>
  <div class="taskConfirm_tableList">
    <!-- 商品详情 -->
    <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"
      @modal_confirm="modal_confirm"
    >
    </modal-red>
    <p-modal
      title="确认"
      width="80%"
      :visible="visible"
      :enlargeable="true"
      :draggable="true"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <!-- 弹出窗口任务确认data同拣选主表data -->
      <a-table
        :columns="columns2"
        :data-source="data2"
        :has-row-count="true"
        rowKey="pickTaskDId"
        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" v-model="operatorCode" disabled style="margin-top: 16px">
        <span slot="suffix" style="color: #ccc">工号</span>
      </p-input>
    </p-modal>

    <!-- <div class="btnGroup">
			<p-button type="primary" icon="unlock" @click="confirmNum">数量解锁</p-button>
	</div> -->

    <!-- 顶部拣选单号及确认按钮 -->
    <div
      v-if="pickOrderId"
      style="font-size: 16px; color: #333333; font-weight: bold; border-bottom: 1px solid #e9e9e9; padding-bottom: 12px"
    >
      <span>{{ pickOrderId }}</span>
      <p-button type="primary" icon="unlock" style="float: right" @click="unlock">数量解锁</p-button>
      <p-button type="primary" icon="check" style="float: right; margin-right: 15px" @click="confirmNum">确认</p-button>
      <p-grid-form style="margin-top: 10px" ref="search2" :items="items" @submit="handleSubmit" />
    </div>

    <p-table
      ref="table"
      dragle
      auto-width
      rowSelectFixed
      :row-select-type="2"
      :scroll="{ x: true }"
      hasRowSelectCheck
      rowKey="pickTaskDId"
      :columns="columnsES"
      :data-source="data"
      :bordered="true"
      :selectedRowKeys.sync="selectedRowKeys"
      @checkRow="checkRow"
      @dblclickRow="dblclickRow"
      @change="changePagination"
      :pagination="pagination"
      :loading="loading"
    >
      <template slot="printStatus" slot-scope="text"> {{ text == '1' ? '已打印' : '未打印' }} </template>
      <template v-slot:operation="text, rows, index">
        <a @click="checkItem(rows)">详情</a>
      </template>
    </p-table>
    <!-- <p-button @click="getData"> 获取数据 </p-button> -->
  </div>
</template>
<script>
import { sorter } from '@/views/kzyWMS/utils/sort.js'
// 商品详情
import itemDetail from '@/views/kzyWMS/components/itemDetail'
import modalRed from '../../components/modal_red.vue'
import workerLogin from '@/views/kzyWMS/outBound/check/innerCheck/components/workerLogin.vue'
import { items, columns, columns2, modal_columns } from '../../config/zeroStockPicking.js'
import { picktask_confirm, page_picktask, picktask_confirm_red, isSupervised } from '../../config/api.js'
import { mapGetters } from 'vuex'
export default {
  components: { workerLogin, modalRed, itemDetail },
  props: {
    pickOrderId: {
      type: String,
      default: ''
    },
    values: {
      type: Object,
      default: null
    }
  },
  computed: {
    ...mapGetters(['userInfo', 'warehouse'])
  },
  data() {
    return {
      form: this.$form.createForm(this, { name: 'horizontal_login' }),
      loading: false, //text==1?'待拣选':(text==2?'待复核':'完成'
      items: items(this),
      columnsES: sorter([
        ...columns
        // { dataIndex: 'barcode', title: '标签条码',width:120 },
      ]),
      columns2: sorter(columns2),
      visible: false,
      confirmLoading: false,
      loading: false,
      loginVisible: false,
      isSupervisedData: {},
      itemId: null,
      selectedRows: [], //
      selectedRowKeys: [], //
      operatorCode: '', //员工工号
      data: [],
      data2: [],
      modal_visible: false, //红冲弹窗
      modal_columns,
      modal_data: [],
      red_params: {
        operatorCode: '', //工号 {红冲解锁人登录工号}
        redQty: 0, //冲红数量
        messageType: '', //错误处理方式
        redReason: '' //冲红原因
      },
      pagination: {
        total: 0,
        pageSize: 10, //每页中显示10条数据
        current: 1,
        showSizeChanger: true,
        pageSizeOptions: ['10', '15', '20'], //每页中显示的数据
        showTotal: total => `共有 ${total} 条数据` //分页中显示总的数据
      }
    }
  },
  created(){
    console.log(this.userInfo,'userInfouserInfouserInfo')
  },
  methods: {
    getData(params) {
      params = {
        pageNum: this.pagination.current,
        pageSize: this.pagination.pageSize,
        ...params
      }
      this.data = []
      if (!params.pickOrderId) return
      this.loading = true
      page_picktask(params).then(res => {
        if (res.success) {
          this.data = res.data.list
          //   this.data = res.data.list.filter((item) => {
          //     return item.qty !== item.saleRedQty
          //   })
          // 扫描监管码数据
          // this.$emit('emitData',[...res.data.list]);
          this.pagination.total = Number(res.data.totalCount)
          this.loading = false
          this.selectedRowKeys.length = 0
          this.selectedRows.length = 0
        } else {
          this.loading = false
          this.$exception(res)
        }
      })
    },
    changePagination(pagination, filters, sorter) {
      // 分页变化
      console.log(pagination, filters, sorter, '分页变化分页变化')
      this.pagination = pagination
      this.getData({ pickOrderId: this.pickOrderId }) //分页查询所有列表
    },

    // 查询
    handleSubmit(e, form) {
      e.preventDefault()
      form.validateFields((err, values) => {
        if (!err) {
          console.log('接收的values值：', values)
          this.getData({ pickOrderId: this.pickOrderId, ...values }) //分页查询所有列表
        }
      })
    },
    handleReset() {
      this.form.resetFields()
      this.$refs.search2.form.setFieldsValue({
        containerId: '', //容器id
        containerCode: ''
      })
    },
    // 查询仓库时设置仓库代码
    setContainerCode(event, selectId, selectData) {
      console.log('selectId：', selectId)
      console.log('selectData：', selectData)
      this.$refs.search2.form.setFieldsValue({
        containerId: selectData[0].containerId //容器id
      })
    },
    // 清除查询仓库时设置仓库代码
    clearContainerCode(event, selectId, selectData) {
      console.log('clearsevent：', event)
      console.log('clearselectId：', selectId)
      console.log('clearselectData：', selectData)
      if (!selectId) {
        this.$refs.search2.form.setFieldsValue({
          containerId: '' //容器Id
        })
      }
    },
    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])
    },
    reset() {
      this.$refs.table.reset()
    },
    // 确认保存
    confirmNum(event) {
      if (this.selectedRows.length) {
        this.selectedRows = this.selectedRows.map(item => {
          return {
            ...item,
            refBillId: item.pickTaskId, //拣选任务主表id
            refBillLineId: item.pickTaskDId, //拣选任务明细id
          }
        })
        let temp = this.selectedRows.filter(item => item.isSupervise == 1)
        // //是否完成扫描监管码
        isSupervised(temp).then(res => {
          if (res.success) {
            if (!res.data && temp.length) {
              this.$emit('emitData', this.selectedRows, true, true)
            } else {
              this.data2 = [...this.selectedRows]
              this.visible = true //弹出拣货确认
              this.$emit('search') //将父页查询参数同步传到确认子组件
            }
          }
        })
      } else {
        this.$message.warning('请选择数据！')
      }
    },
    // 确认 旧方法
    /* confirmNum() {
		if(this.selectedRows.length){
				this.data2 = [...this.selectedRows];
				this.visible = true;
				this.$emit('search');
		} else {
			this.$message.warning('请选择数据！');
		}
		
    }, */
    // 拣货确认前过滤data数据
    getData_modal(val) {
      let _this = this
      return new Promise(function(resolve, reject) {
        let temp = _this.data.map(item => {
          return {
            operatorCode: val, // 拣选人工号
            pickQty: item.pickQty, //已拣数量
            pickTaskDId: item.pickTaskDId //拣选主表id
          }
        })
        return resolve(temp)
      })
    },
    // 弹出框确认
    handleOk(e) {
      this.confirmLoading = true
      if (this.selectedRows.length) {
        let params = this.selectedRows.map(item => {
          return {
            ...item,
            operatorCode: this.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.confirmLoading = false
              this.visible = false
              this.$message.success('确认成功')
              this.getData({ pickOrderId: this.pickOrderId, ...this.$refs.search2.form.getFieldsValue() })
              this.selectedRows.length = 0
              this.$emit('redsuccess')
            } else {
              this.$exception(res)
              this.confirmLoading = false
            }
          })
          .finally(() => {
            this.confirmLoading = false
          })
      } else {
        this.$message.warning('无数据')
      }
      /* this.$refs.modalOk.form.validateFields((err, values) => {
			        if (!err) {
			          console.log('弹出框: ', values);
			        }
			      }); */
    },
    // 红冲确认
    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({pickOrderId: this.pickOrderId});
            this.$emit('redsuccess')
            this.getData({ pickOrderId: this.pickOrderId, ...this.$refs.search2.form.getFieldsValue() })
          } else {
            this.$exception(res2)
            this.confirmLoading = false
          }
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },
    // 登录成功后返回函数
    loginResult(bool, values) {
      let employeeNo = this.userInfo.employeeNo
      // 解锁数量 登录工号this.$store.getters.userInfo.employeeNo;
      this.red_params.operatorCode = employeeNo
      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]
      })
    },
    // 数量解锁
    async unlock() {
      if (this.selectedRows.length) {
        await this.$emit('search')
        this.isSupervisedData = {
          warehouseId: this.values.warehouseId,
          specialWorkType: '零货拣货红冲'
        }
        console.log('数量解锁：', this.values)
        this.loginVisible = true
      } else {
        this.$message.warning('请选择数据！')
      }
    },
    handleCancel(e) {
      console.log('Clicked cancel button')
      this.visible = false //关闭确认弹窗
      this.loginVisible = false //关闭登录弹窗
    },
    checkRow(selectId, selectedRows) {
      console.log('选择checkRow：', selectId, selectedRows)
      this.selectedRows = [...selectedRows]
      this.$emit('emitData', this.selectedRows)
    },
    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('该单所有商品，无需扫描药品追溯码')
      }
    },
    // 商品详情
    checkItem(item) {
      this.itemId = item.itemId
      this.$refs.detailItem.open()
    }
  }, //methods
  watch: {
    // 监控左侧任务列表点击时
    pickOrderId(nVal, oVal) {
      console.log('右侧列表点击')
      if (nVal) {
        this.getData({ pickOrderId: nVal })
      } else {
        this.data = []
      }
    }
  }, //watch
  mounted() {
    // 工号 赋值默认
    this.operatorCode = this.userInfo.employeeNo
    this.$bus.$on('refreshData', v => {
      // 监管码后的刷新
      this.selectedRowKeys.length = 0
      this.selectedRows.length = 0
      this.getData({ pickOrderId: this.pickOrderId }) //分页查询所有列表
      // 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">
.taskConfirm_tableList {
  position: relative;
  ::v-deep {
    .ant-btn {
      border-radius: 2px;
    }
    .p-table-edit .ant-table-body {
      min-height: 0;
    }
    .notshow {
      display: none;
    }
  }
}
</style>
