<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input v-model="deptName" placeholder="请输入部门名称" clearable size="small" prefix-icon="el-icon-search" style="margin-bottom: 20px" />
        </div>
        <div class="head-container">
          <el-tree ref="tree" :data="deptOptions" :props="defaultProps" :expand-on-click-node="false" :filter-node-method="filterNode" default-expand-all highlight-current @node-click="handleNodeClick" />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
          <el-form-item prop="userOrPhone">
            <el-input v-model="queryParams.employeeName" placeholder="请输入姓名/手机号" clearable style="width: 240px" @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="入职时间">
            <el-date-picker v-model="queryParams.hiredate" style="width: 240px" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
            <el-button v-hasPermi="['system:employee:add']" type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
          </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="userList">
          <el-table-column label="姓名" prop="employeeName" />
          <el-table-column label="手机号" prop="phone" />
          <el-table-column label="部门" prop="orgName" />
          <el-table-column label="上级领导" prop="leaderName" />
          <el-table-column label="入职时间" prop="hiredate" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.hiredate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="260">
            <template slot-scope="scope">
              <el-button v-hasPermi="['system:employee:edit']" type="text" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button v-hasPermi="['system:employee:logoff']" type="text" @click="handleLogoff(scope.row)">注销</el-button>
              <el-button v-hasPermi="['system:employee:release']" type="text" @click="handleRelease(scope.row)">释放线索</el-button>
              <el-button v-hasPermi="['system:employee:remove']" type="text" @click="handleRemove(scope.row)">删除</el-button>
              <!-- <el-button
                v-hasPermi="['system:employee:resetPwd']"
                type="text"
                icon="el-icon-key"
                @click="handleReset(scope.row)"
              >重置密码</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-col>
    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" custom-class="dialog500" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="employeeName">
              <el-input v-model="form.employeeName" placeholder="请输入员工姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色" prop="roleIdList">
              <el-select v-model="form.roleIdList" multiple placeholder="请选择" class="wp100">
                <el-option v-for="item in roleOptions" :key="item.id" :label="item.name" :value="item.id" :disabled="item.status == 1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属部门" prop="orgId">
              <treeselect v-model="form.orgId" class="wp100" :options="deptOptions" :disable-branch-nodes="true" :show-count="true" placeholder="请选择归属部门" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权重" prop="weight">
              <el-input v-model="form.weight" placeholder="权重，1-100" type="number" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户性别">
              <el-select v-model="form.sex" placeholder="请选择" class="wp100">
                <el-option v-for="dict in sexOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入职日期">
              <el-date-picker v-model="form.hiredate" :editable="false" type="date" value-format="yyyy-MM-dd" placeholder="请选择入职时间" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status" class="wp100">
                <el-radio v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictValue">{{ dict.dictLabel }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最大线索数">
              <el-input v-model="form.maxClueNum" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否考勤">
              <el-radio-group v-model="form.checkin" class="wp100">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否参与统计">
              <el-radio-group v-model="form.count" class="wp100">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="小程序权限">
              <el-radio-group v-model="form.hasStudent">
                <el-radio :label="true">开通</el-radio>
                <el-radio :label="false">关闭</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="12">
            <el-form-item label="管理系统权限">
              <el-radio-group v-model="form.hasSys">
                <el-radio :label="true">开通</el-radio>
                <el-radio :label="false">关闭</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col> -->
          <el-col :span="24">
            <el-form-item label="备注">
              <!-- <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input> -->
              <editor v-model="form.remark" :height="200" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import empAPi from '@/api/system/employee';
import { deptTreeSelect } from '@/api/system/dept';
import { getRoleOptions } from '@/api/system/role';
import { resetUserPwd } from '@/api/system/user';
import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';
import editor from '@/components/Editor';

export default {
  name: 'Employee',
  components: { Treeselect, editor },
  data() {
    return {
      // 遮罩层
      loading: true,
      userId: localStorage.getItem('userId'),
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: '',
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 状态数据字典
      statusOptions: [],
      // 性别状态字典
      sexOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nameOrPhone: undefined,
        status: '0',
        orgId: undefined,
        roleId: undefined,
        hiredate: []
      },
      // 表单校验
      rules: {
        employeeName: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
        roleIdList: [
          {
            required: true,
            type: 'array',
            message: '角色不能为空',
            trigger: 'blur,change'
          }
        ],
        orgId: [
          {
            required: true,
            message: '归属部门不能为空',
            trigger: 'blur,change'
          }
        ],
        weight: [
          {
            required: true,
            message: '权重不能为空',
            trigger: 'blur,change'
          }
        ],
        phone: [
          { required: true, message: '手机号码不能为空', trigger: 'blur' },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ]
      },
      userOptions: [],
      areaOptions: []
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    this.getDeptTree();
    this._getRoleOptions();
    this.getDicts('sys_normal_disable').then((response) => {
      this.statusOptions = response.data;
    });
    this.getDicts('sys_user_sex').then((response) => {
      this.sexOptions = response.data;
    });

    this.getDicts('dm_area').then((response) => {
      this.areaOptions = response.data;
    });
    this.getConfigKey('sys.user.initPassword').then((response) => {
      this.initPassword = response.msg;
    });
    empAPi.getEmployee().then((resp) => {
      if (resp.code === 200) {
        this.userOptions = resp.data;
        // this.userOptions.push({
        //   id: '6ce3239c8c154f83befb9eb7441a01c7',
        //   name: 'DM',
        // })
      }
    });
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      empAPi.pageList(this.queryParams).then((response) => {
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    _getRoleOptions() {
      getRoleOptions().then((resp) => {
        this.roleOptions = resp.data;
      });
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.orgId = data.id;
      this.getList();
    },
    // 用户状态修改
    handleStatusChange(row) {
      const text = row.status === '0' ? '启用' : '停用';
      this.$confirm('确认要"' + text + '""' + row.userName + '"用户吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function () {
          const model = {
            employeeId: row.employeeId,
            status: row.status
          };
          return empAPi.update(model);
        })
        .then(() => {
          this.msgSuccess(text + '成功');
        })
        .catch(function () {
          row.status = row.status === '0' ? '1' : '0';
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        orgId: undefined,
        employeeName: undefined,
        phone: undefined,
        sex: '0',
        status: '0',
        remark: undefined,
        roleIdList: [],
        hiredate: undefined,
        leader: this.userId,
        discardClue: false,
        maxPublicClue: undefined,
        checkin: true,
        areaList: [],
        weight: undefined,
        count: true,
        officeId: undefined
      };
      this.resetForm('form');
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm');
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getDeptTree();
      this.open = true;
      this.title = '添加员工';
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getDeptTree();
      this.form = Object.assign({}, row);
      this.open = true;
      this.title = '修改员工';
    },
    /** 重置密码按钮操作 */
    handleReset(row) {
      resetUserPwd({ employeeId: row.employeeId }).then((response) => {
        if (response.code === 200) {
          this.msgSuccess('重置密码成功!');
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.$set(this.form, 'deptId', this.$store.getters.schoolId);
          if (this.form.employeeId) {
            empAPi.update(this.form).then((response) => {
              if (response.code === 200) {
                this.$message.success('修改成功');
                this.open = false;
                this.getList();
              }
            });
          } else {
            empAPi.add(this.form).then((response) => {
              if (response.code === 200) {
                this.$message.success('新增成功');
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    handleLogoff(row) {
      this.$confirm('注销后将立即释放线索，并禁用该员工，是否确认注销?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        // 走释放线索逻辑，并禁用该用户
      }).then(() => {
        this.msgSuccess('注销成功！');
      });
    },
    handleRelease(row) {
      this.$confirm('是否立刻释放该员工拥有的线索?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        // 应该只释放未成交的线索
      }).then(() => {
        this.msgSuccess('释放成功！');
      });
    },
    handleRemove(row) {
      this.$confirm('是否删除该员工，建议只在数据错误时删除?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        // 检查一下，如果被使用，提示不可删除
      }).then(() => {
        this.msgSuccess('删除成功！');
      });
    }
  }
};
</script>

<style>
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}

.el-icon-arrow-down {
  font-size: 12px;
}
</style>
