<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"
              :inline="true"
              label-width="80px"
              label-position="left"
      >
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="批次" prop="params.CHARGE">
              <el-Input v-model="queryParams.params.CHARGE" clearable placeholder="请输入批次" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="物料编号" prop="params.MATERIALSPECNAME">
              <el-Input
                      v-model="queryParams.params.MATERIALSPECNAME"
                      clearable
                      placeholder="请输入物料编号"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="page-search-btns">
        <el-button type="primary" @click="queryInfo">搜索</el-button>
      </div>
    </el-row>
    <!-- 左右结构 -->
    <div class="vue-element-page-table">
      <el-row>
        <el-col :span="24">
          <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>
                <el-tag size="large" style="margin-left: 30px" type="success"
                >累计个数：{{ GSSUM }}</el-tag
                >
                <el-tag size="large" style="margin-left: 20px" type="success"
                >累计数量：{{ BQSUM }}</el-tag
                >
              </div>
              <div class="page-table-operateBtns">
                <el-popover
                        :persistent="false"
                        placement="right"
                        popper-class="config-table-wrap"
                        trigger="click"
                >
                  <template #reference>
                    <el-button class="operateBtns-setting">
                      <svg-icon icon-class="table_title" width="16px" height="16px" />
                    </el-button>
                  </template>
                  <ConfigTable :list="materialTableConfig.column" @updateList="updateList" />
                </el-popover>
              </div>
            </div>
            <el-table
                    border
                    v-loading="loading"
                    :data="state.MaterialPackingList"
                    highlight-current-row
                    :row-key="getRKey"
                    ref="tableRef"
                    :height="tableHeight"
                    @cell-mouse-enter="handleCellMouseEnter"
                    style="width: 100%"
                    :default-sort="{ prop: 'MATERIALQUANTITY', order: 'descending' }"
                    @selection-change="handleSelectionChange"
            >
              <el-table-column :reserve-selection="true" type="selection" width="40" />
              <el-table-column type="index" width="50" label="序号"> </el-table-column>
              <template v-for="(col, index) in materialTableConfig.column" :key="index">
                <el-table-column
                        v-if="!col.hide"
                        :label="col.header"
                        :prop="col.field"
                        show-overflow-tooltip
                        :sort-orders="['descending', 'ascending']"
                        :sortable="true"
                        align="center"
                >
                  <template #default="scope">
                    <span v-if="col.field === 'status'">
                      <span v-if="scope.row[col.field]" class="table-status-active">启用</span>
                      <span v-else class="table-status-inActive">禁用</span>
                    </span>
                    <span v-else>{{ scope.row[col.field] }}</span>
                  </template>
                </el-table-column>
              </template>
            </el-table>

            <pagination
                    v-if="state.total > 0"
                    :total="state.total"
                    v-model:pageNumTo="state.queryParams.pageNum"
                    v-model:pageSizeTo="state.queryParams.pageSize"
                    @pagination="handleQuery"
            />
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="vue-element-page-table">
      <el-row class="page-search" align="middle" :gutter="20">
        <el-col :span="5" style="padding-top: 12px">
          <el-form-item label="库存组织" prop="ERPFACTORY">
            <el-select
                    filterable
                    v-model="desParams.params.ERPFACTORY"
                    placeholder="下拉选择组织"
                    @change="changeFac"
                    size="small"
                    @blur="focusLocW"
            >
              <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="5" style="padding-top: 12px">
          <el-form-item label="目的仓库" prop="ERPLOCATION">
            <el-select
                    size="small"
                    filterable
                    v-model="desParams.params.ERPLOCATION"
                    placeholder="下拉选择仓库"
            >
              <el-option
                      v-for="item in locDecList1"
                      :key="item.ENUMVALUE"
                      :label="item.DESCRIPTION"
                      :value="item.ENUMVALUE"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5" style="padding-top: 12px">
          <el-form-item label="目的货位" prop="LOCATIONNAME">
            <el-select
                    size="small"
                    filterable
                    v-model="desParams.params.LOCATIONNAME"
                    default-first-option
                    placeholder="下拉选择货位"
                    :filter-method="getlocDec"
            >
              <el-option
                      v-for="item in locDecList2"
                      :key="item.STORAGENAME"
                      :label="item.DESCRIPTION"
                      :value="item.STORAGENAME"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4" style="padding-top: 12px" :offset="3">
          <div class="block" style="float: right">
            <el-form-item label="过账日期" prop="state.commitDate">
              <el-date-picker
                      :clearable="true"
                      :editable="true"
                      v-model="state.commitDate"
                      type="date"
                      placeholder="选择过账时间"
                      value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="2" style="display: none">
          <el-Input v-model="state.OpCode" :disabled="false" readonly />
        </el-col>
        <el-col :span="2">
          <div class="page-search-btns" style="float: right">
            <el-button
                    v-loading="state.loading2"
                    type="primary"
                    @click="submit"
                    :disabled="state.Button_state"
            >确定</el-button
            >
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

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

<script lang="ts" setup>
  import { reactive, ref, onMounted, toRefs, getCurrentInstance, nextTick } from 'vue'
  import { ElForm, ElMessageBox, ElTable, CascaderProps } from 'element-plus'
  import { getQueryList, getQueryPageList } from '@/api/common'
  import { FGStockIn } from '@/api/StockIn'

  import { bTableHeight } from '../../../composables/calcTableHeight'
  import { getORG } from '@/api/auth'
  import { cals } from '@/utils/cal'
  import { getOpCode } from '@/api/opcode'
  import request from '@/utils/request'

  const { tableContainer, tableHeight, updateTableHeight, handleResize } = bTableHeight(330)
  const queryFormRef = ref(ElForm)
  const { proxy }: any = getCurrentInstance()
  const tableRef = ref<InstanceType<typeof ElTable>>()

  const materialTableConfig = ref({
    loading: false,
    column: [] as any,
    data: []
  })
  const state = reactive({
    OpCode: '', //过账流水
    BQSUM: 0,
    GSSUM: 0,
    commitDate: '',
    ERPFactoryList: [] as any, // 组织
    ERPLocationList: [] as any, //仓库
    LocationList: [] as any, //货位
    rsa: '',
    Button_state: false,
    total: 0,
    total2: 0,
    BoxList: [] as any,
    firstLocation: '',
    MaterialPackingList: [] as any,
    Storage1Select: [] as any,
    Storage1SelectList: [] as any,
    StorageSelect: [] as any,
    StorageSelectList: [] as any,
    locDecList1: [] as any,
    locDecList2: [] as any,
    queryParams: {
      queryId: '',
      version: '',
      params: {
        SITENAME: 'SDK',
        MATERIALSPECNAME: '',
        // ERPLOCATION: '',
        // ERPFACTORY: '',
        // LOCATIONNAME: '',
        CHARGE: ''
      },
      pageNum: 1,
      pageSize: 10
    },
    desParams: {
      queryId: '',
      version: '',
      params: {
        SITENAME: 'SDK',
        ERPFACTORY: '',
        LOCATIONNAME: '',
        ERPLOCATION: ''
      },
      pageNum: 1,
      pageSize: 10
    },
    RightqueryParams: {
      queryId: '',
      version: '',
      params: {
        SITENAME: 'SDK', //localStorage.getItem("siteName"),
        DELIVERYTYPE: '', //移动类型
        SUPPLIERNAME: '',
        SHIPREQUESTNAME: '',
        MATERIALSPECNAME: '',
        AREANAME: '',
        MATERIALPACKING: '',
        DURABLENAME: '',
        CHARGE: '',
        ERPFACTORYNAME: '',
        ERPLOCATION: '',
        SDK_ID: '',
        PHASE: '',
        ERPFACTORY: '',
        SHIPREQUESTDETAILNAME: ''
      }
    },
    ChangeParams: {
      header: {
        MESSAGENAME: 'ModifyLocation',
        LANGUAGE: 'Chinese'
      },
      body: {
        BOXLIST: [] as any,
        SITENAME: 'SDK',
        AREANAME: '',
        LOCATIONNAME: '',
        ERPLOCATION: ''
      }
    },
    operateParams: {
      date: new Date()
    },
    operateOptions: [] as any, // 操作类型
    actNoOptions: [] as any, // 抬头文本
    checkResultOptions: [
      {
        label: 'OK',
        value: 'OK'
      },
      {
        label: 'NG',
        value: 'NG'
      }
    ], // 质检结果
    loading: false,
    loading2: false,
    loading3: false, //左箭头loading flag
    column1: [] as any,
    column: [] as any,
    column2: [] as any,
    MoveLibraryList: [] as any, //column对应的数据
    waitAssignmentList: [] as any, //column1对应的数据
    AssignmentList: [] as any, //column2对应的数据
    LeftSelection: [], //左边选择的未分配数据
    RightSelection: [], //右边选择的分配数据
    column3: [] as any,
    column4: [] as any,
    column5: [] as any,
    locDecListAll: [] as any,
    queryParamsERPFactory: {
      queryId: 'GetErpFactoryList',
      version: 'WEB00001',
      params: {
        SITENAME: localStorage.getItem('siteName') || 'SDK'
      },
      pageNum: 1,
      pageSize: 10
    },
    queryParamsERPLocation: {
      queryId: 'GetErpLocationList',
      version: 'WEB00001',
      params: {
        SITENAME: localStorage.getItem('siteName') || 'SDK',
        ERPFACTORYNAME: ''
      },
      pageNum: 1,
      pageSize: 10
    },
    queryParamsLocation: {
      queryId: 'GetLocationList',
      version: 'WEB00001',
      params: {
        SITENAME: localStorage.getItem('siteName') || 'SDK',
        ERPLOCATION: ''
      },
      pageNum: 1,
      pageSize: 10
    }
  })
  const {
    GSSUM,
    BQSUM,
    Button_state,
    StorageSelectList,
    StorageSelect,
    ERPFactoryList,
    ERPLocationList,
    LocationList,
    desParams,
    queryParams,
    loading3,
    loading,
    column,
    column1,
    column2,
    locDecList1,
    locDecList2
  } = 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
    materialTableConfig.value.column = [
      // { header: '工厂', field: 'SITENAME', hide: true },
      { header: '标签编号', field: 'MATERIALPACKINGNAME', hide: false },
      { header: '批号', field: 'CHARGE', hide: false },
      { header: '物料编号', field: 'MATERIALSPECNAME', hide: false },
      { header: '品名', field: 'DESC_CN', hide: false },
      { header: '数量', field: 'MATERIALQUANTITY', hide: false },
      { header: '阶段', field: 'PHASE', hide: false },
      { header: 'SDK规格', field: 'SPECNAME', hide: false },
      { header: '实际规格', field: 'TRUEGG', hide: false },
      { header: '立库货区', field: 'AREANAME', hide: false },
      { header: '立库货位', field: 'SHELFNAME', hide: false },
      { header: '载具', field: 'DURABLENAME', hide: false },
      { header: '生产订单/投放计划', field: 'REQUESTNAME', hide: false },

      // { header: '单位', field: 'FNAME', hide: false },
      // { header: 'Hold 状态', field: 'HOLDSTATE', hide: false },
      // { header: '品质状态', field: 'OQARESULTSTATE', hide: false },
      // { header: '品质结果', field: 'PACKINGGRADE', hide: false },
      // { header: '入库日期', field: 'SHIPTIME', hide: false },
      // { header: '仓库编码', field: 'ERPLOCATION', hide: false },
      // { header: '仓库名称', field: 'ERPLOCATIONDESC', hide: false },
      // { header: '货位编码', field: 'LOCATIONNAME', hide: false },
      // { header: '货位名称', field: 'LOCATIONNAMEDESC', hide: false }
    ]
    // let pwd: any = localStorage.getItem('remeberPwd')
    ERPFactoryQuery()
    queryInfo()

    updateTableHeight()
    window.addEventListener('resize', handleResize)
    StorageList()
    getStorageSpecLocationList()
  })

  function getRKey(row: any) {
    // console.log(row.CHARGE)
    return row.CHARGE
  }

  function handleCellMouseEnter(row: any, column: any, cell: any, event: any) {
    // console.log(row, column, cell, event);
    if (column.type === 'selection' && event.shiftKey) {
      // 且按着 shift 键 则勾选这一行
      tableRef.value!.toggleRowSelection(row, true)
    }
  }
  function changeFac(e: any) {
    // state.queryParamsERPLocation.params.ERPFACTORYNAME = e
    state.locDecList1 = []
    StorageList(e)
  }
  async function StorageList(firstLocation: any) {
    const res = await getQueryList({
      queryId: 'GetErpLocationList',
      version: 'WEB00001',
      params: {
        ERPFACTORYNAME: firstLocation,
        SITENAME: 'SDK'
      },
      pageNum: 1,
      pageSize: 10
    })
    state.locDecList1 = res.data
    if (state.locDecList1.length == 0) {
      proxy.$ElMessage.info('目的仓库为空!')
      return
    }
    const nodes = state.locDecList1.map((item: any) => ({
      value: item.ENUMVALUE,
      label: item.DESCRIPTION,
      leaf: 0
    }))
    state.StorageSelectList = nodes
  }
  //ERP工厂查询
  function ERPFactoryQuery() {
    getORG({ orgNo: null })
            .then((res: any) => {
              state.ERPFactoryList = res.resultObj
              state.ERPFactoryList.unshift({
                ERPFACTORY: ''
              })
            })
            .catch(() => {})
  }
  // 更新列
  const updateList = (col: any) => {
    materialTableConfig.value.column = col
  }
  function queryInfo() {
    state.queryParams.pageNum = 1
    handleQuery()
  }
  async function handleQuery() {
    // if (state.queryParams.params.ERPFACTORY) {
    state.queryParams.queryId = 'GetMaturationLibraryToERP'
    state.queryParams.version = '00001'
    state.MoveLibraryList = []
    await getQueryPageList(state.queryParams)
            .then((res: any) => {
              console.log(res)
              if (res.data.list.length == 0) {
                state.MaterialPackingList = []
                state.total = 0
                // ElMessageBox.alert('查无数据！', '提醒框', {
                //   confirmButtonText: 'OK'
                // })
              } else {
                state.MaterialPackingList = res.data.list
                state.total = res.data.total
              }
            })
            .catch((error: any) => {
              // ElMessageBox.alert('系统内部错误，请找IT！', '提醒框', {
              //   confirmButtonText: 'OK'
              // })
            })
  }
  const props: CascaderProps = {
    lazy: true,
    async lazyLoad(node, resolve) {
      // console.log(66,node, resolve)
      const { level, value } = node
      if (state.column4.length > 0 && level) {
        const childrenRes = await getQueryList({
          queryId: 'Get2stAreaName',
          version: '00002',
          params: {
            ERPLOCATION: value,
            SITENAME: 'SDK'
          },
          pageNum: 1,
          pageSize: 10
        })
        state.locDecList2 = childrenRes.data || []
        const nodes = state.locDecList2.map((item: any) => ({
          value: item.ERPLOCATION,
          label: item.ERPLOCATION,
          leaf: level < 3
        }))
        resolve(nodes)
      }
    }
  }
  function resetQuery() {
    queryFormRef.value.resetFields()
    handleQuery()
  }
  function focusLocW() {
    // console.log(111,state.column4)
    if (!state.column4.length) {
      ElMessageBox.alert('请选择标签信息', '提醒框', {
        confirmButtonText: 'OK'
      })
      return
    }
  }
  async function changeLocW() {
    state.desParams.params.LOCATIONNAME = ''
    await getQueryList({
      queryId: 'GetLocationForCreatePO',
      version: '00001',
      params: {
        ERPLOCATION: state.desParams.params.ERPLOCATION,
        SITENAME: 'SDK'
      }
    }).then((res: any) => {
      state.locDecListAll = res.data
      getlocDec('')
    })
    // state.locDecList2 = childrenRes
    // state.locDecListAll = childrenRes/
    // getlocDec('')
    // console.log(state.locDecListAll)
  }
  function getlocDec(query: any) {
    // console.log(query)
    let arr = state.locDecListAll.filter((item: any) => {
      return item.STORAGENAME.includes(query) || item.STORAGENAME.includes(query)
    })
    // console.log(arr)
    if (arr.length > 50) {
      state.locDecList2 = arr.slice(0, 50)
    } else {
      state.locDecList2 = arr
    }
  }
  function handleSelectionChange(selection: any) {
    state.column4 = selection
    let sumList = [...state.column4]
    state.BQSUM = 0
    state.BQSUM = sumList.reduce((accumulator, currentValue) => {
      console.log(accumulator, currentValue)
      return cals.add(accumulator, currentValue.MATERIALQUANTITY).toNumber()
    }, 0)
    state.GSSUM = sumList.length
    console.log(state.column4)
    state.locDecList1 = []
    state.locDecList2 = []
    // else {
    //   ElMessageBox.alert('请选择标签信息', '提醒框', {
    //     confirmButtonText: 'OK'
    //   })
    // }
  }

  async function submit() {
    console.log(state.column4)
    if (state.commitDate == null) {
      ElMessageBox.alert('过账时间不可清空', {
        confirmButtonText: 'OK'
      })
      return
    }
    state.Button_state = true
    state.loading2 = true
    if (
            state.column4.length > 0 &&
            // state.desParams.params.LOCATIONNAME &&
            state.desParams.params.ERPLOCATION
    ) {
      let BoxListInfo = JSON.parse(JSON.stringify(state.column4))
      for (let k = 0; k < BoxListInfo.length; k++) {
        BoxListInfo[k].ERPFACTORY = state.desParams.params.ERPFACTORY
        BoxListInfo[k].ERPLOCATION = state.desParams.params.ERPLOCATION
        BoxListInfo[k].LOCATIONNAME = state.desParams.params.LOCATIONNAME
      }

      getOpCode({
        opcode: state.OpCode,
        user: localStorage.getItem('userId')
      }).then((res: any) => {
        console.log(res.resultObj)
        state.OpCode = res.resultObj
        let params = {
          boxList: BoxListInfo,
          user: localStorage.getItem('userId'),
          siteName: 'SDK',
          commitDate: state.commitDate,
          opcode: state.OpCode
        }

        FGStockIn(params)
                .then((res: any) => {
                  console.log('res', res)
                  if (res?.success) {
                    ElMessageBox.alert(res?.message, '提醒框', {
                      confirmButtonText: 'OK'
                    })
                    if (state.column4.length > 0) {
                      tableRef.value!.clearSelection()
                      state.column4 = []
                    }
                    state.OpCode = ''
                    state.MaterialPackingList = []
                    handleQuery()
                  } else {
                    ElMessageBox.alert(res?.message, '提醒框', {
                      confirmButtonText: 'OK'
                    })
                  }

                  state.loading2 = false
                  state.Button_state = false
                })
                .catch((error: any) => {
                  console.log(error)
                  ElMessageBox.alert(error?.response?.data?.message || error?.message, '提醒框', {
                    confirmButtonText: 'OK'
                  })
                  state.loading2 = false
                  state.Button_state = false
                })
      })
    } else {
      ElMessageBox.alert('请先选择标签', '提醒框', {
        confirmButtonText: 'OK'
      })
      state.Button_state = false
      state.loading2 = false
    }
    // state.loading2 = false
    state.Button_state = false
  }

  async function getStorageSpecLocationList() {
    let erpLocation = JSON.parse(localStorage.getItem('orgNo'));
    request({
      url: '/api/api/storage/getLocationNameForERPLocation',
      method: 'post',
      data: {
        erpLocation: erpLocation,
        SITENAME: 'SDK',
      },
    }).then((res: any) => {
      state.locDecListAll = res.resultObj;
      console.log(state.locDecList2)
    });
  }
</script>

<style scoped lang="scss">
  .operate-bottom {
    width: 80px;
    height: 28px;
    float: right;
    margin-top: 20px;
  }
</style>
