<template>
  <!-- 面包屑 -->
  <el-breadcrumb>
    <el-breadcrumb-item>客户管理</el-breadcrumb-item>
    <el-breadcrumb-item to="/user/list">客户列表</el-breadcrumb-item>
  </el-breadcrumb>
  <!-- 搜索 -->
  <el-form inline :model="params">
    <el-form-item label="客户">
      <el-input v-model="params.user" placeholder="请输入客户信息"></el-input>
    </el-form-item>
    <el-form-item label="状态">
      <el-select v-model="params.user_status" clearable placeholder="请选择状态">
        <el-option label="启用" value="1"></el-option>
        <el-option label="停用" value="2"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="tableRef.reload()" icon="ElIconSearch">搜索</el-button>
    </el-form-item>
  </el-form>
  <el-row style="margin-bottom: 5px">
    <!-- 添加客户 -->
    <AddUserDialog :done="() => tableRef.reload()"></AddUserDialog>

    <!-- 导出 -->
    <el-button style="margin-left: 10px;" icon="ElIconDocument" @click="exportExcel()">导出</el-button>

    <!-- 导入 -->
    <el-upload class="upload-demo" :action="importExcel" :headers="headers" :on-success="handleExcelSuccess"
      :on-progress="uploadLoading" :on-error="closeUploadLoading" style="margin-left: 10px" :show-file-list="false">
      <el-button type="primary">导入</el-button>
    </el-upload>

    <!-- 下载导入模板 -->
    <el-button style="margin-left: 10px;" icon="ElIconDownload" @click="downloadTemplate()">下载导入模板</el-button>

    <!-- 下拉操作 -->
    <el-dropdown style="margin-left: 10px;" v-if="selectionData.length">
      <el-button type="primary">
        批量操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
      </el-button>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item @click="showResetPassword">重置密码</el-dropdown-item>
          <el-dropdown-item @click="handleDelete(selectionData)">
            批量删除
          </el-dropdown-item>
          <el-dropdown-item @click="changStatus(1)">启用</el-dropdown-item>
          <el-dropdown-item @click="changStatus(2)">禁用</el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </el-row>

  <!-- 数据表格 -->
  <DataTable ref="tableRef" style="width: 100%" :onSelectionChange="data => (selectionData = data)" :column="column"
    :params="params" :request="params => getUserList(params)">
    <template #user_img="scope">
      <el-image v-if="scope.row.user_img" :src="scope.row.user_img" lazy :preview-src-list="[scope.row.user_img]"
        :preview-teleported="true"></el-image>
      <template v-else>暂无图片</template>
    </template>
    <template #role="scope">
      {{ scope.row.roles.map(v => v.role_name).join() }}
    </template>
    <template #user_status="scope">
      <dict-tag :options="user_status" :value="scope.row.user_status" />
    </template>
    <template #chaoz="scope">
      <el-space>
        <!-- <el-button size="small" @click="restPasswordDialogVisible = scope.row">
          重置密码
        </el-button> -->
        <el-button size="small" @click="editUserDialogVisible = scope.row">
          编辑
        </el-button>
        <el-dropdown @command="handleCommand">
          <el-button type="primary" size="small">
            更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item :command="{ type: 'detail', row: scope.row }">
                详情
              </el-dropdown-item>
              <el-dropdown-item :command="{ type: 'delete', row: scope.row }">
                删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-space>
    </template>
  </DataTable>
  <!-- 重置密码 -->
  <RestPassword v-model="restPasswordDialogVisible" :data="selectionData"></RestPassword>
  <!-- 编辑客户 -->
  <EditUserDialog v-model="editUserDialogVisible" :done="() => tableRef.reload()"></EditUserDialog>
  <!-- 客户详情 -->
  <DetailUserDialog v-model="detailUserDialogVisible"></DetailUserDialog>
</template>
<script setup>
import { ArrowDown } from '@element-plus/icons-vue';
import { ref, reactive } from 'vue';
import { getUserList, deleteUser, updateUserStatus, exportExcel, downloadTemplate, importExcel, getDictionary } from '~/service/user';
import RestPassword from './components/RestPassword.vue';
import AddUserDialog from './components/AddUserDialog.vue';
import EditUserDialog from './components/EditUserDialog.vue';
import DetailUserDialog from './components/DetailUserDialog.vue';
import { useLoginStore } from "~/store";

const store = useLoginStore();
const headers = {
  Accept: "application/json",
  ...store.headers,
};
const tableRef = ref();
const selectionData = ref([]);

// 查询参数
const params = reactive({
  user: '',
  user_status: ''
});
const column = [
  {
    fixed: true,
    type: 'selection'
  },
  {
    prop: 'user_name',
    label: '用户名',
    width: '150'
  },
  {
    prop: 'user_img',
    label: '头像',
    width: '150'
  },
  {
    prop: 'role_name',
    label: '角色',
    width: '150'
  },
  {
    prop: 'user_phone',
    label: '手机号码',
    width: '150'
  },
  {
    prop: 'user_status',
    label: '状态',
    width: '150'
  },
  {
    label: '操作',
    prop: 'chaoz',
    width: '250'
  }
];

const restPasswordDialogVisible = ref(false);
const editUserDialogVisible = ref({});
const detailUserDialogVisible = ref({});

let loading = null;
const uploadLoading = () => {
  loading = ElLoading.service({
    lock: true,
    text: "正在导入中...",
    background: "rgba(255, 255, 255, 0.7)",
  });
};
const closeUploadLoading = () => loading.close();
const handleExcelSuccess = (value) => {
  if (value.code == 0) {
    ElMessageBox.alert(value.msg, "导入信息", {
      dangerouslyUseHTMLString: true,
      confirmButtonText: "确定",
    });
  } else {
    ElMessage.error(value.msg);
  }
  closeUploadLoading();
  tableRef.value.reload();
};

// 选择详情或删除
const handleCommand = ({ type, row }) => {
  switch (type) {
    case 'detail':
      detailUserDialogVisible.value = row;
      break;
    case 'delete':
      handleDelete([row]);
      break;
  }
};

// 字典获取
const user_status = ref([]);
async function get_user_status() {
  await getDictionary({ dictionary_value: 'user_status' }).then((res) => {
    user_status.value = res
  })
}
get_user_status()

// 删除数据
const handleDelete = data => {
  ElMessageBox.confirm(`您确定要删除该客户吗？`).then(async () => {
    const { code } = await deleteUser({
      user_guid: data.map(v => v.user_guid).join()
    });
    if (code == 0) {
      tableRef.value.reload();
    }
  });
};
// 显示重置密码
const showResetPassword = () => {
  if (selectionData.value.length == 0) {
    ElMessage.warning('请选择数据');
    return;
  }
  restPasswordDialogVisible.value = true;
};
// 修改状态
const changStatus = async status => {
  if (selectionData.value.length == 0) {
    ElMessage.warning('请选择数据');
    return;
  }
  const { code } = await updateUserStatus({
    user_guid: selectionData.value.map(v => v.user_guid).join(),
    user_status: status
  });
  if (code == 0) {
    tableRef.value.reload();
  }
};
</script>
