<template>
  <el-config-provider :locale="zhCn">
    <el-container class="content">
      <div class="work-area">
        <fieldset class="search-area">
          <el-form ref="stockQueryFormRef" :model="stockQuery" :label-position="labelPosition"
                   label-width="auto" style="max-width: 100%" status-icon>
            <div style="display: flex;justify-content: space-between;">
              <div style="align-content: center;">
                <el-row>
                  <el-button type="primary"                             style="height: 40px; width: 120px; margin: auto 15px 5px auto; color: black;"
                             @click="queryStocks()">进行库存比对</el-button>
                  <el-button type="success"                             style="height: 40px; width: 80px; margin: auto 5px 5px auto; color: black;"
                             @click="search()">查询</el-button>
                </el-row>
              </div>
            </div>
          </el-form>
        </fieldset>
        <div class="table-area">
          <el-table :data="displayStocks" stripe border v-loading="tableLoading" class="table-class"
                    :max-height="maxHeight" highlight-current-row @row-click="getCurrentRow" :row-style="rowStyle"
                    :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center', 'color': 'black' }"
                    @sort-change="handleSortChange">
            <el-table-column width="65px" fixed="left">
              <template v-slot="scope">
                <el-radio :label="scope.row.id" v-model="stockId">&nbsp;</el-radio>
              </template>
            </el-table-column>
            <el-table-column type="index" label="序号" fixed="left" min-width="80px" show-overflow-tooltip />
            <el-table-column prop="goodsId" label="物料编号" fixed="left" min-width="120px"
                             show-overflow-tooltip />
            <el-table-column prop="goodsDesc" label="物料描述" min-width="120px"  show-overflow-tooltip />
            <el-table-column prop="wmsTotalNum" label="WMS总数量"  min-width="120px" show-overflow-tooltip />
            <el-table-column prop="ewmTotalNum" label="EWM总数量"  min-width="120px" show-overflow-tooltip />
            <el-table-column prop="specialStock" label="特殊库存标识" min-width="120px" show-overflow-tooltip />
            <el-table-column prop="specialStockNo" label="SO单号/供应商编号" min-width="150px" show-overflow-tooltip />
            <el-table-column prop="specialStockItemNo" label="特殊库存item号" min-width="130px" show-overflow-tooltip />
            <el-table-column prop="batchNo" label="批次号" min-width="120px" show-overflow-tooltip />
            <el-table-column prop="createTime" label="创建时间"  :formatter="timeFormat"
                             min-width="180px" show-overflow-tooltip />
            <el-table-column prop="compareStatus" label="对比状态" min-width="150px"  show-overflow-tooltip>
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.compareStatus)">
                  {{ getStatusText(scope.row.compareStatus) }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
          <br />
          <el-pagination v-model:current-page="baseTableQuery.currentPage"
                         v-model:page-size="baseTableQuery.pageSize" :page-sizes="[10, 25, 50]" :small="false"
                         :disabled="false" :background="false" :default-page-size="10" @size-change="search"
                         @current-change="search" layout="total, sizes, prev, pager, next, jumper"
                         :total="baseTableQuery.total" />
        </div>
      </div>
    </el-container>
  </el-config-provider>
</template>

<script setup>import store from '@/store'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import {getCompareData, queryStocksCompare} from '@/api/task.js'
import { timeFormatter } from '@/utils/formatter.js'
import { ref, reactive, onMounted, nextTick, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import { labelPosition } from '@/constant/form'

/**
 * 常量定义
 */
/**
 * 变量定义
 */
let maxHeight = ref(window.innerHeight * 0.55)
let tableLoading = ref(false)
let displayStocks = ref([])
let baseTableQuery = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  sortBy: new Map([['createTime', true]]),
  standId: store.getters.getStandId,
  userName: store.getters.getUserName
})
let stockQuery = reactive({
  goodsId: '',
  compareStatus: ''
})
let stockQueryFormRef = ref()
let stockId = ''
/**
 * 系统方法
 */
onMounted(() => {
  nextTick(() => {
    window.addEventListener('resize', resizeHeight)
    search()
  })
})
onBeforeUnmount(() => {
  nextTick(() => {
    window.removeEventListener('resize', resizeHeight)
  })
})
const resizeHeight = () => {
  maxHeight.value = window.innerHeight * 0.55
}
/**
 * 自定义方法
 */
/**
 * 自定义方法
 */
// 查询
const search = () => {
  tableLoading.value = true
  getCompareData().then((res) => {
    const response = res.data
    if (response.code === 0) {
      const data = response.data
      if (data != null) {
        displayStocks.value = data
        baseTableQuery.total = data.length
      } else {
        displayStocks.value = []
        baseTableQuery.total = 0
      }
    } else {
      ElMessage.error(response.message)
    }
  }).catch(err => {
    console.log(err)
    ElMessage.error('查询库存对比信息异常。')
  }).finally(() => {
    tableLoading.value = false
  })
}

/**
 * 执行库存比对
 */
const queryStocks = () => {
  tableLoading.value = true;

  // 调用库存比对API
  queryStocksCompare().then((res) => {
    const response = res.data;
    if (response.code === 0) {
      ElMessage.success('库存比对执行成功');

      // 刷新表格数据
      search();
    } else {
      ElMessage.error(response.message || '库存比对执行失败');
    }
  }).catch(err => {
    console.error('库存比对异常:', err);
    ElMessage.error('执行库存比对时发生异常');
  }).finally(() => {
    tableLoading.value = false;
  });
}


const timeFormat = (row, column, cellValue, index) => {
  return timeFormatter(cellValue)
}

const rowStyle = ({ row, rowIndex }) => {
  // 根据compareStatus设置行样式
  if (row.compareStatus === 0) {
    return { "color": "green" }
  } else if (row.compareStatus === 1 || row.compareStatus === -1) {
    return { "color": "orange" }
  } else if (row.compareStatus === 2 || row.compareStatus === -2) {
    return { "color": "red" }
  }
}

const handleSortChange = (data) => {
  if (baseTableQuery.sortBy.has(data.prop)) {
    baseTableQuery.sortBy.delete(data.prop)
  }
  baseTableQuery.sortBy.set(data.prop, data.order == 'ascending')
  search()
}

const getCurrentRow = (row) => {
  stockId = row.id
}

const getStatusText = (status) => {
  const statusMap = {
    '0': '数量一致',
    '1': 'WMS多于EWM',
    '-1': 'EWM多于WMS',
    '2': 'WMS有EWM没有',
    '-2': 'EWM有WMS没有'
  }
  return statusMap[status] || '未知状态'
}

const getStatusType = (status) => {
  const typeMap = {
    '0': 'success',
    '1': 'warning',
    '-1': 'warning',
    '2': 'danger',
    '-2': 'danger'
  }
  return typeMap[status] || 'info'
}
</script>
<style scoped>
.content {
  display: flex;
  width: 100%;
}

.work-area {
  width: 100%;
  /* padding: 5px; */
}

.search-area {
  margin: auto;
  min-height: fit-content;
  max-height: 40%;
  margin-bottom: 10px;
  min-width: inherit;
  border: solid 1px;
  border-radius: 10px;
  box-shadow: 0px 15px 10px -15px #000;
  overflow: auto;
  padding: 10px;
}

.table-area {
  margin: auto;
  min-height: fit-content;
  max-height: 60%;
  margin-bottom: 10px;
  min-width: inherit;
  border: solid 1px;
  border-radius: 10px;
  box-shadow: 0px 15px 10px -15px #000;
  overflow: auto;
  padding: 10px;
}

.el-form-item {
  margin: 5px 5px 5px 5px;
}

.el-form-item .el-input {
  width: 196px;
}

.table-class {
  margin: 5px 5px 5px 5px;
  width: inherit;
  color: black;
}

.el-pagination {
  padding-left: 5px;
}

.my-autocomplete li {
  width: 196px;
  line-height: normal;
  padding: 7px;
}

.my-autocomplete li .name {
  text-overflow: ellipsis;
  overflow: hidden;
}

.my-autocomplete li .addr {
  font-size: 12px;
  color: #b4b4b4;
}

.my-autocomplete li .highlighted .addr {
  color: #ddd;
}

.my-autocomplete li .goods_id {
  color: brown;
}

.my-autocomplete li .goods_name {
  color: cornflowerblue;
}
</style>