<template>
  <div class="page-box SupplierAsnPage" v-loading="Loading.appMainLoading">
    <tablePagination
      :currenButtonData="currenButtonData"
      :tableData="tableData"
      :tableLoading="Loading.tableLoading"
      :tableColumns="tableColumns"
      @rowDrop="rowDrop"
      :tableSelection="false"
      :totalCount="totalCount"
      :multipleSelection="multipleSelection"
      :MaxResultCount="PageListParams.MaxResultCount"
      @topbutton="topbutton"
      @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>
    <!-- 表格导入 -->
    <!-- <upload-excel-component 
      :DrawerLoading="Loading.DrawerLoading"
      :before-upload="beforeUpload"
      :show="displayDialog.importDialog"
      @postImportDown="importDown()"
      @submitForm="uploadSubmitForm"
    /> -->
    <!-- 抽屉 -->
    <curren-Drawer
      :title="tableColumns"
      :DrawerLoading="Loading.DrawerLoading"
      :drawer="displayDialog.detailsDialog"
      :propsData="propsData"
      :tabsDesTions="tabsDesTions"
      :Butttondata="[]"
      @drawerShut="(val) => (displayDialog.detailsDialog = val)"
      @handleCommand="drawerHandle"
      @close-value="closeValue"
      :currenButtonData="currenButtonData"
      :tableColumns="detailsTableColumns"
      @handleSelectionChange="handleSelectionChange"
      @inlineDialog="inlineDialog"
      :totalCount="totalCountDetails"
      :MaxResultCount="MaxResultCountDetails"
      @alterResultCountDetails="alterResultCountDetails"
      @alertoldSkipCountDetails="alertoldSkipCountDetails"
    ></curren-Drawer>
  </div>
</template>
<script>
import { supplierAsnCreateMany } from "@/api/wms-api"
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 UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { supplierAsnExcel } from "@/filters/excelOrReportsOption";
import {SupplierAsnCtypeStaBack} from "@/filters/status"
import { formatTimeToT,formatTimeStampToNorm } from "@/utils/formatTime"
import store  from '@/store'
export default {
  name: "SupplierAsn",
  mixins: [
    tableMixins,
    LoadingMixins,
    drawerMixins,
    TableHeaderMixins,
    mixins,
  ],
  components: { UploadExcelComponent },
  computed: {
    editDialog: {
      get: function () {
        return this.displayDialog.newDialog || this.displayDialog.editDialog;
      },
    },
  },
  data () {
    return {
      URL: 'wms/store/supplier-asn',
      // importUploadURL:"wms/store/supplier-asn/newImport",
      //常用按钮数据
      currenButtonData: [
        // this.defaultImportBtn(),//导入
        this.defaultFieldSettingBtn(),//字段设置
        this.defaultFreshBtn(),//刷新
        this.defaultFilterBtn(),//筛选
      ],
    };
  },
  mounted () {
    this.paging();
  },
  methods: {
    // 创建外部主表数据
    build(data,str){
      
      return {
        str:str,//用于对比数据
        details:[],
        supplierCode:data[supplierAsnExcel.supplierCode],
        planUserCode:data[supplierAsnExcel.planUserCode],
        contactUserName:data[supplierAsnExcel.planUserCode],
        planArriveDate:formatTimeStampToNorm(data[supplierAsnExcel.planArriveDate],'datetime'),
        shipDate:formatTimeStampToNorm(data[supplierAsnExcel.shipDate],'datetime'),
        remark:data[supplierAsnExcel.remark],
        // 接口需要默认配置项：
        company:localStorage.getItem("company"),
        warehouseCode:localStorage.getItem("warehouseCode"),//仓库
        dockCode:"FWDY",//收货口
        rpNumber:"123456",//要货计划单号
        timeWindow:"00:00-24:00",//时间窗口
      }
    },
    // 创建详情detail数据
    builddDeails(data,item){
      data.details.push({
        ctype:SupplierAsnCtypeStaBack(item[supplierAsnExcel.details.ctype]) || null,
        projectCode:item[supplierAsnExcel.details.projectCode] || null,
        itemCode:item[supplierAsnExcel.details.itemCode] || null,
        uom:item[supplierAsnExcel.details.uom] || null,
        qty:item[supplierAsnExcel.details.qty] || null,
        recommendErpCode:item[supplierAsnExcel.details.recommendErpCode] || null,
        lot:item[supplierAsnExcel.details.lot] || null,
        supplierBatch:item[supplierAsnExcel.details.lot] ? item[supplierAsnExcel.details.lot].replaceAll('-','') : '',
        produceDate:formatTimeStampToNorm(item[supplierAsnExcel.details.produceDate],'datetime'),
        expireDate:formatTimeStampToNorm(item[supplierAsnExcel.details.expireDate],'datetime'),
        packingCode:item['明细-箱标签'] || null,
        // 默认配置项：
        warehouseCode:localStorage.getItem("warehouseCode"),//仓库
      })
    },
    uploadSubmitForm(index,data){
      // 确定
      if(index == '1'){
        let _result = data.results;
        let _data = [];
        // 查询物料代码是否重复
        // let _itemArr = [];
        // let _hasSame = false
        // data.results.forEach(item=>{
        //   if(_itemArr.indexOf(item[supplierAsnExcel.details.itemCode]) >= 0){
        //     _hasSame = true
        //   }else{
        //     _itemArr.push(item[supplierAsnExcel.details.itemCode])
        //   }
        // })
        // if(_hasSame){
        //   this.$message.error("模板中存在相同物料代码，请修改模板重新导入")
        //   return 
        // }
        // 查重重组
        for(let i=0;i<_result.length;i++){
          let _itemStr = ""
          // _itemStr =(_result[i][supplierAsnExcel.poNumber] || '') + (_result[i][supplierAsnExcel.number] || '')
          let entity=this.build(_result[i],_itemStr);
    
         if(_data.find(e => e.str == _itemStr)){
          continue;
         }
         _result.forEach((element,key) => {
            // let temp =(element[supplierAsnExcel.poNumber] || '') + (element[supplierAsnExcel.number] || '')
            let temp = ""
            if(temp==_itemStr){
              this.builddDeails(entity,element);
            }
          });
          _data.push(entity);
        }
        // 提交数据处理
        _data.forEach(item=>{
          item.createType = 1
          item.planArriveDate = formatTimeToT(item.planArriveDate)
          item.shipDate = formatTimeToT(item.shipDate)
          item.details.forEach(item_d=>{
            item_d.produceDate = formatTimeToT(item_d.produceDate)
            item_d.expireDate = formatTimeToT(item_d.expireDate)
            item_d.itemName = ""
          })
          item.worker = store.getters.name.userName;
          return delete item.str
        })
        this.Loading.appMainLoading = true
        supplierAsnCreateMany(_data)
          .then((response) => {
            this.$message.success("创建成功！")
            this.Loading.appMainLoading = false
            this.displayDialog.importDialog = false;
            this.paging();
          })
          .catch(()=>{
            this.Loading.appMainLoading = false
            this.$message.error("创建失败，请重试。")
          })
      }
      // 取消
      else{
        if(!data.results || data.results.length <= 0){
          this.displayDialog.importDialog = false;
          return;
        }
        this.$confirm('您还未提交, 是否取消?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.displayDialog.importDialog = false;
        }).catch(() => {
          document.getElementsByClassName("v-modal")[0].style.display = "none"
        });
      }
    },
    beforeUpload(file) {
      // const isLt1M = file.size / 1024 / 1024 < 1
      // if (isLt1M) {
      //   return true
      // }
      // this.$message({
      //   message: 'Please do not upload files larger than 1m in size.',
      //   type: 'warning'
      // })
      // return false
      return true
    }

  },
};
</script>
<style lang="scss" scoped>
@import "../../../styles/mainbasicData.scss";
</style>
<style lang="scss">
.SupplierAsnPage{
  .el-dialog__body{
    padding-top:10px !important
  }
}
</style>
