<template>
  <div style="height:80vh;background-color:#F0F0F0;">
  <a-row :gutter="10" style="height: 100%;">
    <a-col class="gutter-row" :span="9">
      <a-card title="填写检查项" style="height:100%">
        <BasicForm ref="refForms" @register="registerForm" layout="horizontal">
          <template #splitLine="{ model, field }">
            <a-divider style="border-color: blue" orientation="center">下面内容是制定依据(法律法规)</a-divider>
          </template>
        </BasicForm>
      </a-card>
    </a-col>
    <a-col class="gutter-row" :span="15" style="height:100%">
      <a-card title="填写检查方法" style="height:100%">
        <vxe-table
          keep-source
          ref="tableRef"
          size="small"
          height="auto"
          auto-resize
          :data="dataList"
          :show-radio="true"
          :row-config="{ isCurrent: true, isHover: true, useKey: true }"
          @current-change="rowChangeEvent"
          :column-config="{useKey: true,resizable: true }"
          :scroll-y="{ enabled: true, gt: 50 }"
          :edit-config="{ trigger: 'click', mode: 'cell' }"
          :mouse-config={selected:true} 
          :radio-config="{ labelField: 'name', highlight: true }"
        >
          <template #empty>
            <vxe-button mode="text" icon="vxe-icon-add" @click="insertEvent(null)">
              <div style="font-size: 20px;"> 添加</div>
            </vxe-button> 
          </template>

          <vxe-column type="seq" width="50" />
          <vxe-column field="checkid" type="html" title="" :visible="false" />
          <vxe-column field="pid" sortable type="html" title="" :visible="false" />
          <vxe-column field="tp" title="类别" max-width="300" min-width="200" :edit-render="{ autofocus: '.my-input', autoselect: true }">
            <template #default="{ row }">
              <vxe-radio-group v-model="row.tp" style="min-height:70px;overflow-y:hidden;">
                <vxe-radio style="margin:5px;" v-for="item in tpOptions" :key="item.value" :label="item.value*1" :content="item.label"></vxe-radio>
              </vxe-radio-group>
            </template>
            <template #edit="{ row }">
              <vxe-radio-group v-model="row.tp" style="min-height:70px;overflow-y:hidden;">
                <vxe-radio style="margin:5px;" v-for="item in tpOptions" :key="item.value" :label="item.value*1" :content="item.label"></vxe-radio>
              </vxe-radio-group>
            </template>
          </vxe-column>
          <vxe-column field="name" title="检查方法" :edit-render="{ autofocus: '.my-input', autoselect: true }" min-width="150" max-width="350">
            <template #default="{ row }">
              <vxe-textarea v-model="row.name" type="text" placeholder="请输入检查方法" size="small" clearable :rows="4" />
            </template>
            <template #edit="{ row }">
              <vxe-textarea v-model="row.name" type="text" placeholder="请输入检查方法" size="small" clearable :rows="4" />
            </template>
          </vxe-column>
          <vxe-column field="des" sortable :edit-render="{ autofocus: '.my-input', autoselect: true }" title="备注"  min-width="150">
            <template #default="{ row }">
              <vxe-textarea v-model="row.des" type="text" placeholder="请输入备注" size="small" clearable :rows="4" />
            </template>
            <template #edit="{ row }">
              <vxe-textarea v-model="row.des" type="text" placeholder="请输入备注" size="small" clearable :rows="4" />
            </template>
          </vxe-column>
          <vxe-column field="id" title="" :visible="false" />
          <vxe-column title="操作" width="130">
            <template #default="{ row }">
              <vxe-button mode="text" icon="vxe-icon-add" @click="insertEvent(row)" />
              <vxe-button mode="text" icon="vxe-icon-delete" @click="removeEvent(row)" />
            </template>
          </vxe-column>a-bu
        </vxe-table>
        <template #extra>
          <a-space wrap>
            <a-button type="link" block  @click="insertEvent(null)">添加</a-button>
            <a-button type="link" block  @click="clearForm()">清空</a-button>
          </a-space>
        </template>
      </a-card>
    </a-col>
  </a-row>
</div>
</template>

<script setup lang="ts">
  import { ref, reactive, nextTick } from 'vue';
  import { VXETable, VxeTableInstance } from 'vxe-table';
  import { defHttp } from '/@/utils/http/axios';
  import { FormSchema } from '/@/components/Table';
  import { BasicForm, useForm } from '/@/components/Form/index';
  const checkItems = '/audit/auditProjectItem/listAll';


  const formSchemaCheck: FormSchema[] = [
    {
      label: '检查内容',
      field: 'content',
      component: 'InputTextArea',
      componentProps: {
        rows: 4,
        showCount: true,
        maxlength: 1024,
      },
      required: true,
      colProps: { lg: 24 },
    },
    {
      label: '备注',
      field: 'des',
      component: 'InputTextArea',
      componentProps: {
        rows: 4,
        showCount: true,
        maxlength: 1024,
      },
      colProps: { lg: 24 },
    },
    {
      label: '控制项',
      field: 'actIds',
      component: 'JCaSelect',
    },
   
    {
      label: '',
      field: 'splitList',
      component: 'Input',
      slot:"splitLine"
    },
    {
      label: '标题(条目)',
      field: 'item',
      component: 'Input',
    },
    
    {
      label: '合规内容',
      field: 'complineContent',
      component: 'InputTextArea',
      componentProps: {
        rows: 4,
        showCount: true,
        maxlength: 1024,
      },
    },
    {
      label: '来源文件',
      field: 'fileUploadPath',
      component: 'JUpload',

    },
    {
      label: 'id',
      field: 'id',
      component: 'Input',
      show: false,
    },

    {
      label: 'citemid',
      field: 'citemid',
      component: 'Input',
      show: false,
    },
    {
      label: 'checkid',
      field: 'checkid',
      component: 'Input',
      show: false,
    },
    
  ];

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


  const deleteOne = '/audit/auditProjectItem/delete';

  const emit = defineEmits(['callback']);

  const dataList = ref();
  const tableRef = ref();
  const curCheck = ref({});
  const tpOptions = ref([]);
  const projectid = ref();


  const iniData = async (tpOps, data, project) => {  
    tpOptions.value = tpOps;  
    if (!data) return;
    const { checkid,citemid, content, des, isPublic, actIds, actNames,complineContent,item,filePath} = data;   
      projectid.value = project.id;  
      curCheck.value = {  
          id: checkid, 
          complineContent, 
          actIds: [], 
          fileUploadPath: filePath,
          citemid:citemid
        };  
      
      if(checkid) {
        curCheck.value.content = content
        curCheck.value.des = des
        curCheck.value.item = item
        curCheck.value.isPublic= isPublic
      }
     
    if (actIds) {  
      const actIdsArray = actIds.split(',').map(Number);  
      const actNamesArray = actNames?.split(',') ?? [];  
      curCheck.value.actIds = [actNamesArray, actIdsArray];  
    }  

    await setCheckItems();  
    await setFieldsValue({ ...curCheck.value });  
  };  

  const rowChangeEvent = async ({ row }) => {
    emit('callback', row);
  };

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

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

  const getData = async () => {
    const $table = tableRef.value;
    const values = await validate();
    return {
      newRow: $table?.getInsertRecords(),
      updateRow: $table?.getUpdateRecords(),
      delRow: $table?.getRemoveRecords(),
      check: values,
    };
  };

  const setRowTpName = (row) => {
    const foundOption = tpOptions.value.find((option) => option.value * 1 === row.tp * 1);
    return foundOption?.label;
  };

  const setCheckItems = async () => {
    if(!curCheck.value.id) return 
    dataList.value = await defHttp.get({
      url: checkItems,
      params: {
        checkid: curCheck.value.id,
        pid: projectid.value,
      },
    });
  };

  const clearForm = async () => {
    await resetFields();
    dataList.value = []
  };


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

<style scope>
  .ant-card-body {
    padding: 5px;
    height: 90%;
  }
</style>
