<template>
  <div>
    <el-card class="no-bottom">
      <el-form
        ref="searchForm"
        :model="searchForm"
        label-width="80px"
        inline
      >
        <el-form-item
          label="账号:"
          prop="account"
        >
          <el-input v-model="searchForm.account" />
        </el-form-item>
        <el-form-item
          label="所属租户:"
          prop="tenantId"
        >
          <el-select v-model="searchForm.tenantId" placeholder="请选择">
            <el-option label="全部" :value="null" />
            <el-option
              v-for="(tenant, index) in tenantList"
              :key="index"
              :value="tenant.id"
              :label="tenant.tenantName"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="getTenantAccountList(1)">查询</el-button>
          <el-button icon="el-icon-refresh" @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="margin-top-20">
      <div class="buttons-group" style="margin-bottom: 20px">
        <el-button v-permission="'MenuMgr_add'" type="primary" icon="el-icon-plus" @click="addRow">增加账号</el-button>
      </div>

      <el-table
        :data="tableData"
        border
      >
        <el-table-column
          type="index"
          label="序号"
          width="50px"
          align="center"
        />
        <el-table-column
          prop="account"
          label="账号"
        />
        <el-table-column
          prop="realName"
          label="联系人姓名"
        />
        <el-table-column
          prop="mobile"
          label="联系人电话"
        />
        <el-table-column
          prop="tenantName"
          label="所属租户"
        />
        <el-table-column
          label="操作"
          width="140px"
          align="center"
        >
          <template slot-scope="props">
            <el-button
              v-permission="'SysMgr_update'"
              type="text"
              :disabled="!props.row.canEdited"
              @click="editItem(props.row)"
            >编辑
            </el-button>
            <el-popconfirm
              title="确定要删除此条记录吗？"
              @onConfirm="deleteItem(props.row.id)"
            >
              <el-button
                slot="reference"
                type="text"
                :disabled="!props.row.canEdited"
              >删除
              </el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        style="margin-top: 20px;text-align: right"
        :current-page="pageForm.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageForm.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageForm.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />

    </el-card>

    <el-dialog
      :title="add ? '增加账户' : '编辑账户'"
      :visible.sync="dialogVisible"
      width="700px"
      :before-close="beforeClose"
    >
      <el-form
        ref="addForm"
        :model="addForm"
        label-width="100px"
        :rules="addFormRules"
      >
        <el-form-item
          label="账号:"
          prop="account"
        >
          <el-input v-model="addForm.account" />
        </el-form-item>
        <el-form-item
          label="联系人姓名:"
          prop="realName"
        >
          <el-input v-model="addForm.realName" />
        </el-form-item>
        <el-form-item
          label="联系人电话:"
          prop="mobile"
        >
          <el-input v-model="addForm.mobile" />
        </el-form-item>
        <el-form-item
          label="所属租户:"
          prop="tenantId"
        >
          <el-select
            v-model="addForm.tenantId"
            :disabled="!add"
          >
            <el-option
              v-for="(tenant, index) in tenantList"
              :key="index"
              :value="tenant.id"
              :label="tenant.tenantName"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="add" label="初始密码:" prop="password">
          <el-input v-model="addForm.password" />
        </el-form-item>
        <el-form-item v-if="!add" label="新密码:">
          <el-input v-model="addForm.password" />
          <div>如果不更改密码，此处请留空</div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="saveSystem">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getTenantAccountList, addTenantAccount, updateTenantAccount, deleteTenantAccount } from '@/api/tenant-management/tenant-account'
import { getAllTenantList } from '@/api/tenant-management/tenant-management'
import { validUserName } from '@/utils/validate'
import md5 from 'md5'

export default {
  name: 'Index',
  data() {
    const validatePass = (rule, value, callback) => {
      if (!validUserName(value)) {
        callback(new Error('仅可输入字母和数字'))
      } else {
        callback()
      }
    }
    return {
      searchForm: {
        account: null,
        tenantId: null
      },
      add: true,
      dialogVisible: false,
      tableData: [],
      addForm: {
        account: null,
        realName: null,
        mobile: null,
        tenantId: null,
        password: null
      },
      addFormRules: {
        account: [
          { required: true, message: '请输入账号名称', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' },
          { validator: validatePass, trigger: 'change' }
        ],
        realName: [
          { required: true, message: '请输入联系人姓名', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
        ],
        tenantId: [
          { required: true, message: '请选择所属租户', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      },
      currentId: null,
      pageForm: {
        pageSize: 10,
        pageNum: 1,
        total: 0
      },
      tenantList: []
    }
  },
  created() {
    this.getTenantAccountList(1)
    this.getAllTenantList()
  },
  methods: {
    getAllTenantList() {
      getAllTenantList({})
        .then(res => {
          const { data } = res
          this.tenantList = data
        })
        .catch(err => {
          this.$message.error('操作失败')
          console.error(err.message)
        })
    },
    getTenantAccountList(pageNum) {
      const params = {
        current: pageNum,
        size: this.pageForm.pageSize,
        ...this.searchForm
      }
      getTenantAccountList(params)
        .then(res => {
          const { data } = res
          this.tableData = data.records
          this.pageForm.total = data.total
        })
        .catch(err => {
          this.$message.error('操作失败')
          console.error(err.message)
        })
    },
    resetFields() {
      this.addForm = {
        account: null,
        realName: null,
        mobile: null,
        tenantId: null,
        password: null
      }
      this.$refs.addForm.clearValidate()
    },
    beforeClose(done) {
      this.resetFields()
      this.$nextTick()
        .then(_ => {
          done()
        })
    },
    closeDialog() {
      this.resetFields()
      this.$nextTick()
        .then(_ => {
          this.dialogVisible = false
        })
    },
    resetForm() {
      this.$refs.searchForm.resetFields()
    },
    addRow() {
      this.add = true
      this.dialogVisible = true
    },
    editItem(row) {
      const { id, account, realName, mobile, tenantId } = row
      this.currentId = id
      this.addForm = {
        account,
        realName,
        mobile,
        tenantId,
        password: null
      }
      this.add = false
      this.dialogVisible = true
    },
    deleteItem(id) {
      deleteTenantAccount({ id: id })
        .then(res => {
          this.$message.success('操作成功')
          this.getTenantAccountList(1)
        })
        .catch(err => {
          this.$message.error('操作失败')
          console.error(err.message)
        })
    },
    saveSystem() {
      this.$refs.addForm.validate()
        .then(_ => {
          const params = this.addForm
          if (params.password !== null) {
            params.password = md5(params.password)
          }
          if (this.add) {
            addTenantAccount(params)
              .then(res => {
                this.$message.success('操作成功')
                this.getTenantAccountList(this.pageForm.pageNum)
              })
              .catch(err => {
                this.$message.error('操作失败')
                console.error(err.message)
              })
          } else {
            params.id = this.currentId
            updateTenantAccount(params)
              .then(res => {
                this.$message.success('操作成功')
                this.getTenantAccountList(this.pageForm.pageNum)
              })
              .catch(err => {
                this.$message.error('操作失败')
                console.error(err.message)
              })
          }
          this.dialogVisible = false
        })
        .catch(_ => {})
    },
    handleSizeChange(val) {
      this.pageForm.pageSize = val
      this.getTenantAccountList(this.pageForm.pageNum)
    },
    handleCurrentChange(val) {
      this.pageForm.pageNum = val
      this.getTenantAccountList(val)
    }
  }
}
</script>

<style scoped>

</style>
