<template>
  <el-drawer v-model="isDrawer" :size="width" :title="title" @close="handleReset">
    <el-form
      :model="formParams"
      :rules="rules"
      ref="formRef"
      label-placement="left"
      :label-width="80"
    >
      <el-form-item label="租户编码" prop="tenantCode">
        <el-input placeholder="请输入租户编码" v-model="formParams.tenantCode" />
      </el-form-item>
      <el-form-item label="租户名称" prop="tenantName">
        <el-input placeholder="请输入租户名称" v-model="formParams.tenantName" />
      </el-form-item>
      <el-form-item label="开始时间" prop="beginDate">
        <el-date-picker
          v-model="formParams.beginDate"
          type="datetime"
          clearable
          placeholder="请选择开始时间"
          :disabled-date="handleDisabledBeginDate"
        />
      </el-form-item>
      <el-form-item label="结束时间" prop="endDate">
        <el-date-picker
          v-model="formParams.endDate"
          type="datetime"
          clearable
          placeholder="请选择结束时间"
          :disabled-date="handleDisabledEndDate"
        />
      </el-form-item>
      <el-form-item label="状态" prop="tenantStatus">
        <el-radio-group v-model="formParams.tenantStatus" name="tenantStatusGroup">
          <el-radio-button :key="0" :label="0">启用</el-radio-button>
          <el-radio-button :key="1" :label="1">禁用</el-radio-button>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-space size="middle">
        <el-button @click="handleReset">重置</el-button>
        <el-button type="primary" :loading="subLoading" @click="formSubmit">提交</el-button>
      </el-space>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
  import { ref, onMounted } from 'vue';
  import { ElMessage, ElSpace } from 'element-plus';
  import type { FormRules } from 'element-plus';
  import type { formParamsType } from './types';
  import { cloneDeep } from 'lodash-es';
  import { addTenant, editTenant, tenantInfo } from '@/api/tenant/index';
  import { formatToDateTime } from '@/utils/dateUtil';
  import dayjs, { Dayjs } from 'dayjs';

  const rules: FormRules = {
    tenantCode: {
      required: true,
      message: '请填写租户编码',
      trigger: 'blur',
    },
    tenantName: {
      required: true,
      message: '请填写租户名称',
      trigger: 'blur',
    },
    beginDate: {
      required: true,
      message: '请选择开始时间',
      trigger: 'change',
      type: 'date',
    },
    endDate: {
      required: true,
      message: '请选择结束时间',
      trigger: 'change',
      type: 'date',
    },
  };

  const emit = defineEmits(['change']);

  defineProps({
    title: {
      type: String,
      default: '添加租户',
    },
    width: {
      type: Number,
      default: 450,
    },
    permissionList: {
      type: Array,
    },
  });

  const defaultValueRef = () => ({
    tenantId: undefined,
    beginDate: undefined,
    endDate: undefined,
    tenantCode: '',
    tenantStatus: 0,
    tenantName: '',
  });

  const message = ElMessage;
  const formRef: any = ref(null);
  const isDrawer = ref(false);
  const subLoading = ref(false);

  const formParams = ref<formParamsType>(defaultValueRef());

  function openDrawer(tenantId?) {
    if (tenantId) {
      formParams.value.tenantId = tenantId;
      getInfo();
      return;
    }
    isDrawer.value = true;
  }

  function closeDrawer() {
    isDrawer.value = false;
  }

  function formSubmit() {
    formRef.value.validate((valid) => {
      if (!valid) {
        return message.error('请填写完整信息');
      }
      const params = cloneDeep(formParams.value);
      params.beginDate = formatToDateTime(params.beginDate || '', 'YYYY-MM-DD HH:mm:ss');
      params.endDate = formatToDateTime(params.endDate || '', 'YYYY-MM-DD HH:mm:ss');
      if (formParams.value.tenantId) {
        editTenant(params).then((_) => {
          message.success('编辑成功');
          emit('change');
          handleReset();
          closeDrawer();
        });
      } else {
        addTenant(params).then((_) => {
          message.success('添加成功');
          emit('change');
          handleReset();
          closeDrawer();
        });
      }
    });
  }

  function handleReset() {
    formRef.value.resetFields();
    formParams.value = Object.assign(formParams.value, defaultValueRef());
  }

  function getInfo() {
    tenantInfo({ id: formParams.value.tenantId }).then((res) => {
      const info = {
        tenantId: res.tenantId,
        tenantName: res.tenantName,
        tenantCode: res.tenantCode,
        beginDate: new Date(res.beginDate).toString(),
        endDate: new Date(res.endDate).toString(),
        tenantStatus: res.tenantStatus,
      };
      formParams.value = info;
      isDrawer.value = true;
    });
  }

  const handleDisabledBeginDate = (currentDate: Date) => {
    const endDate = formParams.value.endDate;
    if (!endDate) return false;
    return !dayjs(currentDate).isBefore(endDate, 'day');
  };

  const handleDisabledEndDate = (currentDate: Date) => {
    const beginDate = formParams.value.beginDate;
    if (!beginDate) return false;
    return !dayjs(currentDate).isAfter(beginDate, 'day');
  };

  defineExpose({
    openDrawer,
    closeDrawer,
  });
</script>
