<template>
  <div class="page-modal">
    <el-dialog :title="title" v-model="dialogVisible" width="30%" center destroy-on-close>
      <jy-form v-bind="modalConfig" v-model="formData" ref="formRef">
        <template v-for="item in modalConfig.formItems" #[item.slot]>
          <template v-if="item.slot">
            <slot :name="item.slot"></slot>
          </template>
        </template>
      </jy-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleConfirmClick"> 确 定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
  import { defineComponent, nextTick, ref, watch } from 'vue';
  import useSystemStore from '@/store/main/system/system';

  import JyForm from '@/base-ui/form';
  import { loadRouteLocation } from 'vue-router';
import { ElMessage } from 'element-plus';

  export default defineComponent({
    components: {
      JyForm,
    },
    props: {
      // title: {
      //   type: String,
      //   default: '新建'
      // },
      mainKey: {
        type: String,
        default: '',
      },
      modalConfig: {
        type: Object,
        required: true,
      },
      defaultInfo: {
        type: Object,
        default: () => ({}),
      },
      otherInfo: {
        type: Object,
        default: () => ({}),
      },
      pageName: {
        type: String,
        require: true,
      },
      searchInfo: {
        type: Object,
        default: () => ({}),
      },
      dataProcessingFn: {
        // 用于请求前处理数据，必须要有返回值
        type: Function,
        default: (data) => {
          return data;
        },
      },
    },
    emits: ['submit','dataChange'],
    setup(props, { emit }) {
      const dialogVisible = ref(false);
      const slotName = ref('otherchildslot');
      const formData = ref({});
      const title = ref(props.title);
      const input = ref('');
      const mainKey = ref(props.mainKey);
      const hideTypeObj = ref(false);

      let pageInfo = ref();

      const formRef = ref();

      nextTick(() => {
        // formRef.value.show();
      });
      watch(
      () => formData.value,
      (newValue) => {
        console.log(newValue)
        emit('dataChange', newValue)
      }
    )
      watch(
        () => props.defaultInfo,
        (newValue) => {
          if (props.modalConfig.formItems) {
          }
          props.modalConfig.formItems.forEach((element) => {
            if (element.type === 'hideType') {
              console.log(props.defaultInfo);
              hideTypeObj.value = true;
            }
          });
          if (Object.keys(props.defaultInfo).length && !hideTypeObj.value) {
            if (props.modalConfig.editTitle) title.value = props.modalConfig.editTitle;
            else title.value = '编辑';
          } else {
            if (props.modalConfig.title) title.value = props.modalConfig.title;
            else title.value = '添加';
          }

          for (const item of props.modalConfig.formItems) {
            formData.value[`${item.field}`] = newValue[`${item.field}`];
            if (
              item.type === 'select' &&
              item.otherOptions?.multiple &&
              typeof newValue[`${item.field}`] === 'string'
            ) {
              formData.value[`${item.field}`] = newValue[`${item.field}`]?.split(',').map((o) => {
                if (isNaN(o)) return o;
                return Number(o);
              });
            }

            // 时间选择器为数组，把数据转换为数组
            if (item.type === 'datepicker' && item.fieldArray) {
              formData.value[`${item.field}`] = [newValue[`${item.fieldArray[0]}`], newValue[`${item.fieldArray[1]}`]];
            }
           
          }
        },
      );

      // 点击确定按钮的逻辑
      const handleConfirmClick = () => {
        formRef.value.ruleFormRef.validate((valid, fields) => {
          if (valid) {
            let form = props.dataProcessingFn({
              ...formData.value,
              ...props.otherInfo,
            });

            // 时间日期转换
            for (const item of props.modalConfig.formItems) {

              // 时间选择器为数组，把数据转换为数组
              if (item.type === 'datepicker') {

                if (item.fieldArray) {
                  form[`${item.fieldArray[0]}`] = item.resFormat ? item.resFormat(form[`${item.field}`][0]) : form[`${item.field}`][0]
                  form[`${item.fieldArray[1]}`] = item.resFormat ? item.resFormat(form[`${item.field}`][1]) : form[`${item.field}`][1]
                } else if (item.otherOptions.type === 'datetime' && item.resFormat) {
                  console.log(form[`${item.field}`], 'asfasdf')
                  form[`${item.field}`] = form[`${item.field}`] ? item.resFormat(form[`${item.field}`]) : ''
                }


              }
            }


            dialogVisible.value = false;
            //此处hideTypeObj是增加了页面表单不存在的字段，可在父级组件中，增加表单字段，type设置为hideType，newCallback方法中直接赋值defaultInfo的键值
            if (
              (Object.keys(props.defaultInfo).length && !hideTypeObj.value) ||
              (hideTypeObj.value && Object.keys(props.defaultInfo).length > 1)
            ) {
              // 编辑
              let mainField = mainKey.value;
              if (!mainField)
                mainField = props.pageName.split('/')[props.pageName.split('/').length - 1] + 'Id';

              
              
              let query = {
                pageName: props.pageName,
                editData: form,
                id: props.defaultInfo[mainField],
                idName: mainField,
                subimitLoding: props.modalConfig.subimitLoding,
                searchInfo: props.searchInfo,
              };

              if (pageInfo.value && pageInfo.value.currentPage) {
                query.pageNum = pageInfo.value.currentPage;
                query.pageSize = pageInfo.value.pageSize;
              }

              console.log(query, 'query');

              useSystemStore()
                .editPageDataAction(query)
                .then((res) => {
                  if (res.state && res.state === 'success') {
                    ElMessage.success('操作成功');
                    emit('submit', form);
                  } else {
                    ElMessage.error('操作失败');
                  }
                  
                });
            } else {
              // 新建
              let query = {
                pageName: props.pageName,
                newData: form,
                subimitLoding: props.modalConfig.subimitLoding,
              };

              if (pageInfo.value && pageInfo.value.currentPage) {
                query.pageNum = pageInfo.value.currentPage;
                query.pageSize = pageInfo.value.pageSize;
              }

              useSystemStore()
                .createPageDataAction(query)
                .then((res) => {
                  // emit('submit', form);
                  if (res.state && res.state === 'success') {
                    ElMessage.success('操作成功');
                    emit('submit', form);
                  } else {
                    ElMessage.error('操作失败');
                  }
                });
            }
          } else {
            ElMessage.error('操作失败');
            console.log('error submit!', fields);
          }
        });
      };

      return {
        pageInfo,
        hideTypeObj,
        title,
        input,
        formRef,
        slotName,
        dialogVisible,
        formData,
        handleConfirmClick,
      };
    },
  });
</script>

<style scoped></style>
