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

import addEdit from "./addEdit.vue";
import resetPassword from "./resetPassword.vue";

const { logout } = useNav();

defineOptions({
  name: "supplierAccountManage"
});

const powers = ref([]);
const form = reactive({
  nickname: "",
  username: "",
  status: "",
  page: 1,
  size: 15
});

const dataList = ref([]);
const loading = ref(true);
const showModel = ref(false);
const itemId = ref("");
const isDetails = ref("add");

const { columns } = useColumns();
const { currentCompany } = useCompany();

const sitem = reactive<menuType>({
  id: "", //账户id
  nickname: "", //真实姓名
  mobile: "", //手机号
  role: "", //角色,
  companyArr: []
});

const passwordModelId = ref("");
const passwordModel = ref(false);
const formRef = ref<FormInstance>();

const pagination = reactive<PaginationProps>({
  total: 0,
  pageSize: 15,
  currentPage: 1,
  background: true
});

// 重置密码
const resetRwd = async row => {
  const { id } = row;
  passwordModelId.value = id;
  passwordModel.value = 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,
    // companyNo: currentCompany.value.companyNo,
    noRela: true
    //currentCompany.value.companyNo === ""
  });

  responseHandle({
    code,
    message,
    logout,
    handler: () => {
      const { list, count } = data;
      dataList.value = list ?? [];
      pagination.total = count ?? 0;
      pagination.pageSize = form.size;
      pagination.currentPage = form.page;
    }
  });

  loading.value = false;
}
async function resetSearch() {
  form.page = 1;
  await onSearch();
}
//新建/编辑/详情弹窗
function editItem(id, type, item) {
  itemId.value = id;
  isDetails.value = type;
  for (let key in item) {
    sitem[key] = item[key];
  }
  showModel.value = true;
}
const submitRefresh = () => {
  showModel.value = false;
  onSearch();
};
const submitCancel = () => {
  showModel.value = false;
};
const resetCancel = () => {
  passwordModel.value = false;
};

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

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

onMounted(() => {
  powers.value = useUserStoreHook().getMenuActions("supplierAccoutManage");
  onSearch();
});
</script>

<template>
  <div class="main">
    <div v-show="powers.some(i => i == '001')">
      <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="nickname">
          <el-input v-model="form.nickname" placeholder="真实姓名" clearable />
        </el-form-item>
        <el-form-item prop="username">
          <el-input v-model="form.username" 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"
        size="small"
        @refresh="onSearch"
      >
        <template #buttons>
          <el-button
            type="primary"
            size="small"
            :icon="useRenderIcon('add')"
            @click="editItem('', 'add', {})"
            v-if="powers.some(i => i == '002')"
          >
            新增账号
          </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-popconfirm :title="'确认重置密码？'" @confirm="resetRwd(row)">
                <template #reference>
                  <el-button
                    class="reset-margin"
                    link
                    type="primary"
                    size="small"
                    v-if="powers.some(i => i == '012')"
                    :icon="useRenderIcon('refresh-right')"
                  /> </template
              ></el-popconfirm>
              <el-button
                class="reset-margin"
                v-if="powers.some(i => i == '007')"
                link
                type="primary"
                size="small"
                @click="editItem(row.id, 'view', row)"
                :icon="useRenderIcon('eye-view')"
              />
              <el-button
                class="reset-margin"
                link
                v-if="powers.some(i => i == '005')"
                type="primary"
                size="small"
                @click="editItem(row.id, 'edit', row)"
                :icon="useRenderIcon('edits')"
              />
              <el-popconfirm
                :title="
                  String(row.status) === '1' ? '改为禁用？' : '改为启用？'
                "
                v-if="
                  (powers.some(i => i == '004') && row.status + '' === '1') ||
                  (powers.some(i => i == '003') && row.status + '' === '0')
                "
                @confirm="handleStatus(row)"
              >
                <template #reference>
                  <el-button
                    class="reset-margin"
                    link
                    type="primary"
                    size="small"
                    :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"
        :sitem="sitem"
      />
      <reset-password
        :itemId="passwordModelId"
        :show-model="passwordModel"
        @refresh="resetCancel"
        @cancel="resetCancel"
      />
    </div>
    <NoAuth v-show="!powers.some(i => i == '001')" />
  </div>
</template>

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