<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="1024" @ok="handleSubmit">
      
      <a-spin :spinning="spinning">
      <a-row :gutter="24">
          <a-col :span="12">
              <a-card>
                  <div style="height: 75vh;overflow-y: auto;">
                    <BasicTree
                          ref="treeRef"
                          :style="{ minWidth: '20px' }"
                          selectable
                          defaultExpandAll="true"
                          @select="onSelect"
                           :checkable="true" 
                          :treeData="treeData"
                          :selectedKeys="selectedDepIds"
                          :expandedKeys="expandedKeys"
                          :clickRowToExpand="true"
                      >
                      </BasicTree>
                      
                  </div>
              </a-card>
          </a-col>
          <a-col :span="12">
              <a-card>
                  <div style="height: 75vh;overflow-y: auto;">
                    
                      <div>
                       <BasicForm @register="registerForm"/>
                      </div>
                  </div>
              </a-card>
          </a-col>
      </a-row>
      </a-spin>
  </BasicModal>
</template>

<script lang="ts" setup>
    import { message } from 'ant-design-vue';
    import { onMounted, reactive, ref,toRaw,inject,computed, unref  } from 'vue';
    import { PageWrapper } from '/@/components/Page';
    import {BasicModal, useModalInner} from '/@/components/Modal';
    import {BasicForm, useForm} from '/@/components/Form/index';
    import {formSchema} from '../RateTaskuser.data';
    import {saveOrUpdate,getTaskUserDeptDomainTreeList, getTaskUserDeptDomainTreeListByid} from '../RateTaskuser.api';
    import { BasicTree } from '/@/components/Tree/index';
    import { useRoute } from 'vue-router';
    import { useMessage } from '/@/hooks/web/useMessage';
    const route = useRoute();
    const spinning = ref(true)
    const searchVal = ref('')
    const showFlag =ref(false)
    const isDetail = ref(true)
    const fistData = ref({})
    const hasOptFlag = ref(false)
     const addkey = ref(0)
      let taskdeptId = ref('');
    let rateTaskId = ref('');
    const { createMessage } = useMessage();
    //树的实例
   const treeRef = ref(null);
    // Emits声明
    const emit = defineEmits(['register','success']);
    const isUpdate = ref(true);
    //表单配置
    const [registerForm, {setProps,resetFields, setFieldsValue, validate}] = useForm({
        //labelWidth: 150,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: {span: 24}
    });
    //表单赋值
    const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
        //重置表单
        await resetFields();
        setModalProps({confirmLoading: false,showCancelBtn:!!data?.showFooter,showOkBtn:!!data?.showFooter});
        isUpdate.value = !!data?.isUpdate;
        if(data.key!=undefined){
//why mod 
        if(addkey.value!=data.key.value){
          getTaskUserDeptDomainTreeList({rateTaskId:rateTaskId}).then(rep=>{
          treeData.value = rep.treeList
          treeNextKeys.value = rep.keys
        // record.value = rep.record
          expandedKeys.value = rep.expandedKeys
          if(!!treeData.value){
            handlerExpandedKeys()
            autoFirst()
          }
          spinning.value = false
          })


        }

        }


        if (unref(isUpdate)) {
            //表单赋值

        getTaskUserDeptDomainTreeListByid({id:data.record.id}).then(rep=>{
            treeData.value = rep.treeList
            treeNextKeys.value = rep.keys
            // record.value = rep.record
            expandedKeys.value = rep.expandedKeys
            if(!!treeData.value){
            handlerExpandedKeys()
            autoFirst()
            }
            spinning.value = false
        })
           



            await setFieldsValue({
                ...data.record,
            });
        }
        // 隐藏底部时禁用整个表单
       setProps({ disabled: !data?.showFooter })
    });
    //设置标题
    const title = computed(() => (!unref(isUpdate) ? '分配填报人' : '分配填报人'));

   

    

    const treeData = ref([
    ]);
    // 进行数据记录
    const record = ref([])
    const treeNextKeys = ref([])
    const treeNextIndex = ref(0)
    const selectedDepIds = ref([]);
    const expandedKeys = ref([]);
    // 设置treeIndex
    function settingTreeeIndex(key){
    let size = treeNextKeys.value.length
    for(var i=0;i<size;i++){
        if(treeNextKeys.value[i]==key){
        treeNextIndex.value = i;
        break;
        }
    }
    }

    function onSelect(selectedKeys, info){
  if(selectedKeys.length==0){
   // message.warning("请选择子节点！")
    return
  }

  hasOptFlag.value = false
  if(info.selectedNodes[0].leaf){
    let tempkey=info.selectedNodes[0].key.replace('index', '');
    
    initRateOptions(tempkey)
   
    settingTreeeIndex(info.selectedNodes[0].key)

   
  }else{
   // message.warning("请选择复选框！")
   
  }
}

    function initRateOptions(key){
    //getRateStdOptionList({key:key}).then(rep=>{
    // rateOptions.value = rep
    //})
    }
    function autoFirst(){
    
    selectedDepIds.value = [fistData.value.key]
    
    showFlag.value = true

    }

    function handlerExpandedKeys(){
    var len = treeData.value.length
    if(len==0){
        return
    }
    var keys = []
    for(var i=0;i<len;i++){
        if(i==0){
        fistData.value = treeData.value[i].children[0]
        }
        //keys.push(treeData.value[i].key)
    }
    //expandedKeys.value = keys
    }

    onMounted(() => {
  const id = toRaw(route.query).id;
  rateTaskId = toRaw(route.query).rateTaskId;
  console.log('-----------id: ', id);
  taskdeptId=id;
  //console.log('-----------taskdeptId: ', taskdeptId);
  
})



function onNextStep(){
  let index = treeNextIndex.value
  index ++
  // 索引相等标识到最后一项
  if(index >= treeNextKeys.value.length){
    return
  }
  if(!formData.value.id){
    message.error("项目关联信息丢失，请关闭后重新点击填报")
    return
  }
  if(!formData.value.rateCheck){
    message.error("请选择评分项")
    return
  }
  


  treeNextIndex.value = index
  let key = treeNextKeys.value[index]
  selectedDepIds.value = [key]
  initRateOptions(key)
}
function onUpperStep(){
  let index = treeNextIndex.value
  index --
  if(index <0){
    return;
  }
  
  treeNextIndex.value = index
  let key = treeNextKeys.value[index]
  selectedDepIds.value = [key]
  initRateOptions(key)
}

 /**
   * 获取tree实例
   */
  function getTree() {
    const tree = unref(treeRef);
    if (!tree) {
      throw new Error('tree is null!');
    }
    return tree;
  }

  function handleGetSelectData() {

     const keys = unref(getTree().getCheckedKeys()).join(',')

        //const keys = getTree().getSelectedKeys();
        createMessage.success(JSON.stringify(keys));
      }



    //表单提交事件
    async function handleSubmit(v) {
        try {
            let values = await validate();
            setModalProps({confirmLoading: true});

            const keys = unref(getTree().getCheckedKeys()).join(',')

            //console.log('----》JSON.stringify(keys): ', JSON.stringify(keys));
            //createMessage.success(JSON.stringify(keys));
            values.rateTaskId=rateTaskId;
            values.taskdeptId=taskdeptId;
            values.keyitemId=JSON.stringify(keys);
             console.log('----》values: ', values);
             isUpdate.value=true;




            //提交表单
            await saveOrUpdate(values, isUpdate.value);
            //关闭弹窗
            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>