<template>
  <div>
    <button type="primary" @click="showModal" class="button">{{ title }}</button>
		<custom-dialog  ref="addOrSubSignRef" :title="title" :hasCloseIcon="true" :hasFooterIcon="true" @close="handleVisible(false)"> 
		  <SimpleForm
		    ref="formRef" 
		    :formProps="formDataProps"
		    :isCustomForm="isCustomForm"
		    @model-change="
		      (val) => {
		        simpformModal = val;
		      }
		    "
		  />
		  <template #footer> 
				<div class="modal-btn-box">
					<button @tap="handleCancel" type="default" class="button">取消</button>
					<button @tap="handleConfirm" type="primary" class="button">确定</button> 
				</div>
		  </template>
		</custom-dialog> 
  </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 );
        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();
			 handleVisible(true)
    } else {
      uni.showToast({
        title: '未绑定弹窗',
        duration: 2000,
				icon:'error'
      });
    }
  };
  function handleVisible(v) {
		if(v){
			setTimeout(() => {
			  if (formRef.value) {
			    formRef.value.setFormData(formModel.value);
			    emit('open', formModel.value);
			  }   
			}, 300);
		}else if (!v) {
			emit('close', simpformModal.value);
		} 
  }
  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() {
    props.outParams?.forEach(async (o) => {
      let data = JSON.parse(o.component);
      let maindata = JSON.parse(o.mainComponent);
      if (data.table && mainformModel) {
        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();
		handleVisible(false)
	}
  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;
 } 
:deep(.wrap .dialog-box){
	 height: calc(90% - 30px);background: #fff;
 }
 :deep(.footer-box),
 :deep(.uni-scroll-view){ 
	 border-top: 1px solid #E7EBF2;
 }
 .example{
	 padding-bottom: 20px;
 }
 .modal-btn-box{
 	 display: flex;
	 justify-content: space-around;
	 padding: 10px 0;
 	 .button{ 
		 width: 150px;
 		 line-height: 32px;
 		 height: 32px;
 	 }
 }
</style>