<template>
  <el-dialog :title="operateM.tit" :visible.sync="userDialogVisible">
    <el-form
      :model="userForm"
      :rules="userRules"
      ref="userForm"
      class="form-main"
      label-width="80px">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item v-if="activeShow" label="账号状态">
            <span>{{actived?'正常账号':'停用账号'}}</span>
          </el-form-item>
        </el-col>
        <el-col :span="item.span||''" v-for="item in formItem" :key="item.index">
          <el-form-item v-if="readonlyShow && !item.right" v-show="userForm[item.prop]" :label="item.tit">
            <span>{{userForm[item.prop]}}</span>
          </el-form-item>
          <el-form-item v-if="!readonlyShow && !item.right" :label="item.tit" :prop="item.prop">
            <el-input v-model="userForm[item.prop]" :placeholder="`请填写${item.tit}`" :maxlength="item.num||''"></el-input>
          </el-form-item>
          <el-form-item v-if="readonlyShow && viewShow && item.right" v-show="userForm[item.prop]" label="权限">
            <span>{{rightCodeShow(userForm[item.prop])}}</span>
          </el-form-item>
          <el-form-item v-if="item.right && !activeShow && !viewShow" :prop="item.prop" label-width="0">
            <template>
              <el-card shadow="never">
                <div class="card-title" slot="header">
                  <span>{{item.tit}}</span>
                </div>
                <el-checkbox-group
                  v-model="userForm[item.prop]"
                  :min="1"
                  :max="moduleOption.length"
                  @change="handleCheckedChange">
                  <el-checkbox v-for="mod in moduleOption" :label="mod.id" :key="mod.index">{{mod.name}}</el-checkbox>
                </el-checkbox-group>
              </el-card>
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="24" class="el-btn-col">
          <div class="el-btn-col-box">
            <el-button v-if="viewShow" type="primary" @click="userDialogVisible=false">确定</el-button>
            <el-button v-else type="primary" @click="submitForm('userForm')">保存</el-button>
          </div>
        </el-col>
        <el-col :span="24" v-if="timeShow">
          <el-form-item align="right">
            <span>创建时间: {{createTime}}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-dialog>
</template>

<script>
  import { parseTime } from '@/utils'
  import {
    requiredTip,
    limitNumTip,
    checkEmailV
  } from '@/utils/validator'
  import {
    existUser,
    addUser,
    updateUser,
    updatePermission,
    queryUserOne
  } from '@/api/sysSetting'

  export default {
    props: ['operateM'],
    data() {
      return {
        userDialogVisible: false,
        moduleOption: [
          { id: '1', name: '内容发布' },
          { id: '2', name: '特约专家' },
          { id: '3', name: '合作机构' },
          { id: '4', name: '企业中心' },
          { id: '5', name: '平台信息' },
          { id: '6', name: '用户信息' },
          { id: '7', name: '需求中心' },
          { id: '8', name: '统计' }
        ],
        userId: '',
        actived: 0,
        oldAccount: '',
        createTime: '',
        formItem: [
          {
            span: 12,
            prop: 'account',
            tit: '账号',
            num: 20,
            required: true
          },
          {
            span: 12,
            prop: 'name',
            tit: '用户名',
            required: true
          },
          {
            span: 12,
            prop: 'phone',
            tit: '联系电话',
            num: 20,
            required: true
          },
          {
            span: 12,
            prop: 'email',
            tit: '联系邮箱',
            num: 50
          },
          {
            span: 12,
            prop: 'job',
            tit: '职位',
            num: 20
          },
          {
            span: 12,
            prop: 'dep',
            tit: '所在部门',
            num: 20
          },
          {
            span: 24,
            prop: 'comp',
            tit: '所在机构',
            num: 50
          },
          {
            span: 24,
            prop: 'rightCode',
            tit: '分配权限',
            right: true,
            required: true
          }
        ],
        userForm: {
          account: '',
          name: '',
          phone: '',
          email: '',
          job: '',
          dep: '',
          comp: '',
          rightCode: []
        },
        userRules: {}
      }
    },
    computed: {
      readonlyShow() {
        if (this.operateM.type === 'right' || this.operateM.type === 'view') {
          return true
        } else {
          return false
        }
      },
      viewShow() {
        return this.operateM.type === 'view' || false
      },
      activeShow() {
        return this.operateM.type === 'edit' || false
      },
      timeShow() {
        return this.operateM.type !== 'add' || false
      }
    },
    watch: {
      userDialogVisible(val) {
        !val && setTimeout(() => {
          if (!this.operateM.type === 'right') {
            this.$refs['userForm'].resetFields()
          }
          this.$refs['userForm'].clearValidate()
        }, 0)
      }
    },
    created() {
      this.pushRulesFn()
    },
    methods: {
      getUserDetail(id) {
        var that = this
        that.userId = id
        if (that.userId) {
          that.$http.get(queryUserOne, {
            id: that.userId
          }, function(res) {
            if (res.success) {
              const opeRow = res.data
              if (opeRow.createTime) {
                that.createTime = parseTime(opeRow.createTime)
              }
              that.actived = opeRow.actived
              that.oldAccount = opeRow.account
              that.userForm = {
                account: opeRow.account,
                name: opeRow.name,
                phone: opeRow.phone,
                email: opeRow.email,
                job: opeRow.job,
                dep: opeRow.dep,
                comp: opeRow.comp,
                rightCode: opeRow.rightCode ? opeRow.rightCode : []
              }
            }
          })
        } else {
          this.actived = 0
          this.createTime = ''
          this.userForm = {
            account: '',
            name: '',
            phone: '',
            email: '',
            job: '',
            dep: '',
            comp: '',
            rightCode: []
          }
        }
        setTimeout(function() {
          that.userDialogVisible = true
        }, 0)
      },
      pushRulesFn() {
        const formItem = this.formItem
        const userRules = this.userRules
        for (let i = 0; i < formItem.length; ++i) {
          const ru = []
          if (formItem[i].required) {
            ru.push({ required: true, message: requiredTip(formItem[i].tit), trigger: 'blur' })
          }
          if (formItem[i].num) {
            ru.push({ max: formItem[i].num, message: limitNumTip(formItem[i].tit, formItem[i].num), trigger: 'blur, change' })
          }
          switch (formItem[i].prop) {
            case 'email':
              ru.push({ validator: checkEmailV, trigger: 'blur' })
              break
          }
          userRules[formItem[i].prop] = ru
        }
      },
      isExistUserFn(fn) {
        var that = this
        var opeRow = that.userForm
        this.$http.get(existUser, {
          account: opeRow.account
        }, function(res) {
          if (res.success) {
            if (res.data) {
              that.$message({
                message: '账户已存在，请重新输入',
                type: 'warning'
              })
              return false
            } else {
              fn()
            }
          }
        })
      },
      rightCodeShow(code) {
        if (!code) {
          return
        }
        var codeShow = []
        for (let i = 0; i < code.length; ++i) {
          const nowC = this.moduleOption.find((item) => {
            return item.id === code[i]
          })
          codeShow.push(nowC.name)
        }
        return codeShow.join('，')
      },
      submitForm(formName) {
        var that = this
        this.$refs[formName].validate((valid) => {
          if (valid) {
            var opeRow = that.userForm
            var paramsData = {
              account: opeRow.account,
              name: opeRow.name,
              phone: opeRow.phone,
              email: opeRow.email,
              job: opeRow.job,
              dep: opeRow.dep,
              comp: opeRow.comp,
              rightCode: opeRow.rightCode
            }
            if (that.operateM.type === 'add') {
              that.isExistUserFn(function() {
                that.$http.post(addUser, paramsData, function(res) {
                  if (res.success) {
                    that.successFun()
                  }
                })
              })
            } else if (that.operateM.type === 'edit') {
              const paramsId = { id: that.userId }
              const obj = Object.assign(paramsId, paramsData)
              if (that.oldAccount === opeRow.account) {
                that.$http.put(updateUser, obj, function(res) {
                  if (res.success) {
                    that.successFun()
                  }
                })
              } else {
                that.isExistUserFn(function() {
                  that.$http.put(updateUser, obj, function(res) {
                    if (res.success) {
                      that.successFun()
                    }
                  })
                })
              }
            } else if (that.operateM.type === 'right') {
              that.$http.put(updatePermission + that.userId, opeRow.rightCode, function(res) {
                if (res.success) {
                  that.successFun()
                }
              })
            }
          } else {
            return false
          }
        })
      },
      successFun() {
        this.userDialogVisible = false
        this.$refs['userForm'].resetFields()
        this.$parent.dialogChanged()
      },
      handleCheckedChange(value) {
        this.userForm.rightCode = value
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss">
  .el-card__header{
    padding: 8px 15px;
    .card-title{
      font-size: 18px;
      font-weight: bold;
      span:before{
        content: '*';
        color: #f56c6c;
        margin-right: 4px;
      }
    }
  }
  .el-checkbox-group{
    .el-checkbox{
      font-size: 16px;
      margin: 10px 60px;
      .el-checkbox__inner{
        width: 16px;
        height: 16px;
      }
      .el-checkbox__inner::after{
        left:5px;
        top:2px;
      }
      .el-checkbox__label{
        line-height:24px;
        font-size:16px;
      }
    }
  }
</style>
