<template>
  <el-config-provider :locale="zhCn">
    <el-container class="content">
      <div class="work-area">
        <fieldset class="search-area">
          <el-form ref="dbsQueryFormRef" :model="dbsQueryFormEntity" :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="dbsQueryFormEntity.workOrder" @keyup.enter="search()" clearable/>
                </el-form-item>
                <el-form-item label="零件号">
                  <el-input v-model="dbsQueryFormEntity.productId" @keyup.enter="search()" clearable/>
                </el-form-item>
                <el-form-item label="状态">
                  <el-select-v2 style="width: 196px" v-model="dbsQueryFormEntity.dbsStatus" placeholder="工单状态"
                                :options="addAllOptionOfOptions(dbsStatusOptions)"
                                @change="search()"></el-select-v2>
                </el-form-item>
                <el-form-item label="计划开工日期">
                  <el-date-picker v-model="dbsQueryFormEntity.planStartDate" type="date"
                                  placeholder="计划开工日期" :shortcuts="shortcuts" style="width: 196px;" clearable/>
                </el-form-item>
                <el-form-item label="需求工单列表">
                  <el-select
                      v-model="selectedOrders"
                      multiple
                      collapse-tags
                      collapse-tags-tooltip
                      placeholder="请选择工单列表"
                      style="width: 196px"
                  >
                    <el-option
                        v-for="item in orderOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                  </el-select>
                </el-form-item>
                <el-button style="height: 32px; background-color: #40E0D0;" class="btn-search"
                           @click="addAllListOfSearch()">全部添加
                </el-button>
              </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-button style="background-color: #6495ED;" class="btn-search"
                             @click="openRequirementDialog()">生成需求
                  </el-button>
                </el-row>
                <el-row>
                  <el-button style="background-color: #00CED1;" class="btn-search"
                             @click="openUploadDialog()">导入DBS
                  </el-button>
                  <el-button type="success" class="btn-search"
                             @click="exportExcel()">导出excel
                  </el-button>
                  <el-button style="background-color: #ADD8E6;" class="btn-search"
                             @click="genKanban()">生成看板
                  </el-button>
                </el-row>
              </div>
            </div>
          </el-form>
        </fieldset>
        <div class="table-area">
          <el-table :data="displayDbs" 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' }"
                    @sort-change="handleSortChange">
            <el-table-column width="65px" fixed="left">
              <template v-slot="scope">
                <el-radio :label="scope.row.dbsId" v-model="dbsId">&nbsp;</el-radio>
              </template>
            </el-table-column>
            <el-table-column prop="workOrder" label="工单" fixed="left" min-width="120px" sortable="custom"
                             show-overflow-tooltip/>
            <el-table-column prop="productIdOrigin" label="元零件号" fixed="left" min-width="120px"
                             sortable="custom" show-overflow-tooltip/>
            <el-table-column prop="productId" label="零件号" fixed="left" min-width="120px" sortable="custom"
                             show-overflow-tooltip/>
            <el-table-column prop="testPlanStartDate" label="Test计划开始时间" :formatter="dateFormat"
                             fixed="left" min-width="160px" sortable="custom" show-overflow-tooltip/>
            <el-table-column prop="testPlanFinishDate" label="Test计划完成时间" :formatter="dateFormat"
                             min-width="160px" sortable="custom" show-overflow-tooltip/>
            <el-table-column prop="pntPlanStartDate" label="PNT计划开始时间" :formatter="dateFormat"
                             min-width="170px" sortable="custom" show-overflow-tooltip/>
            <el-table-column prop="pntPlanFinishDate" label="PNT计划完成时间" :formatter="dateFormat"
                             min-width="170px" sortable="custom" show-overflow-tooltip/>
            <el-table-column prop="planProduction" label="计划产量" min-width="120px" sortable="custom"
                             show-overflow-tooltip/>
            <el-table-column prop="equipmentName" label="设备名称" min-width="120px" sortable="custom"
                             show-overflow-tooltip/>
            <el-table-column prop="workShift" label="班次" sortable="custom" min-width="120px"
                             show-overflow-tooltip/>
            <el-table-column prop="family" label="Family" min-width="120px" sortable="custom"
                             show-overflow-tooltip/>
            <el-table-column prop="testNo" label="Test No#" sortable="custom" min-width="120px"
                             show-overflow-tooltip/>
            <el-table-column prop="dbsStatus" label="状态" :formatter="dbsStatusFormat" fixed="right"
                             min-width="120px" sortable="custom" show-overflow-tooltip/>
            <el-table-column prop="workStand" label="工作站台" min-width="120px" sortable="custom"
                             show-overflow-tooltip/>
            <el-table-column prop="realWorkDate" label="实际工作日期" sortable="custom" :formatter="dateFormat"
                             min-width="140px" show-overflow-tooltip/>
            <el-table-column prop="finishTime" label="完成时间" min-width="120px" :formatter="timeFormat"
                             sortable="custom" show-overflow-tooltip/>
            <el-table-column prop="kittingRemark" label="K料备注" sortable="custom" min-width="120px"
                             show-overflow-tooltip/>
            <el-table-column prop="remark" label="备注" min-width="120px" sortable="custom"
                             show-overflow-tooltip/>
            <el-table-column fixed="right" label="操作" width="240px">
              <template v-slot="scope">
                <el-button plain type="primary" @click="addRequirement(scope.row)">添加需求</el-button>
                <el-button plain type="danger" @click="deleteCurrentRow(scope.row)">删除</el-button>
              </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="showGoodsRequireDialog" title="物料需求" width="50%" center>
          <el-button type="success" style="margin-left: 5px" @click="exportRequirements()">导出需求</el-button>
          <el-table :data="goodsRequireList" stripe border class="table-class" max-height="450px"
                    :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }">
            <el-table-column prop="goodsId" show-overflow-tooltip label="料号" fixed="left"/>
            <el-table-column prop="goodsDesc" show-overflow-tooltip label="描述"/>
            <el-table-column prop="needQty" show-overflow-tooltip label="需求数量"/>
            <el-table-column prop="stockQty" show-overflow-tooltip label="库存数量"/>
            <el-table-column prop="lackQty" show-overflow-tooltip label="缺少数量"/>
            <el-table-column prop="goodsType" show-overflow-tooltip label="补料类型"/>
            <el-table-column prop="stockType" show-overflow-tooltip label="存放类型"/>
          </el-table>
        </el-dialog>
        <el-dialog v-model="showDbsUploadDialog" title="上传DBS" width="40%" draggable :show-close="true">
          <fieldset class="search-area">
            <legend>导入dbs</legend>
            <UploadExcelDbs></UploadExcelDbs>
          </fieldset>
        </el-dialog>
      </div>
    </el-container>
  </el-config-provider>
</template>

<script setup>
import store from '@/store'
import {
  queryDbsByPage,
  deleteDbsPlan,
  getGoodsRequirement,
  genClcKanbanRequirement,
  getTargetOrderList
} from '@/api/kateWork.js'
import {dateFormatter, timeFormatter} from '@/utils/formatter.js'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import {ref, reactive, onMounted, nextTick, onBeforeUnmount} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {genTableRequest, addAllOptionOfOptions} from '@/utils/generator.js'
import {labelPosition, shortcuts} from '@/constant/form'
import {dbsStatusOptions} from '@/constant/options'
import UploadExcelDbs from '@/excel/UploadExcelDbs.vue'
import {exportDbsWithExcel} from '@/api/excel'
import {loading} from "@/utils/loading";
import {useRouter} from 'vue-router';
import {exportToExcel} from "@/utils/excelUtils";

/**
 * 常量定义
 */
const USER_NAME = store.getters.getUserName
const STAND_ID = store.getters.getStandId
const router = useRouter()
/**
 * 变量定义
 */
let maxHeight = ref(window.innerHeight * 0.55)
let tableLoading = ref(false)
let displayDbs = ref([])
let baseTableQuery = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  sortBy: new Map([['workOrder', true]]),// 按照工单顺序排序
  standId: STAND_ID,
  userName: USER_NAME
})
let dbsQueryFormEntity = reactive({
  workOrder: '',
  productId: '',
  dbsStatus: -99,
  planStartDate: null
})
let dbsQueryFormRef = ref()
let dbsId = ''
let showDbsUploadDialog = ref(false)
let selectedOrders = ref([])
let orderOptions = ref([])
let goodsRequireList = ref([])
let showGoodsRequireDialog = ref(false)
/**
 * 系统方法
 */
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
  let request = genTableRequest(baseTableQuery)
  // 设定查询参数
  request.workOrder = dbsQueryFormEntity.workOrder.trim()
  request.productId = dbsQueryFormEntity.productId.trim()
  request.dbsStatus = dbsQueryFormEntity.dbsStatus === -99 ? null : dbsQueryFormEntity.dbsStatus
  request.planStartDate = dateFormatter(dbsQueryFormEntity.planStartDate)
  queryDbsByPage(request).then((res) => {
    const response = res.data
    if (response.code === 0) {
      const data = response.data
      if (data != null) {
        displayDbs.value = data.lists
        baseTableQuery.total = data.total
      } else {
        displayDbs.value = []
        baseTableQuery.total = 0
      }
    } else {
      ElMessage.error(response.message)
    }
  }).catch(err => {
    console.log(err)
    ElMessage.error('查询DBS数据异常。')
  }).finally(() => {
    tableLoading.value = false
  })
}
const clearQuery = () => {
  dbsQueryFormEntity.workOrder = ''
  dbsQueryFormEntity.productId = ''
  dbsQueryFormEntity.dbsStatus = -99
  dbsQueryFormEntity.planStartDate = null
}
const dbsStatusFormat = (row, column, cellValue, index) => {
  switch (cellValue) {
    case 0:
      return '未开始'
    case 1:
      return '已开始'
    case 2:
      return '已完成'
    default:
      return '未知状态'
  }
}
const dateFormat = (row, column, cellValue, index) => {
  return dateFormatter(cellValue)
}
const timeFormat = (row, column, cellValue, index) => {
  return timeFormatter(cellValue)
}
const rowStyle = ({row, rowIndex}) => {
  if (row.dbsStatus === 2) {
    return {"color": "green"}
  }
}
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 getCurrentRow = (row) => {
  dbsId = row.dbsId
}
const exportExcel = () => {
  const params = {
    workOrder: dbsQueryFormEntity.workOrder,
    productId: dbsQueryFormEntity.productId,
    dbsStatus: dbsQueryFormEntity.dbsStatus === -99 ? null : dbsQueryFormEntity.dbsStatus,
    planStartDate: dateFormatter(dbsQueryFormEntity.planStartDate)
  }
  exportDbsWithExcel(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 = 'DBS计划' + 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('导出失败')
  })
}
// 删除当前行dbs
const deleteCurrentRow = (row) => {
  ElMessageBox.confirm(
      '当前操作涉及删除工单计划。\n是否确认',
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    const request = {
      dbsId: row.dbsId,
      userName: USER_NAME,
      standId: STAND_ID
    }
    loading.open('删除中...')
    deleteDbsPlan(request).then(res => {
      const response = res.data
      if (response.code === 0) {
        ElMessage.success(response.message)
      } else {
        ElMessage.error(response.message)
      }
    }).catch(err => {
      console.log(err)
      ElMessage.error('删除异常')
    }).finally(() => {
      search()
      loading.close()
    })
  }).catch(() => {
    ElMessage.info('操作取消')
  })
}
const openUploadDialog = () => {
  showDbsUploadDialog.value = true
}
// 添加需求
const addRequirement = (row) => {
  const workOrder = row.workOrder
  if (workOrder === undefined || workOrder === '') {
    ElMessage.error('请先选择工单')
    return
  }
  // 判断之前是否选择过
  if (orderOptions.value.length > 0) {
    const oldOption = orderOptions.value.find((item) => {
      return item.value === workOrder
    })
    if (oldOption === undefined) {
      orderOptions.value.push({
        label: workOrder,
        value: workOrder
      })
    }
  } else {
    orderOptions.value.push({
      label: workOrder,
      value: workOrder
    })
  }
  addSelectWorkOrders(workOrder)
}
// 添加选择列表
const addSelectWorkOrders = (workOrder) => {
  if (selectedOrders.value.find((item) => {
    return item === workOrder
  }) === undefined) {
    selectedOrders.value.push(workOrder)
  } else {
    ElMessage.error('请勿重复添加工单')
  }
}
// 打开物料需求界面
const openRequirementDialog = () => {
  if (selectedOrders.value.length === 0) {
    ElMessage.error('请选择工单。')
    return
  }
  // 生成请求
  const request = {
    orderIds: selectedOrders.value,
    userName: USER_NAME,
    standId: STAND_ID
  }
  getGoodsRequirement(request).then(res => {
    const response = res.data
    if (response.code === 0) {
      if (response.data != null && response.data.length > 0) {
        goodsRequireList.value = response.data
      } else {
        goodsRequireList.value = []
      }
      showGoodsRequireDialog.value = true
      // 下载工单号列表
      downloadSelectedOrders()
    } else {
      ElMessage.error(response.message)
    }
  }).catch(err => {
    console.log(err)
    ElMessage.error('获取需求列表异常。')
  })
}
// 导出需求
const exportRequirements = () => {
  try {
    const header = {
      goodsId: '料号',
      goodsDesc: '物料描述',
      needQty: '需求数量',
      stockQty: '库存数量',
      lackQty: '缺少数量',
      goodsType: '补料类型',
      stockType: '存放类型'
    }
    exportToExcel(header, goodsRequireList.value, '工单需求', '工单需求')
  } catch (e) {
    console.log(e)
    ElMessage.error('导出需求异常。')
  }
}
// 生成看板
const genKanban = () => {
  if (selectedOrders.value.length === 0) {
    ElMessage.error('请选择工单。')
    return
  }
  const request = {
    orderIds: selectedOrders.value,
    standId: STAND_ID,
    userName: USER_NAME
  }
  loading.open('生成中...')
  genClcKanbanRequirement(request).then(res => {
    const response = res.data
    if (response.code === 0) {
      // 下载工单号列表
      downloadSelectedOrders()
      // 如果有看板数量不够的情况
      if (response.data !== null && response.data.length > 0) {
        downloadLackOrders(response.data)
        ElMessage.success('生成看板需求成功，但部分物料缺少看板。')
      } else {
        ElMessage.success('生成看板需求成功。')
      }
      // 跳转界面
      const menuItem = store.getters.getMenuItemByPath('/clcKanban')
      if (menuItem !== undefined) {
        store.commit('mutationSelectTags', menuItem)
        router.push(menuItem.path)
      }
    } else {
      ElMessage.error(response.message)
    }
  }).catch(err => {
    console.log(err)
    ElMessage.error('生成看板需求异常。')
  }).finally(() => {
    loading.close()
  })
}
// 全部添加
const addAllListOfSearch = () => {
  loading.open('添加中...')
  const request = {
    userName: USER_NAME,
    standId: STAND_ID,
    workOrder: dbsQueryFormEntity.workOrder.trim(),
    productId: dbsQueryFormEntity.productId.trim(),
    planStartDate: dateFormatter(dbsQueryFormEntity.planStartDate)
  }
  getTargetOrderList(request).then(res => {
    const response = res.data
    if (response.code === 0) {
      // 添加所有的需求
      addOrders(response.data)
    } else {
      ElMessage.error(response.message)
    }
  }).catch(err => {
    console.log(err)
    ElMessage.error('获取工单号列表异常。')
  }).finally(() => {
    loading.close()
  })
}
// 添加需求进选项
const addOrders = (orderList) => {
  if (orderList === undefined || orderList.length === 0) {
    // 空列表跳过
    return
  }
  for (let i = 0; i < orderList.length; i++) {
    const workOrder = orderList[i]
    // 判断之前是否选择过
    if (orderOptions.value.length > 0) {
      const oldOption = orderOptions.value.find((item) => {
        return item.value === workOrder
      })
      if (oldOption === undefined) {
        orderOptions.value.push({
          label: workOrder,
          value: workOrder
        })
      }
    } else {
      orderOptions.value.push({
        label: workOrder,
        value: workOrder
      })
    }
    // 添加选择项
    if (selectedOrders.value.find((item) => {
      return item === workOrder
    }) === undefined) {
      selectedOrders.value.push(workOrder)
    }
  }
}
// 弹出下载
const downloadSelectedOrders = () => {
  try {
    const header = {
      workOrder: '工单号'
    }
    // 将列表转化为实体
    const selectedOrdersEntity = selectedOrders.value.map((item) => {
      return {
        workOrder: item
      }
    })
    exportToExcel(header, selectedOrdersEntity, '已选工单列表', '已选工单列表')
  } catch (e) {
    console.log(e)
    ElMessage.error('导出选择的工单列表异常。')
  }
}
// 弹出下载缺少的看板
const downloadLackOrders = (lackKanbanList) => {
  try {
    const header = {
      goodsId: '料号',
      needKanbanQty: '需要看板数量',
      haveKanbanQty: '已有看板数量',
      lackKanbanQty: '缺少看板数量',
    }
    exportToExcel(header, lackKanbanList, '缺少看板', '缺少看板详情')
  } catch (e) {
    console.log(e)
    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;
}

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