<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"
              >{{$t('add')}}</el-button
            >
          </div>
          <div class="toolbar-search">
            <en-table-search @search="searchEvent" :placeholder="$t('search_placeholde')" @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="$t('user_name')" />
        <el-table-column prop="real_name" :label="$t('real_name')" />
        <el-table-column prop="nickname" :label="$t('nick_name')" />
        <el-table-column prop="sn" :label="$t('admin_sn')" />
        <el-table-column prop="dept_name" :label="$t('dept_name')" />
        <el-table-column prop="post_name" :label="$t('post_name')" />
        <el-table-column prop="user_state" :label="$t('user_state')">
          <template #default="scope">
            {{ scope.row.user_state === 0 ? $t('admin_normal') : $t('delete') }}
          </template>
        </el-table-column>
        <el-table-column prop="role_name" :label="$t('role_name')"/>
        <el-table-column :label="$t('operate')" fixed="right" width="300">
          <template #default="scope">
            <el-button size="small" type="primary" v-if="store.state.user.user.founder !== 1" @click="handleEditAdmin(scope.$index, scope.row)">{{$t('edit')}}</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)"
              >{{$t('delete')}}</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)"
              >{{$t('restore')}}</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 ? $t('edit') : $t('add')"
      v-model="dialogVisible"
      width="500px"
      @open="handleDialogOpen"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      class="!rounded-lg"
    >
      <el-form :model="adminForm" :rules="adminRules" ref="adminFormRef" label-width="120px">
        <el-form-item :label="$t('phone')" prop="phone">
          <el-input v-model="adminForm.phone" :minlength="2" :maxlength="20" clearable :placeholder="$t('place')+$t('phone')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('companyEmail')" prop="email">
          <el-input v-model="adminForm.email" :maxlength="20" clearable :placeholder="$t('place')+$t('companyEmail')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('nick_name')" prop="nickname">
          <el-input v-model="adminForm.nickname" :maxlength="20" clearable :placeholder="$t('place')+$t('nick_name')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('user_name')" prop="username">
          <el-input v-model="adminForm.username" :maxlength="20" clearable :placeholder="$t('place')+$t('user_name')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('admin_password')" prop="password">
          <el-input
            type="password"
            autocomplete="off"
            v-model="adminForm.password"
            :maxlength="20"
            clearable
            :placeholder="adminForm.id ? $t('admin_not_pass') : $t('admin_info')"
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('role_name')" prop="role_id">
          <el-select
            v-model="adminForm.role_id"
            :disabled="adminForm.founder === 1"
            :placeholder="adminForm.founder === 1 ? $t('role_name_info') : $t('role_name_sel')"
            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="$t('dept_name')" 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="$t('post_name')" 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">{{$t('cancel')}}</el-button>
        <el-button type="primary" @click="submitAdminForm">{{$t('submit')}}</el-button>
      </template>
    </el-dialog>
  </div>
</template>
  
  <script lang="ts" setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { useStore } from 'vuex';
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';
import { useI18n } from 'vue-i18n';
const store = useStore();
const { t } = useI18n();
//, Foundation

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:t('place') + t('user_name')+'!' },
    { min: 2, max: 20, message: t('user_name_length') },
    {
      validator: (rule, value, callback) => {
        if (value && !RegExp.userName.test(value)) {
          callback(new Error(t('user_name_bination')));
        } else {
          callback();
        }
      },
    },
  ],
  password: [
    { required: true, message: t('place') + t('admin_password')+'!', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value && !RegExp.password.test(value)) {
          callback(new Error(t('pass_info')));
        } else {
          callback();
        }
      },
    },
  ],
  department: [{ required: true, message: t('change') + t('dept_name')+'!' , trigger: 'change'}],
  role_id: [{ required: true, message: t('change') + t('role_name')+'!', trigger: 'change' }],
  face: [{ required: true, message: '请上传人员头像！' }],
  phone: [{ required: true, message: t('place') + t('phone')+'!' }],
  email: [{ required: true, message: t('place') + t('companyEmail')+'!' }],
});
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 = t('admin_super');
  }
);

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 ? t('admin_super') : 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(t('restore_success'));
    GET_AdministratorList();
  });
};

const handleDeleteAdmin = (index, row) => {
  ElMessageBox.confirm(t('del_info'), t('prompt'), { type: 'warning' })
    .then(() => {
      API_Auth.deleteAdministrator(row.id).then(() => {
        ElMessage.success(t('del_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 === t('admin_super') ? (params.role_id = 0) : null;
      if (id) {
        API_Auth.editAdministrator(id, params).then(() => {
          dialogVisible.value = false;
          ElMessage.success(t('edit_success'));
          GET_AdministratorList();
        });
      } else {
        API_Auth.addAdministrator(params).then(() => {
          dialogVisible.value = false;
          ElMessage.success(t('add_success'));
          GET_AdministratorList();
        });
      }
    } else {
      ElMessage.error(t('form_erroe'));
      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>