<template>
  <el-dialog
    v-dialog-drag
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    :title="`${dialogStatus === 'create' ? '新建' : dialogStatus === 'edit' ? '编辑' : '查看'}租户`"
    :visible.sync="dialogVisible"
    width="550px"
    append-to-body
    @close="handleCancel"
  >
    <el-form ref="form" class="full-form" :model="formState" :rules="rules" label-width="120px">
      <el-form-item label="租户类型" prop="tenantType">
        <el-select v-if="!isEdit" v-model="formState.tenantType" filterable placeholder="请选择租户类型" clearable @change="handleChangeTenantType">
          <el-option
            v-for="dict in dict.type[DICT_TYPE.sys_tenant_type]"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
        <span v-else>{{ getDictLabel(dict.type[DICT_TYPE.sys_tenant_type], editTenantType) }}</span>
      </el-form-item>
      <el-form-item v-if="isEdit" label="租户名称">
        <span>{{ formState.tenantName }}</span>
      </el-form-item>
      <template v-else>
        <el-form-item
          v-if="formState.tenantType === options.sysTenantTypeMap.kindergarten"
          :rules="{ required: true, validator: branchValidator, trigger: 'change' }"
          label="租户名称"
          prop="branchInfo"
        >
          <!--        已开通账号的禁用-->
          <el-select
            v-model="formState.branchInfo"
            filterable
            placeholder="请选择幼儿园"
            value-key="id"
            @change="handleChangeKindergarten"
          >
            <el-option
              v-for="item in allKindergarten"
              :key="item.id"
              :disabled="!!item.tenantAccount"
              :label="item.kindergartenName"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-else label="租户名称" prop="gardenInfo" :rules="{ required: true, validator: gardenValidator, trigger: 'change' }">
          <el-select
            v-model="formState.gardenInfo"
            filterable
            placeholder="请选择"
            value-key="id"
            @change="handleChangeKindergartenGroup"
          >
            <el-option
              v-for="item in allKindergartenGroup"
              :key="item.id"
              :disabled="Number(item.branchCount) <=0 || !!item.params.tenantId"
              :label="item.name"
              :value="item"
            />
          </el-select>
        </el-form-item>
      </template>

      <el-form-item v-show="realTenantType === Number(options.sysTenantTypeMap.kindergarten)" label="所属集团" prop="gardenName">
        <el-input v-model="gardenName" :disabled="true" placeholder="所属集团" />
      </el-form-item>
      <el-form-item label="联系电话" prop="userPhone">
        <el-input v-model="formState.userPhone" minlength="0" maxlength="11" placeholder="请输入手机号码" />
      </el-form-item>
      <el-form-item label="账号" prop="userName">
        <el-input v-model="formState.userName" placeholder="请输入账号" auto-complete="off" :disabled="readonly" />
      </el-form-item>
      <el-form-item v-if="dialogStatus === 'create'" label="密码" prop="password">
        <el-input v-model="formState.password" placeholder="请输入密码" type="password" show-password auto-complete="new-password" />
      </el-form-item>
      <el-form-item label="租户状态">
        <el-radio-group v-model="formState.status">
          <el-radio
            v-for="dict in dict.type[DICT_TYPE.SYSTEM_TENANT_STATUS]"
            :key="dict.value"
            :label="dict.value"
          >{{ dict.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import regex from '@/utils/regex'
import options from '@/utils/dict/options'
import { fetchAllTenantPackage } from '@/api/system/tenantpackage'
import { DICT_TYPE, getDictLabel } from '@/utils/dict/config'
import { addTenant, getTenant, updateTenant } from '@/api/system/tenant'
import { fetchAllKindergarten } from '@/api/system/branch'
import { fetchAllGarden } from '@/api/system/garden'

const initForm = {
  id: null,
  tenantType: null,
  tenantName: null,
  branchInfo: {},
  gardenInfo: {},
  branchId: null, // 幼儿园Id
  gardenId: null, // 集团Id
  userName: null,
  userPhone: null,
  status: options.sysTenantStatusMap.Y,
  remark: null
}
export default {
  name: 'TenantDialog',
  dicts: [DICT_TYPE.SYSTEM_TENANT_STATUS, DICT_TYPE.sys_tenant_type],
  data() {
    return {
      options,
      DICT_TYPE,
      dialogVisible: false,
      dialogStatus: 'create',
      readonly: false,
      hasGardenAccount: false,
      realTenantType: null, // 实际的租户类型
      allTenantPackage: [],
      allKindergarten: [], // 全部幼儿园
      allKindergartenGroup: [], // 全部集团
      gardenName: null, // 所属集团
      selectKindergartenType: null, // 幼儿园类型
      editTenantType: null, // 编辑的租户类型 如果是3 变为2
      formState: Object.assign({}, initForm),
      onFilter: null, // 可选的幼儿园范围
      isEdit: false,
      rules: {
        tenantType: { required: true, message: '租户类型不能为空', trigger: 'change' },
        userPhone: [
          { required: true, message: '手机号码不能为空', trigger: 'blur' },
          { pattern: regex.mobile, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        userName: [
          { required: true, message: '管理员账号不能为空', trigger: 'blur' },
          { pattern: regex.password, message: '账号为6-20位数字、字母、特殊字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { pattern: regex.password, message: '密码为6-20位数字、字母、特殊字符', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '租户状态不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    // 是否为独立幼儿园
    single() {
      return this.selectKindergartenType && [options.kindergartenTypeMap.kindergartenSingle, options.kindergartenTypeMap.other].includes(this.selectKindergartenType)
    }
  },
  created() {
    this.getAllTenantPackage()
    this.getAllKindergarten()
    this.getAllAllGardenGroup()
  },
  methods: {
    getDictLabel,
    gardenValidator(voteRule, value, callback) {
      if (!this.formState.gardenId) {
        callback(new Error('租户名称不能为空'))
      } else {
        callback()
      }
    },
    branchValidator(voteRule, value, callback) {
      if (!this.formState.branchId) {
        callback(new Error('租户名称不能为空'))
      } else {
        callback()
      }
    },
    getAllAllGardenGroup() {
      fetchAllGarden().then(({ data }) => {
        this.allKindergartenGroup = data
      })
    },
    getAllKindergarten() {
      fetchAllKindergarten().then(({ data }) => {
        this.allKindergarten = data
      })
    },
    getAllTenantPackage() {
      fetchAllTenantPackage().then(({ data }) => {
        this.allTenantPackage = data
      })
    },
    handleOpen(readonly = false, isEdit = false, formState = Object.assign({}, initForm)) {
      this.isEdit = isEdit
      this.formState = formState
      this.editTenantType = this.formState.tenantType
      this.dialogStatus = 'create'
      this.readonly = readonly
      this.dialogVisible = true
      this.getAllKindergarten()
      this.getAllAllGardenGroup()
    },
    handleEdit(row, isEdit = true) {
      this.dialogVisible = true
      this.dialogStatus = 'edit'
      this.isEdit = isEdit
      this.getAllKindergarten()
      this.getAllAllGardenGroup()
      getTenant(row.id).then(({ data }) => {
        this.formState = data
        const { tenantType } = data
        this.realTenantType = tenantType
        this.gardenName = data.params && data.params.gardenName || null
        // 如果是独立幼儿园 tenantType改为 '2'
        this.editTenantType = tenantType ? tenantType === Number(options.sysTenantTypeMap.kindergartenSingle) ? options.sysTenantTypeMap.kindergarten : tenantType.toString() : null
        this.formState.password = ''
        this.formState.status = data.status.toString()
      })
    },
    handleChangeKindergarten(row) {
      this.selectKindergartenType = row.kindergartenType
      this.realTenantType = Number(row.kindergartenType)
      this.formState.tenantName = row.kindergartenName
      this.formState.branchId = row.id
      this.gardenName = row.params ? row.params.gardenName : null
      this.formState.gardenId = row.params ? row.params.gardenId : null
    },
    handleChangeKindergartenGroup(row) {
      this.formState.tenantName = row.name
      this.formState.gardenId = row.id
    },
    handleChangeTenantType(val) {
      this.formState.tenantName = null
      this.formState.branchId = null
      this.formState.gardenId = null
      this.formState.branchInfo = {}
      this.gardenName = null
    },
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true
          const fn = this.dialogStatus === 'edit' ? updateTenant : addTenant
          const temp = JSON.parse(JSON.stringify(this.formState))
          // 独立幼儿园的tenantType改为 3，匹配对应的租户基础套餐 只有新增变
          temp.tenantType = this.formState.tenantType === options.sysTenantTypeMap.kindergarten && this.single
            ? options.sysTenantTypeMap.kindergartenSingle : this.formState.tenantType
          fn(temp).then(() => {
            this.$modal.msgSuccess('保存成功')
            this.handleCancel()
            this.$emit('ok')
          }).finally(() => {
            this.loading = false
          })
        }
      })
    },
    handleCancel() {
      this.dialogVisible = false
      this.formState = Object.assign({}, initForm)
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style scoped lang="scss">

</style>
