/*Menu
 * @Author: wfl
 * @LastEditors: lyh
 * @description:
 * @updateInfo:
 * @Date: 2022-08-03 17:15:24
 * @LastEditTime: 2022-08-11 16:10:46
 */
import { deleteDep, getDepList, updateDep } from '@/mainApp/api/sys-default/dep';
import { useMessage } from '@/global/hooks/web/useMessage';
import { Button, FormItem, Input, Skeleton, Switch, Table } from 'ant-design-vue';
// import { Button, Table } from 'ant-design-vue';
import GlContentHeader from '@/global/components/GlContentHeader';
import GlContentSearch from '@/global/components/GlContentSearch';
import { PlusOutlined } from '@ant-design/icons-vue';
import { ikTree } from 'iking-utils';
import * as _ from 'lodash-es';
import { defineComponent, Ref, ref } from 'vue';
import DepModal from './depModal.vue';

const depManage = defineComponent({
  setup() {
    const { createMessage, createConfirm } = useMessage();
    const depTree: Ref<null | Array<any>> = ref(null);
    const loading = ref(false);
    const defaultExpand: Ref<string[]> = ref([]);
    const isChild = ref(false);
    const searchForm = ref({
      name: '',
    });
    const getDepTreeData = (status = false) => {
      // 排序时DOM结构被更改，此操作用于正确显示排序后的结果
      if (status) {
        depTree.value = [];
      }
      loading.value = true;
      getDepList()
        .then(({ success, data, msg }) => {
          if (success) {
            depTree.value = ikTree.listToTree(
              data.map((item, index) => {
                item.key = '' + index;
                return item;
              }),
            );
            defaultExpand.value = depTree.value?.map((item: { key: string }) => item.key) || [];
          } else {
            createMessage.warning(msg);
          }
          loading.value = false;
        })
        .catch(() => {
          loading.value = false;
        });
    };
    getDepTreeData();

    const tableKeys = [
      {
        title: '部门名称',
        dataIndex: 'name',
      },
      {
        title: '主管',
        dataIndex: 'manager.username',
        width: 150,
      },
      {
        title: '电话',
        dataIndex: 'phone',
        width: 150,
      },
      {
        title: '用户数',
        dataIndex: 'permissionCode',
        width: 60,
        align: 'center',
      },
      {
        title: '操作',
        dataIndex: '_1',
        width: 180,
      },
    ];

    const visible = ref(false);
    const editData = ref(null);
    const handNewDep = () => {
      editData.value = null;
      visible.value = true;
    };
    const handleShow = (visib: boolean) => {
      visible.value = visib;
      !visib && (isChild.value = false);
    };

    const handEditDep = (record: any) => {
      visible.value = true;
      editData.value = record;
    };

    const handAddChild = (record: any) => {
      isChild.value = true;
      editData.value = record;
      visible.value = true;
    };
    //获取主管
    const getManage = (record: any) => {
      return record.manager ? record.manager.name : '--';
    };

    const handDeleteDep = (record: any) => {
      createConfirm({
        title: '提示',
        content: '确定删除该部门吗？',
        iconType: 'warning',
        onOk: () => {
          loading.value = true;

          deleteDep(record.id)
            .then(({ success, msg }) => {
              if (success) {
                getDepTreeData();
              } else {
                createMessage.warning(msg);
              }
              loading.value = false;
            })
            .catch(() => {
              loading.value = false;
            });
        },
      });
    };
    const handChangeVisible = (val: boolean, record: any) => {
      loading.value = true;
      updateDep(record)
        .then(({ success, msg }) => {
          if (success) {
            // getMenuTreeData();
          } else {
            createMessage.warning(msg);
            record.visible = !val;
          }
          loading.value = false;
        })
        .catch(() => {
          loading.value = false;
        });
    };
    const btnPagging = '!px-5px';
    return () => (
      <>
        <GlContentSearch formRef={searchForm} onSearch={() => getDepTreeData(true)}>
          {{
            default: () => {
              return (
                <>
                  <FormItem label="部门名称">
                    <Input
                      allowClear
                      placeholder="请输入部门名称"
                      modelValue={searchForm.value.name}
                    ></Input>
                  </FormItem>
                </>
              );
            },
          }}
        </GlContentSearch>
        <DepModal
          title={isChild.value ? '新增子部门' : editData.value ? '修改部门' : '新增部门'}
          visible={visible.value}
          isChild={isChild.value}
          editData={editData.value}
          onVisibleChange={(val) => handleShow(val)}
          onDataChange={() => getDepTreeData()}
        />
        <GlContentHeader
          onSearch={() => getDepTreeData()}
          onRefresh={() => getDepTreeData()}
          title="部门管理"
          btnList={[]}
        >
          {{
            btnList: () => {
              return (
                <>
                  <Button type="primary" onClick={() => handNewDep()}>
                    {{
                      icon: () => <PlusOutlined />,
                      default: '新增部门',
                    }}
                  </Button>
                </>
              );
            },
            default: ({ height, size }) => {
              return depTree.value ? (
                <Table
                  size={size}
                  loading={loading.value}
                  bordered
                  defaultExpandedRowKeys={defaultExpand.value}
                  pagination={false}
                  columns={tableKeys}
                  customRow={(record) => {
                    const attrs = _.cloneDeep(record);
                    attrs?.children && delete attrs.children;
                    return {
                      __attrs: JSON.stringify(attrs),
                    };
                  }}
                  dataSource={depTree.value || []}
                  scroll={{
                    scrollToFirstRowOnChange: true,
                    y: height,
                  }}
                >
                  {{
                    bodyCell: ({ column, record }) => {
                      return column.dataIndex === '_0' ? (
                        <Switch
                          v-model:checked={record.visible}
                          checkedValue={true}
                          unCheckedValue={false}
                          checked-children="显示"
                          un-checked-children="隐藏"
                          onChange={(val: boolean) => handChangeVisible(val, record)}
                        />
                      ) : column.dataIndex === '_1' ? (
                        <>
                          <Button
                            type="link"
                            onClick={() => handAddChild(record)}
                            class={btnPagging}
                          >
                            新增子部门
                          </Button>
                          <Button
                            type="link"
                            onClick={() => handEditDep(record)}
                            class={btnPagging}
                          >
                            编辑
                          </Button>
                          <Button
                            type="text"
                            onClick={() => handDeleteDep(record)}
                            danger
                            class={btnPagging}
                          >
                            删除
                          </Button>
                        </>
                      ) : column.dataIndex === 'manager.username' ? (
                        <span>{getManage(record)}</span>
                      ) : column.dataIndex === 'permissionCode' ? (
                        <span>{record.userCount}</span>
                      ) : (
                        <div>{record[column.dataIndex]}</div>
                      );
                    },
                  }}
                </Table>
              ) : (
                <>
                  <Skeleton active />
                  <Skeleton active />
                </>
              );
            },
          }}
        </GlContentHeader>
      </>
    );
  },
});

export default depManage;
