<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
<!--      <el-input v-model="query.itemCode" clearable placeholder="物料代码" style="width: 140px;" class="filter-item" @keyup.enter.native="crud.toQuery" />-->
      <el-select v-model="query.itemCode" clearable placeholder="物料代码" style="width: 140px;" @change="crud.toQuery" class="filter-item">
        <el-option
          @keyup.enter.native="crud.toQuery"
          v-for="item in this.itemListData"
          :key="item.code"
          :label="item.code"
          :value="item.code">
          <span style="float: left">{{ item.code }}</span>
          <span style="float: right; color: #8492a6; font-size: 13px">{{ item.name }}</span>
        </el-option>
      </el-select>
      <el-input v-model="query.itemName" clearable placeholder="物料名称" style="width: 140px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
      <el-select
        v-model="query.taskStatus"
        clearable
        size="small"
        placeholder="任务状态"
        class="filter-item"
        style="width: 110px"
        @change="crud.toQuery"
      >
        <el-option
          v-for="item in dict.pick_task_status"
          :key="item.id"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-input v-model="query.srcPointCode" clearable placeholder="原点位" style="width: 140px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
      <el-input v-model="query.dstPointCode" clearable placeholder="目标点位" style="width: 140px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
      <date-range-picker v-if="crud.props.searchToggle" v-model="query.createTime" class="date-item" style="width: 100px" />
      <rrOperation :crud="crud" />
<!--      <el-checkbox-button class="filter-item" v-model="query.queryAll" @change="clickChange()" style="width: 10px;border-left: solid lightgray 1px;" type="info" border>全部</el-checkbox-button>-->

      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" :table-key="tableKey">
        <el-button
            v-permission="permission.rgPick"
            slot="right"
            class="filter-item"
            type="primary"
            size="mini"
            icon="el-icon-document-add"
            v-show="true"
            @click="ManualPTFlag=true"
        >
          人工出库
        </el-button>
        <el-button
            v-permission="permission.thInv"
            slot="right"
            class="filter-item"
            type="danger"
            size="mini"
            icon="el-icon-document-add"
            v-show="true"
            @click="FromInventoryFlag=true"
            :disabled="crud.selections.length !== 1 || this.crud.selections[0].taskStatus!='ALLOCATE'
            || this.crud.selections[0].agvTask===null"
        >
          替换分配库存
        </el-button>
        <el-button
            v-permission="permission.lxPick"
            slot="right"
            class="filter-item"
            type="danger"
            size="mini"
            icon="el-icon-edit"
            v-show="true"
            :disabled="crud.selections.length < 1"
            @click="rmCkPickUp(crud.selections)"
        >
          料箱拣货
        </el-button>
      </crudOperation>
      <!--表单组件-->
      <el-dialog title="人工出库" :visible.sync="ManualPTFlag" width="600px">
        <el-form ref="fromBack" :inline="true" :model="fromManualPT" :rules="rules" size="mini" label-width="120px">
          <el-form-item label="RFID" prop="RFID">
            <el-input v-model="fromManualPT.RFID" :rows="3" type="textarea" style="width: 350px;" @change="devan_rfid('R')"/>
          </el-form-item>
          <el-form-item label="明细行号" prop="pdId">
            <el-select v-model="fromManualPT.pdId" @change="devan_rfid('L')" value-key="id" :disabled="false" filterable placeholder="请选择" style="width: 350px;">
              <el-option
                  v-for="item in pickDetailList"
                  :key="item.id"
                  :label="item.lineNo+','+item.pick.relatedBill1+','+item.item.code+','+(item.allocatedQty-item.pickedQty)"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="登记单号" prop="relatedBill2">
            <el-input v-model="fromManualPT.relatedBill2"  :disabled="true" style="width: 100px;"/>
          </el-form-item>
          <el-form-item label="系统单号" prop="relatedBill1">
            <el-input v-model="fromManualPT.relatedBill1"  :disabled="true" style="width: 100px;"/>
          </el-form-item>
          <el-form-item label="sku" prop="sku">
            <el-input v-model="fromManualPT.sku"  :disabled="true" style="width: 330px;"/>
          </el-form-item>
<!--          <el-form-item label="行号" prop="lineNo">
            <el-input v-model="fromManualPT.lineNo"  :disabled="false" style="width: 100px;"/>
          </el-form-item>-->
          <el-form-item label="订单数量" prop="orderQty">
            <el-input v-model="fromManualPT.orderQty"  :disabled="true" style="width: 100px;"/>
          </el-form-item>
          <el-form-item label="出库数量" prop="receivedQty">
            <el-input v-model="fromManualPT.receivedQty"  :disabled="true" style="width: 330px;"/>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="fromManualPT={ };ManualPTFlag = false ">取 消</el-button>
          <el-button type="primary" @click="picking()">确 定</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table border ref="table"  height="66vh" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
<!--        <el-table-column prop="xh" type="index" :index="indexMethod"  label="序号"/>-->
        <el-table-column prop="id"  label="序号"/>
        <el-table-column :show-overflow-tooltip="true" prop="itemCode" label="物料编码">
          <template slot-scope="scope">
            <div>{{ scope.row.item.code }}</div>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" prop="itemName" label="物料名称">
          <template slot-scope="scope">
            <div>{{ scope.row.item.name }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="srcPoint.code" label="原点位" />
        <el-table-column prop="dstPoint.code" label="目标点位" />
        <el-table-column prop="taskStatus" label="任务状态">
          <template slot-scope="scope">
            <span v-if="dict.label.pick_task_status[scope.row.taskStatus] ==null">{{ scope.row.taskStatus }}</span>
            <span v-if="scope.row.taskStatus !=null">{{ dict.label.pick_task_status[scope.row.taskStatus] }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="agvTask" label="AGV搬运任务">
          <template slot-scope="scope">
            <div v-if="scope.row.agvTask !=null">{{ scope.row.agvTask.id }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="beSkip" label="是否AGV任务" />
        <el-table-column prop="planQty" label="计划数量" />
        <el-table-column prop="moveQty" label="移位数量" />
        <el-table-column prop="createBy" label="创建人" />
        <el-table-column prop="createTime" label="创建时间" />
      </el-table>
<!--      <el-dialog title="修改分配库存" :visible.sync="FromInventoryFlag">
        <Inventory ref="inventory" />
      </el-dialog>-->
      <el-drawer
          ref="drawer"
          title="可分配库存"
          style="height: 250%"
          @opened="queryInventoryFrom(crud.selections[0].itemKey.item.id)"
          :visible.sync="FromInventoryFlag"
          :direction="direction"
          :before-close="handleClose">
        <Inventory ref="inventory" v-on:replaceTaskInv="replaceTaskInv"/>
      </el-drawer>
      <!--分页组件-->
      <div style="float: right;">
        <pagination/>
      </div>
    </div>
  </div>
</template>

<script>
import crudTask, {devanRfid,replaceInv,rmCkPickUp} from '@/api/task'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import DateRangePicker from "@/components/DateRangePicker/index.vue";
import {getItemsList} from "@/api/item";
import crudPickDetail, { picking,getPickDetail } from "@/api/pickDetail";
import {getStockTypes} from "@/api/stockType";
import Inventory from "@/views/business-data/inventory/index.vue";

const defaultForm = { id: null, itemId: null, itemKeyId: null, billCode: null, taskType: null, asnDetailId: null, moveDetailId: null, waveDetailId: null, pickDetailId: null, srcStockId: null, dstStockId: null, srcPointId: null, dstPointId: null, srcStockCode: null, dstStockCode: null, srcPointCode: null, dstPointCode: null, invStatus: null, taskStatus: null, beSkip: null, beBack: null, planQty: null, moveQty: null, putCode: null, invId: null, deptId: null, createBy: null, updateBy: null, createTime: null, updateTime: null }
export default {
  name: 'Task',
  components: {Inventory, DateRangePicker, pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['pick_task_status'],
  cruds() {
    return CRUD({ query:{taskType:['RM_CK','FC_CK','SM_CK']}, title: '出库任务', url: 'api/task', idField: 'id', sort: 'id,desc', crudMethod: { ...crudTask },
        optShow: {
          add: false,
          edit: false,
          del: false,
          reset: true,
          download: true
        },
        queryOnPresenterCreated: false
      }
    )
  },
  data() {
    return {
      // 修改分配库存
      direction: 'ttb',
      FromInventoryFlag: false,
      pickDetailList: [],
      ManualPTFlag: false,
      permission: {
        add: ['admin', 'task:add'],
        edit: ['admin', 'task:edit'],
        del: ['admin', 'task:del'],
        download: ['admin', 'task:download'],
        lxPick: ['admin', 'task:lxPick'],
        thInv: ['admin', 'task:thInv'],
        rgPick: ['admin', 'task:rgPick']
      },
      tableKey: 'api/task',
      rules: {
        RFID: [
          {required: true, message: '必填', trigger: 'blur'}
        ],
        relatedBill1: [
          {required: true, message: '必填', trigger: 'blur'}
        ],
        pdId: [
          {required: true, message: '必填', trigger: 'blur'}
        ],
      },
      fromManualPT: {

      },
      queryTypeOptions: [
        { key: 'itemCode', display_name: '物料代码' },
        { key: 'itemName', display_name: '物料名称' },
        { key: 'taskStatus', display_name: '任务状态' },
        { key: 'srcPointCode', display_name: '源点位编码' },
        { key: 'dstPointCode', display_name: '目标点位编码' }
      ],
      itemListData: []
    }
  },
  mounted() {
    //初始化数据
    this.defaultTableList();
    this.itemDataGet();
    this.getPickDetail();
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    indexMethod(index) {
      return index * 1+1;
    },
    defaultTableList() {
      /*let statusList=[];
      statusList.push('OPEN')
      statusList.push('ALLOCATE')
      statusList.push('PICKUP')
      this.query.statusList = statusList
      this.crud.toQuery()*/
      this.crud.toQuery()
    },
    queryInventoryFrom(itemId){
      this.$refs.inventory.queryInventory(itemId)
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
    },
    manualPT(){
      /*crudTask.manualReceiving(this.fromManualPT).then(res => {
        this.crud.notify(res.message, res.status)
        this.crud.toQuery()
      })*/
    },
    //替换分配库存
    replaceTaskInv(invId){
      this.$confirm(`确认替换?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        crudTask.replaceInv(this.crud.selections[0].id,invId).then(res => {
          this.crud.notify(res.message, res.status)
          if (res.status==200) {
            this.FromInventoryFlag = false
            this.crud.toQuery()
          }
        }).catch(() => {

        })
      }).catch(() => {
        this.$parent.notify('取消成功!', CRUD.NOTIFICATION_TYPE.SUCCESS);
      });
    },
    devan_rfid(type) {
      // 人工出库-解析RFID关联的已分配库存信息
      devanRfid(this.fromManualPT.RFID,'PICK').then(res => {
        if (res.status == 200||res.status == 201) {
          this.fromManualPT = res.data
        }else {
          this.fromManualPT = { }
        }
        this.crud.notify(res.message, res.status)
      })
    },
    //出库-人工出库-确认
    picking() {
      this.$confirm(`确认出库?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        crudTask.picking(this.fromManualPT).then(res => {
          this.crud.notify(res.message, res.status)
          this.fromManualPT= { };
          this.crud.toQuery()
        }).catch(() => {

        })

      }).catch(() => {
        this.$parent.notify('取消成功!', CRUD.NOTIFICATION_TYPE.SUCCESS);
      });
    },
    //出库-料箱拣货
    rmCkPickUp(taskList) {
      this.$confirm(`确认拣货?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids=[];
        for (let i = 0; i < taskList.length; i++) {
          ids.push(taskList[i].id)
        }
        crudTask.rmCkPickUp(ids).then(res => {
          this.crud.notify(res.message, res.status)
          this.crud.toQuery()
        }).catch(() => {

        })

      }).catch(() => {
        this.$parent.notify('取消成功!', CRUD.NOTIFICATION_TYPE.SUCCESS);
      });
    },
    getPickDetail() {
      getPickDetail({ }).then(res => {
        this.pickDetailList= res.map(function(obj) {
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
      })
    },
    //物料数据
    itemDataGet() {
      getItemsList().then(res => {
        this.itemListData = res;
      }).catch(e => {
        this.$message({
          showClose: true,
          message: '物料加载失败',
          type: 'error'
        });
      })
    }
  }
}
</script>

<style scoped>

</style>
