<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="800" @ok="handleSubmit">
    <div v-show="!nextFlag">
    <a-form
      ref="formRef"
      name="advanced_search"
      :model="formState"
      @finish="onFinish"
      :labelCol="{xs: {span: 24},sm: {span: 3},}"
      :wrapperCol = "{xs: {span: 24},sm: {span: 21},}"
    >
      <a-row :gutter="24">
          <a-col :span="24">
            <a-form-item
              name="projectCreId"
              label="项目名称"
              :rules="[{ required: true, message: '请选择项目' }]"
            >
              <a-select v-model:value="formState.projectCreId" placeholder="请选择"
                show-search
                :options="searchData"
                @search="queryProject"
                />
            </a-form-item>
          </a-col>
      </a-row>
    </a-form>
    </div>
    <div v-show="nextFlag">
      <BasicTable @register="registerTable" :rowSelection="rowSelection" @selection-change="handlerRowClick"/>
    </div>
    <template #footer>
        <a-button v-show="!nextFlag" @click="handlerCancel">取消</a-button>
        <a-button v-show="!nextFlag" type="primary" @click="handlerNext">下一步</a-button>
        <a-button v-show="nextFlag" @click="handlerUpper">上一步</a-button>
        <a-button v-show="nextFlag" type="primary" @click="handleSubmit">确认</a-button>
    </template>
  </BasicModal>
</template>

<script lang="ts" setup>
    import { message, type FormInstance } from 'ant-design-vue';
import { computed, ref, toRaw, unref } from 'vue';
import { listByProjectId, projectImport } from '../StProblemTaskAssin.api';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicTable } from '/@/components/Table';
import { useListPage } from '/@/hooks/system/useListPage';
import { listPrepar } from '/@/views/project/project/StProjectCre.api';
    // Emits声明
    const emit = defineEmits(['register','success']);
    const isUpdate = ref(true);
    const nextFlag = ref(false);
    //
    const expand = ref(false);
    const searchData = ref([])
    const actCheckbox = ref({})
    const formRef = ref<FormInstance>();
    const formState = ref({
      projectCreId:''
    });
    const {tableContext} = useListPage({
    tableProps:{
         title: '',
         api: listByProjectId,
         columns: [{
          title: '问题项',
          align: 'center',
          dataIndex: 'problemItem'
        },
        {
          title: '问题示例',
          align: 'center',
          dataIndex: 'problemExample'
        },],
         canResize:false,
         useSearchForm: false,
         showIndexColumn: false,
         immediate:false,
         scroll: { x: false },
         showActionColumn:false,
         actionColumn: {
             width: 160
          },
          showTableSetting: false,
          clickToRowSelect: true,
           rowSelection: { 
                onSelect: handlerChecked,
            },
          // beforeFetch(params) {
          //     params = Object.assign(params,{projectCreId:formState.value.projectCreId})
          //   },
    },
})
const [registerTable, {reload,setProps},{ rowSelection, selectedRowKeys }] = tableContext
function handlerChecked(record, selected, selectedRows, nativeEvent){
    if(selected){
        let item = {}
        item[record.id] = true
        actCheckbox.value = Object.assign(actCheckbox.value,item)
    }else{
        let item = {}
        item[record.id] = false
        actCheckbox.value =  Object.assign(actCheckbox.value,item)
    }
  }
  function initActCheckbox(){
    let actInfo = toRaw(actCheckbox)
    let item = {}
    for(let k in actInfo){
        if(!k){
            continue
        }
        item[k] = false
    }
    actCheckbox.value = Object.assign(actCheckbox.value,item)
  }
  function handlerRowClick({keys,rows}){
    initActCheckbox()
    if(keys.length>0){
        let item = {}
        for(var i=0;i<keys.length;i++){
            item[rows[i].id] = true
        }
        actCheckbox.value = Object.assign(actCheckbox.value,item)
    }
  }
    //表单赋值
    const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
        //重置表单
        nextFlag.value = false
        formState.value.projectCreId = ''
        setModalProps({confirmLoading: false,showCancelBtn:!!data?.showFooter,showOkBtn:!!data?.showFooter});
        isUpdate.value = !!data?.isUpdate;
        if (unref(isUpdate)) {
        }
        queryProject(null)
    });
    //设置标题
    const title = computed(() => (!unref(nextFlag) ? '项目导入' : '选择问题'));
    function queryProject(name){
      listPrepar({projectName:name,configStatus:'1'}).then(rep=>{
        let data = []
        if(rep!=null){
          let len = rep.records.length
          for(var i=0;i<len;i++){
            data.push({
              value:  rep.records[i].id,
              label:  rep.records[i].projectName,
            })
          }
        }
        searchData.value = data
      })
    }
    const onFinish = (values: any) => {
      console.log('Received values of form: ', values);
      console.log('formState: ', formState);
    };
    function handlerCancel(){
        closeModal()
    }
    function handlerNext() {
        if(!!formState.value.projectCreId){
          nextFlag.value = true
          querProblem()
        }else{
          formRef.value?.validate()
        }
    }
    function querProblem(){
      setProps({searchInfo:toRaw(formState)});
      reload()
    }
    function handlerUpper() {
        nextFlag.value = false
    }
    //表单提交事件
    async function handleSubmit(v) {
        try {
          if(!formState.value.projectCreId){
            message.warning("请选择项目")
            return
          }
            if(selectedRowKeys.value.length==0){
              message.warning("请选择问题")
              return
            }
            setModalProps({confirmLoading: true});
            console.log(selectedRowKeys)
            console.log(formState)
            let saveData = {}
            saveData.projectCreId = formState.value.projectCreId
            saveData.ids = selectedRowKeys.value.join(",")
            await projectImport(saveData);
            //关闭弹窗
            closeModal();
            //刷新列表
            emit('success');
        } finally {
            setModalProps({confirmLoading: false});
        }
    }
</script>

<style lang="less" scoped>
	/** 时间和数字输入框样式 */
  :deep(.ant-input-number){
		width: 100%
	}

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