<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"
      >
        <template slot="index" slot-scope="{ index }">
          {{ index + 1 }}
        </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"
      >
        <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">
          <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 CustomModal from '@/components/CustomModal'
import { queryall, addUser, editUser, changePassword } from '@/api/api'
import { cloneDeep } from 'lodash'
import FormMixin from '@/mixins/FormMixin'

export default {
  name: 'UserList',
  mixins: [JeecgListMixin, FormMixin],
  components: {
    CustomModal
  },
  data() {
    return {
      queryParam: {
        role: undefined
      },
      columns: [
        {
          title: 'NO',
          align: 'center',
          width: 100,
          scopedSlots: {
            customRender: 'index'
          }
        },
        {
          title: 'USER',
          align: 'center',
          dataIndex: 'username',
          width: 100
        },
        {
          title: 'NAME',
          align: 'center',
          width: 100,
          dataIndex: 'realname'
        },
        {
          title: 'ROLE',
          align: 'center',
          width: 100,
          dataIndex: 'roleCode'
        },
        {
          title: 'PHONE',
          align: 'center',
          width: 100,
          dataIndex: 'phone'
        }
      ],
      url: {
        list: '/sys/user/list',
        delete: '/sys/user/delete'
      },
      roleOptions: [],
      visible: false,
      isAdd: false,
      accountModel: {},
      rules: {
        username: [{ required: true, message: 'Please Enter User' }]
      }
    }
  },
  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)
      } else {
        this.$message.warn('Please select an item you want to edit')
      }
    },

    // 提交
    async onSubmit() {
      await this.$refs.form.validate()
      const request = this.isAdd ? addUser : editUser
      const { success, message } = await request(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 item?',
          okText: 'OK',
          cancelText: 'Cancel',
          onOk: () => {
            this.handleDelete(this.selectedRowKeys[0])
          }
        })
      } else {
        this.$message.warn('Please select an item you want 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 you want to reset password')
      }
    }
  },
  computed: {
    formItems() {
      return [
        {
          type: 'a-input',
          label: 'User',
          name: 'username',
          span: 4
        },
        {
          type: 'a-input',
          label: 'Name',
          name: 'realname',
          span: 4
        },
        {
          type: 'custom-select',
          label: 'Role',
          name: 'role',
          span: 4,
          props: {
            options: this.roleOptions
          }
        }
      ]
    }
  }
}
</script>
<style scoped lang="less">
@import '~@assets/less/common.less';
.btn-group {
  img {
    margin-right: 12px;
    height: 18px;
  }
}
</style>
