<template>
  <el-container>
    <el-header
      class="gva-search-box"
      style="line-height: 60px"
    >
      <el-row>
        <el-col :span="19">
          <el-form
            inline
            style="margin-top: 10px"
          >
            <el-form-item label="名称">
              <el-input
                v-model="queryGoodsData.name"
                placeholder="请输入名称"
              />
            </el-form-item>
            <el-form-item label="类型">
              <el-cascader
                  clearable
                  @clear="queryGoodsData.genre = 0"
                  :options="goodsTypeData"
                  @change="changeQueryGoodsType"
                  :props="goodsTypeProps"/>
            </el-form-item>
            <el-form-item label="特征">
              <el-input
                  placeholder="请输入特征"
                  v-model="queryGoodsData.characteristic"
              />
            </el-form-item>
            <el-form-item label="规格">
              <el-input
                  placeholder="请输入规格"
                  v-model="queryGoodsData.specifications"
              />
            </el-form-item>
            <el-form-item>
              <el-button @click="searchData" type="primary" icon="Search">搜索</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="5">
          <el-button
              @click="inboundDialog = true"
          >入库</el-button>
          <el-button
              @click="outboundDialog = true"
          >出库</el-button>
          <el-button
              @click="isOpenGoodsAdd = true"
          >货品新增</el-button>
          <el-button
              @click="isOpenCommodityGenre = true"
          >货品类型</el-button>
        </el-col>
      </el-row>
    </el-header>
    <el-main class="gva-table-box">
      <el-table
        :data="goodsListData"
        style="height: 600px"
      >
        <el-table-column
          prop="name"
          label="货品名称"
          align="center"
        />
        <el-table-column
          prop="goodsGenre.name"
          label="类型"
          align="center"
        />
        <el-table-column
          prop="number"
          label="数量"
          align="center"
        />
        <el-table-column
          prop="position"
          label="位置"
          align="center"
        />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="openGoodsEdit(scope.row)"
            >编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--      分页-->
      <div class="gva-pagination">
        <el-pagination
          :current-page="queryGoodsData.pageInfo.page"
          :page-size="queryGoodsData.pageInfo.pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
      <!--      修改-->
      <el-drawer
        v-model="isOpenGoodsEdit"
        title="修改货品信息"
        direction="rtl"
        size="30%"
      >
        <div>
          <el-form
            label-position="left"
            label-width="auto"
            style="max-width: 400px"
            size="large"
          >
            <el-form-item label="货品名称">
              <el-input v-model="goodsEditData.name" />
            </el-form-item>
            <el-form-item label="货品类型">
              <el-cascader
                  v-model="goodsEditData.goodsGenreId"
                  :options="goodsTypeData"
                  @change="editHandleChange"
                  :props="goodsTypeProps"/>
            </el-form-item>
            <el-form-item label="特征">
              <el-input
                v-model="goodsEditData.characteristic"
              />
            </el-form-item>
            <el-form-item label="规格">
              <el-input v-model="goodsEditData.specifications" />
            </el-form-item>
            <el-form-item label="单位">
              <el-input v-model="goodsEditData.unit" />
            </el-form-item>
            <el-form-item label="数量">
              <el-input v-model="goodsEditData.number" type="number"/>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="editGoodsSubmit"
              >提交</el-button>
              <el-button @click="isOpenGoodsEdit = false">关闭</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-drawer>
      <el-drawer
        v-model="isOpenGoodsAdd"
        title="新增货品"
        direction="rtl"
        size="30%"
      >
        <div>
          <el-form
            v-model="goodsAddDate"
            label-position="left"
            label-width="auto"
            style="max-width: 400px"
            size="large"
          >
            <el-form-item label="货品名称" prop="name">
              <el-input v-model="goodsAddDate.name"/>
            </el-form-item>
            <el-form-item label="货品类型">
              <el-cascader
                  :options="goodsTypeData"
                  @change="handleChange"
                  :props="goodsTypeProps"/>
            </el-form-item>
            <el-form-item label="特性">
              <el-input
                v-model.number="goodsAddDate.characteristic"
              />
            </el-form-item>
            <el-form-item label="规格">
              <el-input
                  v-model="goodsAddDate.specifications"
              />
            </el-form-item>
            <el-form-item label="单位">
              <el-input v-model="goodsAddDate.unit" />
            </el-form-item>
            <el-form-item label="数量">
              <el-input v-model="goodsAddDate.number" type="number"/>
            </el-form-item>
            <el-form-item label="位置">
              <el-input v-model="goodsAddDate.position" />
            </el-form-item>
            <el-form-item>
              <el-button
                  type="primary"
                  @click="goodsAddSubmit"
                  size="large"
              >提交</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-drawer>
      <!--      货品类型-->
      <el-drawer
        v-model="isOpenCommodityGenre"
        title="货品类型"
        direction="rtl"
        size="50%"
      >
        <el-header>
          <el-button
            type="primary"
            @click="isOpenAddGenre = true"
          >新增货品类型</el-button>
        </el-header>
<!--        :data="filterTableData"-->
        <el-main>
          <el-table :data="goodsTypeData"  row-key="ID">
            <el-table-column
              label="ID"
              prop="ID"
              sortable
            />
            <el-table-column
              label="名称"
              prop="name"
              sortable
            />
            <el-table-column
              label="备注"
              prop="remarks"
              sortable
            />
            <el-table-column align="right">
              <template #header>
                <el-input
                  v-model="searchCommodityGenre"
                  placeholder="筛选"
                />
              </template>
              <template #default="scope">
                <el-button
                  type="primary"
                  @click="openUpdateGenre(scope.row)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  @click="omitGoodsType(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-main>
        <!--        新增-->
        <el-dialog
          v-model="isOpenAddGenre"
          title="新增货品类型"
          width="700"
          align-center
        >
          <template #footer>
            <el-form size="large">
              <el-form-item>
                <el-alert
                    show-icon
                    title="注意：如果没有选择父级类型那么添加的类型就属于一级货品类型，否则属于二级货品类型"
                    type="info"
                />
              </el-form-item>
              <el-form-item label="父级类型：">
                <el-select
                    placeholder="请选择父级类型"
                    v-model="createGoodsTypeData.parentId"
                    clearable
                    @clear="createGoodsTypeData.parentId = ''"
                >
                  <el-option
                      v-for="item in goodsTypeData"
                      :key="item.ID"
                      :label="item.name"
                      :value="item.ID"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="类型名称：">
                <el-input
                    placeholder="请输入货物类型名称"
                    v-model="createGoodsTypeData.name"
                    clearable
                />
              </el-form-item>
              <el-form-item label="类型备注：">
                <el-input
                    placeholder="请输入备注"
                    v-model="createGoodsTypeData.remarks"
                    clearable
                />
              </el-form-item>
            </el-form>
            <div class="dialog-footer">
              <el-button
                  @click="isOpenAddGenre = false"
                  size="large">
                取消
              </el-button>
              <el-button type="primary" @click="increaseGoodsType" size="large">
                确认
              </el-button>
            </div>
          </template>
        </el-dialog>
        <!--        编辑-->
        <el-dialog
          v-model="isOpenUpdateGenre"
          title="编辑货品类型"
          width="700"
          align-center
        >
          <template #footer>
            <el-form size="large">
              <el-form-item label="父级类型："  v-show="updateGoodsTypeData.parentId !== ''">
                <el-select
                    placeholder="请选择父级类型"
                    v-model="updateGoodsTypeData.parentId"
                >
                  <el-option
                      v-for="item in goodsTypeData"
                      :key="item.ID"
                      :label="item.name"
                      :value="item.ID"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="类型名称：">
                <el-input
                    placeholder="请输入货物类型名称"
                    v-model="updateGoodsTypeData.name"
                    clearable
                />
              </el-form-item>
              <el-form-item label="类型备注：">
                <el-input
                    placeholder="请输入备注"
                    v-model="updateGoodsTypeData.remarks"
                    clearable
                />
              </el-form-item>
            </el-form>
            <div class="dialog-footer">
              <el-button
                  @click="isOpenUpdateGenre = false"
                  size="large">
                取消
              </el-button>
              <el-button type="primary" @click="modifyGoodsType" size="large">
                确认
              </el-button>
            </div>
          </template>
        </el-dialog>
      </el-drawer>
<!--      入库-->
      <el-drawer
          v-model="inboundDialog"
          title="新建入库单"
          direction="rtl"
          size="50%"
      >
        <div>
          <el-header
              class="gva-search-box"
              style="height: 30px;line-height: 30px;"
          >
            <el-button type="primary" @click="addGoods">添加货品</el-button>
            <el-button type="danger" @click="reduceGoods">减少货品</el-button>
          </el-header>
          <el-main>
            <el-table
                :data="storeData.cargos"
                height="500"
                border
                style="width: 100%;margin-bottom: 20px"
            >
              <el-table-column label="货品" width="300">
                <template #default="{ row }">
                  <el-select
                      v-model="row.goodsId"
                      filterable
                      placeholder="选择货品"
                  >
                    <el-option
                        v-for="item in goodsListData"
                        :key="item.ID"
                        :label="item.name"
                        :value="item.ID"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column
                  label="数量"
                  width="200"
              >
                <template #default="{ row }">
                  <el-input-number
                      v-model="row.number"
                      :min="1"
                  />
                </template>
              </el-table-column>
              <el-table-column label="购买价格">
                <template #default="{ row }">
                  <el-input v-model.number="row.buyingPrice" type="number"/>
                </template>
              </el-table-column>
            </el-table>
            <el-form inline>
              <el-form-item
                  label="标题"
                  prop="title"
              >
                <el-input
                    v-model="storeData.title"
                    style="width: 200px;"
                />
              </el-form-item>
              <el-form-item
                  label="管理人"
                  prop="custodian"
              >
                <el-input
                    v-model="storeData.custodian"
                    style="width: 200px;"
                />
              </el-form-item>
              <el-form-item
                  label="备注"
                  prop="custodian"
              >
                <el-input
                    v-model="storeData.remarks"
                    style="width: 200px;"
                />
              </el-form-item>
              <el-form-item>
                <el-button
                    type="primary"
                    @click="submitInboundForm"
                >提交入库</el-button>
              </el-form-item>
            </el-form>
          </el-main>
        </div>
      </el-drawer>
<!--      出库-->
      <el-drawer v-model="outboundDialog" size="50%" title="新建出库单">
        <el-header
            class="gva-search-box"
            style="height: 30px;line-height: 30px;"
        >
          <el-button type="primary" @click="outAddGoods">添加货品</el-button>
          <el-button type="danger" @click="outReduceGoods">减少货品</el-button>
        </el-header>
        <el-main>
          <el-table
              :data="outboundData.cargos"
              height="500"
              border
              style="width: 100%;margin-bottom: 20px"
          >
            <el-table-column label="货品" width="300">
              <template #default="{ row }">
                <el-select
                    v-model="row.goodsId"
                    filterable
                    placeholder="选择货品"
                >
                  <el-option
                      v-for="item in goodsListData"
                      :key="item.ID"
                      :label="item.name"
                      :value="item.ID"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
                label="数量"
                width="200"
            >
              <template #default="{ row }">
                <el-input-number
                    v-model="row.number"
                    :min="1"
                />
              </template>
            </el-table-column>
            <el-table-column label="购买价格">
              <template #default="{ row }">
                <el-input v-model.number="row.buyingPrice" type="number"/>
              </template>
            </el-table-column>
          </el-table>
          <el-form inline>
            <el-form-item
                label="标题"
                prop="title"
            >
              <el-input
                  v-model="outboundData.title"
                  style="width: 200px;"
              />
            </el-form-item>
            <el-form-item
                label="管理人"
                prop="custodian"
            >
              <el-input
                  v-model="outboundData.custodian"
                  style="width: 200px;"
              />
            </el-form-item>
            <el-form-item
                label="备注"
                prop="custodian"
            >
              <el-input
                  v-model="outboundData.remarks"
                  style="width: 200px;"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                  type="primary"
                  @click="submitOutboundForm"
              >提交出库</el-button>
            </el-form-item>
          </el-form>
        </el-main>
      </el-drawer>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import {
  queryGoodsType,deleteGoodsType,
  createGoodsType,
  updateGoodsType,
  createGoods,
  queryGoodsList,
  updateGoods,
  createInboundManifest,
  createOutboundManifest
} from '@/api/storehouse'
import { ElMessage, ElMessageBox } from 'element-plus'

const goodsTypeProps = {
  label: 'name',
  value: 'ID',
}

const handleChange = (value) => {
  goodsAddDate.goodsGenreId = value[1]
}

const editHandleChange = (val) => {
  goodsEditData.value.goodsGenreId = val[1]
}

// 入库
const inboundDialog = ref(false)
const addGoods = () => {
  storeData.cargos.push({ goodsId: null, number: 1, buyingPrice: 0 })
}

const reduceGoods = () => {
  if (storeData.cargos.length > 1) {
    storeData.cargos.pop()
  } else {
    console.log('只剩一项')
  }
}

const storeData = reactive({
  manifestGenre: '入库',
  title: '',
  custodian: '',
  cargos: [
    { goodsId: null, number: 1, buyingPrice: 0 },
  ],
  remarks: ''
})
const submitInboundForm = async () => {
  if (!validateInboundForm(storeData)) return
  await createInboundManifest(storeData).then(res => {
    if (res.code === 0) {
      ElMessage.success('添加成功')
      getData()
      inboundDialog.value = false
    }
  })
}

//出库
const outboundDialog = ref(false)

const outAddGoods = () => {
  outboundData.cargos.push({goodsId: null, number: 1, buyingPrice: 0})
}

const outReduceGoods = () => {
  if (outboundData.cargos.length > 1) {
    outboundData.cargos.pop()
  } else {
    console.log('只剩一项')
  }
}

const outboundData = reactive({
  manifestGenre: '出库',
  title: '',
  custodian: '',
  cargos: [
    { goodsId: null, number: 1, buyingPrice: 0 },
  ],
  remarks: ''
})

const submitOutboundForm = async () => {
  if (!validateInboundForm(outboundData)) return
  await createOutboundManifest(outboundData).then(res => {
    if (res.code === 0) {
      ElMessage.success('出库成功')
      getData()
      outboundDialog.value = false
    }
  })
}

const validateInboundForm = (data) => {
  if (!data.title.trim()) {
    ElMessage.warning('请输入标题')
    return false
  }

  if (!data.custodian.trim()) {
    ElMessage.warning('请输入负责人')
    return false
  }

  if (!Array.isArray(data.cargos) || data.cargos.length === 0) {
    ElMessage.warning('请至少添加一项商品')
    return false
  }

  for (let i = 0; i < data.cargos.length; i++) {
    const cargo = data.cargos[i]

    if (!cargo.goodsId) {
      ElMessage.warning(`第 ${i + 1} 行商品未选择`)
      return false
    }

    if (!cargo.number || cargo.number <= 0) {
      ElMessage.warning(`第 ${i + 1} 行数量必须大于0`)
      return false
    }

  }

  return true
}

const goodsListData = reactive([])

const total = ref(0)
// 货物类型
const goodsTypeData = ref([])
// 新增货物类型
const createGoodsTypeData = reactive({
  name: "",
  remarks: "",
  parentId: ""
})

const increaseGoodsType = async () => {
  let data = {}
  data.name = createGoodsTypeData.name
  data.remarks = createGoodsTypeData.remarks
  if(createGoodsTypeData.parentId !== '') {
    data.parentId = createGoodsTypeData.parentId
  }
  await createGoodsType(data).then(res => {
    if (res.code === 0) {
      ElMessage.success('添加成功')
      createGoodsTypeData.name = ''
      createGoodsTypeData.remarks = ''
      createGoodsTypeData.parentId = ''
      isOpenAddGenre.value = false
      getData()
    } else {
      ElMessage.error(res.data.msg)
    }
  })
}

// 编辑货品类型
const updateGoodsTypeData = reactive({
  id: 0,
  name: "",
  remarks: "",
  parentId: ""
})

const openUpdateGenre = (val) => {
  isOpenUpdateGenre.value = true
  updateGoodsTypeData.id = val.ID
  updateGoodsTypeData.name = val.name
  updateGoodsTypeData.remarks = val.remarks
  val.children === null ? updateGoodsTypeData.parentId = val.parentId : updateGoodsTypeData.parentId = ''
}

const modifyGoodsType = async () => {
  let data = {}
  data.id = updateGoodsTypeData.id
  data.name = updateGoodsTypeData.name
  data.remarks = updateGoodsTypeData.remarks
  if(updateGoodsTypeData.parentId !== '') {
    data.parentId = updateGoodsTypeData.parentId
  }
  await updateGoodsType(data).then(res => {
    if (res.code === 0) {
      ElMessage.success('编辑成功')
      isOpenUpdateGenre.value = false
      getData()
    } else {
      ElMessage.error('编辑失败')
    }
  })
}

//删除货物类型
const omitGoodsType = (val) => {
  ElMessageBox.confirm(
      '将永久删除该信息。是否继续？',
      '删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async() => {
        await deleteGoodsType(val.ID).then(res => {
          if (res.code === 0) {
            ElMessage.success('删除成功')
            getData()
          } else {
            ElMessage.error('删除失败')
          }
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '删除已取消',
        })
      })
}

// 新增货物类型
const goodsAddDate = reactive({
  name: '投光灯1',
  goodsGenreId: '',
  characteristic: '400w',
  specifications: '',
  unit: '盏',
  number: 5,
  position: '大仓库'
})
const isOpenGoodsAdd = ref(false)

const goodsAddSubmit = async() => {
  if (goodsAddDate.name === '' || goodsAddDate.goodsGenreId === '' || goodsAddDate.unit === '' || Number(goodsAddDate.number) <= 0) {
    ElMessage.error('请将必要的数据填写完整')
    return
  }
  await createGoods(goodsAddDate).then(res => {
    if (res.code === 0) {
      ElMessage.success('新增成功')
      isOpenGoodsAdd.value = false
      getData()
    } else {
      ElMessage.error('新增失败')
    }
  })
}

// 查询货物列表
const queryGoodsData = reactive({
  pageInfo: {
    page: 1,
    pageSize: 10
  },
  genre: 0,
  name: "",
  characteristic: "",
  specifications: ""
})

const changeQueryGoodsType = (val) => {
  queryGoodsData.genre= val[1]
}

// 分页
const handleSizeChange = (val) => {
  queryGoodsData.pageSize = val
  getData()
}

const handleCurrentChange = (val) => {
  queryGoodsData.page = val
  getData()
}

const searchData = async () => {
  queryGoodsData.page = 1
  queryGoodsData.pageSize = 10
  await queryGoodsList(queryGoodsData).then(res => {
    if (res.code === 0) {
      goodsListData.length = 0
      goodsListData.push(...res.data.list)
    }
  })
}

// 获取数据
const getData = async() => {
  await queryGoodsType().then(res => {
    if (res.code === 0) {
      goodsTypeData.value.length = 0
      goodsTypeData.value = res.data
    }
  })
  await queryGoodsList(queryGoodsData).then(res => {
    if (res.code === 0) {
      goodsListData.length = 0
      goodsListData.push(...res.data.list)
    }
  })
}

// 货品类型
const isOpenCommodityGenre = ref(false)

const searchCommodityGenre = ref()

const isOpenAddGenre = ref(false)

const isOpenUpdateGenre = ref(false)


// 编辑货品
const isOpenGoodsEdit = ref(false)
const goodsEditData = reactive({
  id: 0,
  name: "",
  goodsGenreId: 0,
  characteristic: "",
  specifications: "",
  unit: "",
  number: 0
})
const openGoodsEdit = (val) => {
  goodsEditData.id = val.ID
  goodsEditData.name = val.name
  goodsEditData.goodsGenreId = val.goodsGenreId
  goodsEditData.characteristic = val.characteristic
  goodsEditData.specifications = val.specifications
  goodsEditData.unit = val.unit
  goodsEditData.number = val.number
  isOpenGoodsEdit.value = true
}

const editGoodsSubmit = async() => {
  await updateGoods(goodsEditData).then(res => {
    if (res.code === 0) {
      ElMessage.success('编辑成功')
      getData()
    } else {
      ElMessage.error('编辑失败')
    }
    isOpenGoodsEdit.value = false
  })
}

onMounted(() => {
  getData()
})
</script>
