<script setup lang="ts">
import { Ilogistics, IsortingInfo } from '@/types/api/logistics'
import { Edit, Delete, CirclePlus } from '@element-plus/icons-vue'
import {
  getsortingConfigListApi,
  usableAllList,
  createSortingApi,
  updateSortingApi,
  deleteSortingApi,
} from '@/api/logistics'
import { nextTick, ref } from 'vue'
import SplitDiv from '@/components/splitDiv/splitDiv.vue'
import usePageList from '@/utils/hooks/usePageList'
import { ElMessage, ElMessageBox } from 'element-plus'
interface InterForm {
  id?: number
  sortingFacility?: string | null
  sortingArea: number | null
  sortingAreaName?: string | null
  serviceCode: string[]
}
const searchForm = ref({
  sortingFacility: '',
  sortingArea: null,
  serviceCode: [],
})
const selections = ref<IsortingInfo[]>([])
const formRef = ref()
const form = ref<InterForm>({
  sortingFacility: '',
  sortingArea: null,
  sortingAreaName: '',
  serviceCode: [],
})
const createData = ref({
  title: '',
  show: false,
  isEdit: false,
  form: {
    sortingFacility: '',
    sortingArea: null,
    sortingAreaName: '',
    serviceCode: [],
  },
})
const rules = {
  sortingFacility: [
    { required: true, message: '请输入分拣设备', trigger: 'blur' },
  ],
  sortingArea: [{ required: true, message: '请选择分拣口', trigger: 'change' }],
  serviceCode: [
    { required: true, message: '请选择物流方式', trigger: 'change' },
  ],
}
const {
  currentPage,
  pageSize,
  total,
  data: tableData,
  refresh: search,
  onCurrentPageChange: handleCurrentChange,
  onPageSizeChange: handleSizeChange,
} = usePageList({
  query: (page, pageSize) =>
    getsortingConfigListApi(
      {
        ...searchForm.value,
        serviceCode: searchForm.value.serviceCode.join(','),
      },
      page,
      pageSize,
    ).then((res) => res.data),
})
const logisticsMethodsList = ref<Ilogistics[]>([])
const getlogisticsMethods = async () => {
  const res = await usableAllList()
  logisticsMethodsList.value = res.data || []
}
interface interSorting {
  label: string
  value: number
}
const sortingList = ref<interSorting[]>([
  {
    label: 'L1',
    value: 1,
  },
  {
    label: 'R1',
    value: 2,
  },
  {
    label: 'L2',
    value: 3,
  },
  {
    label: 'R2',
    value: 4,
  },
  {
    label: 'L3',
    value: 5,
  },
  {
    label: 'R3',
    value: 6,
  },
  {
    label: 'L4',
    value: 7,
  },
  {
    label: 'R4',
    value: 8,
  },
  {
    label: 'E0',
    value: 99,
  },
])
const handleSelectionChange = (data: IsortingInfo[]) => {
  selections.value = data
}
const handleConfirm = async () => {
  await formRef.value?.validate()
  if (!createData.value.isEdit) {
    await createSortingApi({
      ...form.value,
      serviceCode: form.value.serviceCode.join(','),
    })
  } else {
    await updateSortingApi({
      ...form.value,
      serviceCode: form.value.serviceCode.join(','),
    })
  }
  createData.value.show = false
  ElMessage.success('操作成功')
  await search()
}
const handleBatchDelete = async (row: IsortingInfo | 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: IsortingInfo) => el.id).join(',')
  await deleteSortingApi(str)
  ElMessage.success('删除成功')
  await search()
}
const addLogistics = () => {
  ElMessageBox.prompt('', '物流方式', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputErrorMessage: '请输入物流方式',
    inputPlaceholder: '请输入物流方式',
  }).then(({ value }: { value: string }) => {
    if (!value.trim()) {
      ElMessage.error('物流方式不能为空')
      return
    }
    if (form.value.serviceCode.includes(value)) {
      ElMessage.warning('物流方式已存在')
      return
    }
    form.value.serviceCode.push(value)
    ElMessage.success('添加成功')
  })
}
const createWarehouse = () => {
  createData.value.show = true
  createData.value.isEdit = false
  createData.value.title = '新增'
  form.value = {
    sortingFacility: '',
    sortingArea: null,
    sortingAreaName: '',
    serviceCode: [],
  }
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}
const updateSorting = (item: IsortingInfo) => {
  createData.value.show = true
  createData.value.isEdit = true
  createData.value.title = '修改'
  form.value = {
    id: item.id,
    sortingFacility: item.sortingFacility,
    sortingArea: item.sortingArea,
    sortingAreaName: item.sortingAreaName,
    serviceCode: item.serviceCode ? item.serviceCode.split(',') : [],
  }
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}
getlogisticsMethods()
const sortingChange = (v: number) => {
  const warehouse = sortingList.value.find((w: interSorting) => w.value == v)
  form.value.sortingAreaName = warehouse ? warehouse.label : ''
}
</script>

<template>
  <split-div>
    <template #top>
      <el-card>
        <el-form inline :model="searchForm">
          <el-form-item label="分拣设备">
            <el-input
              v-model.trim="searchForm.sortingFacility"
              placeholder="分拣设备"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="分拣口">
            <el-select
              v-model="searchForm.sortingArea"
              clearable
              style="width: 160px"
            >
              <el-option
                v-for="item in sortingList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="物流方式">
            <el-select
              v-model="searchForm.serviceCode"
              clearable
              filterable
              multiple
              style="width: 160px"
            >
              <el-option
                v-for="item in logisticsMethodsList"
                :key="item.serviceCode"
                :label="item.serviceCode"
                :value="item.serviceCode"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="search">查询</el-button>
            <el-button type="success" @click="createWarehouse">新增</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="tableData"
                  border
                  @selection-change="handleSelectionChange"
                >
                  <el-table-column type="selection" />
                  <el-table-column
                    type="index"
                    label="序号"
                    width="60"
                    align="center"
                  />
                  <el-table-column
                    align="center"
                    label="分拣设备"
                    width="540"
                    show-overflow-tooltip
                    prop="sortingFacility"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    label="分拣口名称"
                    prop="sortingAreaName"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    label="物流编码"
                    width="540"
                    show-overflow-tooltip
                    prop="serviceCode"
                  ></el-table-column>
                  <el-table-column label="操作" align="center" width="100">
                    <template #default="{ row }">
                      <el-icon
                        size="24"
                        title="编辑"
                        color="#EF6C00"
                        style="cursor: pointer; vertical-align: middle"
                        @click="updateSorting(row)"
                      >
                        <Edit />
                      </el-icon>
                      <el-icon
                        size="24"
                        title="删除"
                        color="#f56c6c"
                        style="cursor: pointer; vertical-align: middle"
                        @click="handleBatchDelete(row)"
                      >
                        <Delete />
                      </el-icon>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <div class="pagination">
                <ElPagination
                  v-model:current-page="currentPage"
                  v-model:page-size="pageSize"
                  :page-sizes="[100, 200, 300, 400, 500]"
                  background
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="total"
                  style="margin: 10px auto 0; text-align: right"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                ></ElPagination>
              </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="sortingFacility">
                <el-input
                  v-model.trim="form.sortingFacility"
                  placeholder="分拣设备"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item label="分拣口" prop="sortingArea">
                <el-select
                  v-model="form.sortingArea"
                  clearable
                  @change="sortingChange"
                >
                  <el-option
                    v-for="item in sortingList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="物流方式" prop="serviceCode">
                <div class="flex">
                  <el-select
                    v-model="form.serviceCode"
                    style="width: 320px"
                    clearable
                    filterable
                    multiple
                  >
                    <el-option
                      v-for="item in logisticsMethodsList"
                      :key="item.serviceCode"
                      :label="item.serviceCode"
                      :value="item.serviceCode"
                    ></el-option>
                  </el-select>
                  &ensp;
                  <el-icon
                    color="#409eff"
                    size="30"
                    title="添加物流方式"
                    class="add-btn"
                    @click="addLogistics"
                    ><CirclePlus
                  /></el-icon>
                </div>
              </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>
</template>

<style scoped lang="scss">
.el-card {
  ::v-deep(.el-card__body) {
    height: 100%;
  }
}

.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;
    }
  }
}
.add-btn :hover {
  cursor: pointer;
}
</style>
