<template>
  <div class="p-4">
    <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" @click="handleDelete" color="error" :disabled="hasBatchDelete"> 批量删除 </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 #checktime="{ record }">
        {{ record?.checktime?.replace('.0', "") }}
      </template>
      <template #action="{ record }">
        <TableAction :actions="[
          {
            label: '浏览',
            icon: '' /**clarity:note-edit-line*/,
            onClick: handleViewMap.bind(null, record),
          },
          {
            label: '查看',
            icon: '' /**clarity:note-edit-line*/,
            onClick: handleView.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: '提交审核',
            icon: '',
            color: 'warning',
            ifShow: props.isChild,
            disabled: record.status == 3 ? false : true,
            onClick: sendApprove.bind(null, record),
          },
          {
            label: '删除',
            icon: '' /**ant-design:delete-outlined'*/,
            color: 'error',
            ifShow: props.isChild,
            disabled: record.status == 3 ? false : true,
            onClick: handleDelete.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 #keywords="{ record }">
        <span :id="record.id">{{ getKeywords(record.keywords, record.id) }}</span>
      </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>
      <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>
    </BasicTable>
    <!-- <MapDrawer @register="registerDrawer" @success="handleSuccess" /> -->
    <MapSourceModal @register="registerModal" @success="handleSuccess" />
  </div>
</template>
<script lang="ts">
import { defineComponent, nextTick, onBeforeMount, ref } 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 } from 'ant-design-vue';
import { deleteService, queryResourceById } from '/@/api/resource/map';
import { mapList } from '/@/api/dataAdmin/mrerdr';
import Moment from 'moment';
import { queryFlowInfoPage, submitExamine } from '/@/api/resource/examine';
import getKeywords from '/@/views/minWidgets/Keywords.js';
import uiTool from '/@/utils/uiTool';


export default defineComponent({
  name: 'RoleManagement',
  components: { BasicTable, MapDrawer, MapSourceModal, TableAction, Authority, Switch, Popconfirm },
  props: {
    isChild: {
      type: Boolean,
      default: true,
    }
  },
  setup(props) {
    const tagValue = ref('');
    const [registerModal, { openModal }] = useModal();
    const [registerTable, { setProps, reload, setSelectedRowKeys, getSelectRows }] = useTable({
      title: '地图资源列表',
      api: mapList,
      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,
      },
      handleSearchInfoFn: (t) => {
        tagValue.value = t.resTag;
      },
      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,
      });
    }

    async function handleView(record: Recordable) {
      const res = await queryResourceById(record?.serviceid);
      if (res) {
        const result = Object.assign(res.metadata, res.servicebase);
        if (record.bussid) result.bussid = record.bussid;
        openModal(true, {
          record: result,
          isUpdate: true,
          isView: true,
        });
      }
    }

    async function handleEdit(record: Recordable) {
      const res = await queryResourceById(record?.serviceid);
      if (res) {
        const result = Object.assign(res.metadata, res.servicebase);
        if (record.bussid) result.bussid = record.bussid;
        openModal(true, {
          record: result,
          isUpdate: true,
        });
      }
    }

    function sendApprove(e) {
      console.log("状态:", e.bussid, "详情：", e)
      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) {
            let params = {
              bussInfo: {
                bussname: '地图资源上传',//业务名称
                flowid: flow[0].id,//流程id
                serverids: e.serviceid//资源id
              }
            }
            submitExamine(params).then(res => {
              if (res.resp_code === 0 && res.resp_msg === '提交成功') {
                message.success('申请成功')
                reload();
              } else {
                message.error('申请失败')
              }
            })
          }
        }
      })
    }

    function handleViewMap(record: Recordable) {
      window.open(
        `http://192.168.119.143:8080/onemapV5.0/mapview.html?${record.serviceid}`,
        'target',
        ''
      );
    }

    //删除所有选中
    function handleDelete(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 () => { });

    return {
      props,
      getKeywords,
      moment,
      createMessage,
      registerTable,
      // registerDrawer,
      registerModal,
      handleCreate,
      handleViewMap,
      handleEdit,
      handleView,
      sendApprove,
      handleDelete,
      handleSuccess,
      RoleEnum,
      hasBatchDelete,
      handleDeleteOrBatchDelete,
      statusChange,
    };
  },
});
</script>
<style lang="less" scoped>
.p-4 {
  ::v-deep.vben-basic-table-form-container {
    padding: 0;

    ::v-deep.vben-basic-table .ant-table-wrapper {
      padding: 0 20px 10px;
    }
  }
}
</style>
