<template>
  <div class="Table">
    <!-- 按钮 -->
    <AddButton @add="add"></AddButton>
    <!-- 表格 -->
    <Table :list="datas.tableData" @handleDelete="handleDelete" @handleEdit="handleEdit"></Table>
    <!-- 分页 -->
    <Paging :pagingConfig="datas.pagingConfig" @sizeChange="sizeChange" @currentChange="currentChange"></Paging>
    <!-- 其他模板 -->
    <!-- 新增/编辑 -->
    <myDialog ref="myDialogRef" :title="datas.title" @confirm="confirm" width="40%">
      <el-form ref="ruleFormRef" :rules="datas.rules" :model="datas.DialogForm" label-width="120px">
        <el-form-item label="充值">
          <el-col :span="10">
            <el-input v-model="datas.DialogForm.amount" :min="0" type="number" placeholder="请输入金额">
              <template #prepend>满</template>
              <template #append>元</template>
            </el-input>
          </el-col>
          <el-col :span="2">
          </el-col>
          <el-col :span="10">
            <el-input v-model="datas.DialogForm.giftAmount" :min="0" type="number" placeholder="请输入金额">
              <template #prepend>赠</template>
              <template #append>元</template>
            </el-input>
          </el-col>
        </el-form-item>

        <el-form-item label="积分">
          <el-col :span="12">
            <el-input v-model="datas.DialogForm.giftPoints" :min="0" type="number" placeholder="请输入积分">
              <template #prepend>赠送</template>
              <template #append>积分</template>
            </el-input>
          </el-col>
        </el-form-item>

        <el-form-item label="是否使用优惠券">
          <el-switch v-model="datas.DialogForm.isGiftCoupon" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <template v-if="datas.DialogForm.isGiftCoupon == 1">
          <el-form-item label="选择优惠卷">
            <el-button type="primary" @click="addgoods();">添加优惠券</el-button>
          </el-form-item>
          <el-form-item v-for="(item, index) in datas.DialogForm.couponsList" :label="item.title">
            <el-input-number v-model="item.number" min="1" controls-position="right" placeholder="请输入数量" />
            <el-button type="" text @click="removegoods(index)">删除</el-button>
          </el-form-item>
        </template>
      </el-form>
    </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 Paging from '@/components/mycomponents/myPaging.vue'
import myDialog from '@/components/mycomponents/myDialog.vue'
import eventBus from '@/utils/eventBus'
import API from './api'
import ShopList from './component/shopList.vue'

const datas = reactive({
  tableData: [], // 表格数据
  title: '新增数据',
  pagingConfig: {
    total: 0, // 总数
    pageSize: 10, // 每页数据数量
    pageNumber: 1, // 当前页码
  },
  DialogForm: { // 弹窗表单数据
    name: "",
    telephone: "",
    address: "",
    remark: "",
    coupons: [],
    couponsList: []
  },
  // 优惠券
  rules: {
    name: [
      { required: true, message: '请输入供应商名称', trigger: 'blur' },
      { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
  }
})
const myDialogRef = ref(null)
const ruleFormRef = ref(null)
const shopListRef = ref(null)
onMounted(() => {
  getList()
  eventBus.on('search', (res) => {
    getList(res)
  })
})
function removegoods(index) {
  datas.DialogForm.couponsList.splice(index, 1)
}
function selectShopRes(item) {
  item.forEach(ele => {
    ele.number = 1
  })
  datas.DialogForm.couponsList = item
}
function addgoods() {
  shopListRef.value.opens()
}
onBeforeUnmount(() => {
  eventBus.off('search')
})
async function getList(data = {}) {
  const res = await API.getPage({ page: datas.pagingConfig.pageNumber, size: datas.pagingConfig.pageSize, ...data })
  datas.tableData = res
  datas.pagingConfig.total = res.totalRow
  datas.pagingConfig.pageSize = res.pageSize
  datas.pagingConfig.pageNumber = res.pageNumber
}
function add() {
  if (datas.DialogForm.id) {
    rest()
  }
  datas.title = '新增数据'
  myDialogRef.value.open()
}
async function handleEdit(row) {
  datas.title = '编辑数据'
  datas.DialogForm = row
  datas.DialogForm.couponsList = row.couponList
  // 有图片
  // datas.DialogForm.goodsImageUrl = res.goodsImageUrl.split(',')
  myDialogRef.value.open()
}
async function confirm() {
  ruleFormRef.value.validate(async valid => {
    if (valid) {
      let res = null
      let obj = {}
      if (Array.isArray(datas.DialogForm.couponsList)) {
        datas.DialogForm.couponsList.forEach(element => {
          obj[element.id] = element.number || 1
        });
      }
      datas.DialogForm.coupons = JSON.stringify(obj)
      if (datas.title == '新增数据') {
        // 图片处理
        // datas.DialogForm.goodsImageUrl = datas.DialogForm.goodsImageUrl.join(',')
        res = await API.add(datas.DialogForm)
      } else {
        // datas.DialogForm.goodsImageUrl = datas.DialogForm.goodsImageUrl.join(',')
        res = await API.update(datas.DialogForm)
      }
      if (res) {
        ElMessage({
          message: '成功',
          type: 'success',
        })
        rest()
        getList()
        myDialogRef.value.close()
      }
    }
  })
}
// 重置
function rest() {
  datas.DialogForm = { sort: 1, images: [] }
}
async function handleDelete(id) {
  ElMessageBox.confirm("是否删除数据项?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    async () => {
      let res = await API.deleteByIds(id)
      if (res.code == 200) {
        ElMessage({
          message: '删除成功',
          type: 'success',
        })
        getList()
      }
    }
  );
}

// 图片
const addImg = ref(null)
function addimgEvent() {
  (addImg.value)?.show()
}
function successEvent(d) {
  datas.DialogForm['images'].push(d[0].url);
}
function deleteEvent(d) {
  let index = datas.DialogForm.images.findIndex((ele) => ele == d);
  datas.DialogForm.images.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;
}

// 图片库样式
.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>