<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <el-form ref="form" :inline="true" :model="pick" :rules="rules" size="small" label-width="120px">
        <el-form-item label="系统单号" prop="relatedBill1">
          <el-input v-model="pick.relatedBill1" style="width: 135px;" />
        </el-form-item>
        <el-form-item label="登记单号">
          <el-input v-model="pick.relatedBill2" style="width: 135px;" />
        </el-form-item>
        <el-form-item label="单据类型" prop="billType">
          <el-select v-model="pick.billType" value-key="id" filterable placeholder="请选择单据类型"
                     style="width: 135px;">
            <el-option
                v-for="item in billTypeList"
                :key="item.id"
                :label="item.name"
                :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-select v-model="pick.status" filterable placeholder="请选择" style="width: 135px;">
            <el-option
                v-for="item in dict.pick_status"
                :key="item.id"
                :label="item.label"
                :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单来源">
          <el-input v-model="pick.orderOrigin" style="width: 135px;" />
        </el-form-item>
        <el-form-item label="优先级">
          <el-input v-model="pick.priority" style="width: 135px;" />
        </el-form-item>
        <el-form-item label="货主">
          <el-input v-model="pick.owner" style="width: 135px;" />
        </el-form-item>
        <el-form-item label="来源名称">
          <el-input v-model="pick.sourceName" style="width: 135px;" />
        </el-form-item>
        <el-form-item label="发货时间">
          <el-date-picker v-model="pick.dispatchDate" type="datetime" style="width: 135px;" />
        </el-form-item>
        <el-form-item label="操作时间">
          <el-date-picker v-model="pick.erTime" type="datetime" style="width: 135px;" />
        </el-form-item>
      </el-form>
      <el-divider></el-divider>
      <!--      业务操作-->
      <crudOperation :permission="permission" :table-key="tableKey">
        <el-button
            slot="left"
            v-permission="permission.pointUsed"
            class="filter-item"
            type="primary"
            size="mini"
            @click="editPick()"
        >
          保存
        </el-button>
        <el-button
            slot="right"
            v-permission="permission.add"
            class="filter-item"
            type="primary"
            size="mini"
            plain="plain"
            icon="el-icon-document-add"
            @click="crud.toAdd"
        >
          添加物料
        </el-button>
        <el-button
          v-permission="permission.allocate"
          slot="right"
          class="filter-item"
          type="success"
          icon="el-icon-check"
          size="mini"
          :disabled="crud.selections.length !== 1 || this.crud.selections[0].orderQty<=this.crud.selections[0].allocatedQty"
          @click="allocate(crud.selections)"
        >
          分配
        </el-button>

        <el-button
            v-permission="permission.cancelAllocate"
          slot="right"
          class="filter-item"
          type="success"
          icon="el-icon-check"
          size="mini"
          :loading="crud.delAllLoading"
          :disabled="show_cancelfp"
          @click="cancelAllocate(crud.selections)"
        >
          取消分配
        </el-button>

        <el-button
            v-permission="permission.pickTask"
          slot="right"
          class="filter-item"
          type="danger"
          icon="el-icon-document-add"
          size="mini"
          :loading="crud.delAllLoading"
          :disabled="crud.selections.length !== 1 || this.crud.selections[0].allocatedQty<=this.crud.selections[0].pickedQty"
          @click="getPickTask(crud.selections[0].id)"
        >
          拣货确认
        </el-button>

      </crudOperation>
      <el-table
        ref="table"
        border
        :data="crud.data"
        size="small"
        style="width: 100%;"
        height="58vh"
        @selection-change="selectionChangeHandlerTwo"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column
          prop="date"
          align="center"
          label="序号"
          :resizable="false"
          type="index"
          width="50"
        />
        <el-table-column prop="lineNo" width="120" label="行号" />
        <el-table-column prop="pick.relatedBill1" width="120" label="系统单号" />
        <el-table-column :show-overflow-tooltip="true" prop="itemName" label="物料编码">
          <template slot-scope="scope">
            <div>{{ scope.row.item.code }}</div>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" prop="itemCode" label="物料名称">
          <template slot-scope="scope">
            <div>{{ scope.row.item.name }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            {{ dict.label.pick_status[scope.row.status] }}
          </template>
        </el-table-column>
        <el-table-column prop="propC1" label="中标批次名称" />
        <el-table-column prop="propC2" label="成品物料编码" />
        <el-table-column prop="propC3" :show-overflow-tooltip="true" label="序列号" />
        <el-table-column prop="orderQty" label="订单数量" />
        <el-table-column prop="allocatedQty" label="分配数量" />
        <el-table-column prop="pickedQty" label="拣货数量" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column prop="propC4" label="出库方式" />
        <el-table-column prop="propC5" label="目标点位" />

        <el-table-column prop="createBy" label="创建人" />
        <el-table-column prop="createTime" width="150px" label="创建时间" />
        <el-table-column label="操作" width="150px" fixed="right" align="center">

          <template slot-scope="scope">
            <udOperation
                :data="scope.row"
                :permission="permission"
                :show-dle="true"
                :showPointIn="true"
                style="float: left"
            >
            </udOperation>
          </template>
        </el-table-column>
      </el-table>
      <!--拣货确认界面-->
      <PickTask ref="pickTask" />
      <!--表单组件-->
      <el-dialog
        :close-on-click-modal="false"
        :before-close="crud.cancelCU"
        :visible.sync="crud.status.cu > 0"
        :title="crud.status.title"
        width="580px"
      >
        <el-form ref="form" :inline="true" :model="form" :rules="rules" size="small" label-width="120px">
          <el-form-item v-if="false" label="出库单ID">
            <el-input v-model="form.pick.id" style="width: 135px;" />
          </el-form-item>
          <el-form-item label="明细行号">
            <el-input v-model="form.lineNo" style="width: 135px;" />
          </el-form-item>
          <el-form-item label="物料" prop="item">
            <el-select
              v-model="form.item"
              filterable
              placeholder="请选择物料"
              value-key="id"
              style="width: 135px;"
              @focus="getItem"
            >
              <el-option
                v-for="item in items"
                :key="item.id"
                :label="item.code"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="订单数量">
            <el-input v-model="form.orderQty" style="width: 135px;" />
          </el-form-item>
          <el-form-item label="中标批次名称">
            <el-input v-model="form.propC1" style="width: 135px;" />
          </el-form-item>
          <el-form-item label="成品物料编码">
            <el-input v-model="form.propC2" style="width: 135px;" />
          </el-form-item>
          <el-form-item label="序列号">
            <el-input v-model="form.propC3" style="width: 135px;" />
          </el-form-item>
          <el-form-item label="操作方式">
            <el-select
                v-model="form.propC4"
                size="small"
                placeholder="操作方式"
                class="filter-item"
                style="width: 135px"
            >
              <el-option
                  v-for="item in dict.bill_type_pt"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="目标点位">
            <el-input v-model="form.propC5" style="width: 135px;" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.remark" :rows="3" type="textarea" style="width: 370px;" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->

      <!--分页组件-->
      <div style="float: right;">
        <pagination />
      </div>
    </div>
  </div>
</template>

<script>
import crudPickDetail from '@/api/pickDetail'
import curdPoint from '@/api/point'
import crudPick, { getPickList } from '@/api/pick'
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 { getItems, getItemsList } from '@/api/item'
import PickTask from '@/views/business-data/pickDetail/pickTicketTask.vue'
import DateRangePicker from '@/components/DateRangePicker/index.vue'
import DonMessage from "@/utils/message";
import curdAsn, {getAsnList} from "@/api/asn";
import {getBillType} from "@/api/billType";

const defaultForm = {
  id: null,
  pick: { relatedBill1: null,id: null },
  item: null,
  lineNo: 1,
  po: null,
  status: 'OPEN',
  orderQty: 100,
  allocatedQty: 0,
  pickedQty: 0,
  shippedQty: 0,
  weight: 0,
  volume: 0,
  remark: null,
  propC1: null,
  propC2: null,
  propC3: null,
  propC4: 'AGV_PT',
  propC5: null,
  propC6: null,
  propD1: null,
  propD2: null,
  deptId: null,
  sourceName: null,
  sourceId: null,
  createBy: null,
  updateBy: null,
  createTime: null,
  updateTime: null
}
export default {
  name: 'PickDetail',
  components: { DateRangePicker, PickTask, pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['pick_status', 'bill_type_pt'],
  cruds() {
    return CRUD({
      title: '出库明细',
      url: 'api/pickDetail',
      idField: 'id',
      sort: 'id,desc',
      crudMethod: { ...crudPickDetail },
      optShow: {
        add: false,
        edit: false,
        del: false,
        reset: false,
        download: true
      },
      queryOnPresenterCreated: false
    })
  },
  data() {
    return {
      tjwlFromFlag: false,
      show_jh: true,
      show_cancelfp: true,
      pickList: [],
      billTypeList: [],
      pick: { id: null, deptId: null, billType: null, orderOrigin: null, priority: null, owner: null, relatedBill1: null, relatedBill2: null, sourceName: null, status: null, address: null, dispatchDate: null, erTime: null, createBy: null, updateBy: null, createTime: null, updateTime: null, orderDate: null },
      radio3: '全部',
      items: [],
      permission: {
        add: ['admin', 'pickDetail:add'],
        edit: ['admin', 'pickDetail:edit'],
        del: ['admin', 'pickDetail:del'],
        download: ['admin', 'pickDetail:download'],
        cancelAllocate: ['admin', 'pickDetail:cancelAllocate'],
        allocate: ['admin', 'pickDetail:allocate'],
        pickTask: ['admin', 'pickDetail:pickTask']
      },
      queryAll: false,
      tableKey: 'api/pickDetail',
      rules: {
        item: [
          { required: true, message: '物料必填', trigger: 'blur' }
        ],
        pick: [
          { required: true, message: '所属出库单必填', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'itemCode', display_name: '物料编码' },
        { key: 'itemName', display_name: '物料名称' },
        { key: 'po', display_name: '任务号' },
        { key: 'status', display_name: '状态' }
      ],
      itemListData: []
    }
  },
  pick: { relatedBill1: null },
  mounted() {
    // 初始化数据
    this.getItem()
    this.itemDataGet()
    this.getPicks()
    this.getBillType()
    this.defaultTableList()
    /* 默认AGV出库，过滤目标点位*/
    this.getBillTypePt()
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    getPicks() {
      crudPick.getPickList({}).then(res => {
        this.pickList = res.map(function (obj) {
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
      })
    },
    getBillTypePt(){
      const billCode=this.pick.billType.code;
      curdPoint.getPickEnd({billCode}).then(res => {
        const propC5s = res.map(function(obj) {
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
        defaultForm.propC5=propC5s[0].code
      })
    },
    getItem() {
      getItemsList({}).then(res => {
        this.items = res.map(function(obj) {
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
      })
    },
    getBillType() {
      getBillType({}).then(res => {
        this.billTypeList = res.map(function(obj) {
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
      })
    },
    selectionChangeHandlerTwo(val) {
      this.crud.selections = val
      if (this.crud.selections.length === 0) {
        this.show_jh = true
        this.show_fp = true
        this.show_cancelfp = true
        return
      }

      const status = []
      for (let i = 0; i < val.length; i++) {
        status.push(this.crud.selections[i].status)
      }

      if (this.isAllEqual(status) && status[0] == 'OPEN') {
        this.show_jh = true
        this.show_fp = false
        return
      }

      if (this.isAllEqual(status) && status[0] == 'ALLOCATE') {
        this.show_jh = true
        this.show_fp = true
        this.show_cancelfp = false
      }
      // 拣货
      if (this.crud.selections.length == 1 && this.crud.selections[0].orderQty == this.crud.selections[0].allocatedQty) {
        this.show_jh = false
        this.show_fp = true
        return
      }
    },
    allocate(datas) {
      this.$confirm(`选中的${datas.length}条数据分配确认?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = []
        for (let i = 0; i < datas.length; i++) {
          ids.push(datas[i].id)
        }
        crudPickDetail.allocate(ids).then(res => {
          this.crud.notify(res.message, res.status)
          this.crud.toQuery()
        }).catch(() => {
          this.crud.toQuery()
        })
      }).catch(() => {
        this.$refs.table.clearSelection()
        this.crud.notify('取消成功！', CRUD.NOTIFICATION_TYPE.SUCCESS)
      })
    },
    cancelAllocate(datas) {
      this.$confirm(`选中的${datas.length}条数据取消分配确认?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = []
        for (let i = 0; i < datas.length; i++) {
          ids.push(datas[i].id)
        }
        crudPickDetail.cancelAllocate(ids).then(res => {
          this.crud.notify(res.message, res.status)
          this.crud.toQuery()
        }).catch(() => {

        })
      }).catch(() => {
        this.$refs.table.clearSelection()
        this.crud.notify('取消成功！', CRUD.NOTIFICATION_TYPE.SUCCESS)
      })
    },
    getPickTask(id) {
      this.$refs.pickTask.dialog = true
      this.$refs.pickTask.queryPickTask(id)
    },
    shuaxin() {
      this.crud.toQuery()
    },
    // 默认数据
    defaultTableList() {
      this.pick = this.$route.query.pick
      if (this.pick.id===undefined){
        this.crud.notify("找不到出库单",400)
      }else {
        this.query.pickId = this.pick.id
        defaultForm.pick.id = this.pick.id
        this.crud.toQuery()
      }
    },
    editPick() {
      crudPick.edit(this.pick).then(res => {
        this.crud.notify("保存成功",200)
      })
    },
    deletePick(data) {
      this.crud.doDelete(data)
    }, isAllEqual(array) {
      if (array.length > 0) {
        return !array.some(function(value, index) {
          return value !== array[0]
        })
      } else {
        return true
      }
    },
    // 物料数据
    itemDataGet() {
      getItemsList().then(res => {
        this.itemListData = res
      }).catch(e => {
        this.$message({
          showClose: true,
          message: '物料加载失败',
          type: 'error'
        })
      })
    }
  }
}
</script>

<style scoped>

</style>
