<template>
  <div class="page-box recycledAdjustmentPage" v-loading="Loading.appMainLoading">
    <!-- <tablePagination
      :currenButtonData="currenButtonData"
      :tableData="tableData"
      :tableLoading="Loading.tableLoading"
      :tableColumns="tableColumns"
      @rowDrop="rowDrop"
      :totalCount="totalCount"
      :multipleSelection="multipleSelection"
      :MaxResultCount="PageListParams.MaxResultCount"
      @topbutton="topbuttonHandle"
      @inlineDialog="inlineDialog"
      @sortChange="sortChange"
      @alertoldSkipCount="alertoldSkipCount"
      @alterResultCount="alterResultCount"
      @handleSelectionChange="handleSelectionChange"
      :currentPageProps="oldSkipCount"
      :quicklySearchOption="quicklySearchOption"
      @quicklySearchClick="quicklySearchClick"
      @quicklySearchClear="quicklySearchClear"
      :primarySearchOption="primarySearchOption"
      @overallSearchFormClick="overallSearchFormClick"
      :httpOverallSearchData="httpOverallSearchData"
    >
    </tablePagination> -->
    <!-- 新导入 disabledMethod 导入方式禁用 disabledIsAllowPartImport 是否局部导入禁用-->
    <!-- methodValue 导入方式默认选项  是否局部导入 默认选项  -->
    <!-- <importFile
      :loading="Loading.importLoading"
      :show="displayDialog.importDialog"
      :URL="URL"
      :disabledMethod="{ method1: false, method2: false, method3: false }"
      :disabledIsAllowPartImport="{ isAllowPartImport1: false, isAllowPartImport2: false, }"
      isAllowPartImportValue="1"
      @importClick="postImportMergeClick(arguments)"
      @postImportDown="importDown"
    ></importFile> -->
    <!-- <curren-Drawer
      :title="tableColumns"
      :DrawerLoading="Loading.DrawerLoading"
      :drawer="displayDialog.detailsDialog"
      :propsData="propsData"
      :Butttondata="DrawerButtonData"
      :tabsDesTions="tabsDesTions"
      @drawerShut="(val) => (displayDialog.detailsDialog = val)"
      @close-value="closeValue"
      @drawerbutton="drawerbutton"
      :tableColumns="detailsTableColumns"
      :totalCount="totalCountDetails"
      :MaxResultCount="MaxResultCountDetails"
      @alterResultCountDetails="alterResultCountDetails"
      @alertoldSkipCountDetails="alertoldSkipCountDetails"
    ></curren-Drawer> -->
    <!-- 新增弹窗 -->
    <el-dialog
      :visible="addPopShow"
      :modal-append-to-body="false"
      :append-to-body="false"
      :modal="false"
      :fullscreen="true">
      <div class="addPopMain">
        <div class="addPopContent addPopContent_FS">
          <span class="addPopTypeTitle">粉碎料</span>
          <currenTableFlex
            :flexTableData="addPopData_FS"
            :flexSearchOptions="editOptions"
            :flexTableColumns="addPopColumns_FS"
            @detailsDataPush="pushFS"
          ></currenTableFlex>
        </div>
        <div class="addPopContent addPopContent_YL">
          <span class="addPopTypeTitle">原料</span>
          <currenTableFlex
            ref="flexTable_Ref"
            :flexTableData="addPopData_YL"
            :flexSearchOptions="editOptions"
            :flexTableColumns="addPopColumns_YL"
            @detailsDataPush="pushYL"
            @updateSelectListTable="updateSelectListTable_YL"
            @changeSelect="changeSelect_YL"
            @clearHandle="clearHandle_YL"
          ></currenTableFlex>
        </div>
        <div class="addPopContent addPopContent_HB">
          <span class="addPopTypeTitle">混拌料</span>
          <currenTableFlex
            :flexTableData="addPopData_HB"
            :flexSearchOptions="editOptions"
            :flexTableColumns="addPopColumns_HB"
            :showAddBtn="false"
            :showAllDeleteButton="false"
            @detailsDataPush="pushHB"
          ></currenTableFlex>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addPopResetHandle">重 置</el-button>
        <el-button type="primary" @click="addPopSureHandle">提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { tableMixins } from "@/mixins/TableMixins"
import { LoadingMixins } from "@/mixins/LoadingMixins"
import { drawerMixins } from "@/mixins/drawerMixins"
import { TableHeaderMixins } from "@/mixins/TableHeaderMixins"
import { mixins } from "@/mixins/mixins"
import { requestData } from "@/utils/processButtonData"
import currenTableFlex from "@/components/currenTableFlex"
import { filterSelectMixins } from '@/mixins/filter-Select'
import detailsRules from '@/utils/rules';
import { getPageList,itemTransformNewCreate } from "@/api/wms-api"
import { postInventoryLabelCode_count } from "@/api/wms-core"
import store  from '@/store'
export default {
  name: "materialsAdjustmentFunc",
  mixins: [
    tableMixins,
    LoadingMixins,
    drawerMixins,
    TableHeaderMixins,
    mixins,
    filterSelectMixins,
  ],
  components:{
    currenTableFlex
  },
  watch: {
    'packingsYL_Options':{
      handler(val) {
        console.log(128,val)
        this.addPopColumns_YL[1].userOptions = val;
      },
      deep: true,
      immediate: true,
    },
  },
  data () {
    return {
      URL: 'wms/store/item-transform-request',
      //常用按钮数据
      currenButtonData: [
        this.defaultAddBtn(),//新增
        this.defaultImportBtn(),//导入
        this.defaultFieldSettingBtn(),//字段设置
        this.defaultFreshBtn(),//刷新
        this.defaultFilterBtn(),//筛选
      ],
      DrawerButtonData: requestData(this),
      addPopShow:true,//新增弹窗显隐
      //粉碎料信息
      addPopData_FS:[{
        itemCode:null,
        qty:null,
        locationCode:null,
      }],
      //粉碎料表头信息
      addPopColumns_FS:[
        { type: "filterSelect", label: "物品代码", prop: "itemCode", optionsLabel: "name", optionsValue: "code", 
          focus: (type,val) => { return this.getFilterList(type, val, "basedata/Item-Basic")},//this.isFilter("isRecycled","true")
          searchButton: (val) => { this.showSerarchPage(val, 'basedata/Item-Basic', 'ItemBasic', '物品选择', this.addPopData_HB) }, 
          width:"auto", searchButton:false
        },
        { type: "filterSelect", label: "目标库位", prop: "locationCode", optionsLabel: "name", optionsValue: "code", 
          focus: (type,val) => { return this.getFilterList(type, val, "basedata/Location",this.isFilter("type", "2"))},
          searchButton: (val) => { this.showSerarchPage(val, 'basedata/Location', 'InventoryBalance', '库位选择', this.addPopData_HB) }, 
          width:"auto", searchButton:false
        },
        { type: "input", validType:'pointNumber', label: "数量", prop: "qty", width:"auto",
          rules:  [{
            type: "number",
            trigger: ["change","blur"],
            validator: (rule, value, callback) => {
              let _index = rule.field.slice(8,9)
              let _qty = Number(this.addPopData_FS[_index].qty)
              if(_qty <= 0){
                return callback(new Error('数量必须大于0'))
              }else{
                callback()
              }
            }
          }]
        },
      ],
      //原料信息
      addPopData_YL:[{
        itemCode:null,
        packingCode:null,
        inventoryQty:null,
        locationCode:null,
        qty:null
      }],
      packingsYL_Options:[],
      itemPackings_YL:{},
      //原料表头信息
      addPopColumns_YL:[
        { type: "filterSelect", label: "物品代码", prop: "itemCode", optionsLabel: "name", optionsValue: "code", 
          focus: (type,val) => { return this.getFilterList(type, val, "basedata/Item-Basic",this.isFilter("type", "10C02"))},
          width:"auto"
        },
        // { type: "filterSelect", label: "箱标签", prop: "packingCode", 
        //   // optionsLabel: "itemCode", optionsValue: "packingCode", 
        //   focus: (type,val) => { return this.getFilterList(type, val, "wms/inventory/Inventory-Balance")},
        //   colSpan: 12 
        // },
        { type: "select", label: "箱码", prop: "packingCode", 
          optionsLabel: "packingCode", optionsValue: "packingCode", 
          userOptions:this.packingsYL_Options,width:"auto",
          filterable:true,clearable:true
        },
        // todo: 库存数量、库位：自动带出
        { label: "库存数量", prop: "inventoryQty", width:"auto" },
        { label: "库位", prop: "locationCode", width:"auto" },
        // todo: 小于等于库存数量
        { type: "input", validType:'pointNumber', label: "数量", prop: "qty", width:"auto",
          rules:  [{
            type: "number",
            trigger: ["change","blur"],
            validator: (rule, value, callback) => {
              let _index = rule.field.slice(8,9)
              if(this.addPopData_YL[_index].qty == null){
                return callback(new Error('数量不能为空'))
              }
              let _qty = Number(this.addPopData_YL[_index].qty)
              let _invenQty = Number(this.addPopData_YL[_index].inventoryQty)
              if(_qty <= 0 || _qty > _invenQty){
                return callback(new Error('数量必须大于0，且不大于库存数量'))
              }else{
                callback()
              }
            }
          }]
        },
      ],
      //混拌料信息
      addPopData_HB:[{
        itemCode:null,
        qty:null,
        locationCode:null,
      }],
      //混拌料表头信息
      addPopColumns_HB:[
        { type: "filterSelect", label: "物品代码", prop: "itemCode", optionsLabel: "name", optionsValue: "code", 
          focus: (type,val) => { return this.getFilterList(type, val, "basedata/Item-Basic")},
          searchButton: (val) => { this.showSerarchPage(val, 'basedata/Item-Basic', 'ItemBasic', '物品选择', this.addPopData_HB) }, 
          width:"auto", searchButton:false
        },
        { type: "filterSelect", label: "目标库位", prop: "locationCode", optionsLabel: "name", optionsValue: "code", 
          focus: (type,val) => { return this.getFilterList(type, val, "basedata/Location")},
          searchButton: (val) => { this.showSerarchPage(val, 'basedata/Location', 'InventoryBalance', '库位选择', this.addPopData_HB) }, 
          width:"auto", searchButton:false
        },
        { type: "input", validType:'pointNumber', label: "数量", prop: "qty", width:"auto",
          rules:  [{
            type: "number",
            trigger: ["change","blur"],
            validator: (rule, value, callback) => {
              let _index = rule.field.slice(8,9)
              let _qty = Number(this.addPopData_HB[_index].qty)
              if(_qty <= 0){
                return callback(new Error('数量必须大于0'))
              }else{
                callback()
              }
            }
          }]
        },
      ],
      itemStagingLists:{},//物料相关内容暂存
      locationStagingLists:{},//库位相关内容暂存
      needNewPackingList:[],//需要生成项目的列表信息（N个粉碎料+1个混拌料）
      newPackArr:[],//已生成的新箱码
    };
  },
  mounted () {
    // this.paging();
  },
  methods:{
    //过滤查询条件
    isFilter (val, data) {
      let filter = [
        {
          logic: "And",
          column: val,
          action: "==",
          value: data
        }
      ]
      return filter
    },
    topbuttonHandle(val){
      if(val == 'newly'){
      }else{
        this.topbutton(val)
      }
    },
    // 初始化数据
    initAddPopData(){
      this.addPopData_FS=[{
        itemCode:null,
        qty:null,
        locationCode:null,
      }]
      this.addPopData_YL=[{
        itemCode:null,
        packingCode:null,
        inventoryQty:null,
        locationCode:null,
        qty:null
      }]
      this.addPopData_HB=[{
        itemCode:null,
        qty:null,
        locationCode:null,
      }]
    },
    // 重置
    addPopResetHandle(){
      this.$confirm('重置后，字段设置将恢复初始设置，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.initAddPopData()
      }).catch(() => {

      });
    },
    // todo:最后提交接口
    lastCommitHttp(){
      console.log(336,this.newPackArr)
      this.addPopColumns_YL.forEach(item=>{
        item.remark = '原料'
      })
      let _allDetails = [
        ...this.addPopData_FS,
        ...this.addPopColumns_YL
      ]
      let _toData = this.addPopColumns_HB[0]
      let _toItemInfo = this.itemStagingLists[_toData.itemCode]
      let _toLocationInfo = this.locationStagingLists[_toData.locationCode]
      let _details = []
      _allDetails.forEach((item,index)=>{
        let _itemInfo = this.itemStagingLists[item.itemCode]
        let _locationInfo = this.locationStagingLists[item.locationCode]
        let _item = {
          remark: item.remark || null,
          itemCode: item.itemCode || null,
          itemName: _itemInfo.name || null,
          itemDesc1: _itemInfo.desc1 || null,
          itemDesc2: _item_info.desc2 || null,
          "fromPackingCode": item.packingCode || null,//todo:粉碎料无packingCode，是否需要添加选择项
          toPackingCode: this.newPackArr[index],
          toItemCode: _toData.itemCode || null,
          toItemName: _toItemInfo.name || null,
          toItemDesc1: _toItemInfo.desc1 || null,
          toItemDesc2: _toItemInfo.desc2 || null,
          uom: _item_info.basicUom || null,
          fromQty: item.qty,
          toQty: _toData.qty,
          "fromSupplierBatch": null,//todo
          "fromArriveDate": null,//todo
          "fromProduceDate": null,//todo
          "fromExpireDate": null,//todo
          "fromLot": null,//todo
          "fromStatus": null,//todo
          fromLocationCode: item.locationCode || null,
          fromLocationArea: _locationInfo.areaCode || null,
          fromLocationGroup: _locationInfo.locationGroupCode || null,
          fromLocationErpCode: _locationInfo.erpLocationCode || null,
          fromWarehouseCode: _locationInfo.warehouseCode || null,
          "fromContainerCode": null,//todo
          "toSupplierBatch": null,//todo
          "toArriveDate": null,//todo
          "toProduceDate": null,//todo
          "toExpireDate": null,//todo
          "toLot": null,//todo
          "toStatus": null,//todo
          toLocationCode: _toData.locationCode || null,
          toLocationArea: _toLocationInfo.areaCode || null,
          toLocationGroup: _toLocationInfo.locationGroupCode || null,
          toLocationErpCode: _toLocationInfo.erpLocationCode || null,
          toWarehouseCode: _toLocationInfo.warehouseCode || null,
          "toContainerCode": null,//todo
          worker: store.getters.name.userName,//todo
          "reasonCode": null,//todo
        }
        _details.push(_item)
      })
      let _recDetail= [
        {
          remark: null,
          itemCode: _toItemInfo.code || null,
          itemName: _toItemInfo.name || null,
          itemDesc1: _toItemInfo.desc1 || null,
          itemDesc2: _toItemInfo.desc2 || null,
          "lot": null,//todo
          "supplierBatch": null,//todo
          "arriveDate": null,//todo
          "produceDate": null,//todo
          "expireDate": null,//todo
          packingCode: this.newPackArr[this.newPackArr.length - 1],
          "containerCode": null,//todo
          uom: _toItemInfo.basicUom || null,
          qty: _toData.qty,
          stdPackQty: Number(_toItemInfo.stdPackQty) || 0,
          locationCode: _toData.locationCode || null,
          locationArea: _toLocationInfo.areaCode || null,
          locationGroup: _toLocationInfo.locationGroupCode || null,
          locationErpCode: _toLocationInfo.erpLocationCode || null,
          "status": null,//todo
          warehouseCode: _toLocationInfo.warehouseCode || null,
          "reasonCode": null,//todo
        }
      ]
      let _finalData = {
        "tenantId": null,//todo
        "remark": null,//todo
        "extraProperties": null,//todo
        worker: store.getters.name.userName,//todo
        activeDate: new Date(),//todo
        "number": null,//todo
        "requestNumber": null,//todo
        "jobNumber": null,//todo
        details:_details,
        recDetails:_recDetail
      }
      itemTransformNewCreate(_finalData)
        .then(item=>{
          this.$successMsg("提交成功！")
          this.initAddPopData()
          this.Loading.appMainLoading = false
        })
        .catch(err=>{
          this.$errorMsg("提交失败！请重试")
          this.Loading.appMainLoading = false
        })
    },
    //递归生成箱码部分
    async resendHandle(index){
      this.Loading.appMainLoading = true
      if(index >= this.needNewPackingList.length){
        // 箱码全部生成进行提交
        this.lastCommitHttp()
        return
      }
      let _resultBack = await this.createNewPack(index)
      //如果成功了，继续发送
      if(_resultBack == 1){
        let _index = Number(index) + 1
        _this.resendHandle(_index)
      }
      //失败了提示不进行任何处理
      else{
        this.Loading.appMainLoading = false
        this.$errorMsg(`创建箱码失败，请重新提交`)
      }
    },
    // 生成新箱码
    async createNewPack(index){
      let _item = this.needNewPackingList[index]
      let _item_info = this.itemStagingLists[_item.itemCode]
      let _location_info = this.locationStagingLists[_item.locationCode]
      let _creatPackData = {
        itemCode: _item_info.code || null,
        itemName: _item_info.name || null,
        itemDesc1: _item_info.desc1 || null,
        itemDesc2: _item_info.desc2 || null,
        lot: null,//todo
        supplierBatch: null,//todo
        arriveDate: null,//todo
        produceDate: null,//todo
        expireDate: null,//todo
        stdPackQty: Number(_item_info.stdPackQty) || 0,
        uom: _item_info.basicUom || null,
        qty: Number(_item.qty),
        labelStatus: 1,//todo
        recommendLocationCode: _location_info.code || null,//todo
        locationErpCode: _location_info.erpLocationCode || null,//todo
        containerCode: null,//todo
        supplierCode: null,//todo
        poNumber: null,//todo
        rpNumber: null,//todo
        asnNumber: null,//todo
        qLevel: _item_info.elevel || null,//todo
        qualityFile: null,//todo
        prodLine: null,//todo
        team: null,//todo
        shift: null,//todo
        specifications: null,//todo
        supplierName: null,//todo
        supplierSimpleName: null,//todo
        supplierItemCode: null,//todo
        supplierItemName: null,//todo
        labelType: null,//todo
        planArriveDate: null,//todo
        remark:null,
      }
      let resultBack = null
      // // 生成标签（接口）
      postInventoryLabelCode_count({count:1}, _creatPackData)
        .then(res=>{ resultBack = 1;this.newPackArr[index] = res })
        .catch(err=>{ resultBack = 0 })

      return resultBack
    },
    // 提交
    addPopSureHandle(){
      // 检测【粉碎料】信息是否填全
      let _err_FS=0
      this.addPopData_FS.forEach(item=>{
        if(!item.itemCode || Number(item.qty <= 0) || !item.locationCode){
          _err_FS++
        }
      })
      if(_err_FS > 0){
        return this.$warningMsg("粉碎料信息未填全，请填写")
      }
      
      // 检测【原料】信息是否填全
      let _err_YL=0
      this.addPopData_YL.forEach(item=>{
        if(!item.itemCode || Number(item.inventoryQty <= 0) || Number(item.qty <= 0) || !item.locationCode || !item.packingCode || item.packingCode.length <= 0){
          _err_YL++
        }
      })
      if(_err_YL > 0){
        return this.$warningMsg("原料信息未填全，请填写")
      }

      // 检测【混拌料】信息是否填全
      let _err_HB=0
      this.addPopData_HB.forEach(item=>{
        if(!item.itemCode || Number(item.qty <= 0) || !item.locationCode){
          _err_HB++
        }
      })
      if(_err_HB > 0){
        return this.$warningMsg("混拌料信息未填全，请填写")
      }

      // 全部通过验证
      // 创建【粉碎料】箱码
      // 先生成箱码
      let _new_FS = {}
      this.needNewPackingList = [
        ...this.addPopData_FS,
        ...this.addPopData_HB
      ]
      this.resendHandle(0)
      console.log('粉碎料',this.addPopData_FS)
      console.log('原料',this.addPopData_YL)
      console.log('混拌料',this.addPopData_HB)
    },
    // 粉碎料下拉
    pushFS(data){
      if(data[1].prop == "itemCode"){
        this.itemStagingLists[data[2]] = data[0]
      }
      if(data[1].prop == "locationCode"){
        this.locationStagingLists[data[2]] = data[0]
      }
    },
    // 原料下拉
    pushYL(data){
      if(data[1].prop="itemCode"){
        let params = {
          Sorting: "",
          MaxResultCount: 1000,
          SkipCount: 0,
          condition: {
            filters: [{
              logic: "And",
              column: "itemCode",
              action: "==",
              value: data[0].code
            }]
          }
        }
        this.Loading.appMainLoading = true
        // todo:字段确定
        console.log(311,data[3].$index)
        this.addPopData_YL[data[3].$index].packingCode = null
        this.addPopData_YL[data[3].$index].inventoryQty = null
        this.addPopData_YL[data[3].$index].locationCode = null
        getPageList(params, "wms/inventory/inventory-balance").then((res)=>{
          this.itemPackings_YL[data[0].code] = res.items 
          this.Loading.appMainLoading = false
        })
        .catch(err=>{
          this.Loading.appMainLoading = false
        })
      }
    },
    // 原料selet更改
    changeSelect_YL(prop, val,item,searchData,scope){
      if(prop == 'packingCode'){
        let _currentRow = this.itemPackings_YL[searchData.itemCode].filter(item=>{
          return val == item.packingCode
        })
        // todo:字段确定
        this.addPopData_YL[scope.$index].inventoryQty = _currentRow.length > 0 ? _currentRow[0].qty : null
        this.addPopData_YL[scope.$index].locationCode = _currentRow.length > 0 ? _currentRow[0].locationCode : null
      }
    },
    // 原料清空
    clearHandle_YL(item,scope){
      this.addPopData_YL[scope.$index].packingCode = null
      this.addPopData_YL[scope.$index].inventoryQty = null
      this.addPopData_YL[scope.$index].locationCode = null
      this.addPopData_YL[scope.$index].qty = null
    },
    // 原料select展开/关闭
    updateSelectListTable_YL(data,item,scope,tableData){
      // 展开
      if(data){
        if(item.prop == "packingCode"){
          this.packingsYL_Options = []
          if(!tableData[scope.$index].itemCode || tableData[scope.$index].itemCode.length == 0){
            this.$warningMsg("请先选择物料")
          }
          if(this.itemPackings_YL[tableData[scope.$index].itemCode]){
            this.packingsYL_Options = this.itemPackings_YL[tableData[scope.$index].itemCode]
          }
        }
      }
    },
    // 混拌料下拉
    pushHB(data){
      if(data[1].prop == "itemCode"){
        this.itemStagingLists[data[2]] = data[0]
      }
      if(data[1].prop == "locationCode"){
        this.locationStagingLists[data[2]] = data[0]
      }
    },
  }
};
</script>
<style lang="scss" scoped>
@import "../../../styles/mainbasicData.scss";

.addPopMain{
  height:100%;

  .addPopContent{
    position:relative;
    padding:0 20px;

    .addPopTypeTitle{
      position:absolute;
      left:0;
      top:10px;
      border-left:#66b1ff solid 6px;
      padding-left:10px;
      height:28px;
      line-height:28px;
      overflow:hidden;
      font-size:18px;
      margin-left: 20px;
    }
  }

  .addPopContent_FS{
    height:calc(50% - 100px);
    margin-bottom:10px;
  }

  .addPopContent_YL{
    height: calc(50% - 70px);
    padding: 15px 20px;
    background: #d4e6fd;
  }

  .addPopContent_HB{
    height:160px;
    padding-top:28px
  }
}
</style>
<style lang="scss" >
.recycledAdjustmentPage {
  .el-dialog .el-dialog__body {
    padding: 0 !important;
  }
  
  .el-form-item{
    margin-bottom:0 !important
  }
}

</style>