<template>
  <div class='main-content'>
    <baseTable
      ref='userTable'
      :tableHeader='tableHeader'
      :tableData='tableData'
      :tableOperate='tableOperate'
      :searchParams='searchParams'
      @searchFn='searchFn'
      @resetFn='resetFn'
      :addBtn='false'
      :more-operation='false'
    >
      <template slot='search'>
        <el-form-item label='姓名'>
          <el-input v-model.trim='searchParams.fullName' placeholder='请输入姓名' />
        </el-form-item>
        <el-form-item label='手机号'>
          <el-input v-model.trim='searchParams.mobile' placeholder='请输入手机号' />
        </el-form-item>
        <el-form-item label='租户'>
          <el-input v-model.trim='searchParams.tenantName' placeholder='请输租户名称' />
        </el-form-item>
      </template>
    </baseTable>
    <el-dialog width='700px' :title='formDialog.title' :visible.sync='formDialog.visible' :close-on-click-modal='false'>
      <el-form
        ref='userForm'
        size='small'
        label-width='120px'
        :model='formDialog.formData'
        :rules='formDialog.formRules'
      >
        <el-form-item label='用户名' prop='username' v-if='formDialog.isAdd'>
          <el-input v-model.trim='formDialog.formData.username' />
        </el-form-item>
        <el-form-item label='姓名' prop='fullName'>
          <el-input v-model.trim='formDialog.formData.fullName' />
        </el-form-item>
        <el-form-item label='手机号码' prop='mobile'>
          <el-input v-model.trim='formDialog.formData.mobile' />
        </el-form-item>
        <el-form-item label='电子邮箱' prop='email'>
          <el-input v-model.trim='formDialog.formData.email' />
        </el-form-item>
        <el-form-item label='角色' prop='roleIds' v-if='formDialog.isAdd'>
          <el-select v-model.trim='formDialog.formData.roleIds' multiple style='width: 100%;'>
            <el-option v-for='item in roles' :key='item.id' :label='item.roleCnName' :value='item.id'></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label='性别' prop='sex'>
          <el-radio-group v-model='formDialog.formData.sex'>
            <el-radio-button v-for='item in dictSex' :key='item.value' :label='item.value'>
              {{ item.label }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot='footer' class='dialog-footer'>
        <el-button type='primary' :loading='formDialog.loading' @click='submitFn'>确定</el-button>
        <el-button @click='cancelFn'>取消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      width='600px'
      :title='accountDialog.title'
      :visible.sync='accountDialog.visible'
      :close-on-click-modal='false'
    >
      <el-form ref='accountForm' size='small' label-width='120px' :model='accountDialog.formData'>
        <el-form-item label='用户名'>{{ accountDialog.formData.username }}</el-form-item>
        <el-form-item label='手机号'>{{ accountDialog.formData.mobile }}</el-form-item>
        <el-form-item label='密码过期时间'>{{ accountDialog.formData.pwdExpired | globalFormatDate('YYYY-MM-DD') }}
        </el-form-item>
        <el-form-item label='锁定账号'>
          <el-switch
            v-model='accountDialog.formData.locked'
            active-color='#13ce66'
            active-value='1'
            inactive-value='0'
            @change='changeLockedFn'
          />
        </el-form-item>
        <el-form-item label='角色'>
          <el-select v-model.trim='accountDialog.formData.roleIds' multiple @change='changeRole'>
            <el-option v-for='item in roles' :key='item.id' :label='item.roleCnName' :value='item.id'></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label='修改密码'>
          <el-col :span='12'>
            <el-input v-model.trim='accountDialog.formData.password' type='password' />
          </el-col>
          <el-col :span='11' style='margin-left: 10px;'>
            <el-button type='primary' size='mini' @click='resetPwdFn'>修改密码</el-button>
          </el-col>
        </el-form-item>
      </el-form>
      <span slot='footer' class='dialog-footer'>
        <el-button @click='accountDialog.visible = false'>关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { formatDict } from '@utils/global';
import { isMobile, isUsername } from '@utils/validate';
import {
  addRole,
  changeLock,
  createUser,
  delRole,
  fetchUserById,
  queryUserAccount,
  queryUserPage,
  removeUser,
  resetPwd,
  updateUserDetail
} from '@api/upms/api-user-tenant';

export default {
  name: 'UserTenant',
  computed: {
    dictSex() {
      return this.$store.getters.dict.dictSex;
    }
  },
  data() {
    let validateUsername = (rule, value, callback) => {
      if (!isUsername(value)) {
        return callback(new Error('请输入正确的用户名，英文字母开头, 长度要求6~20位'));
      } else {
        return callback();
      }
    };
    let validateMobile = (rule, value, callback) => {
      if (!isMobile(value)) {
        return callback(new Error('请输入正确的手机号码'));
      } else {
        return callback();
      }
    };
    return {
      userId: '',
      roleIds: [],
      tableHeader: [
        {
          label: '租户',
          align: 'center',
          minWidth: 100,
          prop: 'tenantName'
        },
        {
          label: '姓名',
          align: 'center',
          minWidth: 100,
          prop: 'fullName'
        },
        {
          label: '角色',
          align: 'center',
          minWidth: 100,
          prop: 'roles'
        },
        {
          label: '用户名',
          align: 'center',
          minWidth: 100,
          prop: 'username'
        },
        {
          label: '性别',
          width: 80,
          align: 'center',
          type: 'render',
          render: (h, params) => {
            return h('span', formatDict(this.dictSex, params.row.sex));
          }
        },
        {
          label: '手机号',
          prop: 'mobile',
          align: 'center',
          minWidth: 120
        }
      ],
      tableData: [],
      tableOperate: [
        {
          label: '新增',
          type: 'success',
          icon: 'el-icon-plus',
          func: (row) => {
            this.addFn(row);
          }
        },
        {
          label: '编辑',
          type: 'primary',
          icon: 'el-icon-edit',
          func: (row) => {
            this.editFn(row);
          }
        },
        {
          icon: 'el-icon-s-check',
          type: 'info',
          label: '账号相关',
          func: (row) => {
            this.accountFn(row);
          }
        },
        {
          label: '删除',
          type: 'danger',
          icon: 'el-icon-delete',
          func: (row) => {
            this.delFn(row);
          }
        }
      ],
      searchParams: Object.assign({}, this.$search),
      roles: [],
      formDialog: {
        title: '',
        visible: false,
        loading: false,
        isAdd: false,
        formData: {},
        defaultData: {
          sex: '3',
          attachDataList: []
        },
        formRules: {
          username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { required: true, validator: validateUsername, trigger: 'blur' }
          ],
          fullName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
          mobile: [
            { required: true, message: '请输入手机号码', trigger: 'blur' },
            { len: 11, message: '长度11个字符', trigger: 'blur' },
            { required: true, validator: validateMobile, trigger: 'blur' }
          ],
          email: [
            {
              required: false,
              type: 'email',
              message: '请输入正确的电子邮箱',
              trigger: 'blur'
            }
          ],
          roleIds: [{ required: true, message: '请选择对应的角色', trigger: 'change' }]
        }
      },
      accountDialog: {
        title: '账号相关',
        visible: false,
        formData: {}
      },
      uploadParams: {}
    };
  },
  methods: {
    searchFn(isReset = false) {
      let vm = this;
      if (isReset) {
        vm.searchParams = Object.assign(vm.searchParams, vm.$search);
      }
      queryUserPage(vm.searchParams).then(
        (res) => {
          vm.tableData = res.data.records;
          vm.searchParams.total = res.data.total;
        },
        (error) => {
          vm.$notify.error({
            title: error.data.msg,
            message: error.data.data
          });
        }
      );
    },
    resetFn() {
      let vm = this;
      vm.searchParams = Object.assign({}, this.$search);
      vm.searchFn();
    },
    addFn(row) {
      let vm = this;
      queryUserAccount({ id: row.id }).then(
        (res) => {
          vm.roles = res.data.roles;
        },
        (error) => {
          vm.$notify.error({
            title: error.data.msg,
            message: error.data.data
          });
        }
      );
      vm.formDialog.title = '新增';
      vm.formDialog.visible = true;
      vm.formDialog.loading = false;
      vm.formDialog.isAdd = true;
      vm.formDialog.formData = Object.assign({ tenantId: row.tenantId }, vm.formDialog.defaultData);
    },
    editFn(row) {
      let vm = this;
      vm.formDialog.title = '编辑';
      vm.formDialog.loading = false;
      vm.formDialog.isAdd = false;
      let params = {
        id: row.id
      };
      fetchUserById(params).then(
        (res) => {
          vm.formDialog.formData = Object.assign({}, res.data);
          vm.formDialog.visible = true;
        },
        (error) => {
          vm.$notify.error({
            title: error.data.msg,
            message: error.data.data
          });
        }
      );
    },
    cancelFn() {
      let vm = this;
      vm.formDialog.visible = false;
      vm.formDialog.loading = false;
      vm.formDialog.isAdd = false;
      vm.formDialog.formData = Object.assign({}, vm.formDialog.defaultData);
      vm.$refs.userForm.resetFields();
    },
    submitFn() {
      let vm = this;
      vm.formDialog.loading = true;
      vm.$refs.userForm.validate((valid) => {
        if (!valid) {
          vm.formDialog.loading = false;
          return;
        }
        if (vm.formDialog.formData.id) {
          let formData = vm.formDialog.formData;
          updateUserDetail(formData).then(
            (res) => {
              vm.$message.success('修改成功');
              vm.formDialog.visible = false;
              vm.formDialog.loading = false;
              vm.searchFn(true);
            },
            (error) => {
              vm.$notify.error({
                title: error.data.msg,
                message: error.data.data
              });
              vm.formDialog.loading = false;
            }
          );
        } else {
          let formData = vm.formDialog.formData;
          createUser(formData).then(
            (res) => {
              vm.$message.success('新增成功');
              vm.formDialog.visible = false;
              vm.formDialog.loading = false;
              vm.searchFn(true);
            },
            (error) => {
              vm.$notify.error({
                title: error.data.msg,
                message: error.data.data
              });
              vm.formDialog.loading = false;
            }
          );
        }
      });
    },
    delFn(row) {
      let vm = this;
      vm.$confirm('此操作将删除该记录, 是否继续?', '提示', {
        type: 'warning'
      }).then(() => {
        let ids = [row.id];
        removeUser({ ids: ids }).then(
          (res) => {
            vm.$message.success('删除成功');
            vm.searchFn(true);
          },
          (error) => {
            vm.$notify.error({
              title: error.data.msg,
              message: error.data.data
            });
          }
        );
      });
    },
    accountFn(row) {
      let vm = this;
      vm.userId = row.id;
      let params = {
        id: row.id
      };
      queryUserAccount(params).then(
        (res) => {
          vm.accountDialog.formData = Object.assign({}, res.data);
          vm.roleIds = res.data.roleIds;
          vm.roles = res.data.roles;
          vm.accountDialog.visible = true;
        },
        (error) => {
          vm.$notify.error({
            title: error.data.msg,
            message: error.data.data
          });
        }
      );
    },
    changeLockedFn(val) {
      let vm = this;
      let params = {
        id: vm.accountDialog.formData.id,
        locked: val
      };
      changeLock(params).then(
        (res) => {
          vm.$message.success(res.msg);
        },
        (error) => {
          vm.$notify.error({
            title: error.data.msg,
            message: error.data.data
          });
        }
      );
    },
    resetPwdFn() {
      let vm = this;
      this.$confirm('此操作将修改密码, 是否继续?', '提示', {
        type: 'warning'
      }).then(() => {
        let params = {
          id: vm.accountDialog.formData.id,
          password: vm.accountDialog.formData.password
        };
        resetPwd(params).then(
          (res) => {
            vm.$message.success(res.msg);
          },
          (error) => {
            vm.$notify.error({
              title: error.data.msg,
              message: error.data.data
            });
          }
        );
      });
    },
    uploadFiles(fileList) {
      this.formDialog.formData.avatar = fileList.length > 0 ? fileList[0].id : '';
    },
    changeRole(val) {
      let vm = this;
      let params = {
        id: vm.userId
      };
      if (val.length > vm.roleIds.length) {
        params.roleIds = val.filter((o) => {
          return vm.roleIds.indexOf(o) === -1;
        });
        addRole(params).then(
          (res) => {
            vm.$message.success(res.msg);
          },
          (error) => {
            vm.$notify.error({
              title: error.data.msg,
              message: error.data.data
            });
          });
      } else {
        params.roleIds = vm.roleIds.filter((o) => {
          return val.indexOf(o) === -1;
        });
        delRole(params).then(
          (res) => {
            vm.$message.success(res.data.msg);
          },
          (error) => {
            vm.$notify.error({
              title: error.data.msg,
              message: error.data.data
            });
          }
        );
      }
      vm.roleIds = val;
    }
  },
  created() {
    this.searchFn();
  }
};
</script>

<style scoped lang='less'></style>
