<template>
  <div style="height:100%;">
    <vxe-grid ref="tableRef" v-bind="gridOptions" keep-source :radio-config="{highlight: true}"  size="small">
      <template #toolbar_buttons>
        <a-button type="link" @click="insertEvent(null)" :loading="loading">新建</a-button>
        <a-button type="link" @click="saveEvent()"  :loading="loading">保存</a-button>
        <a-button type="link" @click="removeBatchEvent()"  :loading="loading">删除</a-button>
      </template>
      <template #operate="{ row }">
        <template v-if="hasActiveEditRow(row)">
          <vxe-button mode="text" size="small" content="取消" @click="clearRowEvent(row)" />
          <vxe-button mode="text" size="small" status="primary" content="保存" @click="saveRowEvent(row)" />
        </template>
        <template v-else>
          <vxe-button mode="text" size="small" content="编辑" @click="editRowEvent(row)" />
          <vxe-button mode="text"  @click="removeEvent(row)">删除 </vxe-button>
          <vxe-button mode="text" @click="addInnerCtrlItem(row)">要求</vxe-button>
        </template>
 
      </template>
    </vxe-grid>
    <AuditInnerCtrlModal @register="registerModal"/>
  </div>
</template>

<script lang="ts" setup>
import { reactive,ref,nextTick } from 'vue'
import { VxeUI,VxeGridProps } from 'vxe-table'
import { defHttp } from '/@/utils/http/axios';
import { saveOrUpdate,list,deleteOne,batchDelete } from './api/AuditInnerCtrl.api';
import { useModal } from '/@/components/Modal';
import AuditInnerCtrlModal from './modal/AuditInnerCtrlModal.vue';

const [registerModal, { openModal }] = useModal();

interface RowVO {
  id: string
  name: string
  des: string
}

interface SrhParam {
  name: string
  column:string
  order:string
  pageNo:number
  pageSize:number
}

const addInnerCtrlItem = (data)=>{
  openModal(true, {
    isDetail: false,
    showFooter: false,
    data
  });
}


const tableRef = ref();
const loading = ref(false)
const emit = defineEmits(['callBack']);
const srhParams = ref<SrhParam>({  
  name: '',  
  column: 'createTime',  
  order: 'desc',  
  pageNo: 1,  
  pageSize: 10  
});

const gridOptions = reactive<VxeGridProps<RowVO>>({

  border: true,
  height:"auto",
  columnConfig: {
    resizable: true
  },
  checkboxConfig: {
    reserve: true
  },
  pagerConfig: {
    enabled: true,
    pageSize: 10
  },
  editConfig: {
    trigger: 'manual',
    mode: 'row',
    showStatus: true,
  },
  columns: [
    { type: 'checkbox', visible: true, width: '40', showOverflow: false }, 
    {
      field: 'name',
      title: '内控文件名称',
      width: '30%',
      editRender: { name: 'input' },
      sortable:true
     },{
      field: 'des',
      title: '说明',
      editRender: { name: 'input' },
      minWidth:'30%',
      sortable:true
    },{
      field: 'createTime',
      title: '创建时间',
      width: '10%',
      visible: true,
      type: 'html',
      sortable:true
    },{
      field: 'id',
      title: '',
      visible: false,
    },{
       field: 'createUser', title: '创建人', visible: true , width: '10%',  sortable:true
    }, { 
      title: '操作', width: '15%', visible: true, align: 'center', fixed: 'right', slots: { default: 'operate' } 
    },
  ],
  toolbarConfig: {
      refresh: true,
      zoom: true,
      custom: true,
      export: true,
      print: true,
      slots: {
        buttons: 'toolbar_buttons',
      },
    },
  proxyConfig: {
    seq: true,
    props: {
      result: 'result',
      total: 'page.total'
    },
    ajax: {
      query: ({ page }) => {
        return findPageList(page.currentPage, page.pageSize)
      }
    }
  }
})

const findPageList = async (currentPage: number, pageSize: number) => {  
  srhParams.value.pageNo = currentPage;  
  srhParams.value.pageSize = pageSize;  
  const retData = await setInnerCtlData();  
  return {  
    page: {  
      total: retData.total  
    },  
    result: retData.records  
  };  
};



async function setInnerCtlData() {
  return await list(srhParams.value)
}


const removeEvent = async (row) => {
  const $table = tableRef.value;
  if (!$table) return;
  const type = await VxeUI.modal.confirm('您确定要删除该数据?');
  if (type === 'confirm') {
    if (row.id) {
      const params = { id: row.id };
      deleteOne(params,queryEvent)
      $table.remove(row)
    }
  }
};

  const removeBatchEvent = async () => {
    const $table = tableRef.value;
    if (!$table) return;

    const ids = await getSelectIds()
    if(ids.length==0){
      VxeUI.modal.message("请选择要删除的数据")
      return false;
    }

    const params = { ids: ids.join(",")};
    batchDelete(params, queryEvent) 
  };

  

  const insertEvent = async (row) => {
    const $table = tableRef.value;
    if ($table) {
      const record = {
        id: null,
        name: '',
        des: '',
      };
      const { row: newRow } = await $table.insertAt(record, row);
      await $table.setEditCell(newRow, 'name');
    }
  };


  async function saveEvent() {
    loading.value = true
    const $table = tableRef.value;
    if (!$table) return;
    const insertRecords = $table.getInsertRecords();
    const updateRecords = $table.getUpdateRecords();
    const mlist = mergeArrays(insertRecords, updateRecords);
    mlist.forEach(async(element) => {
      let formData = {};
      if(element.id) {
        formData['id'] = element.id
      }
      formData['name'] = element.name;
      formData['des'] = element.des;
      await saveOrUpdate(formData,!!element.id);
    });

    await $table.clearEdit();
    nextTick(async ()=>{
      loading.value = false 
      queryEvent()
    })
  
  }

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


  const queryEvent = () => {
    const $grid = tableRef.value
    if ($grid) {
      $grid.commitProxy('query')
    }
  }

  const getSelectIds = async() => {
    let ids = [];
    const $table = tableRef.value;
    if ($table) {
      const selRecords = $table.getCheckboxRecords();
      selRecords.forEach(function (ele) {
        ids.push(ele.id);
      });
    }
    return ids;
  }


  async function iniData(srhTxt:string) {
      if(srhTxt) {
        srhParams.value.name = "*" +srhTxt + "*"
      } else {
        srhParams.value.name = ""
      }
      await findPageList(1,10)
      await queryEvent()
  }

  const hasActiveEditRow = (row) => {
    const $grid = tableRef.value;
    if ($grid) {
      return $grid.isEditByRow(row);
    }
    return false;
  };

  const clearRowEvent = (row) => {
    const $grid = tableRef.value;
    if ($grid) {
      $grid.clearEdit().then(() => {
        // 还原行数据
        $grid.revertData(row);
      });
    }
  };


  
  const editRowEvent = (row) => {
    const $grid = tableRef.value;
    if ($grid) {
      $grid.setEditRow(row);
    }
  };

  const saveRowEvent = async (row) => {
    const $grid = tableRef.value;
    if ($grid) {
      try {
        let formData = {};
        if(row.id) {
          formData['id'] = row.id
        }
        await $grid.clearEdit();
        gridOptions.loading = false;
        formData['name'] = row.name;
        formData['des'] = row.des;
        await saveOrUpdate(formData,!!row.id);
      } catch(e){
        console.log(e)
      } finally {
        gridOptions.loading = false;
        queryEvent()
      }
    }
  };



defineExpose({
  iniData,
});

</script>
