<template>
  <div>
    <BasicTable :rowSelection="{ type: 'checkbox' }" @register="registerTable" :clickToRowSelect="false">
      <template #toolbar v-if="props.isChild">
        <Authority>
          <a-button type="primary" @click="handleCreate">新增组件</a-button>
        </Authority>
        <Authority>
          <!-- <Popconfirm title="您确定要批量删除数据" ok-text="确定" cancel-text="取消" @confirm="handleDeleteOrBatchDelete(null)"> -->
          <a-button type="primary" color="error" :disabled="hasBatchDelete" @click="deleteSelect">
            批量删除
          </a-button>
          <!-- </Popconfirm> -->
        </Authority>
      </template>
      <!-- <template #status="{ record }">
        <Switch :checked="record.status === 1" :loading="record.pendingStatus" checkedChildren="启用" unCheckedChildren="禁用"
          @change="(checked: boolean) => statusChange(checked, record)" />
      </template> -->
      <template #action="{ record }">
        <TableAction :actions="[
          {
            label: '浏览',
            icon: '' /**clarity:note-edit-line*/,
            // ifShow: record.servicealiasname,
            // ifShow: ((action) => action.servicealiasname),
            ifShow: record.servicealiasname,
            onClick: see.bind(null, record),
          },
          {
            label: '查看',
            icon: '' /**clarity:note-edit-line*/,
            onClick: handleSee.bind(null, record),
          },
          {
            label: '编辑',
            icon: '' /**clarity:note-edit-line*/,
            color: 'warning',
            ifShow: props.isChild,
            disabled: record.status == 3 ? false : true,
            onClick: handleEdit.bind(null, record),
          },
          {
            label: '提交审核',
            color: 'warning',
            icon: '' /**clarity:note-edit-line*/,
            ifShow: props.isChild,
            disabled: record.status == 3 ? false : true,
            // ifShow: record.servicealiasname,
            onClick: sendApprove.bind(null, record),
          },
          {
            label: '删除',
            icon: '' /**ant-design:delete-outlined'*/,
            color: 'error',
            ifShow: props.isChild,
            disabled: record.status == 3 ? false : true,
            onClick: deleteSelect.bind(null, record),
            // popConfirm: {
            //   title: '是否确认删除',
            //   confirm: deleteSelect.bind(null, record),
            // },
          },
        ]" />
      </template>
      <template #pdate="{ record }">
        <Tag :color="'red'">
          {{ record.publishdate ? moment(record.publishdate).format('YYYY-MM-DD HH:mm:ss') : '' }}
        </Tag>
      </template>
      <template #nodename="{ record }">
        <!-- <Tag>
          {{
            record.nodename == '归档' ? '已完成' : record.nodename
          }}
        </Tag> -->
        {{ record.nodename }}
      </template>
      <template #checkname="{ record }">
        <!-- <Tag>
          {{ record.nodename == '归档' ? '已完成' : record.checkname === '' ? record.publisher : record.checkname }}
        </Tag> -->
        {{ record.checkname }}
      </template>
      <template #checktime="{ record }">
        {{ record?.checktime?.replace('.0', '') }}
      </template>
      <template #status="{ record }">
        <Tag
          :style="`color:${
            record.nodename && record.status == 0
              ? '#F08718'
              : record.status == 1
              ? '#05B069'
              : record.status == 2
              ? 'red'
              : '#8A38F5'
          };`"
        >
          {{
            record.status == 3
              ? '未提交'
              : !record.status && record.nodename
              ? '审核中'
              : record.status == 2
              ? '审核不通过'
              : record.status == 1
              ? '审核通过'
              : ''
          }}
        </Tag>
      </template>
    </BasicTable>
    <MapSourceModal @register="registerModal" @success="handleSuccess" />
  </div>
</template>
<script lang="ts">
import { defineComponent, nextTick, onBeforeMount } from 'vue';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { delRole, setRoleStatus } from '/@/api/system/system';
import { useModal } from '/@/components/Modal';
import MapDrawer from './MapDrawer.vue';
import MapSourceModal from './MapSourceModal.vue';
import { columns, searchFormSchema } from './map.data';
import { RoleEnum } from '/@/enums/roleEnum';
import { Authority } from '/@/components/Authority';
import { useBatchDelete } from '/@/hooks/web/useBatchDelete';
import { useMessage } from '/@/hooks/web/useMessage';
import { Switch, Popconfirm, message, Modal } from 'ant-design-vue';
import { list, deleteService } from '/@/api/dataAdmin/assembly';
import Moment from 'moment';
//提交授权申请
import { queryFlowInfoPage, submitExamine } from '/@/api/resource/examine';
import uiTool from '/@/utils/uiTool';
import { assList } from '/@/api/dataAdmin/mrerdr';

export default defineComponent({
  name: 'RoleManagement',
  components: { BasicTable, MapDrawer, MapSourceModal, TableAction, Authority, Switch, Popconfirm },
  props: {
    isChild: {
      type: Boolean,
      default: true,
    }
  },
  setup(props) {
    const [registerModal, { openModal }] = useModal();
    const [registerTable, { setProps, reload, setSelectedRowKeys, getSelectRows }] = useTable({
      title: '组件资源列表',
      // api: list,
      api: assList,
      columns,
      formConfig: {
        labelWidth: 100,
        schemas: searchFormSchema,
      },
      useSearchForm: true,
      showTableSetting: true,
      bordered: true,
      showIndexColumn: true,
      actionColumn: {
        width: props.isChild ? 250 : 100,
        title: '操作',
        dataIndex: 'action',
        slots: { customRender: 'action' },
        fixed: 'right',
      },
      pagination: {
        hideOnSinglePage: false,
      },
      tableSetting: {
        redo: true,
        size: true,
        setting: false,
        fullScreen: false,
      },
    });
    const moment = Moment;
    const { createMessage } = useMessage();
    const { hasBatchDelete, handleDeleteOrBatchDelete, selectionOptions, resetSelectedRowKeys } =
      useBatchDelete(delRole, handleSuccess, setProps);
    selectionOptions.rowSelection.getCheckboxProps = (record: Recordable) => {
      // Demo:status为1的选择框禁用
      return { disabled: record.status == 3 ? false : true };
    };
    nextTick(() => {
      setProps(selectionOptions);
    });

    function handleCreate() {
      openModal(true, {
        isUpdate: false,
        isView: null
      });
    }

    //编辑
    function handleEdit(record: Recordable) {
      console.log("编辑:", record);
      openModal(true, {
        record,
        isUpdate: true,
        isView: false
      });
    }
    //查看
    function handleSee(record: Recordable) {
      console.log('查看:', record);
      openModal(true, {
        record,
        isUpdate: true,
        isView: true,
      });
    }

    function see(e) {
      console.log(e);
      if (e.servicealiasname)
        window.open(`../../mapview.html?onlineIde_${e.servicealiasname}`, '_blank');
    }

    //删除所有选中
    function deleteSelect(record) {
      uiTool.delModal('确定删除选中的组件资源？', async () => {
        var ids = record?.serviceid
          ? record.serviceid
          : getSelectRows()
              .map((i) => i.serviceid)
              .toString();
        if (ids) {
          const res = await deleteService(ids);
          if (res?.status !== '-1') {
            reload();
            createMessage.success('删除成功！', 1);
          } else {
            createMessage.error('删除失败！失败原因：' + res?.message, 1);
          }
        }
      });
    }

    function handleSuccess() {
      openModal(false, {
        isUpdate: false,
      });
      reload();
    }

    const statusChange = async (checked, record) => {
      setProps({
        loading: true,
      });
      setSelectedRowKeys([]);
      resetSelectedRowKeys();
      const newStatus = checked ? 1 : 0;
      try {
        await setRoleStatus(record.id, newStatus);
        if (newStatus) {
          createMessage.success(`启用成功`);
        } else {
          createMessage.success('禁用成功');
        }
      } finally {
        setProps({
          loading: false,
        });
        reload();
      }
    };
    onBeforeMount(async () => {});

    function sendApprove(e) {
      let params = {
        bussInfo: {
          bussname: '组件资源上传', //业务名称
          flowid: '', //流程id
          serverids: e.serviceid, //资源id
        },
      };
      if (e && e.flowid && e.flowid !== '') {
        params.bussInfo.flowid = e.flowid;
        submitExamine(params).then((res) => {
          if (res.resp_code === 0 && res.resp_msg === '提交成功') {
            message.success('申请成功');
            reload();
          } else {
            message.error('申请失败');
          }
        });
      } else {
        queryFlowInfoPage({
          page: 1,
          rows: 1000000,
        }).then((flowRes) => {
          console.log('flowRes:', flowRes);
          if (flowRes && flowRes.length) {
            var flow = flowRes.filter((i) => i.FLOWNAME === '组件资源上传');
            if (flow.length) {
              params.bussInfo.flowid = flow[0].id;
              submitExamine(params).then((res) => {
                if (res.resp_code === 0 && res.resp_msg === '提交成功') {
                  message.success('申请成功');
                  reload();
                } else {
                  message.error('申请失败');
                }
              });
            }
          }
        });
      }
    }

    return {
      props,
      handleSee,
      deleteSelect,
      sendApprove,
      moment,
      createMessage,
      registerTable,
      registerModal,
      handleCreate,
      see,
      handleEdit,
      handleSuccess,
      RoleEnum,
      hasBatchDelete,
      handleDeleteOrBatchDelete,
      statusChange,
    };
  },
});
</script>
