<template>
  <PageWrapper dense contentFullHeight fixedHeight>
    <BasicTable @register="registerTable" :isMenuTable="true">
      <template #toolbar>
        <a-button @click.stop="add" type="primary" v-auth="'PublicStamp:add'">{{
          t('新增')
        }}</a-button>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              auth: 'PublicStamp:disable',
              label: record.enabledMark === 1 ? '禁用' : '启用',
              ifShow: record.enabledMark !== -1,
              onClick: setEnabled.bind(null, record),
            },
            {
              auth: 'PublicStamp:defaultStamp',
              label: '设置默认签章',
              ifShow: stampInfo.type == StampType.PRIVATE_SIGNATURE,
              onClick: setDefault.bind(null, record),
            },
            {
              auth: 'PublicStamp:designMaintainPersonnel',
              label: '指定维护人员',
              ifShow: stampInfo.type == StampType.PUBLIC_SIGNATURE && userName == 'admin',
              onClick: checkSingleRow.bind(null, record),
            },
            {
              label: '添加人员',
              auth: 'PublicStamp:addPeople',
              disabled: isDisabled(record.maintain),
              onClick: handleAddUser.bind(null, record),
              ifShow: stampInfo.type == StampType.PUBLIC_SIGNATURE,
            },
            {
              label: '编辑',
              auth: 'PublicStamp:edit',
              disabled: isDisabled(record.maintain),
              onClick: edit.bind(null, record),
            },
            {
              label: '删除',
              auth: 'PublicStamp:delete',
              color: 'error',
              disabled: isDisabled(record.maintain),
              popConfirm: {
                title: t('是否确认删除'),
                confirm: handleDelete.bind(null, record.id),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <StampDetail
      v-if="stampInfo.visible"
      :info="stampInfo.info"
      :type="stampInfo.type"
      :id="stampInfo.id"
      @close="close"
    />
    <SelectMember
      v-if="visible"
      :visible="visible"
      :multiple="true"
      :selectedIds="selectedUserIds"
      @close="
        () => {
          visible = false;
        }
      "
      @change="handleUserpost"
    />
    <SelectUser
      v-if="userVisible"
      :isShow="userVisible"
      :selectedIds="maintainIds"
      :multiple="true"
      @change="designated"
      @close="userVisible = false"
    />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import StampDetail from './components/stamp/StampInfo.vue';
  import {
    getStampList,
    deleteStamp,
    EnabledStamp,
    setDefaultStamp,
    addMaintain,
    getStampMember,
    addMember,
  } from '/@/api/workflow/stamp';
  import { StampInfo } from '/@/api/workflow/model';

  import { SelectUser, SelectMember } from '/@/components/SelectOrganizational/index';
  import { StampType } from '/@/enums/workflowEnum';
  import { useRouter } from 'vue-router';
  import { notification, Switch, Tag, Image } from 'ant-design-vue';

  import { ref, onMounted, computed, reactive, h } from 'vue';
  import { BasicTable, useTable, TableAction, FormSchema, BasicColumn } from '/@/components/Table';
  import { usePermission } from '/@/hooks/web/usePermission';

  import { PageWrapper } from '/@/components/Page';
  import { useUserStore } from '/@/store/modules/user';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const configColumns: BasicColumn[] = [
    {
      title: t('签章名字'),
      dataIndex: 'name',
      width: 180,
      resizable: true,
    },
    {
      title: t('签章分类'),
      dataIndex: 'stampCategoryName',
      width: 160,
      resizable: true,
    },
    {
      title: t('图片'),
      dataIndex: 'fileUrl',
      width: 160,
      resizable: true,
      customRender: ({ record }) => {
        return h(Image, {
          src: record.fileUrl,
          width: '60px',
          height: '22px',
        });
      },
    },
    {
      title: t('状态'),
      dataIndex: 'enabledMark',
      width: 120,

      resizable: true,
      customRender: ({ record }) => {
        return h(Switch, {
          checked: record.enabledMark === 1,
          checkedChildren: t('已启用'),
          unCheckedChildren: t('已禁用'),
        });
      },
    },
    {
      title: t('默认签章'),
      dataIndex: 'isDefault',
      width: 120,
      resizable: true,
      customRender: ({ record }) => {
        return record.isDefault == 1 ? h(Tag, { color: 'processing' }, () => t('默认')) : h('div');
      },
    },
    {
      title: t('备注'),
      resizable: true,
      dataIndex: 'remark',
    },
  ];

  const searchFormSchema: FormSchema[] = [
    {
      field: 'keyword',
      label: t('关键字'),
      component: 'Input',
      colProps: { span: 8 },
      componentProps: {
        placeholder: t('请输入关键字'),
      },
    },
  ];
  const visible = ref<boolean>(false);
  const userVisible = ref<boolean>(false);

  const selectedUserIds = ref<string[]>([]);
  const userStore = useUserStore();
  const { hasPermission } = usePermission();

  const title = computed(() => {
    return stampInfo.type == StampType.PRIVATE_SIGNATURE ? t('电子签章列表') : t('公共签章列表');
  });
  const actionColumn = computed(() => {
    return {
      width: stampInfo.type == StampType.PRIVATE_SIGNATURE ? 250 : 320,
      title: t('操作'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
      fixed: undefined,
    };
  });
  const userName = computed(() => {
    return userStore.getUserInfo.userName;
  });

  let stampInfo: {
    type: StampType;
    id: string;
    visible: boolean;
    info: StampInfo | undefined;
  } = reactive({
    id: '',
    info: undefined,
    visible: false,
    type: StampType.PRIVATE_SIGNATURE,
  });
  const [registerTable, { reload, setColumns, setProps }] = useTable({
    title: title,
    api: getStampList,
    rowKey: 'id',
    columns: configColumns,
    formConfig: {
      rowProps: {
        gutter: 16,
      },
      schemas: searchFormSchema,
      showResetButton: false,
    },
    rowSelection: {
      type: 'radio',
    },
    beforeFetch: (params) => {
      //发送请求默认新增  左边树结构所选区域id
      return { ...params, stampType: stampInfo.type };
    },
    striped: false,
    useSearchForm: true,
    showTableSetting: true,
    tableSetting: {
      size: false,
    },
    customRow: (record) => {
      return {
        ondblclick: () => {
          if (hasPermission('PublicStamp:edit')) {
            edit(record);
          }
        },
      };
    },
  });
  onMounted(async () => {
    const { currentRoute } = useRouter();
    stampInfo.type =
      currentRoute.value.name == 'PublicStamp'
        ? StampType.PUBLIC_SIGNATURE
        : StampType.PRIVATE_SIGNATURE;
    let column = configColumns;
    if (currentRoute.value.name == 'PublicStamp') {
      column = column.filter((o) => {
        return o.dataIndex != 'isDefault';
      });
    }
    setProps({
      actionColumn: actionColumn.value,
    });
    setColumns(column);
  });

  const maintainIds = ref<string[]>([]);

  function isDisabled(ids) {
    if (stampInfo.type == 1) {
      let arr = ids ? ids.split(',') : [];
      return userName.value == 'admin' ? false : !arr.includes(userStore.getUserInfo.id);
    } else {
      return false;
    }
  }

  function add() {
    stampInfo.id = '';
    stampInfo.info = undefined;
    stampInfo.visible = true;
  }
  function edit(row: StampInfo) {
    if (row.id) stampInfo.id = row.id;
    stampInfo.info = row;
    stampInfo.visible = true;
  }
  function close() {
    stampInfo.visible = false;

    reload();
  }
  async function handleDelete(id: string) {
    try {
      let res = await deleteStamp([id]);
      save(res, t('删除'));
    } catch (error) {}
    reload();
  }
  async function setEnabled(record) {
    try {
      let res = await EnabledStamp(record.id);
      save(res, record.enabledMark === 1 ? t('禁用') : t('启用'));
    } catch (error) {}
    reload();
  }
  async function setDefault(record) {
    try {
      let res = await setDefaultStamp(record.id);
      save(res, t('默认签章'));
    } catch (error) {}
    reload();
  }

  async function designated(ids) {
    try {
      let res = await addMaintain(stampInfo.id, ids);
      save(res, t('指定维护人员'));
    } catch (error) {}
    reload();
  }
  function save(res: boolean, title: string) {
    if (res) {
      notification.open({
        type: 'success',
        message: title,
        description: t('成功'),
      });
    } else {
      notification.open({
        type: 'error',
        message: title,
        description: t('失败'),
      });
    }
  }
  function checkSingleRow(record) {
    stampInfo.id = record.id;
    maintainIds.value = record.maintain ? record.maintain.split(',') : [];
    userVisible.value = true;
  }

  function handleAddUser(record: Recordable) {
    stampInfo.id = record.id;
    getStampMember(record.id).then((res) => {
      selectedUserIds.value = res.map((it) => {
        return it.id;
      });
      visible.value = true;
    });
  }
  function handleUserpost(v) {
    addMember(stampInfo.id, v).then(() => {
      notification.success({
        message: t('添加成员成功'),
        description: t('成功'),
      });
    });
  }
</script>
