<template>
  <div class="Table">
    <!-- 按钮 -->
    <AddButton @add="add" @exportsAction="exportsAction"></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="30%">
      <el-form ref="ruleFormRef" :rules="datas.rules" :model="datas.DialogForm" label-width="80px">
        <!-- <el-form-item label="商品图片" required prop="images">
          <div style="display: flex; flex-wrap: wrap">
            <div v-for="(item, index) in datas.DialogForm.images" :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">+</div>
          </div>
        </el-form-item> -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名" prop="account">
              <el-input v-model="datas.DialogForm.account" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话" prop="phone">
              <el-input v-model="datas.DialogForm.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="昵称" prop="nickName">
              <el-input v-model="datas.DialogForm.nickName" placeholder="请输入昵称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="datas.DialogForm.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="性别">
              <el-radio-group v-model="datas.DialogForm.gender">
                <el-radio label="男" value="男" />
                <el-radio label="女" value="女" />
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-switch v-model="datas.DialogForm.status" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="角色">
              <el-select v-model="datas.DialogForm.roleId" placeholder="请选择角色" clearable>
                <el-option :label="item.name" v-for="(item, index) in datas.roleData" :key="index" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="admin账号">
              <el-switch v-model="datas.DialogForm.isAdmin" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="密码" v-if="datas.title == '新增数据'">
          <el-input v-model="datas.DialogForm.password" placeholder="请输入密码" />
        </el-form-item>
      </el-form>
    </myDialog>
    <!-- 选择图片 -->
    <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/account/sysUser'
import API2 from '@/api/account/role'
import { downloadFile } from "@/utils/index";
const datas = reactive({
  tableData: [], // 表格数据
  title: '新增数据',
  pagingConfig: {
    total: 0, // 总数
    pageSize: 10, // 每页数据数量
    pageNumber: 1, // 当前页码
  },
  DialogForm: { // 弹窗表单数据
    gender: "男",
    status: 1,
    isAdmin: 0,
    avatar: "https://cashier-oss.oss-cn-beijing.aliyuncs.com/upload/3/5208d608c94d4a889c53f4fe28097199.png"
  },
  roleData: [],
  rules: {
    account: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
    ],
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
    ],
    nickName: [
      { required: true, message: '请输入昵称', trigger: 'blur' },
    ],
    email: [
      { required: true, message: '请输入邮箱', trigger: 'blur' },
    ],
  },
  searchData: null
})
const myDialogRef = ref(null)
const ruleFormRef = ref(null)
onMounted(() => {
  getList()
  getrolelist()
  eventBus.on('search', (res) => {
    datas.searchData = res
    getList(res)
  })
})
async function exportsAction() {
  const file = await API.download({
    ...datas.searchData
  });
  downloadFile(file, "数据", "xlsx");
}
onBeforeUnmount(() => {
  eventBus.off('search')
})
async function getList(data = {}) {
  const res = await API.getList({ 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
}
async function getrolelist(data = {}) {
  const res = await API2.getList({ page: datas.pagingConfig.pageNumber, size: datas.pagingConfig.pageSize, ...data })
  datas.roleData = res.records
}

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 = row
  datas.DialogForm.password = null

  // 有图片
  // datas.DialogForm.goodsImageUrl = res.goodsImageUrl.split(',')
  myDialogRef.value.open()
}
async function confirm() {
  ruleFormRef.value.validate(async valid => {
    if (valid) {
      let res = null
      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.edit(datas.DialogForm)
      }
      if (res) {
        ElMessage({
          message: '成功',
          type: 'success',
        })
        rest()
        getList()
        myDialogRef.value.close()
      }
    }
  })
}
// 重置
function rest() {
  datas.DialogForm = {
    gender: "男",
    status: 1,
    isAdmin: 0,
    avatar: "https://cashier-oss.oss-cn-beijing.aliyuncs.com/upload/3/5208d608c94d4a889c53f4fe28097199.png"
  }
}
async function handleDelete(id) {
  ElMessageBox.confirm("是否删除数据项?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    async () => {
      let res = await API.delete(id)
      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>