<!-- @format -->

<template>
  <div class="main">
    <div class="left">
      <div class="top">
        <ns-tree-api v-bind="orgTreeConfig" @select="handleSelect">
          <template #title="data">
            {{ data.orgInfo?.orgName }}
          </template>
        </ns-tree-api>
      </div>
      <div class="top">
        <!-- <div class="ns-table-title">关联部门</div>

        <a-input-search
          v-model:value="searchValue2"
          style="margin-bottom: 8px"
          placeholder="请输入关联部门"
          @search="onSearch2" />
        <a-tree
          v-if="treeData2?.length"
          :tree-data="treeData2"
          defaultExpandAll
          @select="handleSelect2">
          <template #title="data">
            {{ data.deptInfo?.deptName }}
          </template>
        </a-tree> -->
        <ns-tree-api v-bind="deptTreeConfig" @select="handleSelect2">
          <template #title="data">
            {{ data.deptInfo?.deptName }}
          </template>
        </ns-tree-api>
      </div>
    </div>
    <div class="right">
      <ns-view-list-table v-bind="tableConfig" :model="data" ref="mainRef" />
    </div>
    <a-drawer
      :width="500"
      :visible="visible"
      :body-style="{ paddingBottom: '80px' }"
      :footer-style="{ textAlign: 'right' }"
      destroyOnClose
      @close="onClose">
      <ns-form
        ref="formRef"
        :schemas="formSchema"
        :model="formData"
        class="form"
        :wrapperCol="{ span: 20 }"
        formLayout="vertical" />
      <span class="admin">用户权限</span>
      <ns-view-list-table
        v-bind="tableConfig2"
        class="drawerTable"
        :model="data"
        :pagination="false"
        rowKey="uuid" />
      <template #footer>
        <a-button style="margin-right: 8px" @click="onClose">取消</a-button>
        <a-button :disabled="!dynamicDisabled" type="primary" @click="onEdit">确定</a-button>
      </template>
    </a-drawer>

    <a-modal
      title="用户信息"
      :width="520"
      :visible="addformvisible"
      cancelText="取消"
      @ok="handleOk"
      @cancel="handleClose">
      <ns-form
        ref="modalFormRef"
        :wrapperCol="{ span: 24 }"
        :schemas="formSchema2"
        :model="formData2"
        formLayout="vertical" />
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
  import { computed, createVNode, defineComponent, reactive, ref, watchEffect } from 'vue';
  import { http } from '/nerv-lib/util/http';
  import { NsMessage, NsModal } from '/nerv-lib/component';
  import { formConfig, formConfig2 } from './config';
  import { origanizemanage } from '/@/api/origanizemanage';

  defineOptions({ name: 'OrderListIndex' });

  const mainRef = ref();
  const data = reactive({});
  let formData = ref({});
  let formData2 = ref({});
  const formRef = ref();
  const modalFormRef = ref();
  const visible = ref(false);
  const addformvisible = ref(false);
  const searchValue = ref<string>('');
  const searchValue2 = ref<string>('');
  const disabled = ref(false);

  const opMap: any = ref({
    type: 'add',
    fuc: () => {},
    record: {},
  });
  watchEffect(() => {
    disabled.value = opMap.value.type === 'edit';
  });
  const formSchema = formConfig(disabled);
  const casData = ref([]);
  const formSchema2 = formConfig2(casData);
  const treeData = ref([]);
  const treeData2 = ref([]);
  const userAuthList = ref([]);
  const orgId = JSON.parse(sessionStorage.getItem('userInfo')).orgId;
  const orgTreeConfig = ref({
    selectedKeys: ['0-0'],
    defaultExpandAll: true,
    api: origanizemanage.queryOrgTree,
    defaultParams: { orgId },
    transform: (data) => {
      const otherOrg = data[0].listOrg;
      let treeData = [];
      // 特殊处理
      if (data[0].orgInfo) {
        treeData = data;
      }
      otherOrg?.map((item) => {
        treeData.push({ orgInfo: item } as never);
      });
      return treeData;
    },
    header: {
      title: '关联企业',
      icon: 'orgLink',
    },
    formConfig: {
      schemas: [
        {
          field: 'orgName',
          component: 'NsInput',
          autoSubmit: true,
          componentProps: {
            placeholder: '请输入企业名称',
          },
        },
      ],
    },
  });
  const deptTreeConfig = ref({
    defaultExpandAll: true,
    api: origanizemanage.queryDeptTree,
    defaultParams: { orgId },

    header: {
      title: '关联部门',
      icon: 'deptLink',
    },
    formConfig: {
      schemas: [
        {
          field: 'deptName',
          component: 'NsInput',
          autoSubmit: true,
          componentProps: {
            placeholder: '请输入部门名称',
          },
        },
      ],
    },
  });
  const dynamicDisabled = computed(() => {
    return formRef.value?.validateResult && userAuthList.value?.length;
  });
  const fetch = (api, params = { orgId }) => {
    return http.post(api, params);
  };

  // 企业树
  const getOrgTree = (params?) => {
    fetch(origanizemanage.queryOrgTree, params).then((res) => {
      const otherOrg = res.data[0].listOrg;
      // 特殊处理
      if (res.data[0].orgInfo) {
        treeData.value = res.data;
      }
      otherOrg?.map((item) => {
        treeData.value.push({ orgInfo: item } as never);
      });
    });
  };
  getOrgTree();
  // 部门树
  fetch(origanizemanage.queryDeptTree).then((res) => {
    treeData2.value = res.data;
  });

  const onSearch = () => {
    console.log(searchValue.value);
    getOrgTree({ orgName: searchValue.value, orgId });
  };
  const onSearch2 = () => {
    console.log(searchValue2.value);
    fetch(origanizemanage.queryDeptTree, { deptName: searchValue2.value, orgId }).then((res) => {
      treeData2.value = res.data;
    });
  };

  const tableFetch = (params) => {
    console.log(params, 'sdfasfasdfasdfasdf');

    // console.log(mainRef.value);

    tableConfig.value.params = {
      ...mainRef.value.params,
      ...params,
    };

    setTimeout(() => {
      mainRef.value?.nsTableRef.reload();
    }, 100);
  };

  const handleSelect = (selectedKeys: any, info: any) => {
    fetch(origanizemanage.queryDeptTree, { orgId: info.node?.orgInfo.orgId }).then((res) => {
      treeData2.value = res.data;
    });
    tableFetch({ orgId: info.node?.orgInfo.orgId });
  };

  const handleSelect2 = (selectedKeys: any, info: any) => {
    tableFetch({ deptId: info.node?.deptInfo.deptId });
  };

  const onClose = () => {
    visible.value = false;
    formData.value = {};
    userAuthList.value.splice(0);
  };

  const onEdit = () => {
    formRef.value?.triggerSubmit().then(() => {
      console.log(formData.value, 'formData.value');
      if (!userAuthList.value.length) {
        NsMessage.error('请添加用户权限');
        return;
      }

      opMap.value.fuc &&
        opMap.value.fuc({ ...formData.value, userRoleList: userAuthList.value, orgId });
    });
  };

  const handleOk = () => {
    if (casData.value?.length !== 3) {
      NsMessage.error('未选择角色');
    }
    const currentOrgId = casData.value[0].value;
    const isSameOrg = userAuthList.value.filter(({ orgId }) => {
      return orgId === currentOrgId;
    });
    if (isSameOrg?.length) {
      NsMessage.error('同一组织只能添加一个角色');
      return;
    }
    console.log(casData.value, userAuthList.value, 'formData2.value');

    const str = casData.value.map((item) => item?.label).join('/');
    userAuthList.value.push({
      deptRoleInfoList: str,
      roleId: casData.value[2].value,
      roleName: casData.value[2].label,
      orgId: casData.value[0].value,
    } as never);
    handleClose();
  };
  const handleClose = () => {
    addformvisible.value = false;
    casData.value = [];
    modalFormRef.value.reset();
  };

  const tableConfig = ref({
    title: '用户管理',
    api: origanizemanage.userList,
    params: {
      orgId,
    },
    headerActions: [
      {
        label: '新增',
        name: 'userAdd',
        type: 'primary',
        handle: () => {
          opMap.value.type = 'add';
          setTimeout(() => {
            formData.value = {
              orgName: JSON.parse(sessionStorage.getItem('userInfo')).orgName,
            };
            userAuthList.value.splice(0);
          });
          opMap.value.fuc = (formData: any) => {
            return http.post(origanizemanage.addUser, formData).then(() => {
              mainRef.value?.nsTableRef.reload();
              visible.value = false;
              NsMessage.success('操作成功');
            });
          };
          visible.value = true;
        },
      },
      {
        label: '导入',
        type: 'primary',
        name: 'userImport',
        handle: () => {},
      },
      {
        label: '模板下载',
        type: 'primary',
        name: 'userTemDownload',
        handle: () => {},
      },
      {
        label: '导出',
        type: 'primary',
        name: 'userExports',
      },
      {
        label: '批量删除',
        type: 'primary',
        name: 'userBatchDel',
        dynamicDisabled: (data: any) => {
          return data.list.length === 0;
        },
        confirm: true,
        isReload: true,
        isClearCheck: true,
        api: origanizemanage.batchDel,
        dynamicParams: { userIds: 'userId[]' },
      },
    ],
    columns: [
      {
        title: '序号',
        dataIndex: 'address',
        customRender: (text: any) => {
          return text.index + 1;
        },
        sorter: {
          compare: (a, b) => a.address - b.address,
        },
      },
      {
        title: '账号',
        dataIndex: 'accountNo',
        sorter: {
          compare: (a, b) => a.accountNo - b.accountNo,
        },
      },
      {
        title: '姓名',
        dataIndex: 'realName',
        sorter: {
          compare: (a, b) => a.realName - b.realName,
        },
      },
      {
        title: '性别',
        dataIndex: 'sex',
        sorter: {
          compare: (a, b) => a.name - b.name,
        },
      },
      {
        title: '手机号',
        dataIndex: 'telephone',
      },
      {
        title: '邮箱',
        dataIndex: 'email',
      },
      {
        title: '组织关系',
        dataIndex: 'orgName',
      },
      {
        title: '部门/角色',
        dataIndex: 'userRoleInfos',
        customRender: ({ value }) => {
          if (!value) return '-';
          return createVNode('div', {}, [
            createVNode('span', {}, value[0]?.deptRoleInfoList),
            value.length > 1 &&
              createVNode(
                'a',
                {
                  onClick: () =>
                    NsModal.info({
                      icon: null,
                      content: createVNode('div', {
                        innerHTML: value.map((item) => item?.deptRoleInfoList).join('<br>'),
                      }),
                    }),
                },
                `+${value.length}`,
              ),
          ]);
        },
      },
      {
        title: '状态',
        dataIndex: 'userStatus',
        customRender: ({ value }) => ['正常', '冻结'][value],
      },
    ],
    columnActions: {
      title: '操作',
      actions: [
        {
          label: '编辑',
          name: 'userEdit',
          // dynamicParams: 'uuid',
          handle: (record: any) => {
            userAuthList.value.splice(0);
            setTimeout(() => {
              formData.value = record;
              userAuthList.value.push(...record.userRoleInfos);
            }, 10);
            opMap.value.type = 'edit';
            opMap.value.fuc = (formData: any) => {
              return http.post(origanizemanage.editUser, formData).then(() => {
                mainRef.value?.nsTableRef.reload();
                visible.value = false;
                NsMessage.success('操作成功');
              });
            };
            visible.value = true;
          },
        },
        {
          label: '冻结',
          name: 'userFrozen',
          confirm: true,
          defaultParams: { userStatus: 1 },
          dynamicParams: 'userId',
          isReload: true,
          ifShow: ({ userStatus }) => userStatus === 0,
          api: origanizemanage.frozen,
        },
        {
          label: '解冻',
          name: 'userUnFrozen',
          confirm: true,
          defaultParams: { userStatus: 0 },
          dynamicParams: 'userId',
          ifShow: ({ userStatus }) => userStatus === 1,
          isReload: true,
          api: origanizemanage.frozen,
        },
        {
          label: '重置密码',
          name: 'userCodeReset',
          confirm: true,
          handle: ({ userId }: any) => {
            http
              .post(origanizemanage.resetPwd, { userId, password: 123456 })
              .then(() => NsModal.success({ content: '密码重置成功,初始密码123456' }));
          },
        },
        {
          label: '删除',
          name: 'userDelete',
          dynamicParams: 'userId',
          confirm: true,
          isReload: true,
          api: origanizemanage.del,
        },
      ],
    },

    formConfig: {
      schemas: [
        {
          field: 'accountNo',
          label: '账号名',
          component: 'NsInput',
          componentProps: {
            placeholder: '请输入账号名',
            maxLength: 30,
          },
        },
        {
          field: 'realName',
          label: '姓名',
          component: 'NsInput',
          componentProps: {
            placeholder: '请输入姓名',
            maxLength: 30,
          },
        },
        {
          field: 'telephone',
          label: '手机号',
          component: 'NsInput',
          componentProps: {
            placeholder: '请输入手机号',
            maxLength: 11,
          },
        },
        {
          field: 'email',
          label: '邮箱',
          component: 'NsInput',
          componentProps: {
            placeholder: '请输入邮箱',
            maxLength: 30,
          },
        },
        {
          field: 'userStatus',
          label: '用户状态',
          component: 'NsSelect',
          componentProps: {
            allowClear: true,
            placeholder: '请选择用户状态',
            options: [
              {
                label: '正常',
                value: 0,
              },
              {
                label: '冻结',
                value: 1,
              },
            ],
          },
        },
      ],
      params: {},
    },
    // pagination: { defaultPageSize: 10 },
    rowKey: 'userId',
  });
  const tableConfig2 = {
    // api: {
    //   url: '/carbon_emission/device/getGatewayList',
    //   method: 'post',
    // },
    value: userAuthList.value,
    rowSelection: null,
    headerActions: [
      {
        label: '新增',
        name: 'userAdd',
        type: 'primary',
        handle: () => {
          addformvisible.value = true;
        },
      },
    ],
    columns: [
      {
        title: '角色信息',
        dataIndex: 'userRoleList',
        customRender: ({ record }) => {
          if (record) {
            // const res = record.userAuthList.reduce((pre, cur) => {
            //   pre.push(cur.label);
            //   return pre;
            // }, []);
            return record.deptRoleInfoList;
          }
          return '-';
        },
      },
    ],
    columnActions: {
      title: '操作',
      actions: [
        {
          label: '删除',
          name: 'userAdd',
          confirm: true,
          handle: (record: any, name: any, reload: any) => {
            const id = record.roleId;
            console.log(userAuthList.value, id);
            let idx = 0;
            userAuthList.value?.some((item, index) => {
              idx = index;
              if (item.roleId === id) return true;
            });
            userAuthList.value.splice(idx, 1);
          },
        },
      ],
    },
  };
</script>
<style lang="less" scoped>
  .main {
    background-color: @ns-content-bg;
    display: flex;
  }
  .left {
    width: 300px;
    // max-height: calc(100vh - 96px);
    margin-right: @ns-gap;
    min-width: fit-content;
    > div {
      border-radius: @ns-border-radius;
      background-color: @white;
      // box-shadow: @ns-content-box-shadow;
      flex: 1;
    }
    .top:first-child {
      margin-bottom: @ns-gap;
    }

    display: flex;
    flex-direction: column;
  }
  .right {
    flex: 1;
    min-width: 0;
  }
  .top {
    overflow: auto;
    // height: 50%;
    // border-bottom: 5px solid rgb(229, 235, 240);
    // overflow-y: auto;
  }
  .ns-table-title {
    text-align: left;
    // height: 46px;
    line-height: 46px;
    font-size: 18px;
    font-weight: bold;
    padding-left: 16px;
  }
  .admin {
    text-align: left;
    height: 42px;
    line-height: 42px;
    font-size: 16px;
    font-weight: bold;
    user-select: text;
    width: calc(100% + 32px);
  }
  .drawerTable {
    :deep(.ns-table-container),
    :deep(.ns-table-main) {
      border-top: 0;
      padding: 0;
    }
  }
</style>