<script setup lang="ts">
import { reactive, ref, onMounted, watch } from "vue";
import { httpList, httpStatus } from "/@/api/system/role";
import { type FormInstance } from "element-plus";
import { ElMessage } from "element-plus";
import { TableProBar } from "/@/components/ReTable";
import { type PaginationProps } from "@pureadmin/table";
import { useRenderIcon } from "/@/components/ReIcon/src/hooks";
import { responseHandle } from "/@/utils/responseHandle";
import { useUserStoreHook } from "/@/store/modules/user";
import { useCompany } from "/@/hooks/core/useCompany";
import { useNav } from "/@/layout/hooks/nav";
import { statusList } from "/@/utils/status";
import { useColumns } from "./columns";
import addEdit from "./addEdit.vue";

const { logout } = useNav();

defineOptions({
  name: "role"
});

const form = reactive({
  level: "",
  role_name: "",
  status: "",
  page: 1,
  size: 15
});

const powers = ref([]);
const dataList = ref([]);
const loading = ref(true);
const { columns } = useColumns();
const showModel = ref(false);
const itemId = ref("");
const isDetails = ref("add");
const formRef = ref<FormInstance>();

const { currentCompany } = useCompany();

const pagination = reactive<PaginationProps>({
  total: 0,
  pageSize: 15,
  currentPage: 1,
  background: true
});
//修改状态
const handleStatus = async row => {
  const { id, status } = row;
  const { code, message } = await httpStatus({
    id,
    status: status + "" === "1" ? "0" : "1"
  });
  responseHandle({
    code,
    message,
    logout,
    handler: () => onSearch()
  });
};

async function handleCurrentChange(val: number) {
  form.page = val;
  await onSearch();
}

async function handleSizeChange(val: number) {
  form.size = val;
  form.page = 1;
  await onSearch();
}

function handleSelectionChange(val) {
  console.log("handleSelectionChange", val);
}

async function onSearch() {
  loading.value = true;
  const { code, data, message } = await httpList(form);
  loading.value = false;

  if (code === 1) {
    const { list, count } = data;
    dataList.value = list ?? [];
    pagination.total = count ?? 0;
    pagination.pageSize = form.size;
    pagination.currentPage = form.page;
  } else if (code > 100 && code < 140) {
    logout();
  } else {
    ElMessage.error(message);
  }
}
async function resetSearch() {
  form.page = 1;
  await onSearch();
}

//新建/编辑/详情弹窗
function editItem(id, type) {
  itemId.value = id;
  isDetails.value = type;
  showModel.value = true;
}
const submitRefresh = () => {
  showModel.value = false;
  onSearch();
};
const submitCancel = () => {
  showModel.value = false;
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  form.page = 1;
  onSearch();
};

onMounted(() => {
  powers.value = useUserStoreHook().getMenuActions("role");
  if (powers.value.some(i => i == "3")) {
    onSearch();
  }
});

// watch(
//   () => currentCompany.value,
//   () => onSearch()
// );
</script>

<template>
  <div class="main role">
    <div v-show="powers.some(i => i == '3')">
      <el-form
        ref="formRef"
        :inline="true"
        :model="form"
        size="small"
        :label-width="0"
        class="bg-white w-99/100 pl-8 pt-4"
      >
        <el-form-item prop="status">
          <el-select
            v-model="form.status"
            style="width: 100%"
            placeholder="角色状态"
            clearable
          >
            <el-option
              v-for="(si, sii) in statusList"
              :key="'status' + si.value + sii"
              :label="si.label"
              :value="si.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="role_name">
          <el-input v-model="form.role_name" placeholder="角色名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :icon="useRenderIcon('search')"
            :loading="loading"
            @click="resetSearch"
          >
            搜索
          </el-button>
          <el-button
            :icon="useRenderIcon('refresh')"
            @click="resetForm(formRef)"
          >
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <TableProBar
        title="公司角色管理"
        :loading="loading"
        :dataList="dataList"
        @refresh="onSearch"
      >
        <template #buttons>
          <el-button
            type="primary"
            size="small"
            v-if="powers.some(i => i == '2')"
            :icon="useRenderIcon('add')"
            @click="editItem('', 'add')"
          >
            新增角色
          </el-button>
        </template>
        <template v-slot="{ size, checkList }">
          <PureTable
            border
            align="left"
            showOverflowTooltip
            table-layout="auto"
            size="small"
            :data="dataList"
            :columns="columns"
            :checkList="checkList"
            :pagination="pagination"
            :paginationSmall="size === 'small' ? true : false"
            :header-cell-style="{ background: '#fafafa', color: '#606266' }"
            @selection-change="handleSelectionChange"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          >
            <template #operation="{ row }">
              <el-button
                class="reset-margin"
                link
                type="primary"
                v-if="powers.some(i => i == '5')"
                :size="size"
                @click="editItem(row.id, 'view')"
                :icon="useRenderIcon('eye-view')"
              />
              <el-button
                class="reset-margin"
                link
                type="primary"
                :size="size"
                v-if="powers.some(i => i == '4')"
                @click="editItem(row.id, 'edit')"
                :icon="useRenderIcon('edits')"
              />
              <el-popconfirm
                :title="
                  String(row.status) === '1' ? '改为禁用？' : '改为启用？'
                "
                v-if="
                  (powers.some(i => i == '7') && row.status + '' === '1') ||
                  (powers.some(i => i == '6') && row.status + '' === '0')
                "
                @confirm="handleStatus(row)"
              >
                <template #reference>
                  <el-button
                    class="reset-margin"
                    link
                    type="primary"
                    :size="size"
                    :icon="
                      useRenderIcon(
                        String(row.status) === '1'
                          ? 'close-circle-line'
                          : 'checkbox-circle-line'
                      )
                    " /></template
              ></el-popconfirm>
            </template>
          </PureTable>
        </template>
      </TableProBar>
      <addEdit
        :itemId="itemId"
        :isDetails="isDetails"
        :show-model="showModel"
        @refresh="submitRefresh"
        @cancel="submitCancel"
      />
    </div>
    <NoAuth v-show="!powers.some(i => i == '3')" />
  </div>
</template>

<style scoped lang="scss">
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}
</style>
