<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" placeholder="物料代码" style="width: 140px;" 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.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="订单编号" 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" :tableKey="this.$options.name">
        <el-button
          slot="right"
          v-permission="permission.checkAsn"
          class="filter-item"
          type="primary"
          size="mini"
          @click="collectMOFlag = true"
          icon="el-icon-document-add"
        >
          收货
        </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)"
        >
          收 货
        </el-button>-->

<!--        <el-button-->
<!--          slot="right"-->
<!--          class="filter-item"-->
<!--          type="primary"-->
<!--          size="mini"-->
<!--          @click="downingthisExcel()"-->
<!--          icon="el-icon-document-add"-->
<!--        >-->
<!--          导出EXCEl-->
<!--        </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-button
          slot="right"
          class="filter-item"
          type="primary"
          size="mini"
          :disabled="crud.selections.length === 0"
          @click="qxshM(crud.selections)"
          :loading="logining3"
        >
          取消收货
        </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="收货" :visible.sync="collectMOFlag" width="400px">
      <el-form ref="putForm" :model="putForm" :rules="rules" size="small" label-width="80px">
        <el-form-item label="库区" prop="area">
          <el-select v-model="putForm.area" value-key="id" filterable placeholder="请选择库区"
                     style="width: 200px;">
            <el-option
              v-for="item in areaList"
              :key="item.id"
              :label="item.code"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="库位" prop="stock">
          <el-select v-model="putForm.point" value-key="id" filterable placeholder="请选择库位"
                     style="width: 200px;">
            <el-option
              v-for="item in pointList"
              :key="item.id"
              :label="item.code"
              :value="item"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="collectMOFlag= false">取 消</el-button>
        <el-button type="primary" @click="putawayConfirmXpp(crud.selections[0].id)">确 定</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-table id="mytable"  ref="table" height="68vh" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;"
              @selection-change="this.selectionChangeHandler" @row-click="this.clickRow" border>
      <el-table-column type="selection" width="55"/>
<!--      <el-table-column type="index" :index="indexMethod" label="序号"/>-->
      <el-table-column :show-overflow-tooltip="true" prop="item.code" label="物料编码">
        <template slot-scope="scope">
          <div>{{ scope.row.item.code }}</div>
        </template>
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" prop="item.name" label="物料名称">
        <template slot-scope="scope">
          <div>{{ scope.row.item.name }}</div>
        </template>
      </el-table-column>
      <el-table-column
        prop="asn_status#status"
        label="状态"
        width="100"
        :filters="filtersStatusS"
        :filter-method="filterTag"
        filter-placement="bottom-end">
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.status === 'OPEN' ? 'primary' : 'success'"
            disable-transitions>{{ dict.label.asn_status[scope.row.status] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="orderQty" label="订单数量"/>
      <el-table-column prop="receivedQty" label="收货数量"/>
      <el-table-column prop="propD1" label="纳入日期">
        <template slot-scope="scope">
          {{getFormatDate(scope.row.propD1)}}
        </template>
      </el-table-column>
      <el-table-column prop="po" label="订单编号" width="200"/>
      <el-table-column prop="remark" label="备注"/>
      <el-table-column prop="createBy" label="创建人"/>
      <el-table-column prop="createTime" label="创建时间" width="135" sortable>
        <template slot-scope="scope">
          {{getFormatDate(scope.row.createTime)}}
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->

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

  </div>
</template>

<script>
import crudAsnDetail, { add, updateContainer, putawayConfirm, rkAndQxButton, rkAndQxButtonQX } from '@/api/asnDetail'
import CRUD, {presenter, header, form, crud} from '@crud/crud'
import rrOperation from '@crud/RR.operation.vue'
import crudOperation from '@crud/CRUD.operation.vue'
import udOperation from '@crud/UD.operation.vue'
import pagination from '@crud/Pagination.vue'
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-asn/asnDetail/viewAsnTask.vue"
import DonMessage from "@/utils/message";
import DateRangePicker from "@/components/DateRangePicker/index.vue";
import {getToken} from "@/utils/auth";
import {queryPointList } from '@/api/point'
import {queryAreaList} from "@/api/area";
import {exportExcel} from '@/components/TableToExcel/ExportExcel'
import {initData} from '@/api/data'
import { formatDate } from '@/utils/commonUtils'

const defaultForm = {
  id: null,
  asn: 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: true,
        download: true
      }
    })
  },
  data() {
    return {
      headers: {'Authorization': getToken()},
      items: [],
      stocks: [],
      pointList: [],
      areaList: [],
      putForm: {point: null,area: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'}
        ],
        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: '状态'}
      ],
      asnDetailButton: {
        button: 0,
        id: 0,
        oneRNumber: 0,
        oneRPoint: {},
        asnDetailData: {},
        asnDetailDataS: []
      },
      collectMOFlag: false,
      // 收货按钮的控制
      receivingStatus: true,
      //容器更换按钮的控制
      containerReplacementStatus: true,
      ontainerReplacementOnOff: false,
      itemListData: [],
      logining3: false,
      // filtersStatusS:[{ text: '打开', value: 'OPEN' }, { text: '收货中', value: 'RECEIVING' }, { text: '收货完成', value: 'RECEIVED' }]
      filtersStatusS:[]
    }
  },
  mounted() {
    //初始化数据
    this.itemDataGet();
    this.getAreaList();
    this.getPointList();
    this.initData();
  },
  methods: {
    initData(){
      let  data = this.dict.asn_status;
      setTimeout(()=>{
        //这里就写你要执行的语句即可，先让数据库的数据加载进去数组中你在从数组中取值就好了
        for (const asnStatusKey of this.dict.asn_status) {
          this.filtersStatusS.push({ text: asnStatusKey.label, value: asnStatusKey.value });
        }
      },800);

    },
    //日期格式化
    getFormatDate(data){
      return  formatDate(data);
    },
    filterTag(value, row) {
      return row.status=== value;
    },

    downingthisExcel() {
      this.crud.loading=true
      initData(this.crud.url,this.crud.getQueryParams2()).then(data => {
        this.crud.data=data.content
        setTimeout(() => {
          this.crud.loading=false
          exportExcel(this.$xlsx, this.$fileSaver,"收货明细","mytable")
        }, 500)

      })
    },
    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
        })
      })
    },
    getPointList() {
      queryPointList({"type":"CH"}).then(res => {
        this.pointList = res.map(function (obj) {
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
      })
    },
    getAreaList() {
      queryAreaList({}).then(res => {
        this.areaList = 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,MO).then(res => {
          DonMessage.success('收货成功！');
          this.crud.toQuery()
          this.getStock()
        })

      }).catch(() => {
        DonMessage.success('收货失败！');
      })
    },
    putawayConfirmXpp(id) {
      this.$refs['putForm'].validate((valid) => {
        if (valid) {
          let date_ = {detailId: null, areaId: null, pointId: null};
          date_.detailId = id;
          date_.areaId = this.putForm.area.id;
          date_.pointId = this.putForm.point.id;
          putawayConfirm(date_).then(res => {
            this.crud.notify(res.message, CRUD.NOTIFICATION_TYPE.SUCCESS)
            this.crud.toQuery()
          }).catch(e => {
            this.crud.notify(res.message, CRUD.NOTIFICATION_TYPE.ERROR)
          })
        }else {
          return false;
        }
      });
    },
    collectMO2() {
      crudAsnDetail.collectMOCreate(this.putForm).then(res => {
        this.collectMOFlag = false
        this.crud.toQuery()
        this.getStock()
        this.resetForm()

      }).catch(() => {
      })
    },
    //取消收货
    qxshM(data_) {
      this.logining3 = true
      this.asnDetailButton.asnDetailDataS = data_
      let data = this.asnDetailButton
      rkAndQxButtonQX(data).then(res=>{
        this.$message.success(res)
        this.logining3 = false
        this.asnDetailButton.asnDetailDataS = []
      }).catch(err=>{
        this.logining3 = false
      })

    },
    rkAndQxButtonM(num) {
      if (num === 1) {   //批量入库
        this.logining1 = true
        let data = this.asnDetailButton
        data.button = num
        data.id = this.asn.id
        rkAndQxButton(data).then(res => {
          this.$message.success(res)
          this.logining1 = false
          this.crud.toQuery()
        }).catch(e => {
          this.logining1 = false
        })
      } else if (num === 3) {
        this.logining3 = true
        let data = this.asnDetailButton
        data.button = num
        const ids = []
        for (let i = 0; i < datas.length; i++) {
          ids.push(datas[i].id)
        }
        data.id = ids
        rkAndQxButton(data).then(res => {
          this.$message.success(res)
          this.logining3 = false
          this.crud.toQuery()
        }).catch(e => {
          this.logining3 = false
        })
      }
    },
    // 显示日志
    doAsnTask(id) {
      this.$refs.asnTask.dialog = true
      this.$refs.asnTask.doInit(id)
    },
    //重置表单
    resetForm() {
      this.$refs["putForm"].resetFields();
      this.$data.putForm = JSON.parse(JSON.stringify(this.$options.data().putForm))
    },
    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;
        }
      }
    },
    //物料数据
    itemDataGet() {
      getItemsList().then(res => {
        this.itemListData = res;
      }).catch(e => {
        this.$message({
          showClose: true,
          message: '物料加载失败',
          type: 'error'
        });
      })
    },
  }
}
</script>

<style scoped>

</style>
