<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="用户名称" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入用户名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="手机号码" prop="phoneNumber">
        <el-input
          v-model="queryParams.phoneNumber"
          placeholder="请输入手机号码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="审核状态" clearable size="small">
          <el-option :label="keys" v-for="(keys, vals)  in stateOption" :key="keys" :value="vals" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="registeredList">
      <el-table-column type="index" label="序号" align="center" :index="indexFormatter" width="80px"></el-table-column>
      <el-table-column type="expand" width="50px">
        <template slot-scope="props">
          <expand-temp :sourceId="props.row.registeredId" @expandExent="expandExent" />
        </template>
      </el-table-column>
      <el-table-column label="用户名称" align="left" prop="username" />
      <el-table-column label="手机号码" align="center" prop="phoneNumber" />
      <el-table-column label="注册邮箱" align="center" prop="email" />
      <el-table-column label="头像" align="center" prop="avatar" width="50px">
        <template slot-scope="scope">
          <div class="demo-image__preview">
            <el-image
              style="width: 30px; height: 25px;"
              :src="getIotFileUrl(scope.row.avatar)"
              :preview-src-list="[getIotFileUrl(scope.row.avatar)]"
            ></el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="注册状态" align="center" prop="status">
        <template slot-scope="scope">
          <span v-text="stateOption[scope.row.status]"></span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-finance"
            v-if="scope.row.status === '1'"
            @click="handleUuser(scope.row)"
          >通过审核</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:registered:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:registered:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改注册用户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="650px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="17">
            <el-form-item label="登录账号" prop="username">
              <el-input v-model="form.username" disabled placeholder="请输入登录账号" />
            </el-form-item>
            <el-form-item label="手机号码" prop="phoneNumber">
              <el-input v-model="form.phoneNumber" disabled placeholder="请输入手机号码" />
            </el-form-item>
            <el-form-item label="登录密码" prop="password">
              <el-input v-model="form.password" placeholder="请输入登录密码" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="avatar" class="table-avatar">
              <upload-image
                :fileType="fileType"
                :imageUrl="form.avatar"
                @eventUrl="(data) => {form.avatar = data}"
              />
              <span
                style="
                line-height: 20px;
                font-size: 15px;
                font-weight: 600;
                display: flex;
                width: 100%;
                justify-content: center;
                "
              >用户头像</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="nickname">
              <el-input v-model="form.nickname" placeholder="请输入用户昵称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="注册邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入注册邮箱" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="企业编码">
              <el-input v-model="form.tenantCode" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="企业名称">
              <el-input v-model="form.tenantName" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-radio v-model="form.sex" label="0">男</el-radio>
              <el-radio v-model="form.sex" label="1">女</el-radio>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="企业法人">
              <el-input v-model="form.corporation" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="营业执照" prop="sex">
              <!-- <el-input v-model="form.businessLicense" disabled /> -->
              <upload-image
                :fileType="fileType"
                :imageUrl="form.businessLicense"
                compStyle="height: 100px; width: 100px;"
                @eventUrl="(data) => {form.businessLicense = data}"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="submitForm">确 定</el-button>
        <el-button size="mini" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listRegistered,
  getRegistered,
  delRegistered,
  addRegistered,
  updateRegistered,
  addUserRegistered
} from "@/api/system/registered";
import { listTenant } from "@/api/system/tenant";
import { listDept } from "@/api/system/dept";
import { listRole } from "@/api/system/role";
import { listPost } from "@/api/system/post";
import { getIotFileUrl } from "@/utils/hciot";
import UploadImage from "@/components/Upload/Image.vue";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import ExpandTemp from "./expandTemp";

const stateOption = {
  "0": "未修改",
  "1": "待审核"
};
const userTypeOption = {
  "1": "租户",
  "02": "项目"
};
export default {
  name: "Registered",
  components: {
    UploadImage,
    Treeselect,
    ExpandTemp
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      deptOptions: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 注册用户表格数据
      registeredList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userType: undefined,
        username: undefined,
        nickname: undefined,
        email: undefined,
        phoneNumber: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        password: [
          { required: true, message: "登录密码不能为空！", trigger: "blur" }
        ],
        tenantId: [{ required: true, message: "请选择租户", trigger: "blur" }],
        roleIds: [{ required: true, message: "请选择角色", trigger: "blur" }],
        email: [
          { required: true, message: "用户昵称不能为空", trigger: "blur" },
          {
            pattern: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
            message: "邮箱格式不正确。"
          }
        ],
        nickname: [
          { required: true, message: "用户昵称不能为空", trigger: "blur" }
        ],
        deptId: [{ required: true, message: "请选择部门", trigger: "blur" }]
      },
      userTypeOption,
      stateOption,
      fileType: ["image/jpeg", "image/png"],
      tenantList: [],
      rouleList: [],
      postList: [],
      roleIds: [],
      postIds: [],
      expandList: []
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getIotFileUrl,
    indexFormatter(val) {
      return (
        val + 1 + (this.queryParams.pageNum - 1) * this.queryParams.pageSize
      );
    },
    getPostList() {
      listPost({
        tenantId: this.form.tenantId,
        pageNum: 1,
        pageSize: 9999
      }).then(response => {
        this.postList = response.rows;
      });
    },
    getRoueList() {
      listRole({
        tenantId: this.form.tenantId,
        pageNum: 1,
        pageSize: 9999
      }).then(response => {
        this.rouleList = response.rows;
      });
    },
    // 获取租户下所有部门信息 选择租户之后触发
    getDepList() {
      listDept({
        tenantId: this.form.tenantId
      }).then(response => {
        this.deptOptions = this.handleTree(response.data, "deptId");
        if (this.deptOptions.length === 0) {
          const menu = { deptId: 0, deptName: "主类目", children: [] };
          this.deptOptions.push(menu);
        }
      });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    tenantIdChange(tenantId) {
      this.rouleList = [];
      this.postList = [];
      this.roleIds = [];
      this.postIds = [];
      this.form.deptId = "";
      this.getDepList();
      this.getRoueList();
      this.getPostList();
    },
    // 获取所有租户信息
    getTenantList() {
      this.tenantList = [];
      listTenant().then(response => {
        this.tenantList = response.rows;
      });
    },
    /** 查询注册用户列表 */
    getList() {
      this.loading = true;
      this.queryParams.status = this.queryParams.status === '' ? undefined : this.queryParams.status
      listRegistered(this.queryParams).then(response => {
        this.registeredList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.deptOptions = [];
      this.tenantList = [];
      this.form = {
        registeredId: undefined,
        deptId: undefined,
        userType: "1",
        username: undefined,
        nickname: undefined,
        email: undefined,
        phoneNumber: undefined,
        sex: "0",
        avatar: undefined,
        password: undefined,
        tenantId: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.registeredId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加注册用户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTenantList();
      const registeredId = row.registeredId || this.ids;
      this.roleIds = [];
      this.postIds = [];
      getRegistered(registeredId).then(response => {
        this.form = Object.assign({}, response.data);
        if (!this.form.sex && this.form.sex !== 0) this.form.sex = "0";
        if (!this.form.userType) this.form.userType = "1";
        this.open = true;
        this.title = "修改注册用户";
        this.tenantIdChange();
        this.form.deptId = response.data.deptId;
        this.roleIds = response.data.roleIds.split(",");
        this.postIds = response.data.postIds.split(",");
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.form.roleIds = this.roleIds.toString();
      this.form.postIds = this.postIds.toString();
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.registeredId != undefined) {
            this.form.status = 1;
            updateRegistered(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addRegistered(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    //审核
    handleUuser(row) {
      this.$confirm(
        // '是否确认删除注册用户编号为"' + registeredIds + '"的数据项?',
        "通过用户注册审核，并且创建正式数据？",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function() {
          return addUserRegistered(row.registeredId);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("成功");
        })
        .catch(function() {});
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const registeredIds = row.registeredId || this.ids;
      this.$confirm(
        // '是否确认删除注册用户编号为"' + registeredIds + '"的数据项?',
        "是否删除该选项",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function() {
          return delRegistered(registeredIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/registered/export",
        {
          ...this.queryParams
        },
        `system_registered.xlsx`
      );
    }
  }
};
</script>
<style lang="scss">
.table-avatar {
  .el-form-item__content {
    margin-left: 20px !important;
  }
}
</style>
