<script setup lang="ts">
import { reactive, onMounted, toRaw } from 'vue';
import { PageContainer } from 'antdv-pro-layout';
import { message, Modal, Form } from 'ant-design-vue/lib';
import { SizeType } from 'ant-design-vue/lib/config-provider';
import { MenuInfo } from 'ant-design-vue/lib/menu/src/interface';
import { ColumnsType } from 'ant-design-vue/lib/table';
import {
  listDept,
  getDept,
  delDept,
  addDept,
  updateDept,
  listDeptExcludeChild,
} from '@/api/system/tenant';
import { parseDateToStr } from '@/utils/date-utils';
import { regExpMobile, regExpEmail } from '@/utils/regular-utils';
import useDictStore from '@/store/modules/dict';
import { parseDataToTree } from '@/utils/parse-tree-utils';
import { RESULT_CODE_SUCCESS } from '@/constants/result-constants';
import useI18n from '@/hooks/useI18n';

const { t } = useI18n();
const { getDict } = useDictStore();

/**字典数据 */
let dict: {
  /**状态 */
  sysNormalDisable: DictType[];
  /**租户类型 */
  sysTenancyType: DictType[];
} = reactive({
  sysNormalDisable: [],
  sysTenancyType: [],
});

/**查询参数 */
let queryParams = reactive({
  /**部门名称 */
  tenantName: '',
  /**部门状态 */
  status: undefined,
});

/**查询参数重置 */
function fnQueryReset() {
  queryParams = Object.assign(queryParams, {
    tenantName: '',
    status: undefined,
  });
  fnGetList();
}

/**表格全展开行key */
let expandedRowKeys: any[] = [];

/**表格状态类型 */
type TabeStateType = {
  /**加载等待 */
  loading: boolean;
  /**紧凑型 */
  size: SizeType;
  /**搜索栏 */
  seached: boolean;
  /**记录数据 */
  data: object[];
  /**全展开 */
  expandedRowAll: boolean;
  /**展开行key */
  expandedRowKeys: (string | number)[];
};

/**表格状态 */
let tableState: TabeStateType = reactive({
  loading: false,
  size: 'middle',
  seached: false,
  data: [],
  expandedRowAll: false,
  expandedRowKeys: [],
});

/**表格字段列 */
let tableColumns: ColumnsType = [
  {
    title: t('views.system.dept.className'),
    dataIndex: 'tenantName',
    align: 'left',
    width: 300,
  },
  {
    title: t('views.system.dept.key'),
    dataIndex: 'tenancyKey',
    align: 'left',
    width: 200,
  },
  {
    title: t('views.system.dept.type'),
    dataIndex: 'tenancyType',
    key: 'tenancyType',
    align: 'center',
    width: 150,
  },
  {
    title: t('views.system.dept.status'),
    dataIndex: 'status',
    key: 'status',
    align: 'center',
    width: 150,
  },

  {
    title: t('views.system.dept.createTime'),
    dataIndex: 'createTime',
    align: 'center',
    width: 150,
    customRender(opt) {
      if (+opt.value <= 0) return '';
      return parseDateToStr(+opt.value);
    },
  },
  {
    title: t('common.operate'),
    key: 'tenantId',
    align: 'left',
  },
];

/**表格紧凑型变更操作 */
function fnTableSize({ key }: MenuInfo) {
  tableState.size = key as SizeType;
}

/**表格展开行key */
function fnTableExpandedRowsAll(checked: boolean | string | number) {
  tableState.expandedRowKeys = checked ? expandedRowKeys : [];
}

/**表格展开行key */
function fnTableExpandedRowsChange(expandedRows: (string | number)[]) {
  tableState.expandedRowKeys = expandedRows;
}

/**初始上级部门选择树 */
let treeDataAll: Record<string, any>[] = [];

/**对话框对象信息状态类型 */
type ModalStateType = {
  /**详情框是否显示 */
  visibleByView: boolean;
  /**新增框或修改框是否显示 */
  visibleByEdit: boolean;
  /**标题 */
  title: string;
  /**表单数据 */
  from: Record<string, any>;
  /**确定按钮 loading */
  confirmLoading: boolean;
  /**上级部门选择树 */
  treeData: Record<string, any>[];
};

/**对话框对象信息状态 */
let modalState: ModalStateType = reactive({
  visibleByView: false,
  visibleByEdit: false,
  title: '部门',
  from: {
    tenantId: undefined,
    tenantName: '',
    email: '',
    leader: '',
    orderNum: 0,
    parentId: '',
    ancestors: '',
    parentName: null,
    phone: '',
    tenancyKey: '',
    tenancyType: '',
    status: '0',
  },
  confirmLoading: false,
  treeData: [],
});

/**对话框内表单属性和校验规则 */
const modalStateFrom = Form.useForm(
  modalState.from,
  reactive({
    parentId: [
      {
        required: true,
        message: t('views.system.dept.highClass') + t('common.unableNull'),
      },
    ],
    tenantName: [
      {
        required: true,
        min: 1,
        max: 50,
        message: t('views.system.dept.className') + t('common.unableNull'),
      },
    ],
  })
);

/**
 * 对话框弹出显示为 查看
 * @param tenantId 部门编号id
 */
function fnModalVisibleByVive(tenantId: string | number) {
  if (!tenantId) {
    message.error(t('common.getInfoFail'), 2);
    return;
  }
  if (modalState.confirmLoading) return;
  const hide = message.loading(t('common.loading'), 0);
  modalState.confirmLoading = true;
  getDept(tenantId).then(res => {
    modalState.confirmLoading = false;
    hide();
    if (res.code === RESULT_CODE_SUCCESS && res.data) {
      if (res.data.parentId === '0') {
        modalState.treeData = [
          {
            tenantId: '0',
            parentId: '0',
            tenantName: t('views.system.dept.node'),
          },
        ];
      } else {
        //modalState.treeData = treeDataAll;
      }
      modalState.from = Object.assign(modalState.from, res.data);
      modalState.title = t('views.system.dept.classInfo');
      modalState.visibleByView = true;
    } else {
      message.error(t('common.getInfoFail'), 2);
    }
  });
}

/**
 * 对话框弹出显示为 新增或者修改
 * @param tenantId 部门编号id, 不传为新增
 * @param parentId 上级部门id
 */
function fnModalVisibleByEdit(
  tenantId?: string | number,
  parentId?: string | number
) {
  if (!tenantId) {
    modalStateFrom.resetFields();
    if (parentId) {
      modalState.from.parentId = parentId;
    }
    modalState.treeData = treeDataAll;
    modalState.title = t('common.addText') + t('views.system.dept.classInfo');
    modalState.visibleByEdit = true;
  } else {
    if (modalState.confirmLoading) return;
    const hide = message.loading(t('common.loading'), 0);
    modalState.confirmLoading = true;
    // 获取部门信息同时查询部门列表（排除节点）
    Promise.all([getDept(tenantId), listDeptExcludeChild(tenantId)])
      .then(resArr => {
        if (resArr[0].code === RESULT_CODE_SUCCESS && resArr[0].data) {
          modalState.from = Object.assign(modalState.from, resArr[0].data);
          if (
            resArr[1].code === RESULT_CODE_SUCCESS &&
            Array.isArray(resArr[1].data)
          ) {
            if (resArr[1].data.length === 0) {
              modalState.treeData = [
                {
                  tenantId: '0',
                  parentId: '0',
                  tenantName: t('views.system.dept.node'),
                },
              ];
            } else {
              modalState.treeData = parseDataToTree(resArr[1].data, 'tenantId');
            }
          }
          modalState.title =
            t('common.editText') + t('views.system.dept.classInfo');
          modalState.visibleByEdit = true;
        } else {
          message.error(t('common.getInfoFail'), 2);
        }
      })
      .finally(() => {
        modalState.confirmLoading = false;
        hide();
      });
  }
}

/**
 * 对话框弹出确认执行函数
 * 进行表达规则校验
 */
function fnModalOk() {
  modalStateFrom
    .validate()
    .then(() => {
      modalState.confirmLoading = true;
      const from = toRaw(modalState.from);
      console.log('from', from);
      const dept = from.tenantId ? updateDept(from) : addDept(from);
      const hide = message.loading(t('common.loading'), 0);
      dept
        .then(res => {
          if (res.code === RESULT_CODE_SUCCESS) {
            message.success({
              content: t('common.msgSuccess', { msg: modalState.title }),
              duration: 2,
            });
            modalState.visibleByEdit = false;
            // 新增时清空上级部门树重新获取
            if (!from.tenantId) {
              treeDataAll = [];
            }
            modalStateFrom.resetFields();
            fnGetList();
          } else {
            message.error({
              content: `${res.msg}`,
              duration: 2,
            });
          }
        })
        .finally(() => {
          hide();
          modalState.confirmLoading = false;
        });
    })
    .catch(e => {
      message.error(t('common.errorFields', { num: e.errorFields.length }), 2);
    });
}

/**
 * 对话框弹出关闭执行函数
 * 进行表达规则校验
 */
function fnModalCancel() {
  modalState.visibleByEdit = false;
  modalState.visibleByView = false;
  modalStateFrom.resetFields();
}

/**
 * 部门删除
 * @param tenantId 部门编号id
 */
function fnRecordDelete(tenantId: string | number) {
  Modal.confirm({
    title: t('common.tipTitle'),
    content: t('views.system.dept.delSure', { tenantId: tenantId }),
    onOk() {
      const hide = message.loading(t('common.loading'), 0);
      delDept(tenantId).then(res => {
        hide();
        if (res.code === RESULT_CODE_SUCCESS) {
          message.success({
            content: t('common.msgSuccess', { msg: t('common.deleteText') }),
            duration: 2,
          });
          fnGetList();
        } else {
          message.error({
            content: `${res.msg}`,
            duration: 2,
          });
        }
      });
    },
  });
}

/**查询部门列表 */
function fnGetList() {
  if (tableState.loading) return;
  tableState.loading = true;
  listDept(toRaw(queryParams)).then(res => {
    if (res.code === RESULT_CODE_SUCCESS && Array.isArray(res.data)) {
      // 转换树状数据
      const treeData = parseDataToTree(res.data, 'tenantId');
      // 初始上级部门和展开编号key
      if (treeDataAll.length <= 0) {
        // 转换树状数据
        treeDataAll = treeData;
        // 展开编号key
        expandedRowKeys = [
          ...new Set(res.data.map((item: any) => item.parentId)),
        ];
        fnTableExpandedRowsAll(tableState.expandedRowAll);
      }
      tableState.data = treeData;
    }
    tableState.loading = false;
  });
}

onMounted(() => {
  // 初始字典数据
  Promise.allSettled([
    getDict('sys_normal_disable'),
    getDict('tenancy_type'),
  ]).then((resArr: any) => {
    if (resArr[0].status === 'fulfilled') {
      dict.sysNormalDisable = resArr[0].value;
    }
    if (resArr[1].status === 'fulfilled') {
      dict.sysTenancyType = resArr[1].value;
    }
  });
  // 获取列表数据
  fnGetList();
});
</script>

<template>
  <PageContainer>
    <a-card
      v-show="tableState.seached"
      :bordered="false"
      :body-style="{ marginBottom: '24px', paddingBottom: 0 }"
    >
      <!-- 表格搜索栏 -->
      <a-form :model="queryParams" name="queryParams" layout="horizontal">
        <a-row :gutter="16">
          <a-col :lg="6" :md="12" :xs="24">
            <a-form-item
              :label="t('views.system.dept.className')"
              name="tenantName"
            >
              <a-input
                v-model:value="queryParams.tenantName"
                allow-clear
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :xs="24">
            <a-form-item :label="t('views.system.dept.status')" name="status">
              <a-select
                v-model:value="queryParams.status"
                allow-clear
                :options="dict.sysNormalDisable"
              >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :xs="24">
            <a-form-item>
              <a-space :size="8">
                <a-button type="primary" @click.prevent="fnGetList">
                  <template #icon><SearchOutlined /></template>
                  {{ t('common.search') }}
                </a-button>
                <a-button type="default" @click.prevent="fnQueryReset">
                  <template #icon><ClearOutlined /></template>
                  {{ t('common.reset') }}</a-button
                >
              </a-space>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <a-card :bordered="false" :body-style="{ padding: '0px' }">
      <!-- 插槽-卡片左侧侧 -->
      <template #title>
        <a-space :size="8" align="center">
          <a-button
            type="primary"
            @click.prevent="fnModalVisibleByEdit()"
            v-perms:has="['system:dept:add']"
          >
            <template #icon><PlusOutlined /></template>
            {{ t('common.addText') }}
          </a-button>
        </a-space>
      </template>

      <!-- 插槽-卡片右侧 -->
      <template #extra>
        <a-space :size="8" align="center">
          <a-tooltip>
            <template #title>{{ t('views.system.role.openSwitch') }}</template>
            <a-switch
              v-model:checked="tableState.expandedRowAll"
              :checked-children="t('views.system.dept.open')"
              :un-checked-children="t('views.system.dept.open')"
              size="small"
              @change="fnTableExpandedRowsAll"
            />
          </a-tooltip>
          <a-tooltip>
            <template #title>{{ t('common.searchBarText') }}</template>
            <a-switch
              v-model:checked="tableState.seached"
              :checked-children="t('common.switch.show')"
              :un-checked-children="t('common.switch.hide')"
              size="small"
            />
          </a-tooltip>
          <a-tooltip>
            <template #title>{{ t('common.reloadText') }}</template>
            <a-button type="text" @click.prevent="fnGetList">
              <template #icon><ReloadOutlined /></template>
            </a-button>
          </a-tooltip>
          <a-tooltip placement="topRight">
            <template #title>{{ t('common.sizeText') }}</template>
            <a-dropdown placement="bottomRight" trigger="click">
              <a-button type="text">
                <template #icon><ColumnHeightOutlined /></template>
              </a-button>
              <template #overlay>
                <a-menu
                  :selected-keys="[tableState.size as string]"
                  @click="fnTableSize"
                >
                  <a-menu-item key="default"
                    >{{ t('common.size.default') }}
                  </a-menu-item>
                  <a-menu-item key="middle"
                    >{{ t('common.size.middle') }}
                  </a-menu-item>
                  <a-menu-item key="small"
                    >{{ t('common.size.small') }}
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </a-tooltip>
        </a-space>
      </template>
      <!-- 表格列表 -->
      <a-table
        class="table"
        row-key="tenantId"
        :columns="tableColumns"
        :loading="tableState.loading"
        :data-source="tableState.data"
        :size="tableState.size"
        :pagination="false"
        :scroll="{ x: tableColumns.length * 120 }"
        children-column-name="children"
        :expanded-row-keys="tableState.expandedRowKeys"
        @expandedRowsChange="fnTableExpandedRowsChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <DictTag :options="dict.sysNormalDisable" :value="record.status" />
          </template>

          <template v-if="column.key === 'tenancyType'">
            <DictTag
              :options="dict.sysTenancyType"
              :value="record.tenancyType"
            />
          </template>

          <template v-if="column.key === 'tenantId'">
            <a-space :size="8" align="center">
              <a-tooltip>
                <template #title>{{ t('common.viewText') }}</template>
                <a-button
                  type="link"
                  @click.prevent="fnModalVisibleByVive(record.tenantId)"
                  v-perms:has="['system:dept:query']"
                >
                  <template #icon><ProfileOutlined /></template>
                </a-button>
              </a-tooltip>
              <a-tooltip>
                <template #title>{{ t('common.editText') }}</template>
                <a-button
                  type="link"
                  @click.prevent="fnModalVisibleByEdit(record.tenantId)"
                  v-perms:has="['system:dept:edit']"
                >
                  <template #icon><FormOutlined /></template>
                </a-button>
              </a-tooltip>
              <a-tooltip v-if="record.parentId !== '0'">
                <template #title>{{ t('common.deleteText') }}</template>
                <a-button
                  type="link"
                  @click.prevent="fnRecordDelete(record.tenantId)"
                  v-perms:has="['system:dept:remove']"
                >
                  <template #icon><DeleteOutlined /></template>
                </a-button>
              </a-tooltip>
              <a-tooltip placement="topRight" v-if="record.status !== '0'">
                <template #title>{{
                  t('views.system.dept.addClass')
                }}</template>
                <a-button
                  type="link"
                  @click.prevent="
                    fnModalVisibleByEdit(undefined, record.tenantId)
                  "
                  v-perms:has="['system:dept:add']"
                >
                  <template #icon><PlusOutlined /></template>
                </a-button>
              </a-tooltip>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 详情框 -->
    <a-modal
      width="800px"
      :visible="modalState.visibleByView"
      :title="modalState.title"
      @cancel="fnModalCancel"
    >
      <a-form layout="horizontal" :label-col="{ span: 6 }" :labelWrap="true">
        <a-form-item
          :label="t('views.system.dept.highClass')"
          name="parentId"
          :label-col="{ span: 3 }"
          :labelWrap="true"
        >
          <a-tree-select
            :value="modalState.from.parentId"
            disabled
            :tree-data="modalState.treeData"
            :field-names="{
              children: 'children',
              label: 'tenantName',
              value: 'tenantId',
            }"
            tree-node-label-prop="tenantName"
          >
            <template #suffixIcon></template>
          </a-tree-select>
        </a-form-item>
        <a-row :gutter="16">
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              :label="t('views.system.dept.className')"
              name="tenantName"
            >
              {{ modalState.from.tenantName }}
            </a-form-item>
          </a-col>
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              :label="t('views.system.dept.classSort')"
              name="orderNum"
            >
              {{ modalState.from.orderNum }}
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item :label="t('views.system.dept.status')" name="status">
              <DictTag
                :options="dict.sysNormalDisable"
                :value="modalState.from.status"
              />
            </a-form-item>
          </a-col>
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              :label="t('views.system.dept.classId')"
              name="tenantId"
            >
              {{ modalState.from.tenantId }}
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :lg="24" :md="24" :xs="24">
            <a-form-item
              :label="t('views.system.dept.type')"
              name="type"
              :label-col="{ span: 3 }"
              :labelWrap="true"
            >
              {{ modalState.from.tenancyType }}
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <template #footer>
        <a-button key="cancel" @click="fnModalCancel">{{
          t('common.cancel')
        }}</a-button>
      </template>
    </a-modal>

    <!-- 新增框或修改框 -->
    <a-modal
      width="800px"
      :keyboard="false"
      :mask-closable="false"
      :visible="modalState.visibleByEdit"
      :title="modalState.title"
      :confirm-loading="modalState.confirmLoading"
      @ok="fnModalOk"
      @cancel="fnModalCancel"
    >
      <a-form
        name="modalStateFrom"
        layout="horizontal"
        :label-col="{ span: 6 }"
        :labelWrap="true"
      >
        <a-form-item
          :label="t('views.system.dept.highClass')"
          name="parentId"
          v-bind="modalStateFrom.validateInfos.parentId"
          :label-col="{ span: 3 }"
          :labelWrap="true"
        >
          <a-tree-select
            v-model:value="modalState.from.parentId"
            show-search
            tree-default-expand-all
            :tree-data="modalState.treeData"
            :field-names="{
              children: 'children',
              label: 'tenantName',
              value: 'tenantId',
            }"
            tree-node-label-prop="tenantName"
            tree-node-filter-prop="tenantName"
            style="width: 100%"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
          >
          </a-tree-select>
        </a-form-item>

        <a-form-item
          :label="t('views.system.dept.className')"
          name="tenantName"
          v-bind="modalStateFrom.validateInfos.tenantName"
          :label-col="{ span: 3 }"
          :labelWrap="true"
        >
          <a-input
            v-model:value="modalState.from.tenantName"
            allow-clear
            :maxlength="30"
          ></a-input>
        </a-form-item>

        <a-row :gutter="16">
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item :label="t('views.system.dept.status')" name="status">
              <a-select
                v-model:value="modalState.from.status"
                default-value="0"
                :options="dict.sysNormalDisable"
              >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              :label="t('views.system.dept.classSort')"
              name="orderNum"
            >
              <a-input-number
                v-model:value="modalState.from.orderNum"
                :min="0"
                :max="9999"
                :step="1"
              ></a-input-number>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item
              :label="t('views.system.dept.type')"
              name="type"
              :labelWrap="true"
            >
              <a-select
                v-model:value="modalState.from.tenancyType"
                allow-clear
                :options="dict.sysTenancyType"
              >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="24" :md="24" :xs="24">
            <a-form-item
              :label="t('views.system.dept.key')"
              name="key"
              :label-col="{ span: 3 }"
            >
              <a-input
                v-model:value="modalState.from.tenancyKey"
                allow-clear
              ></a-input>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
  </PageContainer>
</template>

<style lang="less" scoped></style>
