<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
    @cancel="handleClose"
    :paddingRight="15"
    :bodyStyle="{ minHeight: '400px !important' }"
  >
    <SimpleForm ref="formRef" :formProps="formProps" :formModel="state.formModel" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, reactive, watch } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { addMesProGroup, getMesProGroup, updateMesProGroup } from '/@/api/mes/mesprogroup';

  import { formProps } from './config';
  import { cloneDeep } from 'lodash-es';
  import SimpleForm from '/@/components/SimpleForm/src/SimpleForm.vue';

  const emit = defineEmits(['success', 'register']);

  const { notification } = useMessage();
  const { filterFormSchemaAuth } = usePermission();
  const formRef = ref();
  formProps.schemas = filterFormSchemaAuth(formProps.schemas!, false);
  const state = reactive({
    formModel: {},
    isUpdate: true,
    isView: false,
    rowId: '',
  });

  const { t } = useI18n();
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    state.isUpdate = !!data?.isUpdate;
    state.isView = !!data?.isView;

    setModalProps({
      destroyOnClose: true,
      maskClosable: false,
      showCancelBtn: !state.isView,
      showOkBtn: !state.isView,
      canFullscreen: true,
      width: 800,
    });
    const viewformProps = cloneDeep(formProps);
    setDisabled(viewformProps.schemas);
    formRef.value.setProps(state.isView ? viewformProps : formProps);

    if (state.isUpdate || state.isView) {
      const { updateSchema } = formRef.value;
      updateSchema({ field: 'isSysNum', componentProps: { disabled: true } });
      state.rowId = data.id;
      const record = await getMesProGroup(data.id);
      formRef.value.setFieldsValue(record);
    } else {
      const { updateSchema } = formRef.value;
      updateSchema({ field: 'isSysNum', componentProps: { disabled: false } });
      formRef.value.resetFields();
    }
  });

  const getTitle = computed(() => (state.isView ? '查看' : !state.isUpdate ? '新增' : '编辑'));

  watch(
    //增加子表单监听事件
    () => state.formModel.mesProGroupuserList,
    (newValue, oldValue) => {
      console.log(
        'mesProGroupuserList数组变化了：',
        newValue,
        oldValue,
        state.formModel.leaderUser,
      );
      state.formModel.userCount = newValue ? newValue.length : 0; //设置主表班组人数
      let leaderNum = 0;
      newValue.forEach((e) => {
        // console.log(e.leaderFlag == '1', 'e.leaderFlag');
        if (e.leaderFlag && e.leaderFlag == '1') {
          state.formModel.leaderUser = e.userId; //设置主表班组长
          leaderNum++;
        }
      });
      // console.log('leaderNum', leaderNum);
      if (leaderNum > 1) {
        notification.error({
          message: 'Tip',
          description: t('只能设置一个班组长'),
        }); //提示消息
      }
    },
    { deep: true },
  );

  function setDisabled(schemas) {
    const layoutComponents = ['tab', 'grid', 'card'];
    schemas?.map((info) => {
      if (layoutComponents.includes(info.type!)) {
        info.children?.map((childInfo) => {
          childInfo.list.map((com) => {
            if (layoutComponents.includes(com.type)) {
              setDisabled(childInfo.list);
            } else {
              com.dynamicDisabled = true;
            }
          });
        });
      } else if (info.type == 'one-for-one') {
        setDisabled(info.componentProps.childSchemas);
      } else {
        info.dynamicDisabled = true;
      }
    });
  }

  async function handleSubmit() {
    try {
      const values = await formRef.value?.validate();
      // console.log('state.formModel==', state.formModel);
      // //ifShow为false的隐藏字段重新赋值
      // values.leaderUser = state.formModel.leaderUser;
      // values.leaderNum = state.formModel.leaderNum;
      // values.mesProGroupuserList = state.formModel.mesProGroupuserList;
      // console.log('state.formModel==', values);

      //添加隐藏组件
      if (formProps.hiddenComponent?.length) {
        formProps.hiddenComponent.forEach((component) => {
          values[component.bindField] = component.value;
        });
      }
      setModalProps({ confirmLoading: true });

      // TODO custom api
      if (!state.isUpdate) {
        //false 新增
        await addMesProGroup(values);
        notification.success({
          message: 'Tip',
          description: t('新增成功！'),
        }); //提示消息
      } else {
        values.id = state.rowId;
        await updateMesProGroup(values);
        notification.success({
          message: 'Tip',
          description: t('修改成功！'),
        }); //提示消息
      }

      closeModal();
      formRef.value.resetFields();
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  function handleClose() {
    formRef.value.resetFields();
  }
</script>
