<template>
  <div class="app-container">
    <el-page-header :content="isEdit?'编辑收款用户':'添加收款用户'" @back="goBack" />
    <el-card class="form-container" shadow="never">
      <el-form ref="receiptUserFrom" :rules="formRules" :model="receiptUser" label-width="150px">
        <el-form-item label="收款用户名称：" prop="name">
          <el-input v-model="receiptUser.name" maxlength="100" />
        </el-form-item>
        <el-form-item label="收款用户手机号：" prop="mobile">
          <el-input v-model="receiptUser.mobile" maxlength="100" />
        </el-form-item>
        <el-form-item v-if="passwordFlag" key="password" label="收款用户密码：" prop="password">
          <el-input v-model="receiptUser.password" maxlength="100" />
        </el-form-item>
        <el-form-item v-if="!passwordFlag" key="passwordFlag" label="收款用户密码：">
          <el-button @click="passwordFlag=true">重置密码</el-button>
        </el-form-item>
        <el-form-item label="收款用户类型：" prop="userType">
          <el-radio-group v-model="receiptUser.userType">
            <el-radio :label="1">协销</el-radio>
            <el-radio :label="2">客服</el-radio>
            <el-radio :label="3">财务</el-radio>
            <el-radio :label="4">超级管理员</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="收款用户授权：" prop="permissionIds">
          <el-checkbox-group v-model="permissionChecked" @change="handleCheckedPermission">
            <el-checkbox v-for="item in permissionSelect" :key="item.id" :label="item.id" class="littleMarginLeft">{{ item.permission }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit('receiptUserFrom')">提交</el-button>
          <el-button v-if="!isEdit" type="info" @click="resetForm('receiptUserFrom')">重置</el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getUser, updateUser, createUser, fetchPermissionList } from '@/api/caimei/finance/receipt-user'

const defaultUser = {
  id: '',
  name: '',
  mobile: '',
  password: '',
  userType: '',
  permissionIds: ''
}
export default {
  name: 'ReceiptUserEdit',
  data() {
    const checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('用户手机号不能为空'))
      } else {
        const reg = /^1[3456789]\d{9}$/
        console.log(reg.test(value))
        if (reg.test(value)) {
          callback()
        } else {
          return callback(new Error('请输入正确的手机号'))
        }
      }
    }
    return {
      formRules: {
        name: [{ required: true, message: '用户名称不能为空', trigger: 'blur' }],
        mobile: { required: true, validator: checkPhone, trigger: 'blur' },
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          { min: 6, max: 30, message: '长度在 6 到 30 个字符', trigger: 'blur' }
        ]
      },
      receiptUser: Object.assign({}, defaultUser),
      isEdit: false,
      passwordFlag: true,
      permissionSelect: [],
      permissionChecked: []
    }
  },
  watch: {
    $route(route) {
      this.getFormData()
      this.getPermissionList()
    }
  },
  created() {
    this.getFormData()
    this.getPermissionList()
  },
  methods: {
    goBack() {
      // 调用全局挂载的方法,关闭当前标签页
      this.$store.dispatch('tagsView/delView', this.$route)
      // 返回上一步路由，返回上一个标签页
      this.$router.go(-1)
    },
    getFormData() {
      if (this.$route.query.id) {
        this.receiptUser.id = this.$route.query.id
        this.isEdit = true
        this.passwordFlag = false
        getUser(this.receiptUser.id).then(response => {
          this.receiptUser.name = response.data.name
          this.receiptUser.mobile = response.data.mobile
          this.receiptUser.password = response.data.password
          this.receiptUser.userType = response.data.userType
          this.receiptUser.permissionIds = response.data.permissionIds
          if (response.data.permissionIds) {
            this.permissionChecked = []
            response.data.permissionIds.split(',').forEach(element => {
              this.permissionChecked.push(element * 1)
              console.log(this.permissionChecked)
            })
          }
        })
      } else {
        this.receiptUser.id = ''
        this.isEdit = false
        this.passwordFlag = true
        this.receiptUser = Object.assign({}, defaultUser)
      }
    },
    getPermissionList() {
      fetchPermissionList().then(response => {
        this.permissionSelect = response.data
      })
    },
    handleCheckedPermission() {
      this.receiptUser.permissionIds = this.permissionChecked.join(',')
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.receiptUser = Object.assign({}, defaultUser)
      this.getFormData()
    },
    onSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.$confirm('是否提交数据', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            const self = this
            if (this.isEdit) {
              updateUser(this.$route.query.id, this.receiptUser).then(response => {
                this.$message({
                  message: '修改成功',
                  type: 'success',
                  duration: 1000
                })
                self.goBack()
              })
            } else {
              createUser(this.receiptUser).then(response => {
                this.$refs[formName].resetFields()
                this.resetForm(formName)
                this.$message({
                  message: '提交成功',
                  type: 'success',
                  duration: 1000
                })
                self.goBack()
              })
            }
          })
        } else {
          this.$message({
            message: '验证失败',
            type: 'error',
            duration: 1000
          })
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
</style>
