<template>
  <a-modal
    title="编辑用户"
    width="60%"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-divider orientation="left">个人信息</a-divider>
        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-item label="头像" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-upload
                name="file"
                list-type="picture-card"
                class="avatar-uploader"
                :show-upload-list="false"
                @preview="handlePreview"
                :customRequest="handleUpload"
              >
                <img v-if="imageUrl" style="max-height:200px;max-width:400px;" :src="imageUrl" alt="头像" />
                <div v-else>
                  <a-icon :type="uploading ? 'loading' : 'plus'" />
                  <div class="ant-upload-text">
                    上传头像
                  </div>
                </div>
              </a-upload>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-item style="display: none;">
              <a-input v-decorator="['id']" />
            </a-form-item>
            <a-form-item label="账号" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-input
                placeholder="请输入账号"
                v-decorator="[
                  'account',
                  {
                    validateFirst: true,
                    rules: [
                      { required: true, min: 5, message: '请输入至少五个字符的账号！' },
                      { max: 50, message: '账号最多50个字' }
                    ]
                  }
                ]"
              />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item label="姓名" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-input
                placeholder="请输入姓名"
                v-decorator="[
                  'name',
                  {
                    validateFirst: true,
                    rules: [
                      { required: true, message: '请输入姓名！' },
                      { max: 100, message: '姓名最多100个字' }
                    ]
                  }
                ]"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-item label="昵称" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-input
                placeholder="请输入昵称"
                v-decorator="[
                  'nickName',
                  {
                    validateFirst: true,
                    rules: [{ max: 100, message: '昵称最多100个字' }]
                  }
                ]"
              />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form :form="form">
              <a-form-item label="性别" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
                <a-select
                  placeholder="请选择性别"
                  v-decorator="['sex', { rules: [{ required: true, message: '请选择性别' }], initialValue: 1 }]"
                >
                  <a-select-option
                    v-for="(item, index) in GetClientDataList('gender')"
                    :key="index"
                    :value="item.code"
                    >{{ item.val }}</a-select-option
                  >
                </a-select>
              </a-form-item>
            </a-form>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="12" :sm="24" v-if="$store.state.user.admintype === 1">
            <a-form-item label="账户类型" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-select
                placeholder="请选择账户类型"
                v-decorator="['admintype', { rules: [{ required: true, message: '请选择账户类型' }] }]"
              >
                <a-select-option
                  v-for="(item, index) in GetClientDataList('admintype')"
                  :key="index"
                  :value="item.code"
                  >{{ item.val }}</a-select-option
                >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item label="邮箱" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-input
                placeholder="请输入邮箱"
                v-decorator="['email', { rules: [{ max: 50, message: '邮箱最多50个字' }] }]"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-item label="手机号" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-input
                placeholder="请输入手机号"
                v-decorator="[
                  'phone',
                  {
                    validateFirst: true,
                    rules: [
                      { required: true, message: '请输入手机号！' },
                      { max: 20, message: '手机号最多20个字' }
                    ]
                  }
                ]"
              />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item label="电话" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-input
                placeholder="请输入电话"
                v-decorator="[
                  'tel',
                  {
                    validateFirst: true,
                    rules: [{ max: 20, message: '电话最多20个字' }]
                  }
                ]"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-item label="机构" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-tree-select
                v-decorator="['sysEmpParam.orgId', { rules: [{ required: true, message: '请选择机构！' }] }]"
                style="width: 100%"
                :dropdownStyle="{ maxHeight: '300px', overflow: 'auto' }"
                :treeData="orgTree"
                placeholder="请选择机构"
                treeDefaultExpandAll
                @change="e => initrOrgName(e)"
              >
                <span slot="title" slot-scope="{ id }">{{ id }}</span>
              </a-tree-select>
            </a-form-item>
            <a-form :form="form">
              <a-form-item v-show="false">
                <a-input v-decorator="['sysEmpParam.orgName']" />
              </a-form-item>
            </a-form>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item label="编号" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-input
                placeholder="请输入编号"
                v-decorator="[
                  'sysEmpParam.jobNum',
                  {
                    validateFirst: true,
                    rules: [{ max: 30, message: '编号最多30个字' }]
                  }
                ]"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-item label="职位信息" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-select
                style="width: 100%"
                placeholder="请选择职位信息"
                v-decorator="['sysEmpParam.posIdList', { rules: [{ required: true, message: '请选择职位信息！' }] }]"
              >
                <a-select-option v-for="(item, index) in posList" :key="index" :value="item.id">{{
                  item.name
                }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item label="行业" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-select
                style="width: 100%"
                placeholder="请选择行业"
                v-decorator="['industryid', { rules: [{ required: true, message: '请选择行业！' }] }]"
              >
                <a-select-option v-for="(item, index) in industryList" :key="index" :value="item.id">{{
                  item.name
                }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-item label="是否领导" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-switch v-decorator="['isleader', { valuePropName: 'checked' }]" />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item label="序号" help="数字越小越靠前" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入排序号" type="number" v-decorator="['sortcode', { initialValue: 100 }]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-item label="籍贯" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input
                placeholder="请输入籍贯"
                v-decorator="[
                  'place',
                  {
                    validateFirst: true,
                    rules: [{ max: 100, message: '籍贯最多100个字' }]
                  }
                ]"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="24" :sm="24">
            <a-form-item label="个人爱好" :labelCol="labelCol_JG" :wrapperCol="wrapperCol_JG" has-feedback>
              <a-textarea
                placeholder="请输入个人爱好"
                :rows="4"
                v-decorator="[
                  'interests',
                  {
                    validateFirst: true,
                    rules: [{ max: 500, message: '个人爱好最多500个字' }]
                  }
                ]"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="24" :sm="24">
            <a-form-item label="提供的资源" :labelCol="labelCol_JG" :wrapperCol="wrapperCol_JG" has-feedback>
              <a-textarea
                placeholder="能为智造团提供哪些资源"
                :rows="4"
                v-decorator="[
                  'provide',
                  {
                    validateFirst: true,
                    rules: [{ max: 500, message: '资源最多500个字' }]
                  }
                ]"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="24" :sm="24">
            <a-form-item label="希望的资源" :labelCol="labelCol_JG" :wrapperCol="wrapperCol_JG" has-feedback>
              <a-textarea
                placeholder="希望智造团提供的资源"
                :rows="4"
                v-decorator="[
                  'demand',
                  {
                    validateFirst: true,
                    rules: [{ max: 500, message: '资源最多500个字' }]
                  }
                ]"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
  </a-modal>
</template>
<script>
import { sysUserEdit, sysUserDetail } from '@/api/modular/system/userManage'
import { getOrgTree, getOrgList } from '@/api/modular/system/orgManage'
import { sysPosList } from '@/api/modular/system/posManage'
import { GetClientDataList } from '@/utils/clientdata'
import { UploadImg } from '@/api/modular/main/upload'
import { AllList } from '@/api/modular/main/industry'
import moment from 'moment'
export default {
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      // 机构行样式
      labelCol_JG: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol_JG: {
        xs: { span: 24 },
        sm: { span: 20 }
      },
      count: 1,
      visible: false,
      confirmLoading: false,
      orgTree: [],
      orgList: [],
      posList: [],
      sysEmpParamExtList: [],
      memberLoading: false,
      form: this.$form.createForm(this),
      data: [],
      birthdayString: '',
      uploading: false,
      imageUrl: '',
      headimg: '',
      industryList: []
    }
  },
  methods: {
    GetClientDataList,
    // 初始化方法
    edit(record) {
      this.confirmLoading = true
      this.visible = true
      this.imageUrl = ''
      this.headimg = ''
      this.uploading = false
      this.getOrgData()
      this.getPosList()
      this.getIndustryList()
      // 基本信息加人表单
      setTimeout(() => {
        this.headimg = record.avatar
        this.imageUrl = record.avatarurl
        this.form.setFieldsValue({
          id: record.id,
          account: record.account,
          name: record.name,
          nickName: record.nickname,
          sex: record.sex,
          email: record.email,
          phone: record.phone,
          tel: record.tel,
          interests: record.interests,
          provide: record.provide,
          demand: record.demand,
          industryid: record.industryid,
          isleader: record.isleader,
          sortcode: record.sortcode,
          place: record.place
        })
        if (this.$store.state.user.admintype === 1) {
          this.form.setFieldsValue({
            admintype: record.admintype
          })
        }
      }, 100)
      // 时间单独处理
      if (record.birthday != null) {
        this.form.getFieldDecorator('birthday', { initialValue: moment(record.birthday, 'YYYY-MM-DD') })
      }
      this.birthdayString = moment(record.birthday).format('YYYY-MM-DD')
      // 职位信息加入表单
      this.getUserDetaile(record.id)
    },
    /**
     * 通过用户ID查询出用户详情，将职位信息填充
     * @param id
     */
    getUserDetaile(id) {
      sysUserDetail({ id: id }).then(res => {
        const SysEmpInfo = res.data.sysempinfo
        this.form.getFieldDecorator('sysEmpParam.orgName', { initialValue: SysEmpInfo.orgname })
        if (SysEmpInfo.positions !== null) {
          this.form.getFieldDecorator('sysEmpParam.posIdList', { initialValue: SysEmpInfo.positions.posid })
        }
        this.form.getFieldDecorator('sysEmpParam.jobNum', { initialValue: SysEmpInfo.jobnum })
        this.form.getFieldDecorator('sysEmpParam.orgId', { initialValue: SysEmpInfo.orgid })
        this.confirmLoading = false
      })
    },
    /**
     * 增行
     */
    newMember() {
      const length = this.data.length
      this.data.push({
        key: length === 0 ? '1' : (parseInt(this.data[length - 1].key) + 1).toString(),
        extOrgId: '',
        extPosId: ''
      })
    },
    /**
     * 删除
     */
    remove(key) {
      const newData = this.data.filter(item => item.key !== key)
      this.data = newData
    },
    /**
     * 选择子表单单项触发
     */
    handleChange(value, key, column) {
      const newData = [...this.data]
      const target = newData.find(item => key === item.key)
      if (target) {
        target[column] = value
        this.data = newData
      }
    },
    /**
     * 获取机构数据，并加载于表单中
     */
    getOrgData() {
      getOrgTree().then(res => {
        this.orgTree = res.data
      })
      getOrgList().then(res => {
        this.orgList = res.data
      })
    },
    /**
     * 获取职位list列表
     */
    getPosList() {
      sysPosList().then(res => {
        this.posList = res.data
      })
    },
    // 获取行业列表
    getIndustryList() {
      AllList().then(res => {
        this.industryList = res.data
      })
    },
    /**
     * 选择树机构，初始化机构名称于表单中
     */
    initrOrgName(value) {
      this.form.getFieldDecorator('sysEmpParam.orgName', {
        initialValue: this.orgList.find(item => value === item.id).name
      })
    },
    /**
     * 子表单json重构
     */
    JsonReconsitution() {
      this.sysEmpParamExtList = []
      const newData = [...this.data]
      newData.forEach(item => {
        // eslint-disable-next-line eqeqeq
        if ((item.extOrgId != '') & (item.extPosId != '')) {
          this.sysEmpParamExtList.push({ orgId: item.extOrgId, posId: item.extPosId })
        }
      })
    },
    /**
     * 日期需单独转换
     */
    onChange(date, dateString) {
      this.birthdayString = moment(date).format('YYYY-MM-DD')
    },
    handleSubmit() {
      const {
        form: { validateFields }
      } = this
      this.confirmLoading = true
      validateFields((errors, values) => {
        if (!errors) {
          this.JsonReconsitution()
          // eslint-disable-next-line eqeqeq
          if (this.birthdayString == 'Invalid date') {
            this.birthdayString = null
          }
          values.birthday = this.birthdayString
          values['avatar'] = this.headimg
          sysUserEdit(values)
            .then(res => {
              if (res.code === 0) {
                this.$message.success('编辑成功')
                this.confirmLoading = false
                this.$emit('ok', values)
                this.handleCancel()
              } else {
                this.$myerror('编辑失败：' + JSON.stringify(res.message))
              }
            })
            .finally(res => {
              this.confirmLoading = false
            })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.form.resetFields()
      this.visible = false
      // 清理子表单中数据
      this.data = []
      // 清理时间
      this.birthdayString = ''
      this.form.getFieldDecorator('birthday', { initialValue: null })
    },
    // 上传
    handleUpload(data) {
      const formData = new FormData()
      formData.append('file', data.file)
      this.uploading = true
      UploadImg(formData)
        .then(res => {
          if (res.code === 0) {
            this.imageUrl = res.data.url
            this.headimg = res.data.path
          } else {
            this.$myerror(res.message)
          }
          this.uploading = false
        })
        .catch(() => {
          this.$message.error('上传失败')
          this.uploading = false
        })
    },
    // 图片预览
    async handlePreview(file) {}
  }
}
</script>
