<template>
  <a-card :bordered="false">
    <!-- 搜索栏 -->
    <search-form :items="formItems" v-model="queryParam" @search="searchQuery">
      <a-space style="float: right" class="btn-group" slot="additional">
        <a-button @click="handleAdd" type="primary">
          <img src="@/assets/images/global/add.png" alt="" />
          Add
        </a-button>
        <a-button @click="handleEdit" type="primary">
          <img src="@/assets/images/global/edit.png" alt="" />
          Edit
        </a-button>
        <a-button @click="onDel" type="primary">
          <img src="@/assets/images/global/delete.png" alt="" />
          Delete
        </a-button>
        <a-button @click="handleReset" type="primary">
          <img src="@/assets/images/global/reset-pwd.png" alt="" />
          Reset pwd
        </a-button>
      </a-space>
    </search-form>
    <!-- 搜索栏结束 -->
    <!-- 列表 -->
    <div>
      <custom-table
        size="middle"
        rowKey="id"
        :columns="columns"
        :list="dataSource"
        :pagination="ipagination"
        :loading="loading"
        @change="handleTableChange"
        :selectedRowKeys.sync="selectedRowKeys"
        :scroll="{ y: 'calc(100vh - 370px)' }"
      >
        <template slot="index" slot-scope="{ index }">
          {{ index + 1 }}
        </template>
        <template slot="roles" slot-scope="{ text }">
          <span v-for="role of text" :key="role.id">
            {{ role.roleName }}
          </span>
        </template>
      </custom-table>
    </div>
    <!-- 列表结束 -->
    <!-- 新增/编辑 账号 -->
    <custom-modal :title="isAdd ? 'Add' : 'Edit'" v-model="visible" :width="475" :okHandler="onSubmit">
      <a-form-model
        ref="form"
        layout="horizontal"
        :model="accountModel"
        :rules="rules"
        :labelCol="{ style: { width: '80px' } }"
        :wrapperCol="{ style: { width: '300px' } }"
        autocomplete="off"
        :colon="false"
      >
        <a-form-model-item label="User" prop="username">
          <a-input v-model="accountModel.username"></a-input>
        </a-form-model-item>
        <a-form-model-item label="Name">
          <a-input type="text" v-model="accountModel.realname"></a-input>
        </a-form-model-item>
        <a-form-model-item label="Role" prop="selectedRoles">
          <custom-select :options="roleOptions" mode="multiple" v-model="accountModel.selectedRoles"></custom-select>
        </a-form-model-item>
        <a-form-model-item label="E-Mail">
          <a-input v-model="accountModel.email"></a-input>
        </a-form-model-item>
        <a-form-model-item label="Phone">
          <a-input v-model="accountModel.phone"></a-input>
        </a-form-model-item>
      </a-form-model>
    </custom-modal>
    <!-- 新增/编辑 账号结束 -->
  </a-card>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { queryall, addUser, editUser, changePassword } from '@/api/api'
import { cloneDeep } from 'lodash'
import FormMixin from '@/mixins/FormMixin'

export default {
  name: 'UserList',
  mixins: [JeecgListMixin, FormMixin],
  data() {
    return {
      queryParam: {
        role: undefined
      },
      columns: [
        {
          title: 'NO',
          align: 'left',
          width: 170,
          scopedSlots: {
            customRender: 'index'
          },
          customHeaderCell: () => {
            return {
              style: {
                'padding-left': '60px !important'
              }
            }
          },
          customCell: () => {
            return {
              style: {
                'padding-left': '60px !important'
              }
            }
          }
        },
        {
          title: 'USER',
          align: 'left',
          dataIndex: 'username',
          width: 170
        },
        {
          title: 'NAME',
          align: 'left',
          width: 240,
          dataIndex: 'realname'
        },
        {
          title: 'ROLE',
          align: 'left',
          width: 190,
          dataIndex: 'roles',
          scopedSlots: {
            customRender: 'roles'
          }
        },
        {
          title: 'PHONE',
          align: 'left',
          width: 95,
          dataIndex: 'phone'
        }
      ],
      url: {
        list: '/sys/user/list',
        delete: '/sys/user/deleteById'
      },
      roleOptions: [],
      visible: false,
      isAdd: false,
      accountModel: {},
      rules: {
        username: [{ required: true, message: 'Please Enter User' }],
        selectedRoles: [{ required: true, message: 'Please Select Role', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getRoles()
  },
  methods: {
    customRow(record) {
      return {
        class: this.selectedRowKeys.includes(record.id) ? 'ant-table-row-selected' : '',
        on: {
          click: () => {
            if (this.selectedRowKeys.includes(record.id)) {
              this.selectedRowKeys = []
            } else {
              this.selectedRowKeys = [record.id]
            }
          }
        }
      }
    },
    async getRoles() {
      try {
        const res = await queryall()
        if (res.success) {
          this.roleOptions = res.result.map(item => {
            return {
              label: item.roleName,
              value: item.id
            }
          })
        }
      } catch (error) {
        console.error(error)
      }
    },

    handleAdd() {
      this.visible = true
      this.isAdd = true
      this.accountModel = {}
    },
    handleEdit() {
      if (this.selectedRowKeys && this.selectedRowKeys.length) {
        this.visible = true
        this.isAdd = false
        const find = this.dataSource.find(item => item.id === this.selectedRowKeys[0])
        this.accountModel = cloneDeep(find)
        this.accountModel.selectedRoles = this.accountModel.roles.map(role => role.id)
      } else {
        this.$message.warn('Please Select An Item To Edit')
      }
    },

    // 提交
    async onSubmit() {
      await this.$refs.form.validate()
      const request = this.isAdd ? addUser : editUser
      const selectedroles = this.accountModel.selectedRoles.join(',')
      const { success, message } = await request(Object.assign({ selectedroles }, this.accountModel))
      if (success) {
        this.$message.success(`${this.isAdd ? 'Add' : 'Edit'} Success`)
        this.loadData()
      } else {
        this.$message.error(`${this.isAdd ? 'Add' : 'Edit'} Fail`)
        throw new Error(message)
      }
    },
    onDel() {
      if (this.selectedRowKeys && this.selectedRowKeys.length) {
        this.$confirm({
          title: 'Do You Want To Delete This Account?',
          content: 'Will Delete All Data Related To This Account, Are You Sure?',
          okText: 'OK',
          cancelText: 'Cancel',
          onOk: () => {
            this.handleDelete(this.selectedRowKeys[0])
          }
        })
      } else {
        this.$message.warn('Please Select An Item To Delete')
      }
    },
    handleReset() {
      if (this.selectedRowKeys && this.selectedRowKeys.length) {
        const find = this.dataSource.find(item => item.id === this.selectedRowKeys[0])
        this.$confirm({
          title: 'Do You Want To Reset Password?',
          okText: 'OK',
          cancelText: 'Cancel',
          onOk: async () => {
            const { success, message } = await changePassword({
              username: find.username
            })
            if (success) {
              this.$message.success('Reset Success')
            } else {
              this.$message.error('Reset Fail')
            }
          }
        })
      } else {
        this.$message.warn('Please Select An Item To Reset')
      }
    }
  },
  computed: {
    formItems() {
      return [
        {
          type: 'a-input',
          label: 'User',
          name: 'username',
          props: {
            style: {
              width: '160px'
            }
          },
          style: {
            width: 'auto'
          }
        },
        {
          type: 'a-input',
          label: 'Name',
          name: 'realname',
          props: {
            style: {
              width: '160px'
            }
          },
          style: {
            width: 'auto'
          }
        },
        {
          type: 'custom-select',
          label: 'Role',
          name: 'roleId',
          props: {
            options: this.roleOptions,
            style: {
              width: '160px'
            }
          },
          style: {
            width: 'auto'
          }
        }
      ]
    }
  }
}
</script>
<style scoped lang="less">
@import '~@assets/less/common.less';
.btn-group {
  img {
    margin-right: 12px;
    height: 18px;
  }
}
</style>
