<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.params" :rules="rulesParam" :inline="true" label-position="left">
        <el-row :gutter="20">
          <el-col :span="6" class="col_height">
            <el-form-item label="盘点类型" prop="checkType">  
              <el-select v-model="queryParams.params.checkType" placeholder="选择盘点类型" clearable>
              <el-option value="盘盈" label="盘盈"></el-option>
              <el-option value="盘亏" label="盘亏"></el-option>
            </el-select>
            </el-form-item>
            </el-col>
          <el-col :span="6" class="col_height">
            <el-form-item label="组织" prop="erpFactory">
              <el-select filterable v-model="queryParams.params.erpFactory" placeholder="下拉选择组织" @change="ERPLocationQuery">
                <el-option v-for="item in ERPFactoryList" :key="item.ERPFACTORY" :label="item.DESCRIPTION" :value="item.ERPFACTORY"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" class="col_height">
            <el-form-item label="仓库" prop="erpLocation">
              <el-select v-model="queryParams.params.erpLocation" clearable collapse-tags placeholder="请选择仓库"
                         popper-class="custom-header" :max-collapse-tags="1"
                         @visible-change="GetLocationListForSomeERPLocation" filterable>
                <template #header>
                </template>
                <el-option v-for="item in state.ERPLocationList" :key="item.ENUMVALUE" :label="item.DESCRIPTION"
                           :value="item.ENUMVALUE" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" class="col_height">
            <el-form-item label="货位" prop="location">
              <el-select v-model="queryParams.params.location" clearable collapse-tags placeholder="请选择货位"
                         popper-class="custom-header" :max-collapse-tags="1"
                         remote :remote-method="handleInput" filterable>
                <template #header>
                </template>
                <el-option v-for="item in state.LocationList" :key="item.storageName" :label="item.storageName"
                           :value="item.storageName" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" class="col_height">
            <el-form-item label="物料编号" prop="materialSpecName">
              <el-Input v-model="queryParams.params.materialSpecName" placeholder="输入物料编号" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="6" class="col_height">
            <el-form-item label="差异数量" prop="nums">
              <el-Input-number min="0" v-model="queryParams.params.nums" placeholder="输入差异数量" clearable/>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6" class="col_height">
            <el-form-item label="批次号" prop="CHARGE">
              <el-Input v-model="queryParams.params.CHARGE" placeholder="输入批次号" clearable/>
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
      <div class="page-search-btns">
        <!-- <el-button type="primary" @click="handleSearch">搜索</el-button> -->
        <!-- <el-button type="primary" @click="resetQuery">重置</el-button> -->
        <el-button type="primary" @click="handleConfirm" v-loading="state.loadingC">确认</el-button>
      </div>
    </el-row>
    <!-- table 区域-->
    <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 :height="tableHeight" border v-loading="loading"
                :data="state.dataList" highlight-current-row row-key="id" style="width: 100%">
        <template v-for="(col, index) in tableConfig.column" :key="index">
          <el-table-column v-if="!col.hide" :label="col.header" :prop="col.field" show-overflow-tooltip
                :width="col.width" :sort-orders="['descending', 'ascending']" :sortable="true"/>
        </template>
      </el-table>
      <div>
        <el-form :model="state.updateParams" ref="formDataRef" label-position="left" :rules="rules" style="margin-top: 10px;">
          <el-row :gutter="22">
            <el-col :span="5">
              <el-form-item label="成本中心" prop="costName">
                <el-select filterable v-model="state.updateParams.costName" placeholder="下拉选择成本" size="small">
                  <el-option v-for="item in state.costCenterList" :key="item.costCode"
                    :label="item.costName" :value="item.costCode" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-button type="primary" @click="submit" v-loading.fullscreen.lock="state.loadings">提交</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script lang="ts">
export default {
  name: 'auxiliaryOutIn'
}
</script>
<script lang="ts" setup>
import { reactive, ref, onMounted, toRefs, getCurrentInstance } from 'vue'
import { ElForm, ElMessageBox, ElTable } from 'element-plus'
import { getQueryPageList,getQueryList } from '@/api/common'
import { areAllNotEmpty, msToDate } from '@/utils/CommonUtil';
import { localStorage } from '@/utils/storage'
import { confirm,QTRCommit,QTCCommit } from '@/api/StockIn'
import { bTableHeight } from '@/composables/calcTableHeight'
import { getORG } from '@/api/auth'
import { search } from '@/api/wareHouse'
import { getCostCenter } from '@/api/check'
// 公共变量
const { tableContainer, tableHeight, updateTableHeight, handleResize } = bTableHeight(310)
const { proxy }: any = getCurrentInstance()
const tableConfig = ref({
  loading: false,
  column: [] as any,
  data: []
})
const queryFormRef = ref()
const formDataRef = ref()
// 变量
const state = reactive({
  dataList: [] as any, // 表格数据
  costCenterList: [],
  loadings: false, // 更新按钮
  loadingC: false,
  loading: false, // 表格
  // 组织
  ERPFactoryList: [] as any,
  // 仓库
  ERPLocationList: [] as any,
  // 货位
  LocationList: [] as any,
  commitDate: '',
  // 查询参数
  queryParams: {
    queryId: 'AuxiliaryOutIn',
    version: '00001',
    params: {
      siteName: localStorage.get('siteName') || 'SDK',
      user: localStorage.get('userName'),
      materialSpecName: '', // 物料编号
      location: '',// 货位
      erpLocation: '',
      erpFactory: '',
      CHARGE: '',
      ERPLOCATION: '',
      LOCATIONNAME: '',
      PHASE: '',
      DESC_CN: '',
      REMARK: '',
      checkType: '',
      nums: 0,
    },
    pageNum: 1,
    pageSize: 10
  },
  queryParamsERPLocation: {
    queryId: "GetErpLocationList",
    version: "WEB00001",
    params: {
      SITENAME: localStorage.get("siteName") || 'SDK',
      ERPFACTORYNAME: '',
    },
    pageNum: 1,
    pageSize: 10
  },
  // 更新参数
  updateParams: {
    costName: '',
  },
  // 条件
  rules: {
    costName: [{required: true, message: '请选择成本中心', trigger: 'blur'}],
  },
  rulesParam: {
    checkType: [{required: true, message: '请选择盘点类型', trigger: 'blur'}],
    erpFactory: [{required: true, message: '请选择组织', trigger: 'blur'}],
    erpLocation: [{required: true, message: '请选择仓库', trigger: 'blur'}],
    materialSpecName: [{required: true, message: '请输入料号', trigger: 'blur'}],
    nums: [{required: true, message: '请输入数量', trigger: 'blur'}],
  },
})
const { queryParams, loading, ERPFactoryList, rules, rulesParam } = toRefs(state)

// 加载
onMounted(() => {
  var newDate = new Date()
  var year = newDate.getFullYear()
  var moth = newDate.getMonth() + 1
  if (moth < 10) moth = '0' + moth
  var day = newDate.getDate()
  if (day < 10) day = '0' + day
  state.commitDate = year + '-' + moth + '-' + day;

  tableConfig.value.column = [
    { header: '二维码', field: 'MATERIALPACKINGNAME', hide: false },
    { header: '组织', field: 'ERPFACTORY', hide: false },
    // { header: '组织(CN)', field: 'ERPFACTORYDESC', hide: false, width: 100 },
    { header: '仓库编码', field: 'ERPLOCATION', hide: false, width: 100 },
    // { header: "仓库名称", field: "ERPLOCATIONDESC", hide: false, width: 100 },
    { header: '货位', field: 'LOCATIONNAME', hide: false },
    // { header: '货位名称', field: 'LOCATIONNAMEDESC', hide: false, width: 100 },
    { header: '物料编号', field: 'MATERIALSPECNAME', hide: false, width: 140 },
    { header: '差异数量', field: 'MATERIALQUANTITY', hide: false, width: 140 },
    { header: '规格', field: 'TRUEGG', hide: false, width: 100 },
    { header: '批次号', field: 'CHARGE', hide: false, width: 180 },
  ]
  getErpFactory()
  updateTableHeight()
  getCost()
  window.addEventListener('resize', handleResize)
})

function getCost(){
  getCostCenter({erpFactory: JSON.parse(localStorage.get('orgNo'))}).then((res: any) => {
    state.costCenterList = res.data;
  })
}

function resetQuery() {
  // queryFormRef.value.resetFields();
  state.queryParams.params.erpFactory = ''
  state.queryParams.params.erpLocation = ''
  state.queryParams.params.location = ''
  state.queryParams.params.materialSpecName = ''
  state.queryParams.params.nums = 0
}

// 加载组织
function getErpFactory() {
  getORG({ orgNo: null }).then((res: any) => {
    state.ERPFactoryList = res.resultObj
    state.ERPFactoryList.unshift({
      ERPFACTORY: ''
    })
  })
}

//ERP库位查询
function ERPLocationQuery() {
  state.queryParamsERPLocation.params.ERPFACTORYNAME = state.queryParams.params.erpFactory
  getQueryList(state.queryParamsERPLocation).then((res: any) => {
    state.ERPLocationList = res.data;
    state.ERPLocationList.push({DESCRIPTION:'6101',ENUMVALUE: '6101'}) ;
  });
}
function GetLocationListForSomeERPLocation(value: any) {
  if (!areAllNotEmpty(state.queryParams.params.erpFactory)) {
    proxy.$ElMessage.warning('当前还未选择组织');
    state.queryParams.params.ERPLOCATION = ''
    state.ERPLocationList = []
    return
  }
  if (!areAllNotEmpty(state.queryParams.params.ERPLOCATION)) {
    return
  }
}

function handleInput(val: any) {
    let index = [1, 3, 4, 7, 8]
    if (index.indexOf(val.length) > -1) {
      state.LocationList = []
      search({
        storageName: val,
        orgNo: JSON.parse(localStorage.get('orgNo'))
      }).then((res:any) => {
        if (res.resultObj) {
          state.LocationList = res.resultObj
        } else {
          proxy.$ElMessage.warning(res.message);
        }
      })
    }
  }
  function handleSearch(){
    if(!state.queryParams.params.CHARGE){
      proxy.$ElMessage.warning("请输入批次号");
      return
    }
    getQueryPageList(state.queryParams).then(res => {
      if(res.code == '200'){
        state.dataList = res.data.list;
      } else {
        proxy.$ElMessage.error(res.message);
      }
    })
  }
  function handleConfirm(){
    if(state.queryParams.params.nums == 0){
      proxy.$ElMessage.warning('差异数量不能为0')
      return
    }
    queryFormRef.value.validate((valid: any) => {
      if (!valid) {
        return
      }
      state.loadingC = true
      confirm(state.queryParams.params).then(res => {
        if(res.success){
          state.dataList = res.resultObj;
          resetQuery();
        } else {
          proxy.$ElMessage.error(res.message);
        }
        state.loadingC = false
      })
    })
  }

  // 提交
function submit() {
  formDataRef.value.validate((valid: any) => {
    if (!valid) {
      return
    }
    if (state.dataList.length == 0){
      proxy.$ElMessage.warning("列表没有数据")
      return
    }
    if(!state.queryParams.params.checkType){
        proxy.$ElMessage.warning("请选择盘点类型");
        return
      }
    let param = {
      boxList: state.dataList,
      user: localStorage.get("userId"),
      commitDate: state.commitDate,
      opcode: '',
      qtc: 'Z06',
      costName: state.updateParams.costName,
      siteName: 'SDK'
    }
    state.loadings = true
    if (state.queryParams.params.checkType == "盘盈") {
      let hasEven = state.dataList.some(item =>
        item.STOCKSTATE != 'Created'
      )
      if(hasEven){
        proxy.$ElMessage.warning("列表中含有状态不是Created的数据，不能进行盘盈");
        state.loadings = false
        return
      }
      QTRCommit(param).then(res => {
        if(res.success){
          proxy.$ElMessage.success(res.message);
          state.dataList = [];
          state.queryParams.params.checkType = '';
          state.updateParams.costName = '';
        } else {
          proxy.$ElMessage.error(res.message);
        }
        state.loadings = false
      })
    } else {
      let hasEven = state.dataList.some(item =>
        item.STOCKSTATE != 'Stocked'
      )
      if(hasEven){
        proxy.$ElMessage.warning("列表中含有状态不是Stocked的数据，不能进行盘亏");
        state.loadings = false
        return
      }
      param.qtc = 'Z05'
      QTCCommit(param).then(res => {
        if(res.success){
          proxy.$ElMessage.success(res.message);
          state.dataList = [];
          state.queryParams.params.checkType = '';
          state.updateParams.costName = '';
        } else {
          proxy.$ElMessage.error(res.message);
        }
        state.loadings = false
      })
    }
  })
  
}
</script>
<style>
.col_height {
  padding-top: 3.5px;
  padding-bottom: 3.5px;
}
</style>