<template>
  <a-tabs v-model:activeKey="activeKey" :size="size" type="editable-card" @edit="onEdit" @change="handleChange">
    <a-tab-pane v-for="(pane, ind) in panes" :key="ind" :tab="setTitle(ind)" :closable="activeKey * 1 == ind && !isDetail">
    </a-tab-pane>
  </a-tabs>
  <BasicForm ref="refForms" @register="registerForm" :disabled="isDetail">
    <template #viewRecord="{ field }">
      <AuditMutiRowForm ref="refViewRecord" />
    </template>
    <template #viewRule="{ field }">
      <AuditMutiRowForm ref="refViewRule" />
    </template>
    <template #viewTool="{ field }">
      <AuditMutiRowForm ref="refViewTool" />
    </template>
    <template #viewFlow="{ field }">
      <AuditMutiRowForm ref="refViewFlow" />
    </template>
  </BasicForm>
</template>

<script lang="ts" setup>
  import { ref, reactive, nextTick, defineProps } from 'vue';
  import { FormSchema } from '/@/components/Table';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getActByIds } from '../api/AuditAct.api';
  import type { TabsProps } from 'ant-design-vue';
  import AuditMutiRowForm from './AuditMutiRowForm.vue';
  import { cloneDeep } from 'lodash-es';

  const size = ref<TabsProps['size']>('small');
  const { createConfirm } = useMessage();
  const emit = defineEmits(['register', 'success']);
  const oldInd = ref(0);
  const refViewRecord = ref();
  const refViewRule = ref();
  const refViewTool = ref()
  const refViewFlow = ref()

  const ctiemid = ref();

  defineProps({
    isUpdate: {
      type: Boolean,
      default: true,
    },
    isDetail: {
      type: Boolean,
      default: false,
    },
  });

  interface FormValue {  
      content: string;  
      des: string;   
      actIds: string[];   
      citemid: number;  
      id: number;
      checkMethodItems:[];
      deleteMethodItems:[];
  } 

  const formSchemaCheck: FormSchema[] = [
    {
      label: '检查内容',
      field: 'content',
      component: 'InputTextArea',
      componentProps: {
        rows: 2,
        showCount: true,
        maxlength: 1024,
      },
      required: false,
    },
    {
      label: '备注',
      field: 'des',
      component: 'InputTextArea',
      componentProps: {
        rows: 3,
        showCount: true,
        maxlength: 1024,
      },
    },
    {
      label: '控制项',
      field: 'actIds',
      component: 'JCaSelect',
    },
    {
      label: '制度要求',
      field: 'viewRule',
      component: 'InputTextArea',
      slot:'viewRule'
    },
    {
      label: '记录要求',
      field: 'viewRecord',
      component: 'InputTextArea',
      slot:'viewRecord'
    },
    {
      label: '工具要求',
      field: 'viewTool',
      component: 'InputTextArea',
      slot:'viewTool'
    },
    {
      label: '流程要求',
      field: 'viewFlow',
      component: 'InputTextArea',
      slot:'viewFlow'
    },
    {
      label: 'id',
      field: 'id',
      component: 'Input',
      show: false,
    },
    {
      label: 'citemid',
      field: 'citemid',
      component: 'Input',
      show: false,
    },
    {
      label: 'checkid',
      field: 'checkid',
      component: 'Input',
      show: false,
    },
    {
      label: '',
      field: 'checkMethodItems',
      component: 'Input',
      show: false,
    },
  ];

  const [registerForm, { setProps, resetFields, setFieldsValue, validate }] = useForm({
    schemas: formSchemaCheck,
    showActionButtonGroup: false,
    submitButtonOptions: {},
    showResetButton: false,
  });

  const panes = ref<{ title: string; content: FormValue;  key: number; closable?: boolean;}[] >([]);

  const activeKey = ref(0);

  const add = (content) => {   
    const newKey = panes.value.length;  
    panes.value.push({ title: '', content, key: newKey });  
    activeKey.value = newKey;  
    setFieldsValue({ "citemid": ctiemid.value });  
  };

  const remove = async (targetKey: number) => {  
    try {  
        createConfirm({  
            iconType: 'warning',  
            title: '确认删除',  
            content: '是否删除选中数据',  
            okText: '确认',  
            cancelText: '取消',  
            onOk: async () => {  
                await resetFields();  
                if (panes.value.length === 1) {  
                    activeKey.value = 0;  
                    return;  
                }  
                panes.value.splice(targetKey, 1);  
                oldInd.value = activeKey.value = Math.max(0, targetKey - 1);  
                const newObj = panes.value[activeKey.value]?.content || {};  
                await setActData(newObj);  
                await setFieldsValue({ ...newObj });  
                const checkMethodItems = await groupByTp(newObj.checkMethodItems);  
                await resetViews(newObj.id, checkMethodItems);  
            },  
        });  
        } catch (error) {  
            console.error("Error in remove:", error);   
        }  
    };

  const onEdit = async (targetKey: number, action: string) => {  
    try {  
        if (action === 'add') {  
            const values = await validate();  
            await setItemViews(values);  
            resetFields();  
            add({});  
            resetViews('');  
            oldInd.value = activeKey.value;  
        } else if (action === 'remove') {  
            remove(targetKey);  
        }  
    } catch (error) {  
        console.error("Error in onEdit:", error);  
    }  
  };

  async function setData(datas: any[], itemid: number) {  
    try {  

        await resetFields();  
        ctiemid.value = itemid;
        panes.value = [];
        oldInd.value = 0; 
        if (!datas || datas.length === 0) {  
            add({});  
        } else {   
            datas.forEach(add);  
        }  
        activeKey.value = 0; 
        const firstObj = { ...panes.value[activeKey.value].content };
        const checkid = firstObj.id;  
        if (firstObj.actIds) {  
            const actIds = firstObj.actIds.split(',').map(Number);  
            const caNams = firstObj.caName?.split(',') || []; 
            firstObj['actIds'] = [caNams, actIds];  
        } 

        await setFieldsValue(firstObj);  
        const checkMethodItems = await groupByTp(firstObj.checkMethodItems);  
        await resetViews(checkid, checkMethodItems);  
    } catch (error) {  
        console.error("Error in setData:", error);   
    }  
  }

 async function groupByTp(itemViews) {  
    return itemViews?.reduce((acc, item) => {  
        if (!acc[item.tp]) {  
            acc[item.tp] = [];  
        }  
        acc[item.tp].push(item);  
        return acc;  
    }, {}) || {};  
  }  

  async function resetViews(checkid, itemViews = {}) {  
      refViewTool.value.setData(itemViews[1] || [], 1, checkid);  
      refViewRecord.value.setData(itemViews[2] || [], 2, checkid);  
      refViewRule.value.setData(itemViews[3] || [], 3, checkid);  
      refViewFlow.value.setData(itemViews[6] || [], 6, checkid);  
  }

  async function getData() {  
    try {  
        const values = await validate();  
        await setItemViews(values);  
        let retData: FormValue[] = []; 
        panes.value.forEach(item => {  
            if (item.content && item.content.content) {  
                retData.push(item.content);  
            }  
        });  
        return retData.length === 0 ? null : retData;  
    } catch (error) {  
        console.error("Error fetching data:", error);  
        return null; 
    }  
  }

  async function handleChange(curInd: number) { 
    try {  
        const values = await validate();  
        await setItemViews(values);  
        const newObj = cloneDeep(panes.value[curInd].content);  
        const checkid = newObj.id;  
        if (newObj.actIds) {  
            const actIds = newObj.actIds.split(',').map(Number);  
            if (newObj.caName) {  
                const caNames = newObj.caName.split(',');  
                newObj['actIds'] = [caNames, actIds];  
            } else {  
                await setActData(newObj);  
            }  
        }  else {
          await resetFields()
        }
        nextTick(async () => {  
            try {  
              await setFieldsValue(newObj);  
              const checkMethodItems = await groupByTp(newObj.checkMethodItems);  
              await resetViews(checkid, checkMethodItems);  
            } catch (error) {  
                console.error("Error in nextTick:", error);  
            }  
        });  
        oldInd.value = curInd;  
    } catch (error) {  
        console.error("Error in handleChange:", error);  
    }  
}


  function setTitle(ind) {
    return '检查项[' + (ind + 1) + ']';
  }

  async function setActData(newObj) {
    let ids = newObj.actIds;
    if (!ids) return;
    let retActs = await getActByIds({ ids: ids });
    if (Array.isArray(retActs)) {
      let newIdAry = [];
      let newCaNames = [];
      retActs.forEach(function (item) {
        newIdAry.push(item.id);
        newCaNames.push(item.caName);
      });
      newObj['actIds'] = [newCaNames, newIdAry];
    }
  }

  async function clearForm() {
    await resetFields();
    await resetViews('')
  }

  function mergeArrays(...arrays) {
    return arrays.reduce((accumulator, currentArray) => {
      if (Array.isArray(currentArray)) {
        return accumulator.concat(currentArray);
      }
      return accumulator;
    }, []);
  }

 
  async function setItemViews(formVal) {  
    try {  
        const viewRecord = await refViewRecord.value.getData();  
        const viewRule = await refViewRule.value.getData();  
        const viewTool = await refViewTool.value.getData();   
        const viewFlow = await refViewFlow.value.getData(); 
        const newCheckItems = await mergeArrays(  
            viewRecord['fullData'],   
            viewRule['fullData'],   
            viewTool['fullData'],
            viewFlow['fullData']    
        );   
        const nonEmptyItems = newCheckItems.filter(item =>   
            item.name.trim() !== '' || item.des.trim() !== ''  
        );  
        if (nonEmptyItems.length > 0) {   
            const newAry = nonEmptyItems.map(item => ({  
                id: item.id,  
                name: item.name,  
                tp: item.tp,  
                checkid: item.checkid,  
                des: item.des  
            })); 
            formVal["checkMethodItems"]  = newAry
        }  
        panes.value[oldInd.value].content = formVal
    } catch (error) {  
        console.error("Error in setItemViews:", error);  
    }  
  } 

  function setDetail(isDisabled) {
    refViewTool.value.setReadonly(isDisabled);
    refViewRecord.value.setReadonly(isDisabled);
    refViewRule.value.setReadonly(isDisabled);
    refViewFlow.value.setReadonly(isDisabled);
  }

  defineExpose({
    setData,
    getData,
    clearForm,
    setDetail
  });
</script>

<style lang="less" scoped>
  :deep(.ant-input-number) {
    width: 100%;
  }

  :deep(.ant-calendar-picker) {
    width: 100%;
  }
</style>
