
<template>
  <div>
    <editMode ref="editMode" v-model="formVisible" :loading="detailLoading" :options="formOptions" :data="defaultFormData" :title="titles[mode]" :mode="mode" @dataChange="formData = $event" @submit="submit" @close="close">
      <template #password="{row}">
        <el-input :value="row.password" auto-complete="new-password" show-password type="password" maxlength="16" clearable placeholder="请输入密码" @input="row.password = $event.trim()" />
        <div class="note">
          6-16位数字、字母、符号，其中数字、字母、符号至少包含两种
        </div>
      </template>
      <template #confirmpassword="{row}">
        <el-input
          :value="row.confirmpassword"
          auto-complete="new-password"
          show-password
          type="password"
          maxlength="16"
          clearable
          placeholder="请输入确认密码"
          @input="row.confirmpassword = $event.trim()"
        />
      </template>
      <template #deptId="{row}">
        <DeptSelect v-if="defaultFormData.companyId == 0 || defaultFormData.isDefault == 0" v-model.trim="row.deptName" @change="Object.assign(row, $event)" />
      </template>
      <template #roleList="{row}">
        <el-select
          v-if="defaultFormData.companyId == 0 || defaultFormData.isDefault == 0"
          key="role"
          ref="roleSelect"
          v-model.trim="row.roleList"
          value-key="id"
          multiple
          filterable
          placeholder="请选择角色"
        >
          <div>
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.name"
              :value="item"
            />
          </div>
        </el-select>
        <template v-else>
          {{ row.roleList.map(item => item.name).join(',') }}
        </template>
      </template>
    </editMode>
  </div>
</template>

<script>
import { deepClone } from '@/utils'
import detailMixins from '../mixins/detail'
import { addUser, getUser, updateUser } from '@/apiV2/user'
import secret from '@/utils/secret.js'

export default {
  name: '',
  inject: ['global', 'refresh'],
  mixins: [detailMixins],
  data() {
    return {
      detailLoading: false,
      mode: 'see', // 查看see / 编辑edit / 添加add
      titles: { // 弹窗标题(动态)
        see: '查看用户详情',
        add: '新增用户',
        edit: '编辑用户'
      },
      formVisible: false // 弹窗显示
    }
  },
  computed: {
    roleList() {
      return this.global.roleList.filter(item => this.defaultFormData.companyId == 0 || item.isDefault == 0)
    },
    isEditAdd() {
      return this.mode === 'edit' || this.mode === 'add'
    }
  },
  methods: {
    async showDialog({ mode, formConfig, formData, formTitle }) {
      this.mode = mode || (this.formData.id ? 'edit' : 'add')
      if (mode === 'add') {
        this.resetFormData()
      } else {
        const userRes = await getUser(formData.id)
        this.defaultFormData = deepClone(formData)
        if (userRes.success && userRes.data) {
          Object.assign(this.defaultFormData, userRes.data)
        }
      }
      this.initFormData()
      this.formVisible = true
    },
    initFormData() { // 表单数据初始化
      // const { userRoleList } = this.global
      const { id, roleIds, roleNames } = this.defaultFormData
      const roleList = roleIds.map((id, index) => ({
        id,
        name: roleNames[index]
      }))
      if (this.mode === 'edit') {
        this.$set(this.defaultFormData, 'id', id)
      }
      this.$set(this.defaultFormData, 'roleList', roleList || [])
    },
    filterFormData(formData, originData) { // 提交数据过滤
      const data = deepClone(formData)
      data.roleList = data.roleList.map(item => item.id)
      delete data.roleIds
      delete data.roleNames
      if (this.mode === 'edit') {
        data['id'] = originData.id
      }
      if (this.mode === 'add') {
        data['password'] = secret(data['password'])
        data['confirmpassword'] = secret(data['confirmpassword'])
      }
      return data
    },
    async submit(data, originData) {
      const formData = this.filterFormData(data, originData)
      this.detailLoading = true
      try {
        let res = {}
        if (this.mode === 'add') {
          res = await addUser(formData)
        } else {
          res = await updateUser(formData)
        }
        if (res.success) {
          this.formVisible = false
          this.refresh()
        }
      } finally {
        this.detailLoading = false
      }
    },
    close() {
      this.resetFormData()
      this.$refs.editMode.clearValidate()
      this.formVisible = false
    }
  }
}
</script>

<style scoped lang="scss">

.width-clear {
  width: auto
}
.finish-dialog {
  /deep/ .el-form-item {
    &__content  {
      width: calc(100% - 180px); // 减去label宽
      max-width: none;
      .el-checkbox-group {
        line-height: normal;
      }
    }
    &__label {
      padding-right: 12px !important;
    }
    &.fit-width {
      .el-form-item__content {
        width: fit-content;
      }
    }
  }
  &.edit, &.add {
    /deep/ .el-form-item {
      margin-bottom: 22px;
    }
  }
  &.see {
    .detail-dialog {
      // background-color: #f8f8f8;
      padding: 20px;
    }
    /deep/ .el-form-item {
      &__label, &__content { // 统一行高
        line-height: 2;
      }
      margin-bottom: 10px;
    }
  }
}

/* 穿梭框 */
/deep/ .el-transfer {
  &__buttons {
    display: inline-flex;
    flex-direction: column;
    .el-button + .el-button {
      margin-left: 0;
    }
  }
}
</style>
