<!-- 编辑弹窗 -->
<template>
  <ele-modal
    :width="500"
    :visible="visible"
    :confirm-loading="loading"
    :title="isUpdate ? '修改' : '新建'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="styleResponsive ? { md: 6, sm: 6, xs: 24 } : { flex: '90px' }"
      :wrapper-col="
        styleResponsive ? { md: 18, sm: 20, xs: 24 } : { flex: '1' }
      "
    >
      <a-row :gutter="16">
        <a-col
          v-bind="styleResponsive ? { md: 22, sm: 24, xs: 24 } : { span: 12 }"
        >
          <a-form-item label="租赁单位" name="company">
            <SelectCompany
              :placeholder="`请选择租赁单位`"
              v-model:value="form.companyName"
              @done="chooseCompany"
            />
          </a-form-item>
          <a-form-item label="月租金" name="month">
            <a-input
              allow-clear
              placeholder="请输入月租金"
              v-model:value="form.month"
            />
          </a-form-item>
          <a-form-item label="月数" name="num">
            <a-input
              allow-clear
              placeholder="请输入租金"
              v-model:value="form.num"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { message } from 'ant-design-vue/es';
  import type { FormInstance, Rule } from 'ant-design-vue/es/form';
  import { storeToRefs } from 'pinia';
  import { useThemeStore } from '@/store/modules/theme';
  import useFormData from '@/utils/use-form-data';
  import type { TowerRent } from '@/api/tower/rent/model';
  import { addTowerRent, updateTowerRent } from '@/api/tower/rent';
  import { RuleObject } from 'ant-design-vue/es/form';

  // 是否开启响应式布局
  const themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: TowerRent | null;
  }>();

  const formRef = ref<FormInstance | null>(null);
  // 是否是修改
  const isUpdate = ref(false);
  // 提交状态
  const loading = ref(false);

  // 表单数据
  const { form, resetFields, assignFields } = useFormData<TowerRent>({
    rentId: undefined,
    rent: undefined,
    name: '',
    month: undefined,
    num: undefined,
    totalRent: '',
    companyName: '',
    image: '',
    status: 0,
    yearLife: undefined,
    sortNumber: 100
  });

  // 表单验证规则
  const rules = reactive<Record<string, Rule[]>>({
    company: [
      {
        required: true,
        message: '请选择租赁单位',
        type: 'string',
        trigger: 'blur',
        validator: async (_rule: RuleObject, value: string) => {
          console.log(value);
          if (form.companyName == '') {
            return Promise.reject('请选择租赁单位');
          }
          return Promise.resolve();
        }
      }
    ],
    name: [
      {
        required: true,
        message: '请输入名称',
        type: 'string',
        trigger: 'blur'
      }
    ],
    month: [
      {
        required: true,
        message: '请输入租金',
        type: 'string',
        trigger: 'blur'
      }
    ],
    num: [
      {
        required: true,
        message: '请输入月数',
        type: 'string',
        trigger: 'blur'
      }
    ],
    sortNumber: [
      {
        required: true,
        message: '请输入排序号',
        type: 'number',
        trigger: 'blur'
      }
    ]
  });

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const categoryForm = {
          ...form
        };
        const saveOrUpdate = isUpdate.value ? updateTowerRent : addTowerRent;
        saveOrUpdate(categoryForm)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  const chooseCompany = (row) => {
    console.log(row);
    form.companyName = row.companyName;
    form.companyId = row.companyId;
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          assignFields({
            ...props.data
          });
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
        formRef.value?.clearValidate();
      }
    }
  );
</script>

<style lang="less">
  .tab-pane {
    min-height: 300px;
  }
  .ml-10 {
    margin-left: 5px;
  }
</style>
