<!-- @format -->

<template>
  <ns-view-list-table v-bind="tableConfig" :model="data" ref="mainRef" rowKey="uuid" />
  <ns-drawer v-bind="addDrawerConfig">
    <ns-form ref="formRef" :schemas="formSchema" :model="formData" formLayout="vertical" />
    <template #footer>
      <ns-button style="margin-right: 8px" @click="onClose">取消</ns-button>
      <ns-button type="primary" @click="operateForm" :disabled="!formDisabled">确定</ns-button>
    </template>
  </ns-drawer>
  <ns-drawer v-bind="boundaryDrawer">
    <ns-button type="primary" @click="borderAdd">新增</ns-button>
    <ns-button type="primary" style="margin-left: 10px; margin-bottom: 10px" @click="borderAdd"
      >新增子集</ns-button
    >
    <a-tree v-if="linkTree?.length" v-bind="boundaryTree" class="boundaryTree">
      <template #title="data">
        <span>{{ data.orgInfo.orgName }}</span>
        <!-- <ns-button type="link" danger >删除</ns-button> -->

        <span v-if="data.orgInfo.orgId !== currentBoundaryRecord.orgId" class="nodeDelete">
          <DeleteOutlined @click="deleteTree(data)"
        /></span>
      </template>
    </a-tree>
  </ns-drawer>

  <ns-drawer v-bind="serverDrawer">
    <!-- <ns-input-search
      placeholder="请选择开通模块"
      v-model:value="searchValue"
      style="margin-bottom: 8px"
      @search="onSearch" /> -->
    <a-tree v-if="treeData?.length" v-model:checkedKeys="checkedKeys" v-bind="serverTree" />
  </ns-drawer>

  <TreeAdd ref="treeAdd" @ok="handleOk" />
</template>
<script lang="ts" setup>
  import { Modal } from 'ant-design-vue';
  import { computed, createVNode, defineComponent, reactive, ref, watch } from 'vue';
  import { http } from '/nerv-lib/util/http';
  import { cloneDeep } from 'lodash-es';
  import TreeAdd from './TreeAdd.vue';
  import { DeleteOutlined } from '@ant-design/icons-vue';
  import { h } from 'vue';
  import { formConfig } from './config';
  import { NsMessage, NsModal } from '/nerv-lib/component';
  import { mockData, treeData } from './mock';
  import { enterPrise } from '/@/api/origanizemanage';
  import { tableConfig as insertConfig } from './config';
  defineOptions({
    name: 'EnterpriseManageIndex',
  });

  const data = reactive({});
  const treeAdd = ref();
  const mainRef = ref();
  let formData = ref({});
  const formRef = ref();
  const searchValue = ref<string>('');
  const checkedKeys = ref<string[]>([]);
  const visible = ref(false);
  const borderVisible = ref(false);
  const serviceVisible = ref(false);
  const treeAddVisible = ref(false);
  const formSchema = formConfig;
  const currentServerRecord = ref({});
  const currentBoundaryRecord = ref({});
  const currentSelectBoundaryNode = ref({});
  const linkTree = ref([]);
  const totalCheckedKeys = ref([]);
  const opType = ref<string>('add');
  const calMap = {
    add: enterPrise.save,
    edit: enterPrise.edit,
    serverAdd: enterPrise.orgPermission,
  };
  const comApi = computed(() => {
    return calMap[opType.value as keyof typeof calMap];
  });

  // 公共请求方法，包含tablereload，drawerclose
  const fetch = (params, isReload = true) => {
    http.post(comApi.value, params).then(() => {
      NsMessage.success('操作成功');
      onClose();
      isReload && mainRef.value?.nsTableRef.reload();
    });
  };

  // 表格配置
  const tableConfig = computed(() => {
    return insertConfig({
      visible,
      formData,
      opType,
      getOrgRandomCode,
      borderVisible,
      serviceVisible,
      server: {
        getTree,
        currentServerRecord,
        getPermissionData,
      },
      boundary: {
        getBoundaryTree,
        currentBoundaryRecord,
      },
    });
  });

  // 随机组织id
  const getOrgRandomCode = () => {
    http.post(enterPrise.getCode).then((res) => {
      formData.value.orgCode = res.data;
    });
  };
  // getOrgRandomCode();

  // 公共关闭及后续处理逻辑
  const onClose = () => {
    visible.value = false;
    borderVisible.value = false;
    serviceVisible.value = false;
    checkedKeys.value = [];
    linkTree.value = [];
  };

  // 企业表单drawer
  const addDrawerConfig = ref({
    width: '520',
    visible: visible,
    footerStyle: { textAlign: 'right' },
    destroyOnClose: true,
    onClose: onClose,
  });

  // 表单form配置
  const formDisabled = computed(() => {
    return formRef.value?.validateResult;
  });

  //企业表单数据操作
  const operateForm = () => {
    formRef.value?.triggerSubmit().then((res) => {
      console.log(formData.value, 'formData.value');
      fetch(res);
    });
  };

  // 服务操作逻辑区域
  const serverOK = () => {
    const params = {
      orgId: currentServerRecord.value?.orgId,
      orgName: currentServerRecord.value?.orgName,
      permissionVoList: totalCheckedKeys.value,
    };
    fetch(params, false);
  };
  const ServiceSelect = (selectedKeys: any, info: any) => {
    console.log(selectedKeys, 'selectedKeys');
    console.log(info, 'info');
  };

  // 服务树配置
  const serverTree = ref({
    checkable: true,
    selectable: false,
    onSelect: ServiceSelect,
    defaultExpandAll: true,
    treeData: treeData,
    fieldNames: { children: 'menus', title: 'label', key: 'code' },
    onCheck: (checked, { halfCheckedKeys }) => {
      const result = checked.map((item) => {
        return {
          halfCheck: false,
          permissionId: item,
        };
      });
      const finalResult = halfCheckedKeys
        .map((item) => {
          return {
            halfCheck: true,
            permissionId: item,
          };
        })
        .concat(result);
      totalCheckedKeys.value = finalResult;
    },
  });

  // 获取服务权限树
  const getTree = (params) => {
    return http.post(enterPrise.permissionTree, params).then((res) => {
      treeData.value = res.data?.data;
    });
  };
  getTree({});

  // 获取当前企业拥有的权限数据
  const getPermissionData = (params) => {
    http.post(enterPrise.queryOrgPermission, params).then((res) => {
      checkedKeys.value = res.data
        ?.filter((item) => !item.halfCheck)
        .map((item) => {
          return item.permissionId;
        });
    });
  };

  // 开通服务模块drawer
  const serverDrawer = ref({
    width: 520,
    visible: serviceVisible,
    footerStyle: { textAlign: 'right' },
    destroyOnClose: true,
    ok: serverOK,
    onClose: onClose,
    cancel: onClose,
  });

  // 边界drawer配置
  const boundaryDrawer = ref({
    width: 520,
    visible: borderVisible,
    footerStyle: { textAlign: 'right' },
    destroyOnClose: true,
    ok: onClose,
    onClose,
    cancel: onClose,
  });

  const handleSelect = (selectedKeys: any, info: any) => {
    currentSelectBoundaryNode.value = info;
  };

  // 获取边界树
  const getBoundaryTree = (params) => {
    http.post(enterPrise.queryOrgTree, params).then((res) => {
      const otherOrg = res.data[0].listOrg;
      linkTree.value = res.data;
      otherOrg?.map((item) => {
        linkTree.value.push({ orgInfo: item } as never);
      });
    });
  };

  // 边界树配置
  const boundaryTree = ref({
    defaultExpandAll: true,
    onSelect: handleSelect,
    treeData: linkTree,
    // blockNode: true,
  });

  // 新增边界
  const handleOk = (res) => {
    const params = {
      ...res,
      linkOrgVoList: [
        {
          linkOrgId: res.orgId,
          point: res.point,
          type: 1, //1子集 2 关联
        },
      ],

      orgId: currentBoundaryRecord.value.orgId || '',
    };
    http.post(enterPrise.link, params).then(() => {
      treeAdd.value?.toggle();
      NsMessage.success('操作成功');
      getBoundaryTree({
        orgId: currentBoundaryRecord.value.orgId,
        orgName: currentBoundaryRecord.value.orgName,
      });
    });
  };
  const borderAdd = () => {
    treeAddVisible.value = true;
    treeAdd.value?.toggle();
  };

  const borderAddSon = () => {
    treeAddVisible.value = true;
  };

  const editTree = (title: any, key: any) => {
    console.log(title, 'title');
    console.log(key, 'key');
  };

  const deleteTree = (node: any) => {
    console.log(node, 'node');

    NsModal.confirm({
      title: '是否确定删除',
      content: createVNode('div', { style: 'color:red;' }, ''),
      onOk() {
        const flag = !!node?.children?.length;

        if (flag) {
          NsMessage.error('请先删除子集');
          return;
        }
        // http
        //   .post('/api/parking_merchant/objs/gateInfo/delete', {
        //     uuid: record.uuid,
        //   })
        //   .then((res) => {
        //     mainRef.value.nsTableRef.reload();
        //   });
      },
      onCancel() {
        console.log('Cancel');
      },
      class: 'test',
    });
  };

  const onSearch = () => {
    console.log(searchValue.value);
  };
</script>
<style lang="less" scoped>
  .nodeDelete {
    // display: none;
    margin-left: 40px;
  }
  .boundaryTree {
    background-color: red !important;
  }
  :deep(.ant-tree) {
    background-color: red !important;

    // &:hover {
    .nodeDelete {
      display: block;
    }
    // }
  }
</style>
