<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
          <el-form-item label="姓名" prop="name">
            <el-input
                v-model="queryParams.name"
                placeholder="请输入"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="账号" prop="account">
            <el-input
                v-model="queryParams.account"
                placeholder="请输入"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
                type="primary"
                plain
                @click="add"
                icon="Plus"
            >新增</el-button>
          </el-col>
        </el-row>

        <el-table v-loading="loading" :data="list">
            <el-table-column label="姓名" align="center" prop="name" />
            <el-table-column label="账号" align="center" prop="account" />
            <el-table-column label="用户类型" align="center">
              <template #default="{row}">
                <el-tag v-if="row.type=='admin'" type="success">管理员</el-tag>
                <el-tag v-if="row.type=='general'" type="danger">普通用户</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="状态" align="center" prop="role_name" >
              <template #default="{row}">
                <el-switch
                    v-model="row.state"
                    active-value="normal"
                    inactive-value="disable"
                    :disabled="row.admin==1"
                    @change="handleStateChange(row)"
                ></el-switch>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" align="left" prop="createTime" />
            <el-table-column label="操作" width="270" align="center" class-name="small-padding fixed-width" >
              <template #default="{row}">
                <el-button link type="primary" icon="Refresh" @click="resetPwd(row)">重置密码</el-button>
                <el-button link type="primary" icon="EditPen" @click="handleUpdate(row)">编辑</el-button>
                <el-button link type="primary" icon="Delete" @click="del(row)">删除</el-button>
              </template>
            </el-table-column>
        </el-table>
    
        <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
        />

      <!-- 添加或修改账号问答框 -->
      <el-dialog :title="title" v-model="open" width="400px" append-to-body>
        <el-form ref="postRef" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="form.name" placeholder="请输入姓名" maxlength="10"/>
          </el-form-item>
          <el-form-item label="账号" prop="account">
            <el-input v-model="form.account" placeholder="请输入账号(手机号格式)" :disabled="form.id"/>
          </el-form-item>
          <el-form-item label="用户类型" prop="type">
            <el-select clearable v-model="form.type" placeholder="请选择" style="width: 100%;">
              <el-option label="普通用户" value="general" />
              <el-option label="管理员" value="admin" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitForm">提 交</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-dialog>
 
    </div>
</template>
 
<script setup name="Post">
import {
  dispatchAccountL,
  dispatchAccountC,
  dispatchAccountU,
  dispatchResetPwd,
  dispatchStateU,
  userDelete
} from "@/api/account";

const { proxy } = getCurrentInstance();

const list = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: '',
  },
  rules: {
    roleId: [{ required: true, message: "请选择角色", trigger: "blur" }],
    name: [{ required: true, message: "请输入姓名", trigger: "blur" },
           { pattern : /^[\u4e00-\u9fa5]+$/, message: "不能包含除中文外的其他字符", trigger: "blur" }
    ],
    account: [
        { required: true, message: "请输入账号", trigger: "blur" },
        { pattern: /^1(3|4|5|6|7|8|9)\d{9}$/, message: "请输入正确的账号(手机号)", trigger: "blur" },
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询列表 */
function getList() {
    loading.value = true;
    dispatchAccountL(queryParams.value).then(res => {
      list.value = res.data.list;
      total.value = res.data.total;
      loading.value = false;
    });
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = 10;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = {};
  handleQuery();
}

//新增
function add() {
  form.value = {};
  open.value = true;
  title.value = "新增账号";

  if(proxy.$refs["postRef"]!==undefined){
      proxy.$refs["postRef"].resetFields(); // 清除表单已有校验
  }
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["postRef"].validate(valid => {
    if (valid) {
      if (form.value.id) {
        dispatchAccountU(form.value).then(response => {
          proxy.$modal.msgSuccess('修改成功');
          open.value = false;
          getList();
        });
      } else {
        dispatchAccountC(form.value).then(response => {
          proxy.$modal.msgSuccess('新增成功');
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 编辑按钮操作 */
function handleUpdate(row) {
  form.value = {
    account: row.account,
    name: row.name,
    id:  row.id,
    type: row.type
  }
  open.value = true;
  title.value = "编辑账号";
  if(proxy.$refs["postRef"]!==undefined){
      proxy.$refs["postRef"].resetFields(); // 清除表单已有校验
  }
}

/** 重置密码按钮操作 */
function resetPwd(row) {
    proxy.$modal.confirm('您确定要重置密码吗？').then(function() {
      return dispatchResetPwd({
        id: row.id,
      });
    }).then((res) => {
      getList();
      proxy.$modal.msgSuccess('重置成功');
    }).catch(() => {});
}
function del(row) {
    proxy.$modal.confirm('您确定要删除吗？').then(function() {
      return userDelete({
        id: row.id,
      });
    }).then((res) => {
      getList();
      proxy.$modal.msgSuccess('删除成功');
    }).catch(() => {});
}
/** 取消按钮 */
function cancel() {
  open.value = false;
}

/** 停用/启用 */
function handleStateChange(row) {
  let text = row.state === "normal" ? "启用" : "停用";
  proxy.$modal.confirm('确认要' + text + '"' + row.name + '"的账号吗？').then(function() {
    return dispatchStateU({id:row.id,state: text === "停用" ? "disable" : "normal"});
  }).then((res) => {
    getList();
    proxy.$modal.msgSuccess(text + "成功");
  })
}

getList();
</script>
