<template>
  <div class="card-search">
    <a-form
      ref="formRef"
      name="advanced_search"
      class="ant-advanced-search-form"
      :model="searchParamsState"
    >
      <a-row :gutter="24">
        <a-col :span="6">
          <a-form-item label="用户名" :label-col="{ span: 8 }" name="name">
            <a-input v-model:value="searchParamsState.name" placeholder="" />
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="帐号" :label-col="{ span: 8 }" name="loginID">
            <a-input v-model:value="searchParamsState.loginID" placeholder="" />
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="用户类型" :label-col="{ span: 8 }" name="userType">
            <a-select
              ref="select"
              v-model:value="searchParamsState.userType"
              :options="userTypeList"
              :field-names="{ label: 'name', value: 'value' }"
              :allow-clear="true"
              @change="loadData"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="6" style="text-align: left">
          <a-button type="primary" html-type="submit" @click="onFinish">查询</a-button>
          <a-button
            style="margin: 0 8px"
            @click="
              () => {
                formRef.resetFields();
                loadData();
              }
            "
            >重置</a-button
          >
        </a-col>
      </a-row>
      <a-row class="edit-operation">
        <a-col :span="24" style="text-align: right">
          <a-button type="primary" html-type="submit" functioncode="T0199010105" @click="onAdd('')"
            >新增</a-button
          >
        </a-col>
      </a-row>
    </a-form>
    <div class="search-result-list">
      <a-table
        :columns="columns"
        :data-source="dataList"
        :scroll="{ x: '100%', y: 500 }"
        :pagination="pagination"
        :loading="formState.loading"
        :row-selection="{ selectedRowKeys: formState.selectedRowKeys, onChange: onSelectChange }"
        :row-key="(record) => record.UserID"
        bordered
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, text, record }">
          <template v-if="column.key === 'operation'">
            <div class="table-operation">
              <a-button type="link" functioncode="T0199010105" @click="onAdd(record.UserID)"
                >编辑</a-button
              >
              <a-button
                type="link"
                functioncode="T0199010102"
                @click="onUpdateUserStatus(record.UserID, 1)"
                >启用</a-button
              >
              <a-button
                type="link"
                functioncode="T0199010103"
                @click="onUpdateUserStatus(record.UserID, 0)"
                >禁用</a-button
              >
              <a-button type="link" functioncode="T0199010104" @click="onUpdatePassword(record)"
                >修改密码</a-button
              >
            </div>
          </template>
        </template>
      </a-table>
    </div>
    <UpdatePassword ref="updatePasswordRef"></UpdatePassword>
    <UserAdd ref="userAddRef" :load-data="loadData"></UserAdd>
  </div>
</template>

<script lang="ts">
  import { reactive, ref, computed, defineComponent } from 'vue';
  import type { FormInstance, TableColumnsType, TableProps, SelectProps } from 'ant-design-vue';
  import { getUserListPage, updateUserStatus } from '@/api/system/user';
  import { getSysDictionaryList } from '@/api/system/dictionary';
  import UpdatePassword from '@/views/system/users/updatePassword.vue';
  import UserAdd from '@/views/system/users/addUser.vue';
  import { getPaginationTotalTitle } from '@/utils/common';

  export default defineComponent({
    name: 'UserList',
    components: { UpdatePassword, UserAdd },
    setup() {
      const modalRoleUserRef = ref();
      const modalRoleEditRef = ref();
      const formRef = ref<FormInstance>();
      const searchParamsState = reactive({
        page: 1,
        limit: 20,
        name: '',
        loginID: '',
        userType: '',
      });
      const formState = reactive({
        total: 0,
        selectedRowKeys: [],
        loading: false,
      });
      const columns: TableColumnsType = [
        {
          title: '序号',
          align: 'center',
          width: 80,
          key: 'roleID',
          customRender: (item) =>
            `${searchParamsState.limit * (searchParamsState.page - 1) + item.index + 1}`,
        },
        { title: '用户名', dataIndex: 'Name', key: 'Name', align: 'center', width: 150 },
        { title: '帐号', dataIndex: 'LoginID', key: 'LoginID',align: 'center', width: 150 },
        { title: '用户类型', dataIndex: 'UserTypeName', key: 'UserTypeName',align: 'center', width: 150,},
        { title: '所属区县/机构/驿站', dataIndex: 'dataRangeNames', key: 'dataRangeNames',align: 'center', width: 150,},
        { title: '角色', dataIndex: 'roleName', key: 'roleName',align: 'center', width: 180 },
        { title: '账号状态', dataIndex: 'RecordStatus', key: 'RecordStatus',align: 'center', width: 110,
          customRender: ({ record }) => (record.RecordStatus == 1 ? '正常' : '禁用'),
        },
        { title: '操作', key: 'operation', width: 220, align: 'center' },
      ];
      const pagination = computed(() => ({
        total: formState.total,
        current: searchParamsState.page,
        pageSize: searchParamsState.limit,
        showSizeChanger: true,
        showTotal: (total) => getPaginationTotalTitle(total),
      }));

      const dataList = ref([]);
      const userTypeList = ref<SelectProps['options']>();
      const updatePasswordRef = ref();
      const userAddRef = ref();

      const onSelectChange = (selectedRowKeys: any) => {
        formState.selectedRowKeys = selectedRowKeys;
      };

      const handleTableChange: TableProps['onChange'] = (pag: {
        pageSize: number;
        current: number;
      }) => {
        searchParamsState.page = pag.current;
        searchParamsState.limit = pag.pageSize;
        loadData();
      };

      const onFinish = () => {
        loadData();
      };

      const onAdd = (userId) => {
        userAddRef.value.show(userId);
        /*loadData();*/
      };

      const onUpdateUserStatus = async function (userID, status) {
        await updateUserStatus({ userId: userID, status });
        await loadData();
      };

      const onUpdatePassword = (item) => {
        updatePasswordRef.value.show(item.UserID, item.Name, item.LoginID, false);
      };

      const loadData = async function () {
        formState.loading = true;
        const result: any = await getUserListPage(searchParamsState);
        dataList.value = result.list;
        console.log('dataList', dataList.value);
        formState.total = result.total;
        formState.loading = false;
      };

      const loadUserTypeList = () => {
        getSysDictionaryList('UserType').then((data) => {
          userTypeList.value = data;
        });
      };

      return {
        modalRoleUserRef,
        modalRoleEditRef,
        formRef,
        loadData,
        loadUserTypeList,
        searchParamsState,
        formState,
        columns,
        pagination,
        dataList,
        userTypeList,
        onSelectChange,
        handleTableChange,
        onAdd,
        onFinish,
        onUpdateUserStatus,
        onUpdatePassword,
        updatePasswordRef,
        userAddRef,
      };
    },
    created() {
      this.loadData();
      this.loadUserTypeList();
    },
    activated() {
      if (history.state.params?.reload) this.loadData();
    },
  });
</script>

<style lang="less" scoped></style>
