<template>  
  <a-card class="custom-card" >
    <template v-if="!isTable" #title>
      <span @click="showTplList">
        {{ cardTitle }}
      </span>
    </template>
    <template v-if="!isTable" #extra>
      <a-button type="link" @click="handleSubmit" :loading="loading" :disabled="loading">保存</a-button>
      <a-button type="link" @click="setHistoryWidth" v-show="showHistoryButton">
        <div v-if="collapsed" class="trigger">显示历史</div>
        <div v-else class="trigger">隐藏历史</div>
      </a-button>
    </template>
    <template v-if="isTable">
      <a-tabs v-model:activeKey="activeKey" type="editable-card" @edit="onEdit" @change="handleChange">
        <template #leftExtra>
          <a-button type="link" block @click="showTplList">
            <MenuFoldOutlined class="trigger" />
          </a-button>
        </template>
        <template #addIcon>
          <a-button type="link" :disabled="addDisabled">
            <PlusOutlined style="font-size: '20px'" />
          </a-button>
        </template>
        <template #rightExtra>
          <a-button type="link" @click="handleTableSubmit" :loading="loading" :disabled="loading">保存</a-button>
          <a-button type="link" @click="setHistoryWidth" v-show="showHistoryButton">
            <div v-if="collapsed" class="trigger">显示历史</div>
            <div v-else class="trigger">隐藏历史</div>
          </a-button>
        </template>
        <a-tab-pane v-for="(pane, ind) in tabDatas" :key="ind" :tab="setTitle(ind)" :closable="activeKey * 1 == ind">
        </a-tab-pane>
      </a-tabs>
    </template>
    <div style="height:70vh;overflow-y:auto;margin:0 10px;">
      <vxe-form vertical auto-resize ref="formRef" :data="formData" :items="formItems" titleColon style="">
        <template #fileUpload="{ data,field }">
          <vxe-input v-model="data[field]" placeholder="" style="margin-right: 10px; flex-grow: 1;"></vxe-input>  
          <!-- <input type="file" @change="handleFileChange(data,field)" style="margin: 10px 0px;" />  
          <span v-if="data.fileName">{{ data.fileName }}</span> -->
          <BasicUpload :multiple="false" :maxSize="50" :maxNumber="10" @change="handleChangeUpload($event,data,field)" :api="uploadApi" style="margin: 10px;" :value="[data[field]]"/>
        </template>
      </vxe-form>
      <RecordHistory ref="refRecordHistory" @callback="callbackSetOldValue" v-show="showHistory"></RecordHistory>
    </div>
  </a-card>
</template>

<script lang="ts" setup>
import { PlusOutlined, MenuFoldOutlined } from '@ant-design/icons-vue';
import { ref, reactive, nextTick } from 'vue';
import { VXETable, VxeFormPropTypes } from 'vxe-table';
import { saveBatch, queryTaskRecords, deleteByPitemidAndRind, queryRecord,saveOrUpdate } from '../BaosongTaskRecord.api';
import RecordHistory from './RecordHistory.vue';
import { BasicUpload } from '/@/components/Upload';
import { uploadApi } from '/@/api/sys/upload';

const cardTitle = ref();
const formData = ref({});
const formItems = ref<VxeFormPropTypes.Items>([]);
const curTplItem = ref();
const maxRind = ref(0);
const curTask = ref();
const formRef = ref();
const tabDatas = ref([]);
const activeKey = ref(0);
const showHistoryButton = ref(false);
const collapsed = ref(true);
const addDisabled = ref(false);
const refRecordHistory = ref();
const showHistory = ref(false);
const loading = ref(false);
const isTable = ref(false);

const oldDataIdMap = ref({})

const emit = defineEmits(['showTplList', 'setHistoryWidth']);

const handleChangeUpload= async (retUrl,data,field) => {
  data[field] = retUrl
}

// const handleFileChange = async (data,field) => {
//   const file = event.target.files[0];
//   if (file) {
//     data.fileName = file.name;
//     data[field] =  file.name;
//     data.file = file; // 将文件对象绑定到 data 中
//     // 这里可以添加文件上传的逻辑
//     await uploadFile(file);
//   }
// };

// const uploadFile = async (file) => {
//   const formData = new FormData();
//   formData.append('file', file);
//   try {
//     const response = await fetch('/stm/sys/common/upload', {
//       method: 'POST',
//       body: formData,
//     });
//     const result = await response.json();
//     console.log('文件上传成功:', result);
//     VXETable.modal.message({ content: '文件上传成功', status: 'success' });
//   } catch (error) {
//     console.error('文件上传失败:', error);
//     VXETable.modal.message({ content: '文件上传失败', status: 'error' });
//   }
// };

const handleTableSubmit = async () => {
  try {
    addDisabled.value = false;
    let retFormData = {};
    retFormData["itempid"] = curTplItem.value.id;
    retFormData["tplid"] = curTplItem.value.tplid;
    retFormData["taskid"] = curTask.value.id;
    retFormData["datas"] = formRef.value.data;
    retFormData["rind"] = tabDatas.value[activeKey.value].rind;

    loading.value = true;
    setTimeout(async () => {
      let retData = await saveBatch(retFormData);
      tabDatas.value[activeKey.value]["datas"] = retData;
      VXETable.modal.message({ content: '保存成功', status: 'success' });
      loading.value = false;
    }, 1000);
  } catch (error) {
    loading.value = false;
    console.error("Error in remove:", error);
  }
};

const handleSubmit = async () => {
  try {
    let retFormData = {};
    retFormData["itempid"] = curTplItem.value.id;
    retFormData["tplid"] = curTplItem.value.tplid;
    retFormData["taskid"] = curTask.value.id;
    retFormData["datas"] = formRef.value.data;
    retFormData["rind"] = 1;

    loading.value = true;
    setTimeout(async () => {
      await saveBatch(retFormData);
      VXETable.modal.message({ content: '保存成功', status: 'success' });
      loading.value = false;
    }, 1000);
  } catch (error) {
    loading.value = false;
    console.error("Error in remove:", error);
  }
};

const handleReset = () => {
  formRef.value.reset();
};

function setTitle(ind) {
  return '行[' + (ind + 1) + ']';
}

const iniData = async (node, task) => {
  if (node.pid > 0 && isTable.value) return;
  isTable.value = node.formTp == 'table' ? true : false;
  maxRind.value = 0;
  curTask.value = task;
  curTplItem.value = node;
  if (!node.children) {
    return;
  };

  formData.value = {};
  cardTitle.value = "填写[" + node.title + "]";
  const tmpAry = node.children.map(createFormItem);
  tmpAry.forEach(ele => {
    if (ele.itemRender.name == "VxeCheckboxGroup") {
      formData.value[ele.field] = [];
    } else {
      formData.value[ele.field] = "";
    }
  });

  formItems.value = tmpAry;
  await setOldFormData(node, task);
  await nextTick();
  await refRecordHistory.value.iniData(null);
};

const iniTableData = async (node, task) => {
  addDisabled.value = false;
  isTable.value = node.formTp == 'table' ? true : false;
  maxRind.value = 0;
  curTask.value = task;
  curTplItem.value = node;
  if (!node.children) {
    return;
  };

  formData.value = {};
  cardTitle.value = "填写[" + node.title + "]";
  const tmpAry = node.children.map(createFormItem);
  tmpAry.forEach(ele => {
    if (ele.itemRender.name == "VxeCheckboxGroup") {
      formData.value[ele.field] = [];
    } else {
      formData.value[ele.field] = "";
    }
  });

  await setExistDatas();

  formItems.value = tmpAry;
  handleChange(0);
  let maxRindItem = await getMaxRind(tabDatas.value);
  maxRind.value = maxRindItem.rind;
  await nextTick();
  await refRecordHistory.value.iniData(null);
};

const iniDataSingle = async (node, task) => {

  curTask.value = task;
  addDisabled.value = true;
  const formItem = await createFormItem(node);

  formItems.value = [formItem];
  await nextTick();
  await refRecordHistory.value.iniData(node,task);
};

const createFormItem = (ele) => {
  let itemRender;
  switch (ele.formTp) {
    case 'number':
    case 'input':
      itemRender = {
        name: 'VxeInput',
        props: {
          type: ele.tp === "number" ? "number" : undefined,
          placeholder: '请输入' + (ele.tp === "number" ? "数字,单位[" + ele.unit + "]" : "文本"),
          min:0
        },
        events: {
          change: ({data,field})  => {
            validataSingle(data[field])
            
          }
        }
      };
      break;
    case 'textarea':
      itemRender = {
        name: 'VxeTextarea',
        props: {
          placeholder: '请输入',
          rows: 4
        }
      };
      break;
    case 'date':
      itemRender = {
        name: 'VxeInput',
        props: { type: 'date', placeholder: '选择日期' }
      };
      break;
    case 'yesno':
      itemRender = {
        name: 'VxeRadioGroup',
        options: [{ label: '是', value: '是' }, { label: '否', value: '否' }],
        props: {
          style: {
            display: 'flex',
            flexDirection: 'row',
            flexWrap: 'wrap',
            alignItems: 'flex-start',
            gap: '10px',
            marginLeft: '15px',
            padding: '5px'
          },
        },
      };
      break;
    case 'radio':
      itemRender = {
        name: 'VxeRadioGroup',
        options: setOptions(ele.options),
        props: {
          style: {
            display: 'flex',
            flexDirection: 'column',
            flexWrap: 'wrap',
            alignItems: 'flex-start',
            gap: '5px',
            marginLeft: '15px',
            padding: '5px'
          },
        },
      };
      break;
    case 'checkbox':
      itemRender = {
        name: 'VxeCheckboxGroup',
        options: setOptions(ele.options),
        props: {
          style: {
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'flex-start',
            marginLeft: '15px',
            flexWrap: 'wrap',
            gap: '5px',
            padding: '5px'
          },
        },
      };
      break;
    case 'upload':
      itemRender = {
        name: null,
        slots: { default: 'fileUpload' },
        props: {
          placeholder: '请输入upload',
          rows: 4
        }
      };
      break;
    default:
      itemRender = {
        name: 'VxeInput',
        props: { placeholder: '请输入' }
      };
      break;
  }

  if(ele.formTp=="upload") {
    let retUpload = {
        slots: { default: 'fileUpload' },
        field: ele.id + "_" + ele.code,
        title: "文件上传",
        span: 24,
        itemRender: {},
      };
      return retUpload
  }


  let tmpTitle = ele.tp == 'number' ? ele.title + "，单位[" + ele.unit + "]" : ele.title;
  let retData = {
    field: ele.id + "_" + ele.code,
    title: tmpTitle,
    span: 24,
    itemRender: itemRender,
  };

  if (ele.childNum > 0 && Array.isArray(ele.children)) {
    retData.children = ele.children.map(child => createFormItem(child));
  }

  return retData;
};

const setOptions = (params) => {
  return params.split(/\r\n|\r|\n/).map(item => ({
    value: item.trim(),
    label: item.trim()
  }));
};

const setExistDatas = async () => {
  const params = {
    itempid: curTplItem.value.id,
    taskid: curTask.value.id
  };
  const retDatas = await queryTaskRecords(params);
  tabDatas.value = [];
  if (!retDatas || retDatas.length == 0 || !Array.isArray(retDatas)) {
    add();
    return;
  }

  const groupedData = retDatas.reduce((acc, item) => {
    const key = item.rind;
    if (!acc[key]) {
      acc[key] = [];
    }
    acc[key].push(item);
    return acc;
  }, {});

  let tabIndex = 0;
  for (const key of Object.keys(groupedData)) {
    tabDatas.value.push({
      key: tabIndex,
      rind: key,
      datas: groupedData[key]
    });
    tabIndex++;
  }
};

const handleChange = async (curKey) => {
  activeKey.value = curKey;
  handleReset();
  const tab = tabDatas.value[curKey];
  if (!tab || !tab.datas || !Array.isArray(tab.datas)) return;
  tab.datas.forEach(record => {
    setFormDataOldVale(record);
  });
};

const onEdit = async (targetKey: number, action: string) => {
  try {
    if (action === 'add') {
      add();
    } else if (action === 'remove') {
      remove(targetKey);
    }
  } catch (error) {
    console.error("Error in onEdit:", error);
  }
};

const add = async () => {
  handleReset();
  const currentTabCount = tabDatas.value.length;
  activeKey.value = currentTabCount;
  maxRind.value++;
  tabDatas.value.push({
    key: currentTabCount,
    datas: [],
    rind: maxRind.value
  });
};

const remove = async (targetKey: number) => {
  let rind = tabDatas.value[targetKey].rind;
  let taskid = curTask.value.id;
  let itempid = curTplItem.value.id;
  if (!itempid || !taskid || !rind) {
    return;
  }

  let params = {};
  await deleteByPitemidAndRind(params, function () {
    tabDatas.value.splice(targetKey, 1);
    handleReset();
  });
};

const getMaxRind = async (array) => {
  if (!array || array.length == 0) {
    return 0;
  }
  return array.reduce((max, current) => {
    return (current.rind > max.rind) ? current : max;
  }, array[0]);
};

const setOldFormData = async (node, task) => {
  curTask.value = task;
  curTplItem.value = node;
  const params = {
    itempid: curTplItem.value.id,
    taskid: curTask.value.id
  };
  const oldDatas = await queryTaskRecords(params);

  oldDatas.forEach(record => {
    setFormDataOldVale(record);
  });
};

const callbackSetOldValue = (oldData) => {
  setFormDataOldVale(oldData);
};

const setFormDataOldVale = (record) => {
  if (!record.content) return "";
  const key = `${record.itemid}_${record.tplcode}`;
  if (Array.isArray(formData.value[key])) {
    formData.value[key] = record.content.split(",") || [];
  } else {
    formData.value[key] = record.content;
  }

  oldDataIdMap.value[key] = record.id
};

function showTplList() {
  emit("showTplList");
}

function setHistoryWidth() {
  collapsed.value = !collapsed.value;
  emit("setHistoryWidth");
}

function setHistorySta(sta, isHide) {
  showHistoryButton.value = isHide;
  collapsed.value = sta;
}

async function clearData() {

  handleReset();
  formData.value = {};
  formItems.value = [];
  //cardTitle.value = "";

}


const validataSingle = async (val) => {
  await refRecordHistory.value.validata(val);
};

const copyHistoryValue = async (hisData) => {
  setFormDataOldVale(hisData);
};


defineExpose({
  iniData,
  iniDataSingle,
  iniTableData,
  setHistorySta,
  clearData,
  copyHistoryValue
});
</script>

<style scoped>
.custom-card-header {
  background-color: #f0f2f5;
  padding: 16px;
  font-weight: bold;
  height: 100%;
}

::v-deep .vxe-radio:not(.vxe-radio-button)+.vxe-radio {
  margin-left: 0;
}

::v-deep .vxe-checkbox:not(.vxe-checkbox-button)+.vxe-checkbox {
  margin-left: 0;
}
</style>