<template>
  <div class="page-container column-container">
    <!-- 搜索区 -->
    <el-form
      class="list-search-container"
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item class="section-title" label="员工管理" />
      <el-form-item label="员工编码：" prop="userName">
        <el-input
          v-model.trim="queryParams.userName"
          placeholder="请输入员工编码"
          clearable
          style="width: 130px"
          @keyup.enter="handleQueryUser"
        />
      </el-form-item>
      <el-form-item label="员工姓名：" prop="nickName">
        <el-input
          v-model.trim="queryParams.nickName"
          placeholder="请输入员工姓名"
          clearable
          style="width: 130px"
          @keyup.enter="handleQueryUser"
        />
      </el-form-item>
      <el-form-item label="手机号码：" prop="phoneNumber">
        <el-input
          v-model.trim="queryParams.phoneNumber"
          placeholder="请输入手机号码"
          clearable
          style="width: 130px"
          @keyup.enter="handleQueryUser"
        />
      </el-form-item>
      <el-form-item label="员工状态：">
            <el-select v-model="queryParams.status" placeholder="请选择" clearable style="width: 120px;">
              <el-option
                v-for="dict in sys_normal_disable"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
      <el-form-item>
        <el-button type="info" icon="Search" @click="handleQueryUser"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 功能按钮区 -->
    <div class="list-btns-container">
      <el-button
        type="primary"
        icon="Plus"
        @click="handleShowUserDialog(null)"
        v-hasPermi="['business:emploee:add']"
        >新增</el-button
      >
      <el-button
        type="danger"
        icon="Delete"
        :disabled="multiple"
        @click="handleDeleteMultipleUser"
        v-hasPermi="['business:emploee:remove']"
        >删除</el-button
      >
    </div>
    <!-- 渲染数据区 -->
    <div class="el-table-container">
      <div class="el-table-inner-container">
        <el-table
          v-loading="loading"
          :data="userList"
          height="100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="40" align="center" />
          <el-table-column
            label="员工编码"
            width="100"
            align="center"
            prop="userName"
            v-if="columns[1].visible"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="员工姓名"
            width="100"
            align="center"
            prop="nickName"
            v-if="columns[2].visible"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="手机号码"
            width="120"
            align="center"
            prop="phoneNumber"
            v-if="columns[3].visible"
          />
          <el-table-column
            label="合同单位"
            width="300"
            align="center"
            prop="contractCompanyName"
            v-if="columns[4].visible"
          />
          <el-table-column
            label="性别"
            width="60"
            align="center"
            prop="sex"
            v-if="columns[5].visible"
          />
          <el-table-column
            label="使用单位"
            prop="usageCompanyName"
            width="300"
            align="center"
          />
          <el-table-column label="备注" align="center" prop="remark" />
          <el-table-column label="操作" align="center" width="220">
            <template #default="scope">
              <el-button
                link
                type="warning"
                icon="Edit"
                @click="handleShowUserDialog(scope.row.userId)"
                v-hasPermi="['business:emploee:edit']"
                >编辑</el-button
              >
              <el-button
                link
                type="danger"
                icon="Delete"
                @click="handleDeleteUser(scope.row.userId)"
                v-hasPermi="['business:emploee:remove']"
                >删除</el-button
              >
              <el-button
                link
                type="success"
                icon="Key"
                @click="handleResetPwd(scope.row)"
                v-hasPermi="['business:emploee:resetPwd']"
                >重置密码</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog
      title="员工信息"
      v-model="open"
      width="450px"
      append-to-body
      draggable
    >
      <div class="form-container">
        <el-form
          ref="userRef"
          :model="form"
          class="master-container"
          :rules="rules"
          label-width="90px"
        >
          <el-form-item label="员工姓名" prop="nickName">
            <el-input
              v-model.trim="form.nickName"
              placeholder="请输入员工姓名"
              maxlength="30"
            />
          </el-form-item>
          <el-form-item label="合同单位:" prop="contractCompanyId">
            <el-select-v2
              v-model.trim="form.contractCompanyId"
              :options="contractCompanyList"
              placeholder="请选择合同单位"
              style="width: 100%"
              @change="handleChangeContractCompany"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="phoneNumber">
            <el-input
              v-model.trim="form.phoneNumber"
              placeholder="请输入手机号码"
              maxlength="11"
            />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input
              v-model.trim="form.email"
              placeholder="请输入邮箱"
              maxlength="50"
            />
          </el-form-item>
          <el-form-item
            v-if="form.userId == undefined"
            label="员工编码"
            prop="userName"
          >
            <el-input
              v-model.trim="form.userName"
              placeholder="请输入员工编码"
              maxlength="30"
            />
          </el-form-item>
          <el-form-item
            v-if="form.userId == undefined"
            label="登录密码"
            prop="password"
          >
            <el-input
              v-model.trim="form.password"
              placeholder="请输入登录密码"
              type="password"
              maxlength="20"
              show-password
            />
          </el-form-item>
          <el-form-item label="用户性别">
            <el-select v-model="form.sex" placeholder="请选择">
              <el-option
                v-for="dict in manOrWoman"
                :key="dict.value"
                :label="dict.label"
                :value="dict.label"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="使用单位:" prop="usageCompanyId">
            <el-select-v2
              v-model.trim="form.usageCompanyId"
              filterable
              clearable
              :options="usageCompanyList"
              placeholder="请选择使用单位"
              style="width: 100%"
              @change="handleChangeUsageCompany"
            />
          </el-form-item>
          <el-form-item label="角色">
            <el-select v-model="form.roleIds" multiple placeholder="请选择">
              <el-option
                v-for="item in roleOptions"
                :key="item.roleId"
                :label="item.roleName"
                :value="item.roleId"
                :disabled="item.status == 1"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="员工状态">
            <el-select v-model="form.status" placeholder="请选择">
              <el-option
                v-for="dict in sys_normal_disable"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              v-model.trim="form.remark"
              type="textarea"
              placeholder="请输入内容"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button type="primary" icon="Check" @click="handleSave"
          >确 定</el-button
        >
        <el-button icon="Close" @click="handleCancel">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="User">
import {
  listEmployee,
  resetUserPwd,
  delUser,
  getUser,
  updateUser,
  addUser,
} from "@/api/system/user";
import { listInfo } from "@/api/business/tenant";
const { proxy } = getCurrentInstance();
/** 员工管理变量 */
const userList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
/** 员工信息弹窗变量 */
const contractCompanyList = ref([]);
const open = ref(false);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const roleOptions = ref([]);
const usageCompanyList = ref([]);
const manOrWoman = [
  { label: "男", value: "1" },
  { label: "女", value: "0" },
];
/** 字典 */
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
// 列显隐信息
const columns = ref([
  { key: 0, label: `用户编号`, visible: true },
  { key: 1, label: `员工编码`, visible: true },
  { key: 2, label: `员工姓名`, visible: true },
  { key: 3, label: `部门`, visible: true },
  { key: 4, label: `手机号码`, visible: true },
  { key: 5, label: `状态`, visible: true },
  { key: 6, label: `创建时间`, visible: true },
]);
/** 查询对象 */
const data = reactive({
  form: {
    usageCompanyId: null,
    contractCompanyId:null,
    contractCompanyName:null,
    usageusageCompanyName: null,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: "",
    nickName: "",
    phoneNumber: "",
    // status: 0,
    deptName: "",
  },
  rules: {
    userName: [
      { required: true, message: "员工编码不能为空", trigger: "blur" },
      {
        min: 2,
        max: 20,
        message: "员工编码长度必须介于 2 和 20 之间",
        trigger: "blur",
      },
    ],
    nickName: [
      { required: true, message: "员工姓名不能为空", trigger: "blur" },
    ],
    password: [{ required: true, message: "密码不能为空", trigger: "blur" }],
    contractCompanyId: [{ required: true, message: "合同单位不能为空", trigger: "change" }],
    usageCompanyId: [{ required: true, message: "使用单位不能为空", trigger: "change" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询用户列表 */
function getList() {
  loading.value = true;
  listInfo().then((res) => {
    if (res.code == 200) {
      contractCompanyList.value = res.data;
      usageCompanyList.value = res.data;
    }
  });
  listEmployee(queryParams.value).then((response) => {
    // for(let i = 0; i < response.rows.length; i++) {
    //   for(let j = 0;j<contractCompanyList.value.length;j++) {
    //     if(response.rows[i].tenantId == contractCompanyList.value[j].value) {
    //       response.rows[i].tenantName = contractCompanyList.value[j].label;
    //     }
    //   }
      
    // }
    userList.value = response.rows;
    console.log(userList.value)
    total.value = response.total;
  loading.value = false;
  });
}

/** 搜索按钮操作 */
function handleQueryUser() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQueryUser();
}
/** 删除按钮操作 */
function handleDeleteUser(id) {
  console.log(ids.value);
  if (id) {
    proxy.$modal
      .confirm("是否确认删除？")
      .then(function () {
        return delUser(id);
      })
      .then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
      })
      .catch(() => {});
  }
}

/** 重置密码按钮操作 */
function handleResetPwd(row) {
  proxy
    .$prompt('请输入"' + row.userName + '"的新密码', "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      closeOnClickModal: false,
      inputPattern: /^.{5,20}$/,
      inputErrorMessage: "登录密码长度必须介于 5 和 20 之间",
    })
    .then(({ value }) => {
      resetUserPwd(row.userId, value).then((response) => {
        proxy.$modal.msgSuccess("修改成功，新密码是：" + value);
      });
    })
    .catch(() => {});
}
/** 选择条数  */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.userId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
//使用单位更改
function handleChangeUsageCompany() {
  form.value.tenantId = form.value.usageCompanyId;
  for (let i = 0; i < usageCompanyList.value.length; i++) {
    if (form.value.usageCompanyId == usageCompanyList.value[i].value) {
      form.value.usageCompanyName = usageCompanyList.value[i].label;
    }
  }
}
//合同单位更改
function handleChangeContractCompany() {
  console.log(form.value.contractCompanyName)
  console.log(contractCompanyList.value)
  for (let i = 0; i < contractCompanyList.value.length; i++) {
    if (form.value.contractCompanyId == contractCompanyList.value[i].value) {
      form.value.contractCompanyName = contractCompanyList.value[i].label;
    }
  }
}

/**多选删除按钮操作 */
function handleDeleteMultipleUser() {
  if (ids.value) {
    proxy.$modal
      .confirm("是否确认删除？")
      .then(function () {
        return delUser(ids.value);
      })
      .then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
      })
      .catch(() => {});
  }
}

/** 重置操作表单 */
function reset() {
  form.value = {
    userName: "",
    nickName: "",
    password: "",
    phoneNumber: "",
    email: "",
    sex: "男",
    remark: "",
    contractCompanyId: null,
    status:"0",
    roleIds: [],
  };
  proxy.resetForm("userRef");
}
/** 取消按钮 */
function handleCancel() {
  open.value = false;
  reset();
}
/** 修改/添加按钮操作 */
function handleShowUserDialog(id) {
  reset();
  if (id) {
    getUser(id).then((response) => {
      if(response.data.usageCompanyId == "0") {
        response.data.usageCompanyId =null
        response.data.usageCompanyName = null
      }
      response.data.status = response.data.status+""
      form.value = response.data;
      form.value.roleIds = response.roleIds;
      roleOptions.value = response.roles;
      console.log('response', response)
      form.password = "";
    });
  } else {
    getUser('0').then((response) => {
      roleOptions.value = response.roles;
      console.log('response', response)
    });
  }
  open.value = true;
}

/** 提交按钮 */
function handleSave() {
  proxy.$refs["userRef"].validate((valid) => {
    if (valid) {
      console.log(form.value);
      console.log(form.value);
      if (form.value.userId != undefined) {
        updateUser(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addUser(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

getList();
</script>
