<template>
  <PageWrapper>
    <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"
                />
              </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>
  </PageWrapper>
</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 '../RateTaskdept.data';
  import { getTaskDeptDomainTreeList, getTaskDeptDomainTreeListByid, saveOrUpdate } from '../RateTaskdept.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 closeCurrent = inject('closeCurrent');
  const { createMessage } = useMessage();
  //树的实例
  const treeRef = ref(null);
  const addkey = ref(0);

  // 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;
    console.log('-----------dept data: ', data.key);
    if (data.key != undefined) {
      //why mod

      if (addkey.value != data.key.value) {
        getTaskDeptDomainTreeList({ taskid: taskId }).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;
        });
      }
    }

    console.log('-----------data: ', data.record.id);

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

      getTaskDeptDomainTreeListByid({ 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) ? '批量分配' : '批量分配'));
  let taskId = ref('');

  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;

    //console.log('-----------id: ', id);
    taskId = id;
    //console.log('-----------taskId: ', taskId);
  });

  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 = taskId;
      values.rateDomainId = 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>
