<script setup lang="ts">
import {
  getFactoryWarehouseInfo,
  factoryWarehouseInfo,
  warehouseInfo,
  createWarehouseApi,
  updateWarehouseApi, deleteWarehouseApi, logisticsAddressGetAllList, Address,
} from '@/api/warehouse.ts'
import { nextTick, ref } from 'vue'
// import { add } from 'lodash-es'

const selections = ref<warehouseInfo[]>([])
const formRef = ref()
const createData = ref({
  title: '',
  show: false,
  isEdit: false,
  form: {
    name: '',
    code: '',
    addressId: '',
    sort: '',
    defaulted: 0,
    remarks: '',
  },
})
const rules = {
  name: [
    { required: true, message: '请输入仓库名称', trigger: 'blur' },
  ],
  code: [
    { required: true, message: '请输入仓库编码', trigger: 'blur' },
  ],
  defaulted: [
    { required: true, message: '请选择是否默认仓库', trigger: 'change' },
  ],
  addressId: [
    { required: true, message: '请选择地址', trigger: 'change' },
  ],
}
const leftData = ref<warehouseInfo[]>([])
const pagination = ref<factoryWarehouseInfo>({
  pageSize: 50,
  currentPage: 1,
  total: 0,
})
const addressList = ref<Address[]>([])

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

const handleSelectionChange = (data: warehouseInfo[]) => {
  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 createWarehouseApi(createData.value.form)
  } else {
    await updateWarehouseApi(createData.value.form)
  }
  createData.value.show = false
  ElMessage.success('操作成功')
  await getData()
}

const handleBatchDelete = async () => {
  if (!selections.value.length) {
    return ElMessage.warning('请选择要删除的数据')
  }
  await ElMessageBox.confirm('确定要删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  const str = selections.value.map((el) => el.id).join(',')
  try {
    await deleteWarehouseApi(str)
    ElMessage.success('删除成功')
    await getData()
  } catch (error) {
    await getData()
  }
}
const createWarehouse = () => {
  createData.value.show = true
  createData.value.isEdit = false
  createData.value.title = '新增仓库'
  createData.value.form = {
    name: '',
    code: '',
    addressId: '',
    sort: '',
    defaulted: 0,
    remarks: '',
  }
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}
const updateDefaulted = async (item: warehouseInfo) => {
  await updateWarehouseApi({
    id: item.id,
    defaulted: item.defaulted,
  })
  await getData()
}
const updateWarehouse = (item: warehouseInfo) => {
  createData.value.show = true
  createData.value.isEdit = true
  createData.value.title = '修改仓库'
  createData.value.form = { ...item }
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}
const getAddress = (id:number) => {
  if(!id) return ''
  const item = addressList.value.find((el) => el.id === id)
  if(!item) return  ''
  return  [item.countryName,
    item.stateProvince,
    item.city,
    item.addressLine1,
    item.addressLine2 ,
    item.addressLine3 ,].filter(el => el).join(' ')
}
const getAddressList = async () => {
  const data = await logisticsAddressGetAllList()
  addressList.value = data.data
}
getData()
getAddressList()
</script>

<template>
  <el-card style="height: 100%">
    <div class="manage">
      <div class="header">
        <el-button type="success" @click="createWarehouse">新增仓库</el-button>
        <el-button type="danger" @click="handleBatchDelete">删除</el-button>
      </div>
      <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 label="仓库名称" prop="name" align="center" />
              <el-table-column label="仓库编码" prop="code" align="center" />
              <el-table-column show-overflow-tooltip label="地址" prop="addressId" align="center">
                <template #default="{row}">
                  {{getAddress(row.addressId)}}
                </template>
              </el-table-column>
              <el-table-column width="90" label="仓库序号" prop="sort" align="center" />
              <el-table-column label="备注" prop="remarks" align="center" />
              <el-table-column width="90" label="默认仓库" prop="defaulted" align="center">
                <template #default="{row}">
                  <el-switch
                    v-model="row.defaulted" :active-value="1" :inactive-value="0"
                    @click="updateDefaulted(row)"></el-switch>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center">
                <template #default="{row}">
                  <el-button type="primary" @click="updateWarehouse(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" :title="createData.title">
        <el-form ref="formRef" label-width="110px" :rules="rules" :model="createData.form">
          <el-form-item label="仓库名称" prop="name">
            <el-input v-model="createData.form.name" clearable placeholder="请输入仓库名称"></el-input>
          </el-form-item>
          <el-form-item label="仓库编码" prop="code">
            <el-input v-model="createData.form.code" clearable placeholder="请输入仓库编码"></el-input>
          </el-form-item>
          <el-form-item label="地址" prop="addressId">
            <el-select v-model="createData.form.addressId" clearable filterable>
              <el-option
                v-for="it in addressList" :key="it.id" :value="it.id" :label="[
                it.countryName,
                it.stateProvince,
                it.city,
                it.addressLine1,
                it.addressLine2 ,
                it.addressLine3 ,
              ].filter(el=>el).join(' ')"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="仓库序号" prop="sort">
            <el-input-number v-model="createData.form.sort"></el-input-number>
          </el-form-item>
          <el-form-item label="是否默认仓库" prop="defaulted">
            <el-switch v-model="createData.form.defaulted" :active-value="1" :inactive-value="0"></el-switch>
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input
              v-model="createData.form.remarks" type="textarea" :rows="4" clearable
              placeholder="请输入备注"></el-input>
          </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>

<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;
    }
  }
}
</style>
