<template>
  <el-config-provider :locale="zhCn">
    <el-container class="content">
      <div class="work-area">
        <fieldset class="search-area">
          <el-form ref="searchQueryFormRef" :model="searchQueryFormEntity" :label-position="labelPosition"
                   label-width="158px" style="max-width: 100%" status-icon>
            <div style="display: flex;justify-content: space-between;">
              <el-row>
                <el-form-item label="料号">
                  <el-input v-model="searchQueryFormEntity.goodsId" @keyup.enter="search()"
                            clearable/>
                </el-form-item>
                <el-form-item label="工单详情">
                  <el-input v-model="searchQueryFormEntity.workOrder" @keyup.enter="search()"
                            clearable/>
                </el-form-item>
<!--                <el-form-item label="工单号">-->
<!--                  <el-input v-model="searchQueryFormEntity.goodsDesc" @keyup.enter="search()"-->
<!--                            clearable/>-->
<!--                </el-form-item>-->
              </el-row>
              <div style="align-content: center;">
                <el-row>
                  <el-button type="primary" class="btn-search" @click="search()">查询</el-button>
                  <el-button type="warning" class="btn-search" @click="clearQuery()">清除输入</el-button>
                </el-row>
<!--                <el-row>-->
<!--                  <el-button style="background-color: #00CED1;" class="btn-search"-->
<!--                             @click="openUploadDialog()">导入数据-->
<!--                  </el-button>-->
<!--                  <el-button type="success" class="btn-search"-->
<!--                             @click="exportExcel()">导出excel-->
<!--                  </el-button>-->
<!--                </el-row>-->
              </div>
            </div>
          </el-form>
        </fieldset>
        <div class="table-area">
          <el-table :data="tableData" stripe border v-loading="tableLoading" class="table-class"
                    :max-height="maxHeight" highlight-current-row @row-click="getCurrentRow"
                    :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }"
                    @sort-change="handleSortChange">
            <el-table-column width="65px" fixed="left">
              <template #header>
                <el-checkbox
                    v-model="isSelectAll"
                    @change="handleSelectAllChange">
                  &nbsp;
                </el-checkbox>
              </template>
              <template v-slot="scope">
                <!-- 单选改为多选 -->
                <el-checkbox
                    :label="scope.row.goodsId"
                    v-model="scope.row.checked"
                    @change="handleSelectionChange(scope.row)">
                  &nbsp;
                </el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="workOrder" label="工单详情" fixed="left" min-width="120px" sortable="custom"
                             show-overflow-tooltip/>
            <el-table-column prop="goodsId" label="料号" fixed="left" min-width="120px" sortable="custom"
                             show-overflow-tooltip/>
            <el-table-column prop="needNum" label="需求数量" min-width="120px" sortable="custom"
                             show-overflow-tooltip/>
            <el-table-column prop="distributeNum" label="已分配数量" min-width="120px" sortable="custom"
                             show-overflow-tooltip/>
            <el-table-column prop="pickNum" label="已拣选数量" min-width="120px" sortable="custom"
                             show-overflow-tooltip/>
            <el-table-column prop="outType" label="优先级" min-width="120px" sortable="custom"
                             show-overflow-tooltip/>
            <el-table-column prop="destination" label="呼叫站台" min-width="120px" sortable="custom"
                             show-overflow-tooltip/>
            <el-table-column prop="specialStock" label="特殊库存" min-width="120px" sortable="custom"
                             show-overflow-tooltip/>
            <el-table-column prop="specialStockNo" label="特殊库存号" min-width="120px" sortable="custom"
                             show-overflow-tooltip/>
            <el-table-column prop="specialStockItemNo" label="特殊库存Item号" min-width="120px" sortable="custom"
                             show-overflow-tooltip/>
            <el-table-column prop="batchNo" label="批次号" min-width="120px" sortable="custom"
                             show-overflow-tooltip/>
            <el-table-column prop="taskId" label="任务号" min-width="120px" sortable="custom"
                             show-overflow-tooltip/>
            <el-table-column
                prop="pickingDate"
                label="执行时间"
                fixed="right"
                min-width="120px"
                sortable="custom"
                :formatter="(row, column, cellValue) => formatDateToDay(cellValue)"
                show-overflow-tooltip/>

            <el-table-column label="操作" fixed="right" min-width="180px">
              <template v-slot="scope">
                <div style="display: flex; gap: 5px; justify-content: center;">
                  <el-button size="default" type="success" @click.stop="handleEdit(scope.row)">编辑</el-button>
                  <el-button size="default" type="warning" @click.stop="handleDelete(scope.row)">加急</el-button>
                </div>
              </template>
              <template #header>
                <div style="display: flex; flex-direction: column; align-items: center;">
                  <span>操作</span>
                  <el-button
                      size="small"
                      type="primary"
                      @click="handleBatchEdit"
                      :disabled="selectedRows.length === 0"
                      style="margin-top: 5px;">
                    批量修改时间({{ selectedRows.length }})
                  </el-button>
                </div>
              </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>
        <el-dialog v-model="showEditDialog" title="编辑执行日期" width="30%" draggable>
          <el-form ref="editFormRef" :model="editForm" label-width="100px">
            <el-form-item label="执行时间">
              <el-date-picker
                  v-model="editForm.pickingDate"
                  type="date"
                  placeholder="请选择执行时间"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-form>
          <template #footer>
    <span class="dialog-footer">
      <el-button @click="showEditDialog = false">取消</el-button>
      <el-button type="primary" @click="saveEdit(editForm)">确定</el-button>
    </span>
          </template>
        </el-dialog>
        <el-dialog v-model="showBatchEditDialog" title="批量修改执行日期" width="30%" draggable>
          <el-form ref="batchEditFormRef" :model="batchEditForm" label-width="100px">
            <el-form-item label="执行时间">
              <el-date-picker
                  v-model="batchEditForm.pickingDate"
                  type="date"
                  placeholder="请选择执行时间"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"            style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-form>
          <template #footer>
      <span class="dialog-footer">
        <el-button @click="showBatchEditDialog = false">取消</el-button>
        <el-button type="primary" @click="saveBatchEdit(batchEditForm)">确定</el-button>
      </span>
          </template>
        </el-dialog>
      </div>
    </el-container>
  </el-config-provider>
</template>

<script setup>
import store from '@/store'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import {batchEditDate, editDate, getGoodsInfoByPage, upOutsType} from '@/api/goods.js'
import {ref, reactive, onMounted, nextTick, onBeforeUnmount} from 'vue'
import {ElMessage} from 'element-plus'
import {genTableRequest} from '@/utils/generator.js'
import {labelPosition} from '@/constant/form.js'
import UploadExcelBaseGoods from '@/excel/UploadExcelBaseGoods.vue'
import UploadExcelKanban from '@/excel/UploadExcelKanban.vue'
import {exportGoodsExcel} from "@/api/excel";
import {dateFormatter} from "@/utils/formatter";
import { getUserPermission } from '@/api/user.js'

/**
 * 常量定义
 */
const STAND_ID = store.getters.getStandId
const USER_NAME = store.getters.getUserName
/**
 * 变量定义
 */
let maxHeight = ref(window.innerHeight * 0.55)
let tableLoading = ref(false)
let tableData = ref([])
let baseTableQuery = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  sortBy: new Map([['goodsId', true]]),// 按照料号顺序排序
  standId: STAND_ID,
  userName: USER_NAME
})
let searchQueryFormEntity = reactive({
  goodsId: '',
  goodsDesc: '',
  workOrder: '',
})
let selectedRows = ref([]) // 新增：存储选中的行
let showBatchEditDialog = ref(false) // 新增：控制批量编辑对话框显示
const batchEditForm = reactive({
  pickingDate: ''
}) // 新增：批量编辑表单
let searchQueryFormRef = ref()
let rowEditFlag = ref(false)
let goodsId = ''
let rowEditFormRef = ref()
let rowFormEntity = reactive({})
let showUploadDialog = ref(false)
/**
 * 系统方法
 */
onMounted(() => {
  nextTick(() => {
    window.addEventListener('resize', resizeHeight)
    search()
  })
})
onBeforeUnmount(() => {
  nextTick(() => {
    window.removeEventListener('resize', resizeHeight)
  })
})
const resizeHeight = () => {
  maxHeight.value = window.innerHeight * 0.55
}

// 处理选择变化
const handleSelectionChange = (row) => {
  if (row.checked) {
    // 如果选中且不在列表中，则添加
    if (!selectedRows.value.some(item => item.goodsId === row.goodsId)) {
      selectedRows.value.push(row)
    }
  } else {
    // 如果取消选中，则从列表中移除
    selectedRows.value = selectedRows.value.filter(item => item.goodsId !== row.goodsId)
  }
}
// 修改批量编辑处理函数
const handleBatchEdit = () => {
  const permissionParams = {
    loginAccountUpdate: store.getters.getUser.loginAccount,
    roleIdOp: store.getters.getUser.roleId,
    userName: USER_NAME
  }

  getUserPermission(permissionParams).then(res => {
    if (res.data.code === 0) {
      // 解析权限字符串，检查是否包含"D"（批量修改时间权限）
      const permissionStr = res.data.message || ''
      if (!permissionStr.includes('B')) {
        // 无批量修改时间权限提示
        ElMessage.error('您没有批量修改时间的权限')
        return
      }

      // 有权限，继续执行原有逻辑
      if (selectedRows.value.length === 0) {
        ElMessage.warning('请至少选择一条记录')
        return
      }
      batchEditForm.pickingDate = ''
      showBatchEditDialog.value = true
    } else {
      ElMessage.error(res.data.message || '权限检查失败')
    }
  }).catch(err => {
    console.log(err)
    ElMessage.error('权限检查失败')
  })
}

const handleSelectAllChange = (val) => {
  tableData.value.forEach(row => {
    row.checked = val
  })

  if (val) {
    // 全选
    selectedRows.value = [...tableData.value]
  } else {
    // 取消全选
    selectedRows.value = []
  }
}


// 保存批量编辑
const saveBatchEdit = (form) => {
  if (!form.pickingDate) {
    ElMessage.warning('请选择执行时间')
    return
  }

  const taskIds = selectedRows.value.map(row => row.taskId)
  const request = {
    taskIds: taskIds,
    pickingDate: form.pickingDate
  }

  // 需要在API中实现批量更新接口
  batchEditDate(request).then((res) => {
    if (res.data.code === 0) {
      ElMessage.success('批量修改成功')
      showBatchEditDialog.value = false
      search()
      // 清空选择
      selectedRows.value.forEach(row => {
        row.checked = false
      })
      selectedRows.value = []
    } else {
      ElMessage.error(res.data.message)
    }
  }).catch(() => {
    ElMessage.error('批量修改失败')
  })
}

// 保存编辑
const saveEdit = (editForm) => {
  let request = {
    taskId: editForm.taskId,
    pickingDate: editForm.pickingDate
  }
  editDate( request).then((res) => {
    if (res.data.code === 0) {
      ElMessage({
        message: '操作成功',
        type: 'success',
      });
      search()
    } else {
      ElMessage({
        message: res.data.message,
        type: 'error',
      });
    }
  })
  showEditDialog.value = false
  search() // 刷新表格数据
}



// 修改加急处理函数
const handleDelete = (row) => {
  const permissionParams = {
    loginAccountUpdate: store.getters.getUser.loginAccount,
    roleIdOp: store.getters.getUser.roleId,
    userName: USER_NAME
  }

  getUserPermission(permissionParams).then(res => {
    if (res.data.code === 0) {
      // 解析权限字符串，检查是否包含"C"（加急权限）
      const permissionStr = res.data.message || ''
      if (!permissionStr.includes('B')) {
        // 无加急权限提示
        ElMessage.error('您没有加急操作的权限')
        return
      }

      // 有权限，继续执行原有逻辑
      let request = {
        taskId: row.taskId,
      }
      upOutsType(request).then((res) => {
        if (res.data.code === 0) {
          ElMessage({
            message: '操作成功',
            type: 'success',
          });
          search()
        } else {
          ElMessage({
            message: res.data.message,
            type: 'error',
          });
        }
      })
    } else {
      ElMessage.error(res.data.message || '权限检查失败')
    }
  }).catch(err => {
    console.log(err)
    ElMessage.error('权限检查失败')
  })
}
// 编辑弹窗相关
const showEditDialog = ref(false)
const editForm = reactive({
  pickingDate: '',
  taskId: ''
})
const editFormRef = ref()

// 打开编辑弹窗
const handleEdit = (row) => {
  const permissionParams = {
    loginAccountUpdate: store.getters.getUser.loginAccount,
    roleIdOp: store.getters.getUser.roleId,
    userName: USER_NAME
  }
  getUserPermission(permissionParams).then(res => {
    if (res.data.code === 0) {
      // 解析权限字符串，检查是否包含"C"（下发盘点权限）
      const permissionStr = res.data.message || ''
      if (!permissionStr.includes('B')) {
        // 无下发盘点权限提示
        ElMessage.error('您没有编辑时间的权限')
        return
      }
      editForm.taskId = row.taskId
      // 使用 formatDateToDay 处理日期，避免时区问题
      editForm.pickingDate = row.pickingDate ? formatDateToDay(row.pickingDate) : ''
      showEditDialog.value = true
    }
  })
}

const formatDateToDay = (dateString) => {
  if (!dateString) return '';
  // 直接解析日期字符串，避免时区转换
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};


/**
 * 自定义方法
 */
// 查询
const search = () => {
  tableLoading.value = true
  let request = genTableRequest(baseTableQuery)
  // 设定查询参数
  request.queryType = 1
  request.goodsId = searchQueryFormEntity.goodsId.trim()
  request.vehicleId = searchQueryFormEntity.goodsDesc.trim()
  request.workOrder = searchQueryFormEntity.workOrder.trim()
  getGoodsInfoByPage(request).then((res) => {
    const response = res.data
    if (response.code === 0) {
      const data = response.data
      if (data != null) {
        tableData.value = data.lists
        baseTableQuery.total = data.total
      } else {
        tableData.value = []
        baseTableQuery.total = 0
      }
    } else {
      ElMessage.error(response.message)
    }
  }).catch(err => {
    ElMessage.error('查询数据异常。')
  }).finally(() => {
    tableLoading.value = false
  })
}
const clearQuery = () => {
  searchQueryFormEntity.goodsId = ''
  searchQueryFormEntity.goodsDesc = ''
  searchQueryFormEntity.workOrder = ''
}
const handleSortChange = (data) => {
  if (baseTableQuery.sortBy.has(data.prop)) {
    baseTableQuery.sortBy.delete(data.prop)
  }
  baseTableQuery.sortBy.set(data.prop, data.order.toLowerCase() === 'ascending')
  search()
}
const openUploadDialog = () => {
  showUploadDialog.value = true
}
const getCurrentRow = (row) => {
  goodsId = row.goodsId
}
const exportExcel = () => {
  const params = {
    goodsId: searchQueryFormEntity.goodsId,
    goodsDesc: searchQueryFormEntity.goodsDesc,
    userName: USER_NAME
  }
  exportGoodsExcel(params).then(res => {
    const link = document.createElement('a');//创建a标签
    try {
      // let blob = new Blob([res.data],{type: 'application/vnd.ms-excel'});    //如果后台返回的不是blob对象类型，先定义成blob对象格式，该type导出为xls格式，
      let blob = res.data    //如果后台返回的直接是blob对象类型，直接获取数据
      // let _fileName = res.headers['content-disposition'].split(';')[1].split('=')[1]; //拆解获取文件名，如果后端有给返回文件名的话
      let _fileName = '物料基础信息' + dateFormatter(new Date) + '.xlsx'
      link.style.display = 'none'//隐藏

      // 兼容不同浏览器的URL对象
      const url = window.URL || window.webkitURL || window.moxURL
      link.href = url.createObjectURL(blob)
      link.setAttribute('download', _fileName.substring(_fileName.lastIndexOf('_') + 1))
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      url.revokeObjectURL(link.href)//移除url对象
    } catch (e) {
      console.log(e)
      ElMessage.error('下载文件失败')
    }
  }).catch(err => {
    console.log(err)
    ElMessage.error('导出失败')
  })
}
</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;
}

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

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

.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;
}

.btn-search {
  height: 30px;
  width: 80px;
  margin: auto 5px 5px auto;
  color: black;
}
</style>