<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-input v-model="query.itemName" clearable placeholder="物料名称" style="width: 140px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
      <el-input v-model="query.po" clearable placeholder="MO票" style="width: 140px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
      <el-select
        v-model="query.status"
        clearable
        size="small"
        placeholder="状态"
        class="filter-item"
        style="width: 100px"
        @change="crud.toQuery"
      >
        <el-option
          v-for="item in dict.asn_status"
          :key="item.id"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <date-range-picker v-model="query.createTime" class="date-item" style="width: 100px" />
      <rrOperation :crud="crud" />
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" >
        <el-button
          slot="right"
          v-permission="permission.checkAsn"
          class="filter-item"
          type="primary"
          size="mini"
          @click="collectMO = true"
          icon="el-icon-document-add"
        >
          MO票采集
        </el-button>
        <el-button
          slot="right"
          v-permission="permission.checkAsn"
          class="filter-item"
          size="mini"
          type="primary"
          icon="el-icon-bottom-right"
          :disabled="crud.selections.length === 0"
          @click="checkAsn(crud.selections)"
        >
           收  货
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="info"
          icon="el-icon-s-order"
          @click="doAsnTask(crud.selections[0].id)"
          :disabled="crud.selections.length !== 1"
        >收货详情</el-button>
        <el-upload
          class="upload-demo"
          slot='right'
          style="float: right;padding-left: 5px"
          :headers="headers"
          action="/api/asnDetail/import_mo"
          :file-list="fileList"
          :on-error="handleErr"
          :on-success=" (response, file, fileList) => { return handleSuccess(response, file, fileList,crud);}"
          :show-file-list="true">
          <el-button size="mini" type="success" icon="el-icon-upload2">导入</el-button>
        </el-upload>
      </crudOperation>
      <AsnTask ref="asnTask" />
    </div>
      <!--MO票采集表单组件-->
      <el-dialog title="MO票采集" :visible.sync="collectMO" width="400px">
        <el-form ref="form2" :model="form2" :rules="rules" size="small" label-width="80px">
          <el-form-item label="MO票" prop="po">
            <el-input v-model="form2.po" style="width: 200px;" />
          </el-form-item>
          <el-form-item label="容器"  prop="stock">
            <el-select v-model="form2.stock" @focus="getStock"  value-key="id" filterable placeholder="请选择容器" style="width: 200px;">
              <el-option
                v-for="item in stocks"
                :key="item.id"
                :label="item.code"
                :value="item"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="collectMO= false">取 消</el-button>
          <el-button type="primary" @click="collectMO2()">确 定</el-button>
        </div>
      </el-dialog>
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false"  :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="400px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="物料"  prop="item">
            <el-select v-model="form.item" @focus="getItem" value-key="id" filterable placeholder="请选择物料" style="width: 200px;">
              <el-option
                v-for="item in items"
                :key="item.id"
                :label="item.code"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="容器"  prop="stock">
            <el-select v-model="form.stock"  @focus="getStock" value-key="id"  filterable placeholder="请选择容器" style="width: 200px;">
              <el-option
                v-for="item in stocks"
                :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: 200px;" />
          </el-form-item>
          <el-form-item label="批次号">
            <el-input v-model="form.propC1" style="width: 200px;" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.remark" style="width: 200px;" />
          </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>
      <!--表格渲染-->
      <el-table ref="table" height="68vh" 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 type="index" :index="indexMethod"  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 :show-overflow-tooltip="true" prop="stock" label="容器">
          <template slot-scope="scope">
            <div>{{ scope.row.stock.code }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" >
          <template slot-scope="scope">
            {{ dict.label.asn_status[scope.row.status] }}
          </template>
        </el-table-column>
        <el-table-column prop="orderQty" label="订单数量" />
        <el-table-column prop="receivedQty" label="收货数量" />
        <el-table-column prop="propC1" label="批次号" />
        <el-table-column prop="po" label="MO票" width="200"/>
        <el-table-column prop="remark" label="备注" />
        <el-table-column prop="createBy" label="创建人" />
        <el-table-column prop="createTime" label="创建时间"  width="135" sortable/>
      </el-table>
      <!--分页组件-->

    <div style="float: right;">
      <pagination/>
    </div>

  </div>
</template>

<script>
import crudAsnDetail, {add} from '@/api/asnDetail'
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} from "@/api/item"
import {queryKyStockList} from "@/api/stock"
import Treeselect from '@riophae/vue-treeselect'
import Search from "@/views/monitor/log/search.vue"
import AsnTask from "@/views/business-data/asnDetail/viewAsnTask"
import DonMessage from "@/utils/message";
import DateRangePicker from "@/components/DateRangePicker/index.vue";
import {getToken} from "@/utils/auth";

const defaultForm = { id: null, asnId: null, item: null, stock: null, lineNo: null, po: null, status: 'OPEN', orderQty: 0, receivedQty: 0, moveQty: 0, putQty: 0, weight: 0, volume: 0, remark: null, propC1: null, propC2: null, propC3: null, propC4: null, 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: 'AsnDetail',
  components: {DateRangePicker, AsnTask, Search, Treeselect, pagination, crudOperation, rrOperation, udOperation},
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['asn_status'],
  cruds() {
    return CRUD({ title: '收货数据', url: 'api/asnDetail', idField: 'id', sort: 'id,desc', crudMethod: { ...crudAsnDetail }})
  },
  data() {
    return {
      headers: { 'Authorization': getToken() },
      items: [],
      stocks: [],
      form2: {po: null,stock: null},
      permission: {
        add: ['admin', 'asnDetail:add'],
        edit: ['admin', 'asnDetail:edit'],
        del: ['admin', 'asnDetail:del'],
        checkAsn: ['admin', 'asnDetail:checkAsn']
      },
      rules: {
        item: [
          { required: true, message: '物料不能为空', trigger: 'blur' }
        ],
        stock: [
          { required: true, message: '容器不能为空', trigger: 'blur' }
        ],
        po: [
          { required: true, message: 'MO票不能为空', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'itemCode', display_name: '物料代码' },
        { key: 'itemName', display_name: '物料名称' },
        { key: 'po', display_name: 'MO票' },
        { key: 'status', display_name: '状态' }
      ],
      collectMO: false
    }
  },
  mounted() {
    //初始化数据
  },
  methods: {
    handleSuccess(response, file, fileList,crud) {
      let myError = response.toString();//转字符串
      DonMessage.success("" + response['message'])
      crud.toQuery()
    },
    handleErr(err, file, fileList) {

      let myError = err.toString();//转字符串
      myError = myError.replace("Error: ", "") // 去掉前面的" Error: "
      myError = JSON.parse(myError);//转对象
      DonMessage.error("" + myError['message'])
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    getItem() {
      getItems({ }).then(res => {
        this.items= res.content.map(function(obj) {
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
      })
    },
    getStock() {
      queryKyStockList({ }).then(res => {
        this.stocks= res.map(function(obj) {
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
      })
    },
    indexMethod(index) {
      return index * 1+1;
    },
    checkAsn(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)
        }
        crudAsnDetail.doCheckAsn(ids).then(res => {
          DonMessage.success('收货成功！');
          this.crud.toQuery()
          this.getStock()
        })

      }).catch(() => {
        DonMessage.success('收货失败！');
      })
    },
    collectMO2() {
      crudAsnDetail.collectMOCreate(this.form2).then(res => {
        this.collectMO=false
        this.crud.toQuery()
        this.getStock()
        this.resetForm()

      }).catch(() => {
      })
    },
    // 显示日志
    doAsnTask(id) {
      this.$refs.asnTask.dialog = true
      this.$refs.asnTask.doInit(id)
    },
    //重置表单
    resetForm() {
      this.$refs["form2"].resetFields();
      this.$data.form2=JSON.parse(JSON.stringify(this.$options.data().form2))
    }
  }
}
</script>

<style scoped>

</style>
