
<template>
  <el-dialog
    v-dialog-drag
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    title="权限管理"
    :visible.sync="dialogVisible"
    width="555px"
    append-to-body
    @close="handleCancel"
  >
    <el-form ref="form" class="full-form" :model="formState" :rules="rules" label-width="100px">
      <el-form-item label="租户类型">
        <span>{{ getDictLabel(dict.type[DICT_TYPE.sys_tenant_type], tenantInfo.tenantType) }}</span>
      </el-form-item>
      <el-form-item label="租户名称">
        <span>{{ tenantInfo.tenantName }}</span>
      </el-form-item>
      <el-form-item v-if="tenantInfo.params && tenantInfo.params.gardenName" label="所属集团">
        <span>{{ tenantInfo.params && tenantInfo.params.gardenName }}</span>
      </el-form-item>
      <el-form-item v-if="tenantInfo.tenantType === options.sysTenantTypeMap.group" label="开通业务">
        <span>详见集团下幼儿园开通业务</span>
      </el-form-item>
      <el-form-item v-else label="开通业务" prop="sysServiceIds">
        <el-checkbox-group v-model="formState.sysServiceIds">
          <el-checkbox v-for="item in serviceList" :key="item.id" :label="item.id">{{ item.serviceName }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="有效期限" required>
        <div class="d-flex">
          <el-col :span="18">
            <el-form-item prop="tenantRangeTime">
              <el-date-picker
                v-model="formState.tenantRangeTime"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                clearable
                type="daterange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                @change="handleChangeRangeTime"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item prop="longTerm">
              <el-checkbox
                v-model="formState.longTerm"
                :true-label="options.longTerm.Y"
                :false-label="options.longTerm.N"
                @change="handleChangeLongTerm"
              >长期</el-checkbox>
            </el-form-item>
          </el-col>
        </div>

      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button size="small" @click="handleCancel">取 消</el-button>
      <el-button size="small" type="primary" :loading="loading" @click="handleSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { editTenantService, getTenant } from '@/api/system/tenant'
import { getDictLabel } from '@/utils/dict/config'
import { DICT_TYPE } from '@/utils/dict/config'
import { fetchServicePage } from '@/api/system/service'
import options from '@/utils/dict/options'
import moment from 'moment'

const initForm = {
  id: null,
  sysServiceIds: [],
  sysServiceList: [],
  longTerm: options.longTerm.N,
  tenantRangeTime: [],
  // tenantStartTime: null,
  // tenantEndTime: null,
  createTime: null
}
export default {
  name: 'PermissionDialog',
  dicts: [DICT_TYPE.sys_tenant_type],
  data() {
    const tenantRangeTimeValidator = (voteRule, value, callback) => {
      const { tenantRangeTime, longTerm } = this.formState
      const range = tenantRangeTime && tenantRangeTime.length > 0 ? tenantRangeTime.filter(k => k) : []
      if ((!longTerm || longTerm === options.longTerm.N) && (!range || range.length < 2)) {
        callback(new Error('有效时间不能为空'))
      } else {
        callback()
      }
    }
    const longTermValidator = (voteRule, value, callback) => {
      this.$refs.form.validateField('tenantRangeTime')
      callback()
    }
    return {
      options,
      DICT_TYPE,
      dialogVisible: false,
      loading: false,
      formState: Object.assign({}, initForm),
      tenantInfo: {
        tenantName: null,
        params: { gardenName: null }
      },
      serviceList: [],
      rules: {
        sysServiceIds: { required: true, message: '开通业务不能为空', trigger: 'blur' },
        tenantRangeTime: { validator: tenantRangeTimeValidator, trigger: 'blur' },
        longTerm: { validator: longTermValidator, trigger: 'blur' }
      }
    }
  },
  created() {
    this.getServicePage()
  },
  methods: {
    getDictLabel,
    getServicePage() {
      fetchServicePage({
        pageNum: 0,
        pageSize: 50
      }).then(({ data }) => {
        this.serviceList = data
      })
    },
    handleChangeRangeTime() {
      this.formState.longTerm = options.longTerm.N
    },
    handleChangeLongTerm(val) {
      if (val === options.longTerm.Y) this.formState.tenantRangeTime = []
    },
    handleOpen(row) {
      this.dialogVisible = true
      this.formState.id = row.id
      this.formState.createTime = row.createTime
      getTenant(row.id).then(({ data }) => {
        const { tenantType } = data
        // 如果是独立幼儿园 tenantType改为 '2'
        this.tenantInfo = data
        this.tenantInfo.tenantType = tenantType ? tenantType === Number(options.sysTenantTypeMap.kindergartenSingle) ? options.sysTenantTypeMap.kindergarten : tenantType.toString() : null
        const tmp = Object.assign({}, data)
        this.formState.tenantRangeTime = tmp.tenantStartTime && tmp.tenantEndTime ? [moment(tmp.tenantStartTime).format('yyyy-MM-DD'), moment(tmp.tenantEndTime).format('yyyy-MM-DD')] : []
        this.formState.longTerm = tmp.longTerm
        this.handleChangeLongTerm(tmp.longTerm)
        this.formState.sysServiceIds = tmp.sysServiceList && tmp.sysServiceList.length > 0 ? tmp.sysServiceList.map(item => item.id) : []
      })
    },
    handleCancel() {
      this.formState = Object.assign({}, initForm)
      this.$refs.form.clearValidate()
      this.dialogVisible = false
    },
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true
          const { tenantRangeTime } = this.formState
          this.formState.tenantName = this.tenantInfo.tenantName;
          this.formState.sysServiceList = this.formState.sysServiceIds.map(item => ({ id: item,serviceName: this.serviceList.find(k => k.id === item).serviceName }))
          const tenantStartTime = tenantRangeTime && tenantRangeTime.length > 0 ? tenantRangeTime[0] + ' 00:00:00' : null
          const tenantEndTime = tenantRangeTime && tenantRangeTime.length > 0 ? tenantRangeTime[1] + ' 23:59:59' : null
          console.log('edit', Object.assign({}, this.formState, { tenantStartTime, tenantEndTime }))
          editTenantService(Object.assign({}, this.formState, { tenantStartTime, tenantEndTime })).then(() => {
            this.$modal.msgSuccess('保存成功')
            this.$emit('ok')
            this.handleCancel()
          }).finally(() => {
            this.loading = false
          })
        }
      })
    }
  }
}
</script>
