<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <el-form ref="form4" :inline="true" :model="form4" label-width="70px">
        <el-form-item label="物料编码">
          <el-select v-model="query.itemCode" filterable placeholder="请输入物料编码" style="width: 160px;"
                     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-form-item>

        <el-form-item label="物料名称">
          <el-input v-model="query.itemName" clearable placeholder="请输入物料名称" style="width: 170px;"
                    class="filter-item"
                    @keyup.enter.native="crud.toQuery"/>
        </el-form-item>

        <el-form-item label="MO票">
          <el-input v-model="query.po" clearable placeholder="请输入MO票" style="width: 170px;" class="filter-item"
                    @keyup.enter.native="crud.toQuery"/>
        </el-form-item>

        <label class="el-form-item-label">日期</label>
        <date-range-picker v-model="query.createTime" class="date-item" style="width: 100px"/>

        <rrOperation :crud="crud"/>
        <el-button class="filter-item" size="mini" type="warning" icon="el-icon-refresh-left" @click="resetQuery">重置
        </el-button>
      </el-form>


      <div class="statusButton" style="border-bottom: solid lightgray 1px;">
        <el-radio-group v-model="radio3" @change="clickChange" size="small">
          <el-radio-button label="全部"> 全部</el-radio-button>
          <el-radio-button label="打开"> 打开</el-radio-button>
          <el-radio-button label="收货完成"> 收货完成</el-radio-button>
        </el-radio-group>


      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" :tableKey="this.$options.name">
        <el-button
          slot="right"
          v-permission="permission.checkAsn"
          class="filter-item"
          type="primary"
          size="mini"
          @click="collectMO = true"
          icon="el-icon-document-add"
          v-if="false"
        >
          MO票采集
        </el-button>
        <el-button
          slot="right"
          v-permission="permission.checkAsn"
          class="filter-item"
          size="mini"
          type="primary"
          icon="el-icon-bottom-right"
          :disabled="receivingStatus"
          @click="checkAsn(crud.selections)"
          v-if="false"
        >
          收 货
        </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 !== 1 || containerReplacementStatus"
          @click="ontainerReplacementOnOff=true"
          v-if="false"
        >
          容器更换
        </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"
          v-if="false"
        >收货详情
        </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" v-if="false" type="success" icon="el-icon-upload2">导入</el-button>
        </el-upload>
        <el-button
          slot="left"
          class="filter-item"
          type="primary"
          size="mini"
          @click="doManLiao"
        >
          满料入库
        </el-button>
      </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 title="容器更换" :visible.sync="ontainerReplacementOnOff" width="400px">
      <el-form ref="form3" :model="form3" :rules="rules" size="small" label-width="80px">
        <el-form-item label="原容器" prop="stockName">
          <el-input v-model="form3.stockName" style="width: 200px;" readonly="true"/>
        </el-form-item>
        <el-form-item label="目标容器" prop="newStock" :rules="[{ required: true, message: '目标容器不能为空'}]">
          <el-select v-model="form3.newStock" @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="ontainerReplacementOnOff= false">取 消</el-button>
        <el-button type="primary" @click="performContainerChange">确 定</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
              @click.native="WuLiaoClick(item.packNumber)"
              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-dialog :visible.sync="manliao" title="满料入库" width="400px" :before-close="doManLiaoCancel">
      <el-form ref="manLiaoform" :model="BindStock" :rules="manLiaoRules" size="small" label-width="80px">
        <el-form-item label="物料" prop="itemCode">
          <el-select v-model="BindStock.itemCode" @focus="getItem" value-key="id" filterable placeholder="请选择物料"
                     style="width: 200px;">
            <el-option
              @click.native="WuLiaoClick(item.packNumber)"
              v-for="item in items"
              :key="item.id"
              :label="item.code"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="容器" prop="stockCode">
          <el-select v-model="BindStock.stockCode" @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.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="库区" prop="KuQu">
          <el-select v-model="BindStock.KuQu" style="width:200px" @change="getPointByArea(BindStock.KuQu)"
                     placeholder="请选择库区">
            <el-option
              v-for="item in KuQuList"
              :key="item.value"
              :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="点位" prop="pointCode">
          <el-select v-model="BindStock.pointCode" style="width:200px" placeholder="请选择点位">
            <el-option
              v-for="item in pointList"
              :key="item.id"
              :label="item.name"
              :value="item.code"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="doManLiaoCancel">取消</el-button>
        <el-button type="primary" @click="submitBindStock">确认</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="this.selectionChangeHandler" @row-click="this.clickRow">
      <el-table-column type="selection" width="55"/>
      <el-table-column prop="xh" type="index" :index="indexMethod" label="序号"/>
      <el-table-column prop="itemCode" label="物料编码" width="120">
        <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 == null ? '' : 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="批次号" width="120"/>
      <el-table-column prop="po" label="MO票" width="200"/>
      <el-table-column prop="orderNumber" label="工单号" 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, updateContainer, doBindStock} 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, getItemsList} 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";
import {queryPointList} from "@/api/point";

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},
      optShow: {
        add: false,
        edit: false,
        del: false,
        reset: false,
        download: true
      }
    })
  },
  data() {
    return {
      pointList: [],
      BindStock: {stockCode: null, itemCode: null, pointCode: null},
      KuQu: null,
      KuQuList: [{
        value: '1F满车产线',
        label: '1F满车产线'
      }, {
        value: '2F满车产线',
        label: '2F满车产线'
      }],
      manliao: false,
      headers: {'Authorization': getToken()},
      radio3: '全部',
      fileList: [],
      items: [],
      stocks: [],
      form4: {},
      form2: {po: null, stock: null},
      form3: {stockName: null, newStock: null, asnDetailUpdate: 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'}
        ],
      },
      manLiaoRules: {
        itemCode: [
          {required: true, message: '物料不能为空', trigger: 'blur'}
        ],
        stockCode: [
          {required: true, message: '容器不能为空', trigger: 'blur'}
        ],
        pointCode: [
          {required: true, message: '点位不能为空', trigger: 'blur'}
        ]
      },
      queryTypeOptions: [
        {key: 'itemCode', display_name: '物料代码'},
        {key: 'itemName', display_name: '物料名称'},
        {key: 'po', display_name: 'MO票'},
        {key: 'status', display_name: '状态'}
      ],
      collectMO: false,
      // 收货按钮的控制
      receivingStatus: true,
      //容器更换按钮的控制
      containerReplacementStatus: true,
      ontainerReplacementOnOff: false,
      itemListData: []
    }
  },
  mounted() {
    //初始化数据
    this.itemDataGet();
  },
  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({status: 'FREE'}).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))
    },
    WuLiaoClick(pack_number) {
      this.form.orderQty = pack_number;
    },
    clickRow(row) {
      this.crud.getTable().clearSelection()
      this.crud.getTable().toggleRowSelection(row, true)

      this.selectSingleClick_()
    },
    selectionChangeHandler(val) {
      this.crud.selections = val
      this.selectSingleClick_()
    },
    //收货状态的判断 => 当用户手动勾选全选 Checkbox 时触发的事件
    selectSingleClick_() {
      if (this.crud.selections.length > 0) {
        this.receivingStatus = false;
      } else {
        this.receivingStatus = true;
      }
      this.containerReplacementStatus = true;
      for (const valElement of this.crud.selections) {
        if (valElement.status === 'RECEIVED') {
          this.receivingStatus = true;
        }
        if (valElement.status === 'OPEN') {
          this.containerReplacementStatus = false;
          this.form3.stockName = valElement.stock.name;
          this.form3.asnDetailUpdate = valElement;
        }
      }
    },
    //容器更换按钮触发
    performContainerChange() {
      this.$refs['form3'].validate((valid) => {
        if (valid) {
          let data_ = {data: null, id: null};
          data_.id = this.form3.asnDetailUpdate.stock.id;
          this.form3.asnDetailUpdate.stock = this.form3.newStock;
          data_.data = this.form3.asnDetailUpdate;
          updateContainer(data_).then(res => {
            this.ontainerReplacementOnOff = false;
            this.crud.toQuery()
            this.getStock()
            DonMessage.success('容器更换成功');
          }).catch(() => {
            DonMessage.success('容器更换失败！');
          })
        } else {
          return false;
        }
      });
    },
    //物料数据
    itemDataGet() {
      getItemsList().then(res => {
        this.itemListData = res;
      }).catch(e => {
        this.$message({
          showClose: true,
          message: '物料加载失败',
          type: 'error'
        });
      })
    },
    clickChange(lab) {
      if (lab === "全部") {
        this.crud.resetQuery();
        this.crud.toQuery();
      } else if (lab === "打开") {
        this.query.status = 'OPEN'
        this.crud.toQuery();
      } else if (lab === "收货完成") {
        this.query.status = 'RECEIVED'
        this.crud.toQuery();
      }
    },
    resetQuery() {
      this.radio3 = '全部';
      this.crud.resetQuery()
    },
    doManLiao() {
      this.manliao = true;
    },
    doManLiaoCancel() {
      this.manliao = false;
      this.$refs['manLiaoform'].resetFields();
    },

    getPointByArea(areaName) {
      queryPointList({areaName}).then(res => {
        this.pointList = res
      })
    },

    submitBindStock() {
      this.$refs['manLiaoform'].validate(valid => {
        if (!valid) {
          return
        }
        doBindStock(this.BindStock).then(res => {
          if (res.status = 200) {
            this.manliao = false;//关闭窗口
            this.crud.notify(res.message, CRUD.NOTIFICATION_TYPE.SUCCESS);
            this.crud.toQuery();
          } else {
            this.crud.notify(res.message, CRUD.NOTIFICATION_TYPE.ERROR);
          }
        })
      })
    }
  }
}
</script>

<style scoped>

</style>
