<template>
  <div>
    <el-card :body-style="cardBodyStyle">
      <el-form :model="query" label-width="auto" label-position="right">
        <el-row :gutter="10">
          <el-col :span="5">
            <el-form-item label="所属库房" style="margin-bottom: 0px;">
              <el-select
                v-model="query.wareId"
                placeholder="请选择库房"
                clearable
                style="width: 100%;"
                @visible-change="handleWareSelectVisible"
              >
                <el-option
                  v-for="item in wareOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
<!--          <el-col :span="5">-->
<!--            <el-form-item label="分区名称" style="margin-bottom: 0px;">-->
<!--              <el-input v-model="query.areaName" clearable placeholder="请输入分区名称" style="width: 100%;"></el-input>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="5">-->
<!--            <el-form-item label="分区编码" style="margin-bottom: 0px;">-->
<!--              <el-input v-model="query.areaCode" clearable placeholder="请输入分区编码" style="width: 100%;"></el-input>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="9">
            <el-form-item label="" style="margin-bottom: 0px; margin-top: 5px;">
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button type="success" @click="insertDialog">新增</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <ButtonBox @search="handleSearch" @add="insertDialog"></ButtonBox>

    <el-card :body-style="cardBodyStyle">
      <el-table :data="tableData" border highlight-current-row @selection-change="handleSelectionChange" :height="height">
        <el-table-column type="selection" fixed></el-table-column>
        <el-table-column type="index" label="序号" align="center" width="60">
          <template #default="scope">
            <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="wareName" label="所属库房" width="180" header-align="center" align="center" show-overflow-tooltip />
        <el-table-column prop="areaName" label="分区名称" width="180" header-align="center" align="center" show-overflow-tooltip />
        <el-table-column prop="areaCode" label="分区编码" width="180" header-align="center" align="center" show-overflow-tooltip />
        <el-table-column label="操作" header-align="center" align="center" width="200" fixed="right">
          <template #default="scope">
            <el-button plain type="warning" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button plain type="danger" @click="handleRemove(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card :body-style="cardBodyStyle">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="pageSizes"
        :total="totalRows"
        background="background"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <el-dialog
      class="diaClass"
      :close-on-click-modal="false"
      draggable
      title="新增"
      v-model="dialogVisible"
      width="40%"
      top="5vh"
      @open="openDialog"
    >
      <el-card>
        <el-form :model="form" label-width="120px" label-position="right" inline ref="ruleFormRef" :rules="rules">
          <el-row>
            <el-col :span="12">
              <el-form-item label="所属库房" prop="wareId">
                <el-select v-model="form.wareId" placeholder="请选择库房" style="width: 100%;">
                  <el-option
                    v-for="item in wareOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="分区名称" prop="areaName">
                <el-input v-model="form.areaName" maxlength="100" placeholder="请输入分区名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="分区编码" prop="areaCode">
                <el-input v-model="form.areaCode" maxlength="50" placeholder="请输入分区编码"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" plain @click="handleInsert(ruleFormRef)">保存</el-button>
          <el-button type="danger" plain @click="handleCancelSave">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      class="diaClass"
      :close-on-click-modal="false"
      draggable
      title="编辑"
      v-model="dialogVisibleEdit"
      width="40%"
      top="5vh"
      @open="openDialog"
    >
      <el-card :body-style="cardBodyStyle">
        <el-form :model="form" label-width="120px" label-position="right" inline ref="ruleFormRef" :rules="rules">
          <el-row>
            <el-col :span="12">
              <el-form-item label="所属库房" prop="wareId">
                <el-select v-model="form.wareId" placeholder="请选择库房" style="width: 100%;">
                  <el-option
                    v-for="item in wareOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="分区名称" prop="areaName">
                <el-input v-model="form.areaName" placeholder="请输入分区名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="分区编码" prop="areaCode">
                <el-input v-model="form.areaCode" placeholder="请输入分区编码"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" plain @click="handleSave(ruleFormRef)">保存</el-button>
          <el-button type="danger" plain @click="handleCancelSave2">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { getCurrentInstance, onMounted, reactive, ref } from 'vue'
import tools from '@/tools'
import ButtonBox from '@/components/ButtonBox.vue'

const { proxy } = getCurrentInstance()

const cardBodyStyle = ref(tools.style.card)

const form = ref({
  wareId: '',
  areaName: '',
  areaCode: ''
})

const query = ref({
  wareId: '',
  areaName: '',
  areaCode: ''
})

const wareOptions = ref([])

const tableData = ref([])
const currentPage = ref(1)
const totalRows = ref(0)
const pageSizes = ref([10, 20, 30, 40])
const pageSize = ref(10)

const dialogVisible = ref(false)
const dialogVisibleEdit = ref(false)
const ruleFormRef = ref()

const rules = reactive({
  wareId: [{ required: true, message: '请选择所属库房', trigger: 'change' }],
  areaName: [{ required: true, message: '请输入分区名称', trigger: 'blur' }],
  areaCode: [{ required: true, message: '请输入分区编码', trigger: 'blur' }]
})

const multipleSelection = ref([])
const height = ref(600)

const handleWareSelectVisible = (visible) => {
    fetchWareOptions()
}

const fetchWareOptions = () => {
  proxy.$axios.get('sto/Ware/options','').then((response) => {
    if (response.data.code === 0) {
      wareOptions.value = response.data.data || []
    } else {
      ElMessage.error('获取库房信息失败！' + response.data.msg)
    }
  })
}

const getTableData = () => {
  const params = {
    page: currentPage.value,
    rows: pageSize.value,
    wareId: query.value.wareId,
    areaName: query.value.areaName,
    areaCode: query.value.areaCode,
    json: JSON.stringify(query.value)
  }
  proxy.$axios.get('sto/Area/query', params).then((response) => {
    // console.log(response.data)
    if (response.data.code === 0) {
      // alert(11)
      tableData.value = response.data.data.records
      totalRows.value = response.data.data.total
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}

const handleSearch = () => {
  currentPage.value = 1
  getTableData()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getTableData()
}

const insertDialog = () => {
  form.value = {
    wareId: '',
    areaName: '',
    areaCode: ''
  }
  fetchWareOptions()
  dialogVisible.value = true
}

const openDialog = () => {}

const handleInsert = (formRef) => {
  if (!formRef) return
  formRef.validate((valid) => {
    if (valid) {
      const params = {
        json: JSON.stringify(form.value)
      }
      proxy.$axios.post('sto/Area/save', params).then((response) => {
        if (response.data.code == 0 || response.data.code === '0') {
          ElMessage({
            message: '保存成功',
            type: 'success'
          })
          dialogVisible.value = false
          handleSearch()
        } else {
          ElMessage({
            type: 'error',
            message: '操作失败' + response.data.msg
          })
        }
      })
    }
  })
}

const handleSave = (formRef) => {
  if (!formRef) return
  formRef.validate((valid) => {
    if (valid) {
      const params = {
        json: JSON.stringify(form.value)
      }
      proxy.$axios.post('sto/Area/save', params).then((response) => {
        if (response.data.code == 0 || response.data.code === '0') {
          ElMessage({
            message: '保存成功',
            type: 'success'
          })
          dialogVisibleEdit.value = false
          handleSearch()
        } else {
          ElMessage({
            type: 'error',
            message: '操作失败' + response.data.msg
          })
        }
      })
    }
  })
}

const handleCancelSave = () => {
  dialogVisible.value = false
}

const handleCancelSave2 = () => {
  dialogVisibleEdit.value = false
}

const handleEdit = (row) => {
  const params = {
    id: row.id
  }
  fetchWareOptions()
  proxy.$axios.get('sto/Area/queryByPK', params).then((response) => {
    if (response.data.code === 0) {
      form.value = response.data.data
      dialogVisibleEdit.value = true
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}

const handleRemove = (row) => {
  const params = {
    id: row.id
  }
  ElMessageBox.confirm('确定删除本条记录?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true
  })
    .then(() => {
      proxy.$axios.get('sto/Area/remove', params).then((response) => {
        if (response.data.code === 0) {
          ElMessage({
            type: 'success',
            message: '删除成功！'
          })
          getTableData()
        } else {
          ElMessage.error('操作失败！' + response.data.msg)
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消'
      })
    })
}

const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

const updateViewportHeight = () => {
  height.value = window.innerHeight * 0.65
}

onMounted(() => {
  fetchWareOptions()
  getTableData()
  updateViewportHeight()
})
</script>

<style scoped>
::v-deep .diaClass .el-form-item {
  width: 100%;
}
::v-deep .el-autocomplete {
  width: 100%;
}
::v-deep .el-dialog__body {
  background-color: #F2F6FC;
}
</style>

