<template>
  <div>
    <a-form @submit="handleSubmit" :form="form" class="cust-detail-form">
      <header-tool-bar>
        <span class="cust-title" slot="title">
          <a-icon type="hdd" />系统用户详情
        </span>
        <a-button-group slot="extra">
          <a-button type="primary" htmlType="submit">保存</a-button>
          <a-button type="primary" @click="back" ghost>返回</a-button>
        </a-button-group>
      </header-tool-bar>
      <a-card title="用户基础数据" class="cust-normal-card">
        <a-row :gutter="gutter">
          <a-col :span="span">
            <a-form-item v-bind="formItemLayout" label="用户名">
              <a-input
                v-decorator="[
                  'userName',
                  {
                    initialValue: userDate.userName,
                    rules: [{ required: true, message: '请输入用户名!' }]
                  }
                ]"
              />
            </a-form-item>
          </a-col>
          <a-col :span="span">
            <a-form-item v-bind="formItemLayout" label="真实姓名">
              <a-input
                v-decorator="[
                  'realName',
                  {
                    initialValue: userDate.realName,
                    rules: [{ required: true, message: '请输入真实姓名!' }]
                  }
                ]"
              />
            </a-form-item>
          </a-col>
          <a-col :span="span">
            <a-form-item v-bind="formItemLayout" label="联系电话">
              <a-input
                oninput="value=value.replace(/[^\d]/g,'')"
                v-decorator="[
                  'phone',
                  {
                    initialValue: userDate.phone,
                    rules: [{ required: true, message: '请输入电话!' }]
                  }
                ]"
              />
            </a-form-item>
          </a-col>
          <a-col :span="span">
            <a-form-item v-bind="formItemLayout" label="邮箱">
              <a-input
                v-decorator="[
                  'email',
                  {
                    initialValue: userDate.email,
                    rules: [{ required: false, message: '请输入电话!' }]
                  }
                ]"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :utter="gutter">
          <a-col :span="6">
            <a-form-item v-bind="formItemLayout" label="头像">
              <a-upload
                :rows="3"
                v-decorator="[
                  'avatar',
                  {
                    valuePropName: 'imageList',
                    getValueFromEvent: normFile,
                    rules: [{ required: false, message: '请上传用户头像' }]
                  }
                ]"
                style="width: 100%"
                :defaultFileList="imageList"
                :fileList="imageList"
                listType="picture-card"
                :action="getUploadImageUrl(business)"
                :headers="uploadImageHeader"
                @change="handleChangeImg"
                @preview="handlePreview"
              >
                <div v-if="imageList.length < 1">
                  <a-icon type="plus" />
                  <div class="ant-upload-text">上传图片</div>
                </div>
              </a-upload>
              <a-modal
                :visible="previewVisible"
                :footer="null"
                @cancel="handleCancel"
              >
                <img alt="example" style="width: 100%" :src="previewImage" />
              </a-modal>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              :labelCol="{ span: 4 }"
              :wrapperCol="{ span: 20 }"
              label="备注"
            >
              <a-textarea
                :rows="3"
                v-decorator="[
                  'remark',
                  {
                    initialValue: userDate.remark,
                    rules: [{ required: false, message: '' }]
                  }
                ]"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-card>
      <a-card title="用户角色" class="cust-normal-card">
        <a-table
          :columns="columns"
          :dataSource="roleList"
          rowKey="id"
          size="middle"
          :pagination="false"
          class="cust-card-table"
          :rowSelection="{
            selectedRowKeys: selectedRowKeys,
            onChange: updateSelect
          }"
          bordered
        >
        </a-table>
      </a-card>
    </a-form>
  </div>
</template>

<script>
import HeaderToolBar from '@/components/page/HeaderToolBar'
import { getDetail, save } from '@/api/system/sysUserApi'
import {
  getOneImageURL,
  getUploadImageHeader,
  getUploadImageUrl,
  isLoading,
  isUpdateSuccess
} from '@/api/common/fileUpload'
import { getAll } from '@/api/system/sysRole'

let listPathName = 'sysUserList'
const columns = [
  { title: '角色名称', dataIndex: 'name', width: 250 },
  { title: '角色Code', dataIndex: 'code' },
  { title: '备注', dataIndex: 'remark' }
]

export default {
  name: 'SysUserDetail',
  components: { HeaderToolBar },
  data() {
    return {
      id: 0,
      form: this.$form.createForm(this),
      userDate: {},
      roleList: [],
      typeList: [],
      columns: columns,
      currentEditDate: {},
      selectedRowKeys: [],
      officeList: [],
      visible: false,
      imageList: [],
      orgList: [],
      authorityTypeList: [],
      loading: false,
      previewVisible: false,
      previewImage: '',
      business: 'sys-user',
      uploadImageHeader: getUploadImageHeader(),
      formItemLayout: {
        labelCol: {
          sm: { span: 8 }
        },
        wrapperCol: {
          sm: { span: 16 }
        }
      },
      gutter: 8,
      span: 6
    }
  },
  activated() {
    this.getSysCode()
  },
  deactivated() {
    this.form.resetFields()
    this.userDate = {}
    this.selectedRowKeys = []
    this.imageList = []
  },
  methods: {
    getUploadImageUrl,
    isUpdateSuccess,
    isLoading,
    getOneImageURL,
    initData() {
      this.id = this.$route.query.id || 0
      getDetail(this.id).then((resp) => {
        if (resp && resp.code == SYS_CONST.REQUEST.SUCCEED) {
          this.userDate = resp.data.sysUserDetail
          this.selectedRowKeys = resp.data.sysUserCheckedRoleList || []

          if (this.userDate.avatar != null) {
            let image = {
              uid: '-1',
              name: 'xxx.png',
              status: 'done',
              url: this.userDate.avatar
            }
            this.imageList.push(image)
          }
        }
      })
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          if (this.selectedRowKeys.length === 0) {
            this.$notification.error({
              message: '系统提示',
              description: '至少勾选一个角色',
              duration: 4
            })
            return
          }
          values.avatar = getOneImageURL(this.imageList)
          let saveData = {
            sysUserDetail: this.$valueCopy(this.userDate, values),
            sysUserCheckedRoleList: this.selectedRowKeys
          }
          save(saveData).then((resp) => {
            if (resp && resp.code == SYS_CONST.REQUEST.SUCCEED) {
              this.$notification.success({
                message: '系统提示',
                description: '保存成功',
                duration: 4
              })
              this.$router.push({
                name: listPathName,
                query: { isModify: this.id != 0 }
              })
            }
          })
        }
      })
    },
    updateSelect(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    back() {
      this.$router.push({ name: listPathName })
    },
    normFile(e) {
      if (Array.isArray(e)) {
        return e
      }
      return e && e.fileList
    },
    handleChangeImg({ fileList }) {
      this.isUpdateSuccess(fileList)
      this.loading = this.isLoading(fileList)
      this.imageList = fileList
    },
    handlePreview(file) {
      this.previewImage = file.url || file.thumbUrl
      this.previewVisible = true
    },
    handleCancel() {
      this.previewVisible = false
    },
    getSysCode() {
      this.initData()
      getAll().then(({ data }) => {
        this.roleList = data
      })
    }
  }
}
</script>

