<script setup lang="ts">
import {
  factoryWarehouseInfo,
  warehouseInfo,
  getFactoryLocation,
  warehouseInfoGetAll,
  createPositionApi,
  updatePositionApi,
  positionInfo,
  deleteLocationApi,
  positionFormInfo,
  updatePositionStatusApi,
  factoryWarehouseInfoPrint,
  importWarehouseLocation,
} from '@/api/warehouse.ts'
const uploadExcelRef = ref()
import { Download } from '@element-plus/icons-vue'
import { nextTick, ref } from 'vue'
import SplitDiv from '@/components/splitDiv/splitDiv.vue'
import { filePath } from '@/api/axios.ts'
import UploadExcel from '@/components/UploadExcel.vue'
const importDialogVisible = ref(false)
const importedFileUrl = ref('')
const importLocation = async () => {
  importDialogVisible.value = true
  importedFileUrl.value = ''
  nextTick(() => {
    uploadExcelRef.value?.resetUpload()
  })
}
const handleLocalImport = async ({
  path,
  data,
}: {
  path: string
  data: Blob
}) => {
  try {
    const formData = new FormData()
    formData.append('importExcel', data)
    const res = await importWarehouseLocation(formData)
    if (res.code == 200) {
      importedFileUrl.value = path
      ElMessage.success('导入成功')
      await getData()
    } else {
      importedFileUrl.value = ''
      ElMessage.error(res.message || '导入失败')
    }
  } catch (error) {
    importedFileUrl.value = ''
    ElMessage.error('导入失败')
  } finally {
    importDialogVisible.value = false
    importedFileUrl.value = ''
  }
}
const downloadTemplate = () => {
  const link = document.createElement('a')
  link.href = '/files/warehouseLocationTemplate.xlsx'
  link.download = 'warehouseLocationTemplate.xlsx'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
// const importLoading = ref(false)
const searchForm = ref({
  warehouseId: '',
  locationCode: '',
  status: '',
  locationName: '',
  remark: '',
})
const warehouseList = ref<warehouseInfo[]>([])
const selections = ref<positionInfo[]>([])
const formRef = ref()
const form = ref<positionFormInfo>({
  locationName: '',
  locationCode: '',
  pickingOrder: '',
  warehouseName: '',
  warehouseId: '',
  remark: '',
  status: 1,
})
const createData = ref({
  title: '',
  show: false,
  isEdit: false,
  form: {
    locationName: '',
    locationCode: '',
    pickingOrder: '',
    warehouseName: '',
    warehouseId: '',
    remark: '',
  },
})
const rules = {
  locationName: [
    { required: true, message: '请输入库位名称', trigger: 'blur' },
  ],
  locationCode: [
    { required: true, message: '请输入库位编码', trigger: 'blur' },
  ],
  pickingOrder: [
    { required: true, message: '请输入拣货顺序', trigger: 'blur' },
  ],
  warehouseId: [{ required: true, message: '请选择仓库', trigger: 'change' }],
}
const leftData = ref<positionInfo[]>([])
const pagination = ref<factoryWarehouseInfo>({
  pageSize: 50,
  currentPage: 1,
  total: 0,
})

async function getData() {
  const res = await getFactoryLocation({
    ...pagination.value,
    ...searchForm.value,
  })
  leftData.value = res.data.records
  pagination.value.total = res.data.total
}

const handleSelectionChange = (data: positionInfo[]) => {
  selections.value = data
}
const handleSizeChange = (pageSize: number) => {
  pagination.value.pageSize = pageSize
  getData()
}
const handleCurrentChange = (currentPage: number) => {
  pagination.value.currentPage = currentPage
  getData()
}
const handleConfirm = async () => {
  await formRef.value?.validate()
  if (!createData.value.isEdit) {
    await createPositionApi(form.value)
  } else {
    await updatePositionApi(form.value)
  }
  createData.value.show = false
  ElMessage.success('操作成功')
  await getData()
}
const locationLabelVisible = ref(false)
const locationRadio = ref('PT001')

async function printLocationTag() {
  if (!selections.value.length) {
    return ElMessage.warning('请选择数据')
  }
  locationLabelVisible.value = true
}
async function submitLocationTag() {
  const list = selections.value.map((item) => {
    return {
      locationName: item.locationCode,
      pickingLocation: item.locationName,
    }
  })
  const res = await factoryWarehouseInfoPrint({
    list,
    code: locationRadio.value,
  })
  window.open(filePath + res.message, '_blank')
  locationLabelVisible.value = false
}
const handleBatchDelete = async (row: positionInfo | null) => {
  if (!row && !selections.value.length) {
    return ElMessage.warning('请选择要删除的数据')
  }
  await ElMessageBox.confirm('确定要删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  const str =
    row && row.id
      ? row.id?.toString()
      : selections.value.map((el) => el.id).join(',')
  await deleteLocationApi(str)
  ElMessage.success('删除成功')
  await getData()
}

// const importLocation = async () => {
//   const i = document.createElement('input')
//   i.type = 'file'
//   i.style.display = 'none'
//   i.accept = '.xlsx,.xls'
//   i.click()

//   i.onchange = async () => {
//     if (i && i.files) {
//       importLoading.value = true
//       try {
//         console.log(i.files[0])
//         // const formData = new FormData()
//         // formData.append('importExcel', i.files[0])
//         // await importWarehouseLocation(formData)
//         // ElMessage.success('导入成功')
//         // await getData()
//       } finally {
//         importLoading.value = false
//       }
//     }
//   }
// }
const createWarehouse = () => {
  createData.value.show = true
  createData.value.isEdit = false
  createData.value.title = '新增库位'
  const warehouse = warehouseList.value.find((w) => w.defaulted === 1)
  form.value = {
    locationName: '',
    locationCode: '',
    pickingOrder: '',
    warehouseName: warehouse ? warehouse.name : '',
    warehouseId: warehouse ? warehouse.id : '',
    remark: '',
    status: 1,
  }
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}
const updateStatus = async (item: positionInfo) => {
  await updatePositionStatusApi({
    id: item.id,
    status: item.status,
  })
}
const updateWarehouse = (item: positionFormInfo) => {
  createData.value.show = true
  createData.value.isEdit = true
  createData.value.title = '修改仓库'
  form.value = {
    id: item.id,
    locationName: item.locationName,
    locationCode: item.locationCode,
    pickingOrder: item.pickingOrder,
    warehouseName: item.warehouseName,
    warehouseId: item.warehouseId,
    remark: item.remark,
    status: item.status,
  }
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}
getData()
const getWarehouse = async () => {
  const { data } = await warehouseInfoGetAll()
  warehouseList.value = data
}
const warehouseChange = (v: number) => {
  const warehouse = warehouseList.value.find((w) => w.id == v)
  form.value.warehouseName = warehouse ? warehouse.name : ''
}
getWarehouse()
</script>

<template>
  <split-div>
    <template #top>
      <el-card>
        <el-form inline :model="searchForm">
          <el-form-item label="仓库">
            <el-select
              v-model="searchForm.warehouseId"
              placeholder="请选择仓库"
              clearable
              filterable
              style="width: 150px"
            >
              <el-option
                v-for="item in warehouseList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="库位名称">
            <el-input
              v-model="searchForm.locationName"
              style="width: 140px"
              placeholder="请输入库位名称"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="库位编码">
            <el-input
              v-model="searchForm.locationCode"
              style="width: 140px"
              placeholder="请输入库位编码"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              v-model="searchForm.remark"
              style="width: 140px"
              placeholder="请输入备注"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
              filterable
              style="width: 150px"
            >
              <el-option
                v-for="(item, index) in ['禁用', '启用']"
                :key="index"
                :label="item"
                :value="index"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getData">查询</el-button>
            <el-button type="success" @click="createWarehouse"
              >新增库位</el-button
            >
            <el-button type="primary" @click="importLocation"
              >导入库位</el-button
            >
            <el-button type="primary" @click="printLocationTag"
              >打印库位标签</el-button
            >
            <el-button type="danger" @click="handleBatchDelete(null)"
              >删除</el-button
            >
          </el-form-item>
        </el-form>
      </el-card>
    </template>
    <template #bottom>
      <el-card style="height: 100%">
        <div class="manage">
          <div class="table-flex">
            <div class="left-table">
              <div class="table-container">
                <el-table
                  height="100%"
                  :data="leftData"
                  border
                  @selection-change="handleSelectionChange"
                >
                  <el-table-column type="selection" />
                  <el-table-column type="index" label="序号" width="60" />
                  <el-table-column
                    width="100"
                    label="启用状态"
                    prop="status"
                    align="center"
                  >
                    <template #default="{ row }">
                      <el-switch
                        v-model="row.status"
                        :active-value="1"
                        :inactive-value="0"
                        @click="updateStatus(row)"
                      ></el-switch>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="所属仓库"
                    prop="warehouseName"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    label="库位名称"
                    prop="locationName"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    label="库位编码"
                    prop="locationCode"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    label="拣货顺序"
                    prop="pickingOrder"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    label="备注"
                    prop="remark"
                  ></el-table-column>

                  <el-table-column label="操作" align="center">
                    <template #default="{ row }">
                      <el-button type="primary" @click="updateWarehouse(row)"
                        >编辑</el-button
                      >
                      <el-button type="danger" @click="handleBatchDelete(row)"
                        >删除</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <div class="pagination">
                <el-pagination
                  v-model:current-page="pagination.currentPage"
                  v-model:page-size="pagination.pageSize"
                  :page-sizes="[50, 100, 150, 200]"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="pagination.total"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                />
              </div>
            </div>
          </div>
          <el-dialog
            v-model="createData.show"
            width="500px"
            :title="createData.title"
          >
            <el-form
              ref="formRef"
              label-width="110px"
              :rules="rules"
              :model="form"
            >
              <el-form-item label="库位名称" prop="locationName">
                <el-input
                  v-model="form.locationName"
                  clearable
                  placeholder="请输入库位名称"
                ></el-input>
              </el-form-item>
              <el-form-item label="库位编码" prop="locationCode">
                <el-input
                  v-model="form.locationCode"
                  clearable
                  placeholder="请输入库位编码（例如：A1-01-03）"
                ></el-input>
              </el-form-item>
              <el-form-item label="拣货顺序" prop="pickingOrder">
                <el-input-number
                  v-model="form.pickingOrder"
                  placeholder="拣货顺序"
                ></el-input-number>
              </el-form-item>
              <el-form-item label="所属仓库" prop="warehouseId">
                <el-select v-model="form.warehouseId" @change="warehouseChange">
                  <el-option
                    v-for="item in warehouseList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="备注" prop="remark">
                <el-input
                  v-model="form.remark"
                  type="textarea"
                  :rows="4"
                  clearable
                  placeholder="请输入备注"
                ></el-input>
              </el-form-item>
              <el-form-item label="状态" prop="status">
                <el-switch
                  v-model="form.status"
                  :active-value="1"
                  :inactive-value="0"
                ></el-switch>
              </el-form-item>
            </el-form>
            <template #footer>
              <el-button @click="createData.show = false">取消</el-button>
              <el-button type="primary" @click="handleConfirm">确定</el-button>
            </template>
          </el-dialog>
        </div>
      </el-card>
    </template>
  </split-div>
  <ElDialog
    v-model="importDialogVisible"
    title="导入"
    width="500px"
    :close-on-click-modal="false"
  >
    <div class="import-dialog">
      <div class="import-header">
        <el-button type="primary" link @click="downloadTemplate">
          <el-icon><Download /></el-icon>
          下载模板
        </el-button>
      </div>
      <div class="import-content">
        <UploadExcel
          ref="uploadExcelRef"
          v-model="importedFileUrl"
          :import-type="'localAndUpload'"
          @imported="handleLocalImport"
        />
      </div>
    </div>
  </ElDialog>
  <ElDialog
    v-model="locationLabelVisible"
    title="打印库位标签"
    width="500px"
    :close-on-click-modal="false"
  >
    <div class="mb-2 ml-4 location-box">
      <span class="location-label">打印库位标签格式:</span>
      <el-radio-group v-model="locationRadio">
        <el-radio value="PT001" size="large">中文</el-radio>
        <el-radio value="PT001_EN" size="large">英文</el-radio>
      </el-radio-group>
    </div>
    <template #footer>
      <el-button @click="locationLabelVisible = false">取消</el-button>
      <el-button type="primary" @click="submitLocationTag">确定</el-button>
    </template>
  </ElDialog>
</template>

<style scoped lang="scss">
.el-card {
  ::v-deep(.el-card__body) {
    height: 100%;
  }
}
.location-box {
  display: flex;
  align-items: center;
  .location-label {
    color: #606266;
    margin:0 15px;
  }
}
.import-dialog {
  .import-header {
    display: flex;
    justify-content: flex-end;
  }

  .import-content {
    padding-bottom: 20px;
  }
}
.manage {
  height: 100%;
  display: flex;
  flex-direction: column;

  .header {
    margin-bottom: 10px;
  }

  .table-flex {
    flex: 1;
    flex-shrink: 0;
    overflow: hidden;
    display: flex;
  }

  .right-table {
    flex: 1;
    margin-left: 10px;
    flex-shrink: 0;
  }

  .left-table {
    height: 100%;
    display: flex;
    width: 100%;
    flex-direction: column;

    .pagination {
      display: flex;
      margin-top: 10px;
      justify-content: center;
    }

    .table-container {
      flex: 1;
      flex-shrink: 0;
      overflow: hidden;
    }
  }
}
</style>
