<!-- 编辑弹窗 -->
<template>
  <ele-modal
    :width="800"
    :visible="visible"
    :maskClosable="false"
    :maxable="maxable"
    :title="isUpdate ? '修复到期时间' : '修复到期时间'"
    :body-style="{ paddingBottom: '28px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="styleResponsive ? { md: 4, sm: 5, xs: 24 } : { flex: '90px' }"
      :wrapper-col="
        styleResponsive ? { md: 19, sm: 19, xs: 24 } : { flex: '1' }
      "
    >
      <a-form-item label="选择项目" name="appName">
        <a-select
          v-model:value="form.appName"
          show-search
          :disabled="isUpdate"
          :filter-option="false"
          style="width: 350px"
          placeholder="选择项目"
          :options="state.data"
          @search="fetchProject"
        >
          <template v-if="state.fetching" #notFoundContent>
            <a-spin size="small"/>
          </template>
        </a-select>
      </a-form-item>
      <a-form-item label="到期时间" name="expirationTime">
        <a-date-picker
          v-model:value="form.expirationTime"
          placeholder="修复到期时间"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </a-form-item>
      <a-form-item label="操作员" name="nickname">
        {{ loginUser.nickname }}
      </a-form-item>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
import {ref,computed, reactive, watch} from 'vue';
import {Form, message} from 'ant-design-vue';
import {assignObject} from 'ele-admin-pro';
import {useThemeStore} from '@/store/modules/theme';
import {storeToRefs} from 'pinia';
import {debounce} from 'lodash-es';
import {ItemType} from 'ele-admin-pro/es/ele-image-upload/types';
import {FormInstance} from 'ant-design-vue/es/form';
import {pageProject, updateProject} from "@/api/project/project";
import {Project} from "@/api/project/project/model";
import {listDictData} from "@/api/system/dict-data";
import {DictData} from "@/api/system/dict-data/model";
import {useUserStore} from "@/store/modules/user";

// 是否是修改
const isUpdate = ref(false);
const useForm = Form.useForm;
// 是否开启响应式布局
const themeStore = useThemeStore();
const {styleResponsive} = storeToRefs(themeStore);

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

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

// 提交状态
const loading = ref(false);
// 是否显示最大化切换按钮
const maxable = ref(true);
// 表格选中数据
const formRef = ref<FormInstance | null>(null);
const images = ref<ItemType[]>([]);
const durationDict = ref<DictData[]>([]);
const userStore = useUserStore();
const loginUser = computed(() => userStore.info ?? {});


// 用户信息
const form = reactive<Project>({
  appId: undefined,
  appName: undefined,
  expirationTime: undefined
});

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

// 表单验证规则
const rules = reactive({
  appName: [
    {
      required: true,
      type: 'string',
      message: '请选项项目',
      trigger: 'blur'
    }
  ],
  duration: [
    {
      required: true,
      type: 'number',
      message: '请选择续费时长',
      trigger: 'blur'
    }
  ],
  days: [
    {
      required: true,
      type: 'number',
      message: '请输入续费天数',
      trigger: 'blur'
    }
  ],
  payPrice: [
    {
      required: true,
      type: 'number',
      message: '请输入续费金额',
      trigger: 'blur'
    }
  ],
  payType: [
    {
      required: true,
      type: 'number',
      message: '请选择支付方式',
      trigger: 'blur'
    }
  ]
});

const {resetFields} = useForm(form, rules);

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

let lastFetchId = 0;

const state = reactive<any>({
  data: [],
  value: undefined,
  fetching: false,
});

const fetchProject = debounce(value => {
  lastFetchId += 1;
  const fetchId = lastFetchId;
  state.data = [];
  state.fetching = true;
  pageProject({keywords: value})
    .then(body => {
      if (fetchId !== lastFetchId) {
        return;
      }
      state.data = body?.list.map(d => {
        d.label = d.appName;
        d.value = d.appId;
        return d
      }) || [];
      state.fetching = false;
    });
}, 300);

watch(state.value, () => {
  state.data = [];
  state.fetching = false;
});

listDictData({dictCode:'ProjectDuration'}).then(res => {
  durationDict.value = res.map(d => {
    d.label = d.dictDataName;
    d.value = Number(d.dictDataCode);
    return d;
  });
})

watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      fetchProject(undefined)
      images.value = [];
      if (props.data) {
        assignObject(form, props.data);
        form.money = props.data.renewMoney;
        form.payPrice = props.data.renewMoney;
        form.totalPrice = props.data.renewMoney;
        form.expirationTime = props.data.expirationTime;
        if(!props.data.payType){
          form.payType = 402;
        }
        isUpdate.value = true;
      } else {
        isUpdate.value = false;
      }
    } else {
      resetFields();
    }
  },
  {immediate: true}
);
</script>
