<template>
  <div>
    <!-- <vxe-grid v-bind="gridOptions"  :ref="el => setTableRef(el)" > -->
    <vxe-grid v-bind="gridOptions"  ref="refGrid">
      <template #form_default="{row,column }">
        <template v-if="row[column.field].formType=='number'">
          <vxe-input v-model="formData[row[column.field].field]" width="100%" class="tight-input" type="number" @change="handleInputChange($event, row, column)"></vxe-input>
          <span class="unit"> {{row[column?.field]?.unit }}</span>
        </template>
        <template v-else-if="row[column.field].formType=='date'">
          <vxe-input v-model="formData[row[column.field].field]" width="100%" class="tight-input" type="date"></vxe-input>
        </template>
 
        <template v-else-if="row[column.field].formType=='radio-group'">  
          <vxe-radio-group  v-model="formData[row[column.field].field]">
            <vxe-radio v-for="(opt, optIndex) in row[column.field].options" :key="optIndex" :label="opt">{{ opt }}</vxe-radio>
          </vxe-radio-group>
        </template>
        <template v-else-if="row[column.field].formType=='checkbox-group'">
          <vxe-checkbox-group  v-model="formData[row[column.field].field]">
            <vxe-checkbox v-for="(opt, optIndex) in row[column.field].options" :key="optIndex" :label="opt">{{ opt }}</vxe-checkbox>
          </vxe-checkbox-group>
        </template>
        <template v-else-if="row[column.field].formType=='textarea'">
          <vxe-textarea v-model="formData[row[column.field].field]" :row="3"></vxe-textarea>
        </template>
        <template v-else-if="row[column.field].formType=='yesno'">
          <vxe-radio-group  v-model="formData[row[column.field].field]">
            <vxe-radio label="是">是</vxe-radio>
            <vxe-radio label="否">否</vxe-radio>
          </vxe-radio-group>
        </template>
        <template v-else>
          <vxe-input
              v-model="formData[row[column.field]?.field]"
              width="100%"
              class="tight-input"
              :type="row[column.field]?.formType"
            ></vxe-input>
        </template>
      </template>
      <template #toolbar_buttons>
        {{title}}
        <!-- <vxe-button mode="text" status="primary" content="获取数据" @click="getFormData()"></vxe-button> -->
      </template>
      <template #action="{ row,rowIndex}">
          <vxe-button mode="text" status="primary" icon="vxe-icon-add" @click="insertRow(row,rowIndex)"></vxe-button>
          <vxe-button mode="text" status="error" icon="vxe-icon-delete" @click="removeRow(row,rowIndex)"></vxe-button>
      </template>
    </vxe-grid>
  </div>
</template>

<script lang="ts" setup>
import { reactive,ref } from 'vue'
import type { VxeGridProps } from 'vxe-table'
import { handleChange } from '/@/views/project/plan/StPlanMan.api'


const tableRefs = ref<any[]>([])

const formData = reactive({})

interface RowVO {
  name: string
  role: string
  sex: string
  age: number
  content: string
}

interface FieldInfo {
  itemid: number
  itempid: number
  pcode:number
  code: string
  title: string
  formTp?: string
  options?: string
  tp?: string
  unit?: string
  formType?: string
  field?: string
  name?: string
}

const props = defineProps({
  title: String,

  records: {
    type: Array as () => RowVO[],
    default: () => []
  },
  fields: {
    type: Array as () => FieldInfo[],
    required: true
  },
  columnsPerRow: {
    type: Number,
    default: 6
  },
  showHeader:{
    type:Boolean,
    default:true
  },
  showFooter:{
    type:Boolean,
    default:false
  },
  mergeCells:{
    type: Array as () => RowVO[],
    default: () => []
  },
  calcSum:{
    type: Object as ()=>{
      tp:boolean,
      rows:{},
    },
    default: () => []
  }

})


const gridOptions = reactive<VxeGridProps<RowVO>>({
  size:"small",
  rowConfig: {
    useKey: true,
    resizable:true
  },
  columnConfig: {
    useKey: true,
    resizable:true
  },
  showHeader:props.showHeader,
  columns: props.fields,
  data: props.records,
  toolbarConfig: {
      refresh: true,
      zoom: true,
      custom: true,
      export: true,
      print: false,
      slots: {
        buttons: 'toolbar_buttons',
      },
    },
    mergeCells:props.mergeCells
})

// 设置表格引用
// const setTableRef = (el: any) => {
//   if (el) {
//     tableRefs.value = el
//   }
// }


const refGrid = ref();

const getFormData = () => {
  cancelRow();
  return formData
}

const setFormData = (dataVale) => {
 Object.assign(formData, dataVale);  
}

const insertRow = async (row,ind) => {
  gridOptions.data?.splice(ind, 0, row);
}

const removeRow = async (row,ind) => {
  gridOptions.data?.splice(ind,1);
}

const handleInputChange = (value: any, row: RowVO, column: RowVO) => {
  //formData[row[column.field].field] = value;
  calculateRowTotals(row);
  if (props.showFooter) {
    calculateColumnTotal(gridOptions.data,column.field);
    //debugger;
  }
};

const calculateRowTotals = (currentRow: RowVO) => {
  if (!props.calcSum?.rows) return;
  Object.entries(props.calcSum.rows).forEach(([sumKey, sourceFields]) => {
    const total = sourceFields.reduce((sum, field) => {
      const value = parseFloat(formData[currentRow[field].field] || 0);
      return sum + value;
    }, 0);
    formData[currentRow[sumKey].field] = total;
  });
};


const calculateColumnTotal = (list: RowVO[], field: string) => {
  let count = 0
  for(let i=0;i<list.length-1;i++) {
    count += parseFloat(formData[list[i][field]["field"]] || 0);
  }
  const lastRow = list[list.length-1];
  formData[lastRow[field].field] = count
}

const cancelRow = async () => {
  const $grid = refGrid.value
  if (!$grid) {
    return
  }
  await $grid.clearEdit()
}

defineExpose({
  getFormData,
  setFormData
})

</script>

<style lang="less" scoped>
.tight-input {
  border: 1;
  height: 45px;
  border-radius: 0;
  margin: 0px;
  padding: 0px;
}

:deep(.vxe-body--column) {
  padding: 0;
  margin: 0;
}

</style>
