<template>
  <div class="Table">
    <!-- 按钮 -->
    <AddButton @add="add"></AddButton>
    <!-- 表格 -->
    <Table :list="datas.tableData" @handleDelete="handleDelete" @handleEdit="handleEdit"
      @myDialogRefqs="myDialogRefqsevent">
    </Table>
    <!-- 分页 -->
    <Paging :pagingConfig="datas.pagingConfig" @sizeChange="sizeChange" @currentChange="currentChange"></Paging>
    <!-- 其他模板 -->
    <!-- 新增/编辑 -->
    <myDialog ref="myDialogRef" :title="datas.title" @confirm="confirm" width="30%">
      <el-form ref="ruleFormRef" :rules="datas.rules" :model="datas.DialogForm" label-width="120px">
        <div class="sourceStyle">
          <div :class="[datas.DialogForm.source == 0 ? 'active' : '']" @click="datas.DialogForm.source = 0">手动添加</div>
          <div :class="[datas.DialogForm.source == 1 ? 'active' : '']" @click="datas.DialogForm.source = 1">从商品添加</div>
        </div>
        <template v-if="datas.DialogForm.source == 0">
          <el-form-item label="酒品名" prop="name">
            <el-input v-model="datas.DialogForm.name" placeholder="请输入酒品名" />
          </el-form-item>
          <el-form-item label="酒品图片">
            <div style="display: flex; flex-wrap: wrap">
              <div v-for="(item, index) in datas.DialogForm.imgUrl" :key="index" style="position: relative"
                class="showStyle">
                <el-icon class="buttonstyle" @click="deleteEvent(item)">
                  <DeleteFilled />
                </el-icon>
                <img style="width: 148px; height: 148px; margin-right: 6px" class="imgStyle" :src="item" alt="" />
              </div>
              <div class="upImgStyle" @click="addimgEvent" v-if="datas.DialogForm.imgUrl.length < 1">+</div>
            </div>
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item label="选择商品">
            <div>
              <el-button type="primary" @click="addgoods(index);">添加商品</el-button><br />
            </div>
          </el-form-item>
        </template>
        <template v-if="datas.DialogForm.source == 1">
          <el-form-item label="商品名称">
            {{ datas.seleteData.name }}
          </el-form-item>
          <el-form-item label="商品图片">
            <img :src="datas.seleteData.coverImg" style="width: 120px;height: 120px;" alt="">
          </el-form-item>
        </template>
        <el-form-item label="单位" v-if="datas.DialogForm.source == 0">
          <el-input v-model="datas.DialogForm.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="有效期（天）">
          <el-input-number v-model="datas.DialogForm.period" />
        </el-form-item>
      </el-form>
    </myDialog>
    <!-- 存酒 -->
    <myDialog ref="myDialogRefqs" title="记录" @confirm="confirmqs" width="30%">
      <el-form-item label="选择用户">
        <el-select v-model="datas.DialogForm.userId" filterable placeholder="请选择选择用户" style="width: 240px">
          <el-option v-for="item in datas.options" :key="item.userId" :label="`${item.nickName}/${item.phone}`"
            :value="item.userId" />
        </el-select>
      </el-form-item>
      <el-form-item label="数量">
        <el-input-number v-model="datas.winereNum" />
      </el-form-item>
    </myDialog>
    <!-- 选择图片 -->
    <shopList ref="shopListRef" @success="selectShopRes" />
    <AddImg ref="addImg" @successEvent="successEvent"></AddImg>
  </div>
</template>
<script setup>
import AddButton from './component/AddButton.vue'
import Table from './component/Table.vue'
import shopList from "@/components/mycomponents/shopList.vue";
import Paging from '@/components/mycomponents/myPaging.vue'
import myDialog from '@/components/mycomponents/myDialog.vue'
import eventBus from '@/utils/eventBus'
import API from './api'

const datas = reactive({
  tableData: [], // 表格数据
  title: '新增数据',
  pagingConfig: {
    total: 0, // 总数
    pageSize: 10, // 每页数据数量
    pageNumber: 1, // 当前页码
  },
  DialogForm: { // 弹窗表单数据
    source: 0,
    name: "",
    period: 1,
    imgUrl: []
  },
  options: [],
  rules: {
    name: [
      { required: true, message: '请输入酒名', trigger: 'blur' },
    ],
  },
  // 选择商品的数据
  seleteData: {},
  winereNum: 1
})
const myDialogRef = ref(null)
const ruleFormRef = ref(null)
const shopListRef = ref(null)
const myDialogRefqsdata = ref(null)
const myDialogRefqs = ref(null)
onMounted(() => {
  getList()
  eventBus.on('search', (res) => {
    getList(res)
  })
  getshopUser()
})
function addgoods(index) {
  shopListRef.value.opens()
}
onBeforeUnmount(() => {
  eventBus.off('search')
})
function myDialogRefqsevent(item) {
  myDialogRefqsdata.value = item
  myDialogRefqs.value.open()
}
async function getshopUser(params) {
  const res = await API.getshopUser({ page: 1, size: 999, ...params })
  datas.options = res.records
}
async function getList(data = {}) {
  const res = await API.getPage({ page: datas.pagingConfig.pageNumber, size: datas.pagingConfig.pageSize, ...data })
  datas.tableData = res.records
  datas.pagingConfig.total = res.totalRow
  datas.pagingConfig.pageSize = res.pageSize
  datas.pagingConfig.pageNumber = res.pageNumber
}
// 分组选择商品
function selectShopRes(res) {
  console.log(res, '选择图片')
  datas.seleteData = res[0]
}
async function confirmqs() {
  // 存酒
  let obj = { userId: datas.DialogForm.userId, shopStorageGoodId: myDialogRefqsdata.value.id, num: datas.winereNum, expDay: 1 }
  let res = await API.adds(obj)
  ElMessage({
    message: '成功',
    type: 'success',
  })
  getList()
  myDialogRefqs.value.close()
}
function add() {
  if (datas.DialogForm.id) {
    rest()
  }
  datas.title = '新增数据'
  myDialogRef.value.open()
}
async function handleEdit(row) {
  datas.title = '编辑数据'
  const res = await API.getinfo(row.id)
  datas.DialogForm = res
  if (datas.DialogForm.source == 0) {
    // 图片处理
    // datas.DialogForm.imgUrl = datas.DialogForm.imgUrl.join(',')
  } else {
    datas.seleteData.id = datas.DialogForm.prodId
    datas.seleteData.name = datas.DialogForm.name
    datas.seleteData.coverImg = datas.DialogForm.imgUrl
  }
  // 有图片
  let imgu = res.imgUrl.split(',')
  datas.DialogForm.imgUrl = imgu
  myDialogRef.value.open()
}
async function confirm() {
  ruleFormRef.value.validate(async valid => {
    if (valid) {
      let res = null
      if (datas.DialogForm.source == 0) {
        // 图片处理
        datas.DialogForm.imgUrl = datas.DialogForm.imgUrl.join(',')
      } else {
        datas.DialogForm.prodId = datas.seleteData.id
        datas.DialogForm.name = datas.seleteData.name
        datas.DialogForm.imgUrl = datas.seleteData.coverImg
      }
      if (datas.title == '新增数据') {
        res = await API.add(datas.DialogForm)
      } else {
        res = await API.update(datas.DialogForm)
      }
      ElMessage({
        message: '成功',
        type: 'success',
      })
      datas.seleteData = {}
      rest()
      getList()
      myDialogRef.value.close()
    }
  })
}
// 重置
function rest() {
  datas.DialogForm = { sort: 1, source: 0, imgUrl: [], period: 1 }
}
async function handleDelete(id) {
  ElMessageBox.confirm("是否删除数据项?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    async () => {
      let res = await API.deleteByIds(id)
      ElMessage({
        message: '删除成功',
        type: 'success',
      })
      getList()
    }
  );
}

// 图片
const addImg = ref(null)
function addimgEvent() {
  (addImg.value)?.show()
}
function successEvent(d) {
  datas.DialogForm['imgUrl'].push(d[0].url);
}
function deleteEvent(d) {
  let index = datas.DialogForm.imgUrl.findIndex((ele) => ele == d);
  datas.DialogForm.imgUrl.splice(index, 1);
}
// 分页
function sizeChange(val) {
  datas.pagingConfig.pageSize = val
  getList()
}
function currentChange(val) {
  datas.pagingConfig.pageNumber = val
  getList()
}

</script>
<style scoped lang="scss">
.Table {
  padding: 20px;
  background-color: #fff;
  border: 1px solid #e4e7ed;
  margin-top: 20px;
  border-radius: 4px;
}

.sourceStyle {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;

  >div {
    width: 20%;
    height: 40px;
    line-height: 40px;
    text-align: center;
    background-color: #dcf0e8;
    color: #74dfa3;
    cursor: pointer;
  }

  .active {
    background-color: #39d47a !important;
    color: #fff;
    width: 20%;
    line-height: 30px;
    border: 6px solid #dcf0e8;
  }
}

// 图片库样式
.showStyle:hover>.buttonstyle {
  display: block;
}

.upImgStyle {
  cursor: pointer;
  width: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center;
  border: 1px dashed #ccc;
  border-radius: 1%;
  font-size: 30px;
  color: #ccc;
}

.buttonstyle {
  border-radius: 50%;
  color: #db1616;
  background-color: #fff;
  font-size: 20px;
  display: none;
  position: absolute;
  right: 0px;
  top: -10px;
  z-index: 10;
}
</style>