<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="客户名称" prop="blurry">
              <el-input v-model="queryParams.blurry" placeholder="请输入客户名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="客户状态" prop="status">
              <el-select v-model="queryParams.status" clearable placeholder="客户状态" class="filter-item">
                <el-option label="全部" :value="''" />
                <el-option label="启用" :value="0" />
                <el-option label="禁用" :value="1" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间" style="width: 308px">
              <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
                range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"></el-date-picker>
            </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-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd()">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain :disabled="single" icon="Edit" @click="handleUpdate()">
              修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain :disabled="multiple" icon="Delete" @click="handleDelete()">
              删除
            </el-button>
          </el-col>
          <right-toolbar v-model:show-search="showSearch" :search="true" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="customerList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="客户名称" align="center" prop="nickName" />
        <el-table-column label="客户账号" align="center" prop="userName" :show-overflow-tooltip="true" />
        <el-table-column label="客户状态" align="center" prop="status">
          <template #default="scope">
            <div @click="handleStatusChange(scope.row)">
              <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" />
            </div>
          </template>
        </el-table-column>

        <el-table-column label="创建时间" align="center" prop="createTime" width="160">
          <template #default="scope">
            <span>{{ scope.row.createTime }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" fixed="right" width="180" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip v-if="scope.row.userId !== 1" content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip v-if="scope.row.userId !== 1" content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
        :total="total" @pagination="getList" />
    </el-card>


    <!-- 添加或修改用户配置对话框 -->
    <el-dialog ref="formDialogRef" v-model="dialog.visible" :title="dialog.title" width="25%" append-to-body
      @close="closeDialog">
      <el-form ref="userFormRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="客户名称" prop="nickName">
              <el-input v-model="form.nickName" placeholder="请输入客户名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="客户账号" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入客户账号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item v-if="form.customerId === ''" label="账号密码" prop="password">
              <el-input v-model="form.password" placeholder="请输入账号密码" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" :loading="loadingIng">确 定</el-button>
          <el-button @click="cancel()">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="User" lang="ts">
import api from '@/api/customerManagement';
import { to } from 'await-to-js';
import { ComponentInternalInstance, getCurrentInstance, onMounted, reactive, ref, toRefs } from 'vue';
import { ElDialog, ElForm, ElFormItem, ElInput, ElRow, ElCol, ElButton, ElCard, ElSelect, ElOption, ElDatePicker, ElTable, ElTableColumn, ElTooltip, ElSwitch } from 'element-plus';

// 定义接口
interface UserVO {
  customerId: string | number;
  nickName: string;
  userName: string;
  status: string;
  createTime: string;
  userId: number;
}

interface UserForm extends UserVO {
  password?: string;
  enabled?: boolean;
}

interface UserQuery {
  pageNum: number;
  pageSize: number;
  blurry: string;
  status: string;
  enabled: string;
}

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const customerList = ref<UserVO[]>();
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<UserVO[]>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const initPassword = ref<string>('');
const queryFormRef = ref<InstanceType<typeof ElForm>>();
const userFormRef = ref<InstanceType<typeof ElForm>>();
const formDialogRef = ref<InstanceType<typeof ElDialog>>();
const loadingIng = ref(false)

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: UserForm = {
  userName: '',
  nickName: '',
  password: '',
  enabled: true,
  customerId: '',
  status: '',
  createTime: '',
  userId: 0,
};

const initData: {
  form: UserForm,
  queryParams: UserQuery,
  rules: any
} = {
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    blurry: '',
    enabled: '',
    status: ''
  },
  rules: {
    nickName: [
      { required: true, message: '请输入客户名称', trigger: 'blur' },
    ],
    userName: [
      { required: true, message: '请输入客户账号', trigger: 'blur' },
      {
        min: 2,
        max: 20,
        message: '客户账号长度必须在 2 和 20 之间',
        trigger: 'blur'
      }
    ],

    password: [
      { required: true, message: '请输入账号密码', trigger: 'blur' },
      {
        min: 5,
        max: 20,
        message: '用户密码长度必须介于 5 和 20 之间',
        trigger: 'blur'
      },
      { pattern: /^[^<>"'|\\]+$/, message: '不能包含非法字符：< > " \' \\ |', trigger: 'blur' }
    ],
  }
};
const data = reactive(initData);

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

/** 查询用户列表 */
const getList = async () => {
  loading.value = true;
  const res = await api.customerUser(proxy?.addDateRange(queryParams.value, dateRange.value));
  loading.value = false;
  customerList.value = res.rows;
  total.value = res.total;
};


/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  queryParams.value.pageNum = 1;
  queryParams.value.status=''
  handleQuery();

};

/** 删除按钮操作 */
const handleDelete = async (row?: UserVO) => {
  const customerIds = row ? [row.customerId] : ids.value.map(item => item.customerId);
  const nickNames = row ? row.nickName : ids.value.map(item => item.nickName).join(',');
  const [err] = await to(proxy?.$modal.confirm('是否确认删除"' + nickNames + '"的数据项？', '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }) as any);
  if (!err) {
    await api.deleteCustomer(customerIds);
    await getList();
    proxy?.$modal.msgSuccess('删除成功');
  }
};

/** 用户状态修改  */
const handleStatusChange = async (row: any) => {
  const originalStatus = row.status;
  const actionText = row.status == 0 ? '启用' : '停用';
  try {
    await proxy?.$modal.confirm(`确认要${actionText}"${row.nickName}"客户吗?`, '系统提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    await api.updateCustomer({
      customerId: row.customerId,
      enabled: originalStatus == 0 ? true : false
    });
    proxy?.$modal.msgSuccess(actionText + '成功');
    await getList();
  } catch (err) {
    if (err == 'cancel') {
      console.log(err, 'errr');
      proxy?.$modal.msgWarning('操作已取消');
      await getList();
    }
  }
};


/** 选择条数  */
const handleSelectionChange = (selection: UserVO[]) => {
  ids.value = selection;
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};


/** 重置操作表单 */
const reset = () => {
  form.value = { ...initFormData };
  userFormRef.value?.resetFields();
};
/** 取消按钮 */
const cancel = () => {
  dialog.visible = false;
  reset();
};

/** 新增按钮操作 */
const handleAdd = async () => {
  reset();
  dialog.visible = true;
  dialog.title = '新增客户';
  form.value.password = initPassword.value.toString();
};

/** 修改按钮操作 */
const handleUpdate = async (row?: UserForm) => {
  reset();
  dialog.visible = true;
  dialog.title = '修改客户';
  try {
    if (row) {
      Object.assign(form.value, row);
    } else {
      const selectedId = ids.value[0];
      Object.assign(form.value, selectedId);
    }
  } catch (error) {
    dialog.visible = false;
  }
};

/** 提交按钮 */
const submitForm = () => {
  userFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      loadingIng.value = true;
      try {
        form.value.customerId ? await api.updateCustomer(form.value) : await api.addCustomer(form.value);
        proxy?.$modal.msgSuccess('操作成功');
        dialog.visible = false;
        await getList();
      } finally {
        loadingIng.value = false;
      }
    }
  });
};

/**
 * 关闭用户弹窗
 */
const closeDialog = () => {
  dialog.visible = false;
  resetForm();
};

/**
 * 重置表单
 */
const resetForm = () => {
  userFormRef.value?.resetFields();
  userFormRef.value?.clearValidate();
  form.value.customerId = '';
};

onMounted(() => {
  getList(); // 初始化列表数据
});
</script>
