<template>
  <div>
    <el-card>
      <el-form :inline="true" :model="query" size="mini" v-if="showSearch">
        <el-row>
          <el-col :span="8">
            <el-form-item label="用户账号:">
              <el-input v-model="query.userName" placeholder="用户账号" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item class="query-form-item" label="账号状态:">
              <el-select v-model="query.userFlag" placeholder="请选择账号状态:">
                <el-option label="全部" value=""></el-option>
                <el-option label="禁用" value="0"></el-option>
                <el-option label="正常" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属部门:">
              <el-input v-model="query.deptName" placeholder="所属部门" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div class="top-right-btn">
        <el-button-group>
          <el-button icon="el-icon-view" type="primary" @click="hideSearch">显示/隐藏搜索栏</el-button>
          <el-button type="primary" icon="el-icon-refresh" @click="onReset">重置</el-button>
          <el-button type="primary" icon="el-icon-search" @click="onSubmit">查询</el-button>
          <el-button type="primary" @click.native="handleForm(null, null)" icon="el-icon-plus"
                     :disabled="!configParms.sysUser && query.customerId == 110"
                     v-hasPermi="['system:user:add']">新增
          </el-button>
        </el-button-group>
      </div>

      <el-divider style="margin: 15px"></el-divider>
      <el-table v-loading="loading" :data="list"
                style="width: 100%"
                border highlight-current-row>
        <el-table-column label="序号" type="index"></el-table-column>
        <el-table-column label="用户账号" prop="userName"></el-table-column>
        <el-table-column label="用户名称" prop="employeeName"></el-table-column>
        <el-table-column label="所属部门" prop="deptName"></el-table-column>
        <!--<el-table-column label="所属仓库" prop="warehouseName"></el-table-column>-->
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-tag :type="scope.row.userFlag | statusFilterType">{{
                scope.row.userFlag | statusFilterName
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="comments"></el-table-column>
        <el-table-column
          label="登录时间"
          with="300"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <i class="el-icon-time"></i>
            <span> {{ scope.row.lastLoginTime }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click.native="handleForm(scope.$index, scope.row)"
              :disabled="!configParms.sysUser"
            >编辑
            </el-button>
            <el-button
              type="text"
              :disabled="scope.row.id === '1' || !configParms.sysUser"
              @click.native="handleDel(scope.$index, scope.row)"
              v-hasPermi="['system:user:remove']"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="query.page"
        :limit.sync="query.limit"
        @pagination="getList"
      />
      <!--表单-->
      <el-dialog
        :title="formMap[formName]"
        :visible.sync="formVisible"
        :before-close="hideForm"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        v-if="formVisible"
        class="dialog-two"
        width="60%"
        top="5vh"
      >
        <el-form :model="formData" :rules="formRules" ref="dataForm" label-width="100px">
          <el-row type="flex">
            <el-col :span="11" type="flex">
              <el-form-item label="用户账号" prop="userName">
                <el-input v-model="formData.userName" size="small" style="width: 90%"
                          :disabled="formData.id == 1"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11" class="el-col">
              <el-form-item label="用户名称" prop="employeeName">
                <el-input v-model="formData.employeeName" size="small"
                          style="width: 90%" :disabled="formData.id == 1"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row type="flex" v-if="!formData.id">
            <el-col :span="11" type="flex">
              <el-form-item label="登录密码" prop="passWord">
                <el-input
                  type="password" style="width: 90%"
                  size="small"
                  v-model="formData.passWord"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11" class="el-col">
              <el-form-item label="确认密码" prop="checkPassword">
                <el-input
                  type="password"
                  size="small" style="width: 90%"
                  v-model="formData.checkPassword"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex">

            <el-col :span="11" type="flex">
              <el-form-item label="所属部门">
                <el-select
                  v-model="formData.depts"
                  filterable
                  remote
                  clearable="true"
                  style="width: 90%"
                  multiple
                  size="small"
                  reserve-keyword
                  placeholder="请选择"
                  :remote-method="findDeptMethod"
                  :loading="loading"
                  @change="findInv"
                >
                  <el-option
                    v-for="item in fromDeptOptions"
                    :key="item.code"
                    :label="item.name"
                    :value="item.id">
                    <span style="float: left">{{ item.code }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{
                        item.name
                      }}</span>
                  </el-option>
                </el-select>

              </el-form-item>
            </el-col>
            <el-col :span="11" type="flex">
              <el-form-item label="状态" prop="userFlag">
                <el-radio-group v-model="formData.userFlag" :disabled="formData.id == 1">
                  <el-radio :label="1">正常</el-radio>
                  <el-radio :label="0">禁用</el-radio>

                </el-radio-group>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="11" type="flex">
                <el-form-item label="所属仓库" prop="locInvCode">
                  <el-select
                    v-model="formData.locInvCode"
                    filterable
                    remote
                    clearable="true"
                    style="width: 90%"
                    size="small"
                    reserve-keyword
                    placeholder="请选择"
                    :loading="loading"
                    @change="change"
                  >
                    <el-option
                      v-for="item in fromWarehouseOptions"
                      :key="item.code"
                      :label="item.name"
                      :value="item.code">
                      <span style="float: left">{{ item.code }}</span>
                      <span style="float: right; color: #8492a6; font-size: 13px">{{
                          item.name
                        }}</span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>-->

          </el-row>
          <el-row :gutter="20" type="flex">
            <el-col :span="11" type="flex">
              <el-form-item label="角色" prop="roles">
                <el-checkbox-group v-model="formData.roles" :disabled="formData.id == 1">
                  <el-checkbox
                    v-for="item in roles"
                    :key="item.roleId"
                    :label="item.roleId"
                  >{{ item.roleName }}
                  </el-checkbox
                  >
                </el-checkbox-group>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row type="flex">
            <el-col :span="23" type="flex">
              <el-form-item prop="comments">
                <label slot="label">备&emsp;&emsp;注</label>
                <el-input v-model="formData.comments" size="small" style="width: 90%" type="textarea"
                          row="3"></el-input>
              </el-form-item>
            </el-col>
          </el-row>


        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button
            type="primary"
            size="small"
            @click.native="formSubmit()"
            :loading="formSubmitLoading"
          >提交
          </el-button
          >
          <el-button @click.native="hideForm" size="small">取消</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import {
  authAdminList,
  authAdminSave,
  authAdminDelete,
} from "../../../api/auth/authAdmin";

import store from "../../../store/index";
import {findConfig} from "@/api/sync/spsSyncStatus";
import {isBlank} from "@/utils/strUtil";
import {listRole} from "@/api/system/role";
import {selectSysParamByKey} from "@/api/system/systemParamConfig";
import {filterList, selectInvById, getDeptById} from '@/api/system/invWarehouse'

const formJson = {
  id: "",
  passWord: "",
  userName: "",
  checkPassword: "",
  employeeName: "",
  userFlag: 1,
  comments: '',
  dept: null,
  roles: [],
  depts: [],
};
export default {
  data() {
    let validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        callback();
      }
    };
    let validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.formData.passWord) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      showSearch: true,
      roles: [],
      query: {
        userName: "",
        userFlag: "1",
        deptName: "",
        page: 1,
        limit: 10,
        roleId: "",
        customerId: store.getters.customerId,
      },
      list: [],
      total: 0,
      loading: true,
      index: null,
      enableDept: false,
      formName: null,
      formMap: {
        add: "用户管理-新增",
        edit: "用户管理-编辑"
      },
      formLoading: false,
      formVisible: false,
      formData: formJson,
      selectDeptList: [],
      fromDeptOptions: [],
      fromWarehouseOptions: [],
      configParms: {},
      formRules: {},
      addRules: {
        userName: [
          {required: true, message: "请输入用户账号", trigger: "blur"}
        ],
        passWord: [
          {required: true, message: "请输入密码", trigger: "blur"},
          {validator: validatePass, trigger: "blur"}
        ],
        checkPassword: [
          {
            required: true,
            message: "请再次输入密码",
            trigger: "blur"
          },
          {validator: validatePass2, trigger: "blur"}
        ],
        userFlag: [
          {required: true, message: "请选择状态", trigger: "change"}
        ],
        depts: [
          {required: true, message: "请选择所属部门", trigger: "change"}
        ],
        roles: [
          {required: true, message: "请选择用户角色"}
        ],
        employeeName: [
          {required: true, message: "请输入用户名称", trigger: "blur"}
        ]
      },
      editRules: {
        userName: [
          {required: true, message: "请输入用户账号", trigger: "blur"}
        ],
        userFlag: [
          {required: true, message: "请选择状态", trigger: "change"}
        ],
        passWord: [
          {required: true, message: "请输入密码", trigger: "blur"}
        ]
      },
      deleteLoading: false,
      formSubmitLoading: false,
    };
  },
  methods: {
    getDeptList() {

    },
    hideSearch() {
      this.showSearch = !this.showSearch;
    },
    onReset() {
      this.$router.push({
        path: ""
      });
      this.query = {
        userName: "",
        userFlag: "1",
        deptName: null,
        page: 1,
        limit: 10,
        roleId: "",
        customerId: store.getters.customerId,
      };
      this.getList();
    },
    onSubmit() {
      this.$router.push({
        path: "",
        query: this.query
      });
      this.query.page = 1;
      this.getList();
    },
    change() {
      this.$forceUpdate();
    },
    findInv(val) {
      // 获取仓库列表
      selectInvById(val)
        .then((res) => {
          if (res.code == 20000) {
            this.fromWarehouseOptions = res.data || [];
          }
        })

    },
    handleCurrentChange(val) {
      this.query.page = val;
      this.getList();
    },
    getList() {
      this.loading = true;
      this.query.key = 'key';
      authAdminList(this.query)
        .then(response => {
          this.loading = false;
          this.list = response.data.list || [];
          this.total = response.data.total || 0;
        })
        .catch(() => {
          this.loading = false;
          this.list = [];
          this.total = 0;
          this.roles = [];
        });
    },
    getRoleList() {
      let query = {
        page: 1,
        limit: 1000,
        status: 0,
        isCustomer: 0,

      }
      listRole(query)
        .then(response => {
          this.roles = response.data.list || [];
        })
        .catch(() => {
          this.roles = [];
        });
    },
    // 刷新表单
    resetForm() {
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        this.$refs["dataForm"].clearValidate();
      })
    },
    // 隐藏表单
    hideForm() {
      // 更改值
      this.formVisible = !this.formVisible;
      // 清空表单
      this.$refs["dataForm"].resetFields(); //清除表单数据
      return true;
    },
    // 显示表单
    handleForm(index, row) {
      this.formVisible = true;
      this.resetForm();
      this.formData = JSON.parse(JSON.stringify(formJson));
      if (row !== null) {
        this.formData = {
          id: row.id,
          passWord: row.passWord,
          userName: row.userName,
          checkPassword: "",
          employeeName: row.employeeName,
          userFlag: row.userFlag,
          comments: row.comments,
          roles: row.roles,
          depts: row.depts,
          dept: row.dept,
          locInvCode: row.locInvCode
        };
      }
      this.formName = "add";
      this.formRules = this.addRules;
      if (index !== null) {
        this.index = index;
        this.formName = "edit";
        this.formRules = this.editRules;
      }
      if (row.depts != null && row.depts.length > 0) {
        this.findInv(row.depts);
      }


    },

    formSubmit() {
      if (isBlank(this.formData.userName)) {
        this.$message.error("用户账号不能为空");
        return;
      } else if (isBlank(this.formData.passWord)) {
        this.$message.error("密码不能为空")
        return;
      } else if (isBlank(this.formData.employeeName)) {
        this.$message.error("用户名称不能为空");
        return;
      } else if (this.formData.roles.length === 0) {
        this.$message.error("未指定角色！")
        return;
      }
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.formSubmitLoading = true;
          let data = Object.assign({}, this.formData);
          authAdminSave(data, this.formName).then(response => {
            this.formSubmitLoading = false;
            if (response.code !== 20000) {
              this.$message.error(response.message);
              return false;
            }
            this.$message.success("操作成功");
            this.formVisible = false;
            if (this.formName === "add") {
              // 向头部添加数据
              if (response.data && response.data.id) {
                data.id = response.data.id;
                this.list.unshift(data);
              }
            } else {
              this.list.splice(this.index, 1, data);
            }
            // 刷新表单
            this.resetForm();
            this.getList();
          });
        }
      });
    },
    // 删除
    handleDel(index, row) {
      if (row.id) {
        this.$confirm("确认删除该用户信息?", "提示", {
          type: "warning"
        })
          .then(() => {
            let para = {id: row.id};
            this.deleteLoading = true;
            authAdminDelete(para)
              .then(response => {
                this.deleteLoading = false;
                if (response.code !== 20000) {
                  this.$message.error(response.message);
                  return false;
                }
                this.$message.success("操作成功");
                // 刷新数据
                this.list.splice(index, 1);
                this.getList();
              })
              .catch(() => {
                this.deleteLoading = false;
              });
          })
          .catch(() => {
          });
      }
    },
    getSyncConfig() {
      findConfig()
        .then((response) => {
          if (response.code == 20000) {
            this.configParms = response.data;
          }
        })
        .catch(() => {
        });
    },

    findDeptMethod() {
      let query = {
        status: 1,
      };
      filterList(query)
        .then((response) => {
          var deptList = [];
          this.loading = false;
          for (var i = 0; i < response.data.list.length; i++) {
            if (response.data.list[i].id != 1) {
              deptList.push(response.data.list[i]);
            }
          }
          this.fromDeptOptions = deptList || [];
        })
        .catch(() => {
          this.loading = false;
          this.fromDeptOptions = [];
        });
    },

    deptChange(row) {
      this.formData.corpId = row.code;
      this.formData.corpName = row.name;
    },

  },
  filters: {
    statusFilterType(status) {
      const statusMap = {
        0: "gray",
        1: "success",
        2: "danger"
      };
      return statusMap[status];
    },
    statusFilterName(status) {
      const statusMap = {
        0: "禁用",
        1: "正常",
        2: "未验证"
      };
      return statusMap[status];
    }
  },
  mounted() {
  },
  created() {
    // 将参数拷贝进查询对象
    let query = this.$route.query;
    this.query = Object.assign(this.query, query);
    this.query.limit = parseInt(this.query.limit);
    // 加载表格数据
    this.getList();
    // 加载角色列表
    this.getRoleList();
    this.getSyncConfig();
    this.findDeptMethod();

    //查询是否启用多级仓库，判断是否启用部门
    selectSysParamByKey({paramKey: "muti_inv_mode"}).then((res) => {
      if (res.code === 20000) {
        if (res.data.paramValue === "0") {
          this.enableDept = true;
        }
      }
    })
  }
};
</script>

<style scoped>

.item .el-form-item__label {
  margin-left: 14px;
  width: 300px;
}

</style>

