<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form';
import { useForm } from '@/hooks/web/useForm';
import { PropType, reactive, watch, ref } from 'vue';
import { useValidator } from '@/hooks/web/useValidator';
import { getCsckSystemList } from '@/api/common';
import dayjs from 'dayjs';
import { getNameByUserInfo } from '@/utils/auth';
import { formatToDateTime } from '@/utils/dateUtil';
import { ElMessage } from 'element-plus';
import { ListItem } from '@/api/dict/types';
import { isNotEmpty } from '@/utils/is';
const { required } = useValidator();

// const actionType = ref('add')

const props = defineProps({
  currentRow: {
    type: Object as PropType<any>,
    default: () => null,
  },
  actionType: {
    type: String,
    default: 'add',
  },
});
const systemList = ref<ListItem[]>([]);
const userName = getNameByUserInfo();
const dateTime = formatToDateTime();
getCsckSystemList().then(item => {
  systemList.value = item;
});
const sourceSystemCode = ref('');
const targetSystemCode = ref('');
const checkVersionName = ref('');
const formSchema = reactive<FormSchema[]>([
  {
    field: 'sourceSystemName',
    label: '源系统编码',
    component: 'Input',
    componentProps: {
      // disabled: actionType.value === 'update'
    },
    hidden: true,
    value: sourceSystemCode.value,
  },
  {
    field: 'sourceSystemCode',
    label: '源系统名称',
    component: 'Select',
    // optionApi:async () => {
    //   return await getCsckSystemList()
    // },
    componentProps: {
      options: systemList,
      disabled: props.actionType === 'edit',
      on: {
        change: async (value: string) => {
          const formData = await getFormData();
          let arr: string[] = [];
          const source = systemList.value.find(item => item.value === value);
          const target = isNotEmpty(formData.targetSystemCode) && isNotEmpty(formData.targetSystemName) ? formData.targetSystemCode + '(' + formData.targetSystemName + ')' : '';
          if (source) {
            setValues({
              sourceSystemName: source.label,
            });
            arr = [value + '(' + source.label + ')', target];
          } else {
            setValues({
              sourceSystemName: '',
            });
            arr = ['', target];
          }
          setValues({
            checkVersionName: arr.filter(item => !!item).join('--'),
          });
        },
      },
    },
  },
  {
    field: 'targetSystemName',
    label: '目标系统编码',
    component: 'Input',
    componentProps: {
      // disabled: props.actionType === 'edit',
    },
    hidden: true,
    value: targetSystemCode.value,
  },
  {
    field: 'targetSystemCode',
    label: '目标系统名称',
    component: 'Select',
    // optionApi:async () => {
    //   return await getCsckSystemList()
    // },
    componentProps: {
      options: systemList,
      disabled: props.actionType === 'edit',
      on: {
        change: async (value: string) => {
          const formData = await getFormData();
          let arr: string[] = [];
          const source = isNotEmpty(formData.sourceSystemCode) && isNotEmpty(formData.sourceSystemName) ? formData.sourceSystemCode + '(' + formData.sourceSystemName + ')' : '';
          const target = systemList.value.find(item => item.value === value);
          if (target) {
            setValues({
              targetSystemName: target.label,
            });
            arr = [source, value + '(' + target.label + ')'];
          } else {
            setValues({
              targetSystemName: '',
            });
            arr = [source, ''];
          }
          setValues({
            checkVersionName: arr.filter(item => !!item).join('--'),
          });
        },
      },
    },
  },
  {
    field: 'checkVersion',
    label: '校验版本号',
    component: 'Input',
    componentProps: {
      placeholder: '请输入校验版本号，版本格式: YYYYMMDD。例:[20220101]',
      disabled: props.actionType === 'edit',
    },
  },
  {
    field: 'checkVersionName',
    label: '校验版本名称',
    component: 'Input',
    componentProps: {
      // disabled: actionType.value === 'update'
    },
    value: checkVersionName.value,
  },
  // {
  //   field: 'reportName',
  //   label: '报表名称',
  //   component: 'Input',
  //   componentProps: {
  //     // disabled: actionType.value === 'update'
  //   }
  // },
  // {
  //   field: 'reportVersion',
  //   label: '报表版本号',
  //   component: 'Input',
  //   componentProps: {
  //     // disabled: actionType.value === 'update'
  //   }
  // },
  {
    field: 'startTime',
    label: '开始时间',
    component: 'DatePicker',
    componentProps: {},
  },
  {
    field: 'endTime',
    label: '结束时间',
    component: 'DatePicker',
    componentProps: {},
  },
  {
    field: 'createUser',
    label: '创建人',
    component: 'Input',
    componentProps: {
      disabled: true,
    },
    value: userName,
  },
  {
    field: 'createTime',
    label: '创建时间',
    component: 'DatePicker',
    componentProps: {
      disabled: true,
      type: 'datetime',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
    },
    value: dateTime,
  },
]);

const rules = reactive({
  component: [required()],
  path: [required()],
  sourceSystemCode: [required()],
  sourceSystemName: [required()],
  targetSystemCode: [required()],
  targetSystemName: [required()],
  checkVersion: [required()],
  checkVersionName: [required()],
  reportName: [required()],
  reportVersion: [required()],
  startTime: [required()],
  endTime: [required()],
  createUser: [required()],
  createTime: [required()],
});

const { formRegister, formMethods } = useForm();
const { setValues, getFormData, getElFormExpose } = formMethods;

const submit = async () => {
  const elForm = await getElFormExpose();
  const formData = await getFormData();
  const { startTime, endTime } = formData;
  const valid = await elForm?.validate().catch(err => {
    console.log(err);
  });
  if (dayjs(startTime).valueOf() > dayjs(endTime).valueOf()) {
    ElMessage.error('结束时间需大于开始时间!');
  } else {
    if (valid) {
      // formData.sourceSystemName = sourceSystemCode.value
      // formData.targetSystemName = targetSystemCode.value
      Object.assign(formData, { startTime: dayjs(startTime).format('YYYY-MM-DD') });
      Object.assign(formData, { endTime: dayjs(endTime).format('YYYY-MM-DD') });
      return formData;
    }
  }
};

watch(
  () => props.currentRow,
  currentRow => {
    if (!currentRow) return;
    // actionType.value = 'update'
    setValues(currentRow);
  },
  {
    deep: true,
    immediate: true,
  },
);

defineExpose({
  submit,
});
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="formSchema" />
</template>
