<template>
  <div class="vue-element-page-wrap" ref="tableContainer">
    <el-row class="page-search" justify="space-between" align="bottom">
      <el-form ref="queryFormRef" :model="queryParams" label-width="60px" label-position="left">
        <el-row :gutter="24" class="form-row">
          <el-col :span="6">
            <el-form-item label="发货单号" prop="SHIPREQUESTNAME">
              <el-Input v-model="queryParams.SHIPREQUESTNAME" clearable />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="page-search-btns">
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </div>
    </el-row>
    <div class="vue-element-page-table">
      <div class="page-table-operate">
        <div class="page-table-title">
          <div class="page-table-title-left">
            <span>发货单详情列表</span>
          </div>
        </div>
      </div>
      <el-table
        border
        :height="tableHeight"
        @row-click="selectRow"
        v-loading="loading_d"
        :data="list_d"
        highlight-current-row
        row-key="id"
        style="width: 100%;min-height:50px"
        @selection-change="detailSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <template v-for="(col, index) in column_d" :key="index">
          <el-table-column
            v-if="!col.hide"
            :label="col.header"
            :width="col.width"
            show-overflow-tooltip
          >
            <template #default="scope">
              <span>{{ scope.row[col.field] }}</span>
            </template>
          </el-table-column>
        </template>
      </el-table>
      <!-- <pagination
        v-if="page_d.total"
        :total="page_d.total"
        v-model:pageNumTo="page_d.pageNum"
        v-model:pageSizeTo="page_d.pageSize"
        @pagination="handleQuery_d"
      /> -->
    </div>
    <div class="vue-element-page-table">
      <div class="page-table-operate">
        <div class="page-table-title">
          <div class="page-table-title-left">
            <span>备货信息</span>
          </div>
        </div>
      </div>
      <el-table
        border
        v-loading="loading"
        :data="list"
        highlight-current-row
        row-key="id"
        style="width: 100%;min-height:50px"
        @selection-change="stockSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <template v-for="(col, index) in column" :key="index">
          <el-table-column
            v-if="!col.hide"
            :label="col.header"
            :width="col.width"
            show-overflow-tooltip
          >
            <template #default="scope">
              <span>{{ scope.row[col.field] }}</span>
            </template>
          </el-table-column>
        </template>
      </el-table>
      <!-- <pagination v-if="page.total" :total="page.total" v-model:pageNumTo="page.pageNum"
                v-model:pageSizeTo="page.pageSize" @pagination="handleQuery" /> -->
      <div class="page-table-operate">
        <div class="page-table-title"></div>
        <div>
          <el-button type="primary" v-loading="state.button_loading2" :disabled="state.button_but" @click="handleFn">绑定</el-button>
        </div>
      </div>
    </div>

    <div class="vue-element-page-table">
      <div class="page-table-operate">
        <div class="page-table-title">
          <div class="page-table-title-left">
            <span>备货详情列表</span>
          </div>
        </div>
      </div>
      <el-table
        border
        v-loading="loading_d"
        :data="list_detail"
        highlight-current-row
        row-key="id"
        style="width: 100%;min-height:50px"
      >
        <!-- @selection-change="handleSelectionChange" -->
        <!-- <el-table-column type="selection" width="55" /> -->
        <template v-for="(col, index) in column_det" :key="index">
          <el-table-column
            v-if="!col.hide"
            :label="col.header"
            :width="col.width"
            show-overflow-tooltip
          >
            <template #default="scope">
              <span>{{ scope.row[col.field] }}</span>
            </template>
          </el-table-column>
        </template>
      </el-table>
      <!-- <pagination
        v-if="page_d.total"
        :total="page_d.total"
        v-model:pageNumTo="page_d.pageNum"
        v-model:pageSizeTo="page_d.pageSize"
        @pagination="handleQuery_d"
      /> -->
      <div class="page-table-operate">
        <div class="page-table-title"></div>
        <div>
          <el-button type="primary" :disabled="state.button_state" @click="submit" v-loading="state.button_loading">提交</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
export default {
  name: 'InvoiceOrder'
}
</script>

<script lang="ts" setup>
import { reactive, ref, onMounted, toRefs, getCurrentInstance } from 'vue'
import { ElForm, ElTable, ElMessageBox } from 'element-plus'
import { getQueryPageList } from '@/api/common'
import {
  getSaleOrderInvoice,
  getSalePreOrderInvoice,
  getChargeBindBySale,
  BindSalePreToSale,
  Commit4CToERP
} from '@/api/StockOut'
import { bTableHeight } from "../../../composables/calcTableHeight";

const { tableContainer, tableHeight, updateTableHeight, handleResize } = bTableHeight(610);
const queryFormRef = ref(ElForm)

const state = reactive({
  button_loading : false,
  queryParams: {
    SHIPREQUESTNAME: ''
  },
  page: {
    pageNum: 1,
    pageSize: 10,
    total: 0
  },
  loading: false,
  list: [],
  column: [] as any,
  active_row: {},
  page_d: {
    pageNum: 1,
    pageSize: 10,
    total: 0
  },
  loading_d: false,
  list_d: [],
  list_detail: [],
  invoie_d: [] as any,
  column_d: [] as any,
  invoieChoose: [] as any,
  stockChoose: [] as any,
  detailChoose: [] as any,
  column_det: [] as any,
  button_state: false,
  button_but: false,
  button_loading2 : false,
})

const {
  button_but,
  button_state,
  column_det,
  list_detail,
  invoieChoose,
  detailChoose,
  stockChoose,
  invoie_d,
  loading,
  list,
  column,
  queryParams,
  page,
  page_d,
  loading_d,
  list_d,
  column_d,
  active_row
} = toRefs(state)

onMounted(() => {
  state.column_d = [
    { header: '物料号', field: 'MATERIALSPECNAME', hide: false },
    { header: '规格', field: 'SPECNAME', hide: false },
    { header: '阶段', field: 'PHASE', hide: false },
    { header: '组织', field: 'ERPFACTORY', hide: false },
    { header: '单号', field: 'SHIPREQUESTNAME', hide: false },
    { header: '业助', field: 'LASTEVENTUSER', hide: false },
    { header: '请求数量', field: 'REQUESTQUANTITY', hide: false },
    { header: '绑定数量', field: 'ASSIGNEDQUANTITY', hide: false },
    { header: '剩余数量', field: 'MINUSQTY', hide: false }
  ]
  state.column = [
    { header: '物料号', field: 'MATERIALSPECNAME', hide: false },
    { header: '规格', field: 'SPECNAME', hide: false },
    { header: '阶段', field: 'PHASE', hide: false },
    { header: '组织', field: 'ERPFACTORY', hide: false },
    { header: '单号', field: 'SHIPREQUESTNAME', hide: false },
    { header: '业助', field: 'LASTEVENTUSER', hide: false },
    { header: '备货数量', field: 'ASSIGNEDQUANTITY', hide: false }
  ]
  state.column_det = [
    { header: '物料号', field: 'MATERIALSPECNAME', hide: false },
    { header: '规格', field: 'SPECNAME', hide: false },
    { header: '阶段', field: 'PHASE', hide: false },
    { header: '组织', field: 'ERPFACTORY', hide: false },
    { header: '仓库', field: 'ERPLOCATION', hide: false },
    { header: '货位', field: 'LOCATIONNAME', hide: false },
    { header: '条码', field: 'MATERIALPACKINGNAME', hide: false },
    { header: '条码数量', field: 'MATERIALQUANTITY', hide: false },
    { header: '单号', field: 'SHIPREQUESTNAME', hide: false },
    { header: '备货数量', field: 'MATERIALQUANTITY2', hide: false }
  ]
  // handleQuery()
  
 updateTableHeight();
  window.addEventListener('resize', handleResize);
})

//选择发货详情列表
function detailSelectionChange(selection: any) {
  console.log('调用了', selection)
  state.detailChoose = selection
}
//选择备货
function stockSelectionChange(selection: any) {
  console.log('调用了', selection)
  state.stockChoose = selection
}
//选择发货单
function handleSelectionChange(selection: any) {
  console.log('调用了', selection)
  state.invoieChoose = selection
}
function handleQuery() {
  state.list_d = []
  // state.loading = true
  if(state.queryParams.SHIPREQUESTNAME == ''){
    ElMessageBox.alert('输入条件为空', '提醒框', {
      confirmButtonText: 'OK',
    })
    return ;
  }
  getSaleOrderInvoice(state.queryParams).then((res: any) => {
    console.log(res)
    if(res.resultObj.length == 0){
      ElMessageBox.alert('查无结果', '提醒框', {
        confirmButtonText: 'OK',
      })
    } else {
      state.list_d = res.resultObj
    }
    // state.loading = false
    // state.active_row = state.list[0]
    // if (state.active_row) {
    //     handleQuery_d()
    // }
  })
}
function getBhQuery(data: any) {
  state.loading = true
  getSalePreOrderInvoice(data).then((res: any) => {
    state.list = res.resultObj
    state.loading = false
    // state.active_row = state.list[0]
    // if (state.active_row) {
    //     handleQuery_d()
    // }
  })
}
function getDetailQuery(data: any) {
  state.loading = true
  getChargeBindBySale(data).then((res: any) => {
    state.list_detail = res.resultObj
    state.loading = false
    // state.active_row = state.list[0]
    // if (state.active_row) {
    //     handleQuery_d()
    // }
  })
}
function handleFn() {
  if (state.detailChoose.length > 1) {
    ElMessageBox.alert('发货单详情列表只能勾选一行', '提醒框', {
      confirmButtonText: 'OK'
    })
    return
  }
  console.log(state.detailChoose, state.stockChoose)
  let allQty = 0;
  state.stockChoose.map((value: any) => {
    allQty += parseFloat(value.ASSIGNEDQUANTITY)
  })
  if(allQty != parseFloat(state.detailChoose.MINUSQTY)) {
    ElMessageBox.alert('数量不一致', '提醒框', {
      confirmButtonText: 'OK'
    })
      return
  }
  if (state.detailChoose.length && state.stockChoose.length) {
    state.button_but = true
    state.button_loading2 = true;
    let salePreList = state.stockChoose.map((item: any) => {
							return {
								salePreNo: item.SHIPREQUESTNAME,
								salePreQty: item.ASSIGNEDQUANTITY,
								salePreMaterialSpecName:  item.MATERIALSPECNAME,
								salePreSdk_id: item.SDK_ID,
								salePrePhase: item.PHASE
							}
						})
    BindSalePreToSale({
      user: localStorage.getItem('userId'),
    //   ...state.detailChoose,  第一表格
    //   ...state.stockChoose 第二表格
        saleOrder: state.detailChoose[0].SHIPREQUESTNAME,
        // salePreNo:state.stockChoose[0].SHIPREQUESTNAME,
        // salePreQty:state.stockChoose[0].ASSIGNEDQUANTITY,
        saleQty:state.detailChoose[0].MINUSQTY,
        saleMaterialSpecName:state.detailChoose[0].MATERIALSPECNAME,
        // salePreMaterialSpecName:state.stockChoose[0].MATERIALSPECNAME,
        // salePreSdk_id:state.stockChoose[0].SDK_ID,
        saleSdk_id:state.detailChoose[0].SDK_ID,
        // salePrePhase:state.stockChoose[0].PHASE,
        salePhase:state.detailChoose[0].PHASE,
        salePreList: salePreList
    })
      .then((res: any) => {
        ElMessageBox.alert(res.message, '提醒框', {
          confirmButtonText: 'OK'
        })
        state.button_but = false
        state.button_loading2 = false;
        handleQuery();
        getDetailQuery({...state.active_row, user: localStorage.getItem('userId')})
    })
      .catch((error) => {
        ElMessageBox.alert(error, '提醒框', {
          confirmButtonText: 'OK'
        })
        state.button_but = false
        state.button_loading2 = false;
      })
  } else {
    ElMessageBox.alert('请各勾选一行', '提醒框', {
      confirmButtonText: 'OK'
    })
  }
}
// function handleQuery_d() {
//   state.loading_d = true
//   getQueryPageList({
//     queryId: 'GetMaterialShipRequestDetailList',
//     version: '10001',
//     params: {
//       userId: localStorage.getItem('userId'),
//       ...state.active_row
//     },
//     pageNum: state.page.pageNum,
//     pageSize: state.page.pageSize
//   }).then((res: any) => {
//     state.list_d = res.data.list
//     state.page_d.total = res.data.total
//     state.loading_d = false
//   })
// }

function resetQuery() {
  queryFormRef.value.resetFields()
  handleQuery()
}

function selectRow(row: any) {
  state.active_row = row
  getBhQuery({ ...row, user: localStorage.getItem('userId') })
  getDetailQuery({ ...row, user: localStorage.getItem('userId') })
}
//确认提交按钮
const submit = async () => {
    state.loading = true
    state.button_state = true;
    state.button_loading = true;
    Commit4CToERP({
      user: localStorage.getItem('userId'),
      shipRequestName: state.queryParams.SHIPREQUESTNAME,
      boxList:state.list_detail
    })
      .then((res: any) => {
        state.loading = false
        state.loading_d = false
        state.button_state = false
        state.button_loading = false;
        state.list_d = [];
        state.list = [];
        state.list_detail = [];
        resetQuery()
      })
      .catch((error: any) => {
        ElMessageBox.alert(error, '提醒框', {
          confirmButtonText: 'OK'
        })
        state.button_state = false
        state.button_loading = false;
      })
}
</script>

<style scoped lang="scss">
.form-row {
  padding-right: 100px;
  margin-bottom: 0;
}
</style>
