<template>
  <div class="app-container">
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      label-width="85px"
    >
      <el-form-item label="实验室名称" prop="name">
        <el-input
          v-model="queryParams.name"
          clearable
          placeholder="请输入实验室名称"
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <!--      <el-form-item v-if="isSuper" label="所属站点" prop="tenant_id">-->
      <!--        <SiteOptions v-model="queryParams" :site-list="[]"/>-->
      <!--      </el-form-item>-->

      <el-form-item>
        <el-button
          icon="search"
          size="small"
          type="primary"
          @click="handleQuery"
          >搜索
        </el-button>
        <el-button icon="refresh" size="small" @click="resetQuery"
          >重置
        </el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          icon="plus"
          plain
          size="small"
          type="primary"
          @click="handleAdd"
          >新增
        </el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dataList">
      <el-table-column align="center" label="姓名" prop="name" />
      <!--      <el-table-column align="center" label="手机号" prop="mobile" />-->
      <el-table-column align="center" label="资格证书缩略图">
        <template #default="{ row }">
          <el-image
            :src="row.certificatePics?.split(',')?.[0] ?? ''"
            style="width: 120px; height: 120px"
          ></el-image>
        </template>
      </el-table-column>
      <!-- <el-table-column label="研究方向" align="center" prop="code" />
      <el-table-column
        label="所属领域"
        align="center"
        prop="industrys"
        show-overflow-tooltip
      >
        <template #default="{row}">
          <div>{{ row.industrys[row.industrys.length - 1] }}</div>
        </template>
      </el-table-column> -->
      <!--      <el-table-column align="center" label="站点" prop="area" />-->
      <el-table-column align="center" label="所在地" prop="wordAddress" />
      <el-table-column align="center" label="申请时间" prop="createTime">
        <template #default="{ row }">
          <span>{{ parseTime(row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template #default="{ row }">
          <el-button
            icon="edit"
            link
            size="small"
            type="text"
            @click="handleDetail(row.brokerId)"
            >修改
          </el-button>
          <el-button
            icon="edit"
            link
            size="small"
            type="text"
            @click="openAssignAccount(row.brokerId)"
            >分配账号
          </el-button>
          <el-button
            icon="refresh"
            link
            size="small"
            type="text"
            @click="openResetPassword(row.brokerId)"
            >重置密码
          </el-button>
          <el-button
            icon="delete"
            size="small"
            type="text"
            @click="handleDelete(row.brokerId)"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />

    <el-dialog
      v-model="showAssignAccount"
      append-to-body
      title="分配账号"
      width="400px"
    >
      <el-form
        ref="assignAccountFormRef"
        :model="assignAccountForm"
        :rules="assignAccoutRules"
        label-width="80px"
      >
        <el-form-item label="手机号" prop="username">
          <el-input
            v-model="assignAccountForm.username"
            :maxlength="11"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="assignAccountForm.password"
            show-password
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAssignAccount"
            >确 定
          </el-button>
          <el-button @click="closeAssignAccount">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="showResetPassword"
      append-to-body
      title="重置密码"
      width="400px"
    >
      <el-form
        ref="resetPasswordFormRef"
        :model="resetPasswordForm"
        :rules="assignAccoutRules"
        label-width="80px"
      >
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="resetPasswordForm.password"
            show-password
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitResetPassword"
            >确 定
          </el-button>
          <el-button @click="closeResetPassword">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
// 遮罩层
import { reactive, ref, toRefs } from "vue";
import { useRouter } from "vue-router";
import {
  agentList,
  allocateAccount,
  deleteAgent,
  getAccount,
  resetPassword,
} from "@/api/dataList/agent";
import { parseTime } from "@/utils/ruoyi";
import { ElMessage, ElMessageBox } from "element-plus";
import md5 from "js-md5";
/* TODO: is_super: this.$store.getters.is_super,  */

const router = useRouter();
const showSearch = ref(true);
const loading = ref(true);
const total = ref(0); /*总条数*/
const dataList = ref(null); /*实验室表格数据*/
const queryFormRef = ref();
const isSuper = ref(false);
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
  },
});

const { queryParams } = toRefs(data);

/*查询实验室列表*/
const getList = () => {
  loading.value = true;
  agentList(queryParams.value).then((response) => {
    dataList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.page_num = 1;
  getList();
};

/* 重置按钮操作 */
const resetQuery = () => {
  // dateRange.value = [];
  queryFormRef.value?.resetFields();
  handleQuery();
};

const handleAdd = () => {
  router.push({
    path: "/dataList/agentAdd",
  });
};
const handleDetail = (id) => {
  router.push({
    path: "/dataList/agentAdd",
    query: { id },
  });
};

const assignAccoutRules = {
  username: [
    {
      required: true,
      message: "请输入手机号",
      trigger: "blur",
    },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  vipType: [{ required: true, message: "请选择会员类型", trigger: "change" }],
  expireTime: [
    { required: true, message: "请选择到期时间", trigger: "change" },
  ],
};
const showAssignAccount = ref(false);
const assignAccountForm = reactive({
  username: undefined,
  password: undefined,
});
const assignAccountFormRef = ref();
const resetPasswordForm = reactive({
  password: undefined,
});
const resetPasswordFormRef = ref();
const showResetPassword = ref(false);

const openAssignAccount = async (id) => {
  resetForm();
  const { have, data } = await getAccount(id);
  if (have) {
    ElMessageBox.alert(`已经存在账号：${data}`, "账号已经存在");
  } else {
    assignAccountForm.id = id;
    showAssignAccount.value = true;
  }
};

const openResetPassword = async (id) => {
  resetForm();
  const { have, userId } = await getAccount(id);
  if (have) {
    resetPasswordForm.id = userId;
    showResetPassword.value = true;
  } else {
    ElMessageBox.alert(`尚未分配账号，请先分配账号`, "尚未分配账号");
  }
};
const resetForm = () => {
  if (resetPasswordFormRef.value) {
    resetPasswordFormRef.value.resetFields();
  }
  if (assignAccountFormRef.value) {
    assignAccountFormRef.value.resetFields();
  }
  resetPasswordForm.password = undefined;
  assignAccountForm.username = undefined;
  assignAccountForm.password = undefined;
};
const closeResetPassword = () => {
  resetForm();
  showResetPassword.value = false;
};
const closeAssignAccount = () => {
  resetForm();
  showAssignAccount.value = false;
};

const submitAssignAccount = async () => {
  await assignAccountFormRef.value.validate();
  await allocateAccount({
    ...assignAccountForm,
    password: md5(assignAccountForm.password),
  });
  ElMessage.success("账号分配成功");
  showAssignAccount.value = false;
};

const submitResetPassword = async () => {
  await resetPasswordFormRef.value.validate();
  await resetPassword(resetPasswordForm.id, md5(resetPasswordForm.password));
  ElMessage.success("密码重置成功");
  showResetPassword.value = false;
};

const handleDelete = async (id) => {
  let delIds;
  if (id) {
    delIds = [id];
  } else {
    delIds = ids.value;
  }
  ElMessageBox.confirm(`是否确认删除编号为${delIds.join(",")}的数据项？`)
    .then(async () => {
      await deleteAgent(delIds);
      getList();
      ElMessage.success("删除成功");
    })
    .catch(() => {});
};

getList();
</script>
