<!-- @format -->

<template>
  <div class="main">
    <div class="left">
      <div class="top">
        <div class="ns-table-title">关联企业</div>
        <div style="height: 100%; overflow-y: auto">
          <a-input-search
            v-model:value="searchValue"
            style="margin-bottom: 8px"
            placeholder="请输入关联企业"
            @search="onSearch" />
          <a-tree
            v-if="treeData?.length"
            :tree-data="treeData"
            defaultExpandAll
            @select="handleSelect">
            <template #title="data">
              {{ data.orgInfo?.orgName }}
            </template>
          </a-tree>
        </div>
      </div>
      <div>
        <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>
      </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="600"
      :visible="addformvisible"
      cancelText="取消"
      @ok="handleOk"
      @cancel="handleClose">
      <ns-form ref="modalFormRef" :schemas="formSchema2" :model="formData2" formLayout="vertical" />
    </a-modal>
  </div>
</template>
<script lang="ts">
  import { computed, createVNode, defineComponent, nextTick, reactive, ref } from 'vue';
  import { http } from '/nerv-lib/util/http';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { cloneDeep } from 'lodash-es';
  import { NsMessage, NsModal } from '/nerv-lib/component';
  import { formConfig, formConfig2 } from './config';
  import { origanizemanage, department } from '/@/api/origanizemanage';

  export default defineComponent({
    name: 'OrderListIndex',
    setup() {
      const mainRef = ref();
      const data = reactive({});
      let formData = ref({});
      let formData2 = ref({ userRoleList: [1, 1, 3] });
      const formRef = ref();
      const modalFormRef = ref();
      const visible = ref(false);
      const addformvisible = ref(false);
      const searchValue = ref<string>('');
      const searchValue2 = ref<string>('');
      const formSchema = formConfig;
      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 dynamicDisabled = computed(() => {
        return formRef.value?.validateResult && userAuthList.value?.length;
      });
      const fetch = (api, params = { orgId }) => {
        return http.post(api, params);
      };

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

      // 部门树
      fetch(origanizemanage.queryDeptTree).then((res) => {
        treeData2.value = res.data;
      });
      const opMap: any = {
        type: 'add',
        fuc: () => {},
        record: {},
      };

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

      const tableFetch = (params) => {
        console.log(mainRef.value);

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

        mainRef.value?.nsTableRef.reload();
      };

      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.fuc && opMap.fuc({ ...formData.value, userRoleList: userAuthList.value, orgId });
          visible.value = false;
        });
      };

      const handleOk = () => {
        console.log(casData.value, 'formData2.value');
        if (casData.value?.length !== 3) {
          NsMessage.error('未选择角色');
        }
        const str = casData.value.map((item) => item?.label).join('/');
        userAuthList.value.push({
          deptRoleInfoList: str,
          roleId: casData.value[2].value,
          roleName: casData.value[2].label,
        } as never);
        handleClose();
      };
      const handleClose = () => {
        addformvisible.value = false;
        modalFormRef.value.reset();
      };

      const tableConfig = ref({
        title: '用户管理',
        api: origanizemanage.userList,
        params: {
          orgId,
        },
        headerActions: [
          {
            label: '新增',
            name: 'userAdd',
            type: 'primary',
            handle: () => {
              opMap.type = 'add';
              opMap.fuc = (formData: any) => {
                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,
            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.type = 'edit';
                opMap.fuc = (formData: any) => {
                  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,
              api: origanizemanage.frozen,
            },
            {
              label: '重置密码',
              name: 'userCodeReset',
              confirm: true,
              handle: ({ userId }: any) => {
                http
                  .post(origanizemanage.resetPwd, { userId })
                  .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: {
                placeholder: '请选择',
                allowClear: true,
                options: [
                  {
                    label: '正常',
                    value: 0,
                  },
                  {
                    label: '冻结',
                    value: 1,
                  },
                ],
              },
            },
          ],
          params: {},
        },
        // pagination: { defaultPageSize: 10 },
        rowKey: 'id',
      });
      const tableConfig2 = {
        // api: {
        //   url: '/carbon_emission/device/getGatewayList',
        //   method: 'post',
        // },
        value: userAuthList.value,
        rowSelection: null,
        headerActions: [
          {
            label: '新增',
            name: 'RoleTypeAdd',
            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: 'RoleTypeEdit',
            //   // dynamicParams: 'uuid',
            //   handle: (record: any) => {
            //     console.log(record, 'record');
            //     formData2.value = record;
            //     opMap.type = 'edit';
            //     opMap.fuc = (formData2: any) => {
            //       Object.assign(
            //         mockData.value.filter((item) => item.id === record.id)[0],
            //         formData2,
            //       );
            //     };
            //     addformvisible.value = true;
            //   },
            // },
            {
              label: '删除',
              name: 'RoleTypeEdit',
              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);
              },
            },
          ],
        },
      };

      return {
        formRef,
        tableConfig,
        tableConfig2,
        data,
        mainRef,
        visible,
        addformvisible,
        formSchema,
        formSchema2,
        formData,
        formData2,
        treeData,
        treeData2,
        searchValue,
        searchValue2,
        handleSelect,
        handleSelect2,
        onClose,
        onEdit,
        onSearch,
        onSearch2,
        handleOk,
        handleClose,
        dynamicDisabled,
        modalFormRef,
      };
    },
  });
</script>
<style lang="less" scoped>
  .main {
    display: flex;
  }
  .left {
    width: 350px;
    border-right: 5px solid rgb(229, 235, 240);
    min-width: fit-content;
  }
  .right {
    flex: 1;
    min-width: 0;
  }
  .top {
    height: 50%;
    border-bottom: 5px solid rgb(229, 235, 240);
  }
  .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>
