<template>
  <div>
    <en-table-layout :tableData="tableData.data" :loading="loading">
      <template #toolbar>
        <div class="inner-toolbar w-11/12 flex justify-between">
          <div class="toolbar-btns">
            <el-button size="small" v-if="store.state.user.user.founder !== 1" type="primary" icon="el-icon-circle-plus-outline" @click="handleAddAdmin"
              >添加</el-button
            >
          </div>
          <div class="toolbar-search">
            <en-table-search @search="searchEvent" placeholder="请输入关键字" @advancedSearch="advancedSearchEvent" advanced>
              <!--  <template #advanced-content>v-if="checkPermission(['administratorManage:add'])"
                <el-form ref="advancedForm" :model="advancedForm" label-width="90px">
                  <el-form-item label="状态">
                    <el-select v-model="advancedForm.user_state">
                      <el-option :key="0" label="正常" :value="0" />
                      <el-option :key="-1" label="删除" :value="-1" />
                    </el-select>
                  </el-form-item>
                </el-form>
              </template> -->
            </en-table-search>
          </div>
        </div>
      </template>

      <template #table-columns>
        <el-table-column prop="username" label="登录名" />
        <el-table-column prop="real_name" label="用户名" />
        <el-table-column prop="nickname" label="用户昵称" />
        <el-table-column prop="sn" label="用户编码" />
        <el-table-column prop="dept_name" label="部门" />
        <el-table-column prop="post_name" label="岗位" />
        <el-table-column prop="user_state" label="状态">
          <template #default="scope">
            {{ scope.row.user_state === 0 ? '正常' : '删除' }}
          </template>
        </el-table-column>
        <el-table-column prop="role_name" label="所属角色" />
        <el-table-column label="操作" width="200px">
          <template #default="scope">
            <el-button size="small" type="primary" v-if="store.state.user.user.founder !== 1" @click="handleEditAdmin(scope.$index, scope.row)">编辑</el-button>
            <!-- v-if="checkPermission(['administratorManage:edit'])" -->
            <el-button
              size="small"
              type="danger"
              v-if="scope.row.user_state === 0 && store.state.user.user.founder !== 1"
              @click="handleDeleteAdmin(scope.$index, scope.row)"
              >删除</el-button
            >
            <!-- && checkPermission(['administratorManage:del']) && checkPermission(['administratorManage:restore'])-->
            <el-button
              size="small"
              type="success"
              v-if="scope.row.user_state !== 0 && store.state.user.user.founder !== 1"
              @click="handleRestoreAdmin(scope.$index, scope.row)"
              >恢复</el-button
            >
          </template>
        </el-table-column>
      </template>
      <template #pagination>
        <!-- <el-pagination
          v-if="tableData"
          v-model:current-page="tableData.page_no"
          v-model:page-size="tableData.page_size"
          :page-sizes="[10, 20, 50, 100]"
          :total="tableData.data_total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handlePageSizeChange"
          @current-change="handlePageCurrentChange"
        >
        </el-pagination> -->
        <el-pagination
          v-if="tableData"
          v-model:current-page="tableData.page_no"
          v-model:page-size="tableData.page_size"
          :page-sizes="[10, 20, 50, 100]"
          :total="tableData.data_total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handlePageSizeChange"
          @current-change="handlePageCurrentChange"
        />
      </template>
    </en-table-layout>
    <el-dialog
      :title="adminForm.id ? '编辑人员' : '添加人员'"
      v-model="dialogVisible"
      width="500px"
      @open="handleDialogOpen"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="adminForm" :rules="adminRules" ref="adminFormRef" label-width="120px">
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="adminForm.phone" :minlength="2" :maxlength="20" clearable placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="adminForm.email" :maxlength="20" clearable placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="adminForm.nickname" :maxlength="20" clearable placeholder="请输入昵称"></el-input>
        </el-form-item>
        <el-form-item label="登录名" prop="username">
          <el-input v-model="adminForm.username" :maxlength="20" clearable placeholder="请输入登录名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            autocomplete="off"
            v-model="adminForm.password"
            :maxlength="20"
            clearable
            :placeholder="adminForm.id ? '不修改请留空' : '6-20位数字、英文字母，或者特殊字符'"
          ></el-input>
        </el-form-item>
        <el-form-item label="所属角色" prop="role_id">
          <el-select
            v-model="adminForm.role_id"
            :disabled="adminForm.founder === 1"
            :placeholder="adminForm.founder === 1 ? '超级管理员无须选择角色' : '请选择角色'"
            clearable
          >
            <el-option v-for="item in rolesOptions" :key="item.role_id" :label="item.role_name" :value="item.role_id"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属部门" prop="dept_id">
          <el-cascader
            v-model="adminForm.dept_id"
            :options="deptList"
            :props="{
              label: 'name',
              value: 'id',
              emitPath: false,
              checkStrictly: true,
            }"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="所属岗位" prop="post_id">
          <el-select v-model="adminForm.post_id">
            <el-option v-for="item in postList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAdminForm">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
  
  <script lang="ts" setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { ElMessageBox, FormInstance, ElMessage } from 'element-plus';
import * as API_Auth from '@/api/auth';
import * as API_Setting from '@/api/setting';
import md5 from 'js-md5';
import { RegExp } from '../../composables/ui-utils/RegExp';
//, Foundation
import { useStore } from 'vuex';
const store = useStore();
const deptList = ref([]);
const postList = ref<any>([]);
const loading = ref(false);
interface Params {
  [x: string]: any;
  page_no: number;
  page_size: number;
  user_state: number;
  keyword: string;
  company_id: any;
  start_time?: number;
  end_time?: number;
}

const params: Params = {
  page_no: 1,
  page_size: 10,
  user_state: 0,
  keyword: '',
  company_id: store.state.companId,
};
/* const params = reactive({
  page_no: 1,
  page_size: 10,
  user_state: 0,
  keyword: '',
  company_id: store.state.companId,
}); */
const tableData = ref<any>({});
const adminForm = ref<any>({
  founder: 0,
  real_name: '',
  password: '',
  id: '',
  role_id: '',
  face: '',
  phone: '',
  email: '',
});
const adminFormRef = ref();
const advancedForm = ref<any>({
  user_state: 0,
});
const adminRules = reactive({
  username: [
    { required: true, message: '请输入人员名称！' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符' },
    {
      validator: (rule, value, callback) => {
        if (value && !RegExp.userName.test(value)) {
          callback(new Error('只支持汉字、字母、数字、“-”、“_”的组合！'));
        } else {
          callback();
        }
      },
    },
  ],
  password: [
    { required: true, message: '请输入人员密码！', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value && !RegExp.password.test(value)) {
          callback(new Error('密码应为6-20位数字、英文字母，或者特殊字符！'));
        } else {
          callback();
        }
      },
    },
  ],
  department: [{ required: true, message: '请输入所属部门！' }],
  role_id: [{ required: true, message: '请选择所属角色！', trigger: 'change' }],
  face: [{ required: true, message: '请上传人员头像！' }],
  phone: [{ required: true, message: '请输入手机号！' }],
  email: [{ required: true, message: '请输入邮箱！' }],
});
const dialogVisible = ref(false);
const rolesOptions = ref<any>([]);
const fileList = ref<any>([]);

watch(
  () => adminForm.value.id,
  (newValue) => {
    adminRules.username[0].required = !newValue;
    adminRules.password[0].required = !newValue;
  }
);

watch(
  () => adminForm.value.founder,
  (newValue) => {
    adminRules.role_id[0].required = newValue === 0;
    if (newValue === 1) adminForm.value.role_id = '超级人员';
  }
);

watch(dialogVisible, (newVal) => {
  if (!newVal) {
    fileList.value = [];
  }
});

onMounted(() => {
  GET_AdministratorList();
  API_Auth.getRoleList({ page_size: 10000, company_id: store.state.companId }).then((response) => {
    rolesOptions.value = response.data;
  });
  GET_DeptList();
  GET_StationAllList();
});

const advancedSearchEvent = () => {
  Object.assign(params, advancedForm.value);
  delete params.start_time;
  delete params.end_time;
  if (advancedForm.value.Contract_time_range) {
    params.start_time = parseInt(String(Number(advancedForm.value.Contract_time_range[0]) / 1000));
    params.end_time = parseInt(String(Number(advancedForm.value.Contract_time_range[1]) / 1000));
  }
  delete params.Contract_time_range;
  params.page_no = 1;
  GET_AdministratorList();
};
/* 处理树形数据 */
let buildTree = function buildTree(list, parent_id) {
  const tree: any = [];
  for (let i = 0; i < list.length; i++) {
    if (list[i].parent_id === parent_id) {
      const node = {
        id: list[i].id,
        parent_id: list[i].parent_id,
        name: list[i].name,
        create_time: list[i].create_time,
        remark: list[i].remark,
        sn: list[i].sn,
        sort: list[i].sort,
        type: list[i].type,
        region_ids: list[i].region_ids,
        children: buildTree(list, list[i].id),
      };
      tree.push(node);
    }
  }
  return tree;
};
const GET_DeptList = () => {
  API_Setting.getDeptList({ company_id: store.state.companId }).then((response) => {
    deptList.value = buildTree(response, '0');
  });
};

const GET_StationAllList = () => {
  API_Setting.getStationAllList().then((response) => {
    postList.value = response;
  });
};

const uploadSuccess = (res) => {
  adminForm.value.face = res.url;
};

const delGiftImg = () => {
  fileList.value = [];
  adminForm.value.face = '';
};

const handlePageSizeChange = (size) => {
  params.page_size = size;
  GET_AdministratorList();
};

const handlePageCurrentChange = (page) => {
  params.page_no = page;
  GET_AdministratorList();
};

const handleAddAdmin = () => {
  Object.assign(adminForm, {
    founder: 0,
    real_name: '',
    password: '',
    username: '',
    nickname: '',
    role_id: '',
  });
  fileList.value = [];
  dialogVisible.value = true;
};

const handleEditAdmin = (index, row) => {
  console.log(row);
  adminForm.value=row
 /*  Object.assign(adminForm, row); */
  adminForm.value.role_id = parseInt(adminForm.value.role_id) === 0 ? '超级人员' : adminForm.value.role_id;
  fileList.value = adminForm.value.face ? [{ name: 'face', url: adminForm.value.face }] : [];
  dialogVisible.value = true;
};

const handleRestoreAdmin = (index, row) => {
  API_Auth.restoreAdministrator(row.id).then(() => {
    ElMessage.success('恢复成功！');
    GET_AdministratorList();
  });
};

const handleDeleteAdmin = (index, row) => {
  ElMessageBox.confirm('确定要删除这个人员吗？', '提示', { type: 'warning' })
    .then(() => {
      API_Auth.deleteAdministrator(row.id).then(() => {
        ElMessage.success('删除成功！');
        GET_AdministratorList();
      });
    })
    .catch(() => {});
};

const handleDialogOpen = () => {
  setTimeout(() => {
    adminFormRef.value.clearValidate();
  });
};

const submitAdminForm = () => {
  adminFormRef.value.validate((valid) => {
    if (valid) {
      const { id } = adminForm.value;
      const params = { ...adminForm.value };
      if (params.password) params.password = params.password; //md5();
      if (!params.real_name) delete params.real_name;
      params.role_id === '超级人员' ? (params.role_id = 0) : null;
      if (id) {
        API_Auth.editAdministrator(id, params).then(() => {
          dialogVisible.value = false;
          ElMessage.success('修改成功！');
          GET_AdministratorList();
        });
      } else {
        API_Auth.addAdministrator(params).then(() => {
          dialogVisible.value = false;
          ElMessage.success('添加成功！');
          GET_AdministratorList();
        });
      }
    } else {
      ElMessage.error('表单填写有误，请核对！');
      return false;
    }
  });
};

const searchEvent = (data) => {
  params.keyword = data;
  params.page_no = 1;
  GET_AdministratorList();
};

const GET_AdministratorList = () => {
  loading.value = true;
  API_Auth.getAdministratorList(params)
    .then((response) => {
      loading.value = false;
      tableData.value = response;
    })
    .catch(() => {
      loading.value = false;
    });
};
</script>
  
  <style scoped >
.face-image {
  display: block;
  width: 50px;
  height: 50px;
  margin: 0 auto;
}

:v-deep(.el-dialog__body) {
  padding: 10px 20px;
}
</style>