<template>
  <div>
    <button type="primary" size="default" @click="showModal" class="button">{{ title }}</button>
		<uni-drawer  ref="addOrSubSignRef" mode="right" :mask-click="false" width="80%" @change="handleVisible">
		  <scroll-view style="height: 100%;" scroll-y="true"> 		
				<view style="padding:0 10px 54px">
					<SimpleForm
						ref="formRef" 
						:formProps="formDataProps" 
						:isCustomForm="isCustomForm"
						@model-change="
							(val) => {
								simpformModal = val;
							}
						"
					/>
				</view>
			</scroll-view>
			<div class="form-btn-box">
				<button @tap="handleCancel" type="default" class="button">取消</button>
				<button @tap="handleConfirm" type="primary" class="button">确定</button> 
			</div>
		</uni-drawer> 
  </div>
</template>

<script lang="ts" setup>
  import { inject, ref } from 'vue'; 
 import SimpleForm from '@/components/simple-form/SimpleForm.vue';
  import { getModalManage } from '@/common/api/system/modalmanage/index.js';  
  import { buildAppFormProps,setFormPropsAuth } from '@/utils/simpleForm/changeJson.js';
import { apiConfigFunc } from '@/utils/helper/api.js';
	import { 
		camelCaseString
	} from '@/common/api/magic-api/useApiRequest.js'; 
  import { useUserStore } from "@/common/store/user";
  const userStore = useUserStore();

 
  const props = defineProps({
    title: String,
    innerParams: Array,
    outParams: Array,
    bindModal: String,
  });
  const emit = defineEmits(['open', 'close', 'confirm', 'cancel']);
 const addOrSubSignRef = ref();
  const mainformModel = inject('formModel');
  const isCustomForm = inject('isCustomForm', false);
  // const isCamelCase = inject<boolean>('isCamelCase', false);
  const formDataProps = ref({});
  const formModel = ref({});
  const formRef = ref();
  const simpformModal = ref();
 
  const showModal = async () => {
    if (props.bindModal) {
      let res  = await getModalManage(props.bindModal);

      if (res.data) {
        const { configJson } = res.data;

        let json = JSON.parse(configJson);

        let formJson = json.formJson;
        formDataProps.value = buildAppFormProps(formJson);
				console.log(formDataProps.value,isCustomForm,'formDataProps.value')
        props.innerParams?.forEach(async (o) => {
          let data = JSON.parse(o.component);
          if (data.table) {
            if (data.table.includes('child')) {
              if (!formModel.value[data.table + 'List']) {
                formModel.value[data.table + 'List'] = [{}];
              }
              if (data.field)
                formModel.value[data.table + 'List'][0][data.field] = await getData(o);
            } else {
              if (data.field) formModel.value[data.field] = await getData(o);
            }
          }
        });
				setFormPropsAuth(formDataProps.value.schemas,[],true)
      }
       addOrSubSignRef.value.open(); 
    } else {
      uni.showToast({
        title: '未绑定弹窗',
        duration: 2000,
				icon:'error'
      });
    }
  };
  function handleVisible(v) {
    //setTimeout(() => {
      if (v && formRef.value) {
        formRef.value.setFormData(formModel.value);
        emit('open', formModel.value);
      } else if (!v) {
        emit('close', simpformModal.value);
      }
  //  }, 300);
  }
  async function getData(data) {
    if (data.type == 'value') {
      return data.value;
    } else if (data.type == 'api') {
      return await apiConfigFunc(data.apiConfig, false, formModel.value);
    } else if (data.type == 'info') {
      return getUserInfo(data.value);
    } else if (data.type == 'form') {
      let json = JSON.parse(data.value);
      let newField = !isCustomForm && json.field ? camelCaseString(json.field) : json.field;
      if (json.table && mainformModel.value) {
        if (json.table.includes('child')) {
          let newTable = !isCustomForm ? camelCaseString(json.table + 'List') : json.table + 'List';
          if (mainformModel.value[newTable]) {
            return mainformModel.value[newTable][0][newField];
          }
        } else {
          if (newField) {
            return mainformModel.value[newField];
          }
        }
      }
    }
  }
  function handleConfirm() {
		console.log(simpformModal.value,props.outParams,'simpformModal.value')
    props.outParams?.forEach(async (o) => {
      let data = JSON.parse(o.component);
      let maindata = JSON.parse(o.mainComponent);
      if (data.table && mainformModel.value) {
        if (data.table.includes('child')) {
          if (simpformModal.value[data.table + 'List']) {
            setMainData(
              maindata.table,
              maindata.field,
              simpformModal.value[data.table + 'List'][0][data.field],
            );
          }
        } else {
          if (data.field) {
            setMainData(maindata.table, maindata.field, simpformModal.value[data.field]);
          }
        }
      }
    });
    emit('confirm',simpformModal.value);

    closeAddOrSubSign();
  }
  function handleCancel() {
    emit('cancel', simpformModal.value);
		closeAddOrSubSign();
  }
	function closeAddOrSubSign() {
	  addOrSubSignRef.value.close(); 
	}
  function setMainData(table, field, value) {
    let newField = !isCustomForm && field ? camelCaseString(field) : field;
    if (table.includes('child')) {
      let newTable = !isCustomForm ? camelCaseString(table + 'List') : table + 'List';
      if (!mainformModel.value[newTable]) {
        mainformModel.value[newTable] = [{}];
      }
      if (newField) mainformModel.value[newTable][0][newField] = value;
    } else {
      if (newField) mainformModel.value[newField] = value;
    }
  }

  function getUserInfo(val) {
    switch (val) {
      case '3-name':
        return userStore.getUserInfo.name;
      case '3-id':
        return userStore.getUserInfo.id;
      case '3-code':
        return userStore.getUserInfo.code;
      case '3-mobile':
        return userStore.getUserInfo.mobile;
      case '3-departmentName':
        return userStore.getUserInfo.departmentName;
      case '3-departmentId':
        return userStore.getUserInfo.departmentId;
      case '3-postId':
        return userStore.getUserInfo.postId;
      case '3-roleId':
        return userStore.getUserInfo.roleId;
    }
  }
</script>
<style scoped lang="scss">
 .button{
	 width: 120px;
	 margin: 0;
	 font-size: 14px;
 }
 .form-btn-box{
	 position: absolute;
	 .button{ 
		 line-height: 32px;
		 height: 32px;
	 }
 }
</style>