<template>
  <div class="app-container">
    <el-form
      v-show="showSearch"
      ref="queryRef"
      :inline="true"
      :model="queryParams"
      label-width="68px"
    >
      <el-form-item label="登录账号" prop="userName">
        <el-input
          v-model="queryParams.userName"
          clearable
          placeholder="请输入登录账号"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!--      <el-form-item label="${comment}" prop="password">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.password"-->
      <!--          clearable-->
      <!--          placeholder="请输入${comment}"-->
      <!--          @keyup.enter="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item label="姓名" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          clearable
          placeholder="请输入姓名"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input
          v-model="queryParams.phone"
          clearable
          placeholder="请输入手机号码"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!--      <el-form-item label="${comment}" prop="provinceCode">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.provinceCode"-->
      <!--          clearable-->
      <!--          placeholder="请输入${comment}"-->
      <!--          @keyup.enter="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item label="负责省份" prop="provinceName">
        <el-input
          v-model="queryParams.provinceName"
          clearable
          placeholder="请输入负责省份"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!--      <el-form-item label="${comment}" prop="taskTotal">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.taskTotal"-->
      <!--          clearable-->
      <!--          placeholder="请输入${comment}"-->
      <!--          @keyup.enter="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="${comment}" prop="runTaskTotal">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.runTaskTotal"-->
      <!--          clearable-->
      <!--          placeholder="请输入${comment}"-->
      <!--          @keyup.enter="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item>
        <el-button icon="Search" type="primary" @click="handleQuery"
          >搜索
        </el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['maintenance:user:add']"
          icon="Plus"
          plain
          type="primary"
          @click="handleAdd"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['maintenance:user:edit']"
          :disabled="single"
          icon="Edit"
          plain
          type="success"
          @click="handleUpdate"
          >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['maintenance:user:remove']"
          :disabled="multiple"
          icon="Delete"
          plain
          type="danger"
          @click="handleDelete"
          >删除
        </el-button>
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="userList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column align="center" type="selection" width="55" />
      <!--      <el-table-column align="center" label="id" prop="userId" />-->
      <el-table-column align="center" label="登录账号" prop="userName" />
      <!--      <el-table-column align="center" label="密码" prop="password" />-->
      <el-table-column align="center" label="姓名" prop="nickName" />
      <el-table-column align="center" label="手机号码" prop="phone" />
      <el-table-column align="center" label="性别" prop="sex">
        <template #default="{ row }">
          <dict-tag :options="sys_user_sex" :value="row.sex"></dict-tag>
        </template>
      </el-table-column>
      <!--      <el-table-column align="center" label="${comment}" prop="provinceCode" />-->
      <el-table-column align="center" label="负责省份" prop="provinceName" />
      <el-table-column
        align="center"
        label="进行中任务数"
        prop="runTaskTotal"
      />
      <el-table-column align="center" label="任务总数" prop="taskTotal" />
      <el-table-column
        width="280"
        align="center"
        class-name="small-padding fixed-width"
        label="操作"
      >
        <template #default="scope">
          <el-button
            v-hasPermi="['maintenance:user:edit']"
            icon="Edit"
            link
            type="primary"
            @click="handleUpdate(scope.row)"
            >修改省份
          </el-button>
          <el-button
            v-hasPermi="['maintenance:user:resetPwd']"
            icon="Key"
            link
            type="primary"
            @click="handleResetPwd(scope.row)"
            >重置密码
          </el-button>
          <el-button
            v-hasPermi="['maintenance:user:remove']"
            icon="Delete"
            link
            type="primary"
            @click="handleDelete(scope.row)"
            >删除
          </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="open" :title="title" append-to-body width="500px">
      <el-form ref="userRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item v-if="!form.userId" label="登录账号" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入登录账号" />
        </el-form-item>
        <el-form-item v-if="!form.userId" label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item v-if="!form.userId" label="姓名" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item v-if="!form.userId" label="性别">
          <el-radio-group v-model="form.sex">
            <el-radio
              v-for="dict in sys_user_sex"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="!form.userId" label="手机号码" prop="phone">
          <el-input
            v-model="form.phone"
            :maxlength="11"
            placeholder="请输入手机号码"
          />
        </el-form-item>
        <el-form-item label="省份" prop="provinceCode">
          <el-select v-model="form.provinceCode" @change="handleProvinceChange">
            <el-option
              v-for="item in provinceOptions"
              :key="item.provinceCode"
              :label="item.provinceName"
              :value="item.provinceCode"
            />
          </el-select>
          <!--          <el-input-->
          <!--            v-model="form.provinceCode"-->
          <!--            placeholder="请输入${comment}"-->
          <!--          />-->
        </el-form-item>
        <!--        <el-form-item label="${comment}" prop="provinceName">-->
        <!--          <el-input-->
        <!--            v-model="form.provinceName"-->
        <!--            placeholder="请输入${comment}"-->
        <!--          />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="${comment}" prop="taskTotal">-->
        <!--          <el-input v-model="form.taskTotal" placeholder="请输入${comment}" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="${comment}" prop="runTaskTotal">-->
        <!--          <el-input-->
        <!--            v-model="form.runTaskTotal"-->
        <!--            placeholder="请输入${comment}"-->
        <!--          />-->
        <!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script name="User" setup>
import {
  addUser,
  delUser,
  getUser,
  listUser,
  resetUserPwd,
  updateUser,
} from "@/api/maintenance/user";
import { getCurrentInstance, reactive, ref, toRefs } from "vue";
import { provinceList } from "@/api/config";
import { useDict } from "@/utils/dict";
import DictTag from "@/components/DictTag/index.vue";
import { ElMessage, ElMessageBox } from "element-plus";

const { proxy } = getCurrentInstance();

const userList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const provinceOptions = ref([]);
const { sys_user_sex } = useDict("sys_user_sex");
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: null,
    password: null,
    nickName: null,
    phone: null,
    sex: null,
    provinceCode: null,
    provinceName: null,
    taskTotal: null,
    runTaskTotal: null,
  },
  rules: {
    provinceCode: [],
  },
});

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

/** 查询运维工人列表 */
function getList() {
  loading.value = true;
  listUser(queryParams.value).then((response) => {
    userList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    userId: null,
    userName: null,
    password: null,
    nickName: null,
    phone: null,
    sex: null,
    provinceCode: null,
    provinceName: null,
    taskTotal: null,
    runTaskTotal: null,
  };
  proxy.resetForm("userRef");
}

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

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.userId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加运维工人";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _userId = row.userId || ids.value;
  getUser(_userId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改运维工人省份";
  });
}

/** 重置密码按钮操作 */
function handleResetPwd(row) {
  ElMessageBox.prompt('请输入"' + row.userName + '"的新密码', "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    closeOnClickModal: false,
    inputPattern: /^.{5,20}$/,
    inputErrorMessage: "登录密码长度必须介于 5 和 20 之间",
  })
    .then(({ value }) => {
      resetUserPwd(row.userId, value).then((response) => {
        ElMessage.success("修改成功，新密码是：" + value);
      });
    })
    .catch(() => {});
}

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

/** 删除按钮操作 */
function handleDelete(row) {
  const _userIds = row.userId || ids.value;
  proxy.$modal
    .confirm('是否确认删除运维工人编号为"' + _userIds + '"的数据项？')
    .then(function () {
      return delUser(_userIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "maintenance/user/export",
    {
      ...queryParams.value,
    },
    `user_${new Date().getTime()}.xlsx`
  );
}

const handleProvinceChange = (val) => {
  if (val) {
    form.value.provinceName =
      provinceOptions.value.find((el) => el.provinceCode === val)
        ?.provinceName ?? undefined;
  }
};

const getProvinceList = () => {
  provinceList().then((resp) => {
    // console.log(resp);
    provinceOptions.value = resp.data;
  });
};
getProvinceList();
getList();
</script>
