<!-- 场景资源上传 -->
<template>
  <div style="height: 100%; width: 100%; margin-top: 0; padding: 0">
    <!-- 使用搜索框和表格封装组件 -->
    <BasicTable :rowSelection="{ type: 'checkbox' }" @register="registerTable" :clickToRowSelect="false">
      <!-- 表格右上角按钮 -->
      <template #toolbar>
        <Authority>
          <a-button type="primary" @click="addMethod">新增场景</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 #action="{ record }">
        <TableAction :actions="[
          {
            label: '浏览',
            // auth: 'api:yt:role:saveOrUpdateRoleInfoWithMenu:update',
            icon: '', //'clarity:note-edit-line', //图标
            onClick: viewScene.bind(null, record),
          },
          {
            label: '查看',
            //auth: 'api:yt:role:saveOrUpdateRoleInfoWithMenu:update',
            icon: '', //'clarity:note-edit-line',
            onClick: handleView.bind(null, record),
          },
          {
            label: '编辑',
            //auth: 'api:yt:role:saveOrUpdateRoleInfoWithMenu:update',
            icon: '', //'clarity:note-edit-line',
            color: 'warning',
            disabled: record.status == 3 ? false : true,
            onClick: handleEdit.bind(null, record),
          },
          {
            label: '提交审核',
            icon: '',
            color: 'warning',
            // ifShow: record.nodename === '',
            disabled: record.status == 3 ? false : true,
            onClick: sendApprove.bind(null, record),
          },
          {
            label: '删除',
            //auth: 'api:yt:role:delete',
            icon: '', //'ant-design:delete-outlined',
            color: 'error',
            ifShow: true,
            disabled: record.status == 3 ? false : true,
            onClick: handleDelete.bind(null, record),
          },
        ]" />
      </template>
      <template #pdate="{ record }">
        <Tag>
          {{ record.publishdate ? moment(record.publishdate).format('YYYY-MM-DD HH:mm:ss') : '' }}
        </Tag>
      </template>
      <template #edate="{ record }">
        <Tag :color="'red'">
          {{ record.edate ? moment(record.edate).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.status === 1 ? '审核完成' : '未提交') : record.nodename
          }}
        </Tag>
      </template>
      <template #checktime="{ record }">
        {{ record?.checktime?.replace(".0", "") }}
      </template>
      <template #checkname="{ record }">
        <Tag>
          {{ record.checkname === '' ? record.publisher : record.checkname }}
        </Tag>
      </template>
    </BasicTable>
    <!-- 新增和编辑 -->
    <!-- <RoleDrawer @register="registerDrawer" @success="handleSuccess" /> -->
    <AddMethod @register="registerModal" @success="handleSuccess"></AddMethod>
  </div>
</template>

<script lang="ts">
import { defineComponent, nextTick } from 'vue';
import { BasicTable, TableAction, useTable } from '/@/components/Table';
import { Authority } from '/@/components/Authority';
import { useModal } from '/@/components/Modal';
import { Popconfirm, message } from 'ant-design-vue';
import { useMessage } from '/@/hooks/web/useMessage';
import { columns, searchFormSchema } from './sceneUploadData';
import { useBatchDelete } from '/@/hooks/web/useBatchDelete';
import AddMethod from './AddMethod.vue';
import Moment from 'moment';
import { list } from '/@/api/resource/scene';
import { deleteService, queryResourceById } from '/@/api/resource/map';
import { queryFlowInfoPage, submitExamine } from '/@/api/resource/examine';
import { sceneList } from '/@/api/dataAdmin/mrerdr';
import getKeywords from '/@/views/minWidgets/Keywords.js';
import uiTool from '/@/utils/uiTool';


export default defineComponent({
  name: 'mapUpload',
  components: { BasicTable, Authority, Popconfirm, TableAction, AddMethod },
  setup() {
    const moment = Moment;
    const { createMessage } = useMessage();
    //按钮的权限控制标识
    const bottomAuthority = 'api:dataresource:sceneupload:';
    const authList = {
      addAuth: bottomAuthority + 'sceneuploadAdd', //新增权限控制
      deleteAuth: bottomAuthority + 'sceneuploadDelete', //删除权限控制
      editAuth: bottomAuthority + 'sceneuploadEdit', //编辑权限控制
    };
    // 新增和编辑界面
    // const [registerDrawer, { openDrawer }] = useDrawer();
    const [registerModal, { openModal: openModal }] = useModal();
    // 新增和编辑界面操作函数
    function handleSuccess() {
      reload();
    }
    // 配置下方表格
    const [registerTable, { setProps, reload, setSelectedRowKeys, getSelectRows }] = useTable({
      // 表格题目
      title: '场景资源列表',
      // 分页查询请求函数
      api: sceneList,//list,
      // 表头
      columns,
      // 查询条件框配置
      formConfig: {
        labelWidth: 120,
        schemas: searchFormSchema,
      },
      useSearchForm: true,
      showTableSetting: true,
      bordered: true,
      // 表格控制序号显示
      showIndexColumn: true,
      // 表格操作栏
      actionColumn: {
        width: 250,
        title: '操作',
        dataIndex: 'action',
        slots: { customRender: 'action' },
        fixed: 'right',
      },
      pagination: {
        hideOnSinglePage: false,
      },
      tableSetting: {
        redo: true,
        size: true,
        setting: false,
        fullScreen: false,
      },
    });
    //
    const { hasBatchDelete, handleDeleteOrBatchDelete, selectionOptions, resetSelectedRowKeys } =
      useBatchDelete(deleteService, handleSuccess, setProps);
    //
    selectionOptions.rowSelection.getCheckboxProps = (record: Recordable) => {
      // Demo:status为1的选择框禁用
      // if (record.status === 1) {
      //   return { disabled: true };
      // } else {
      //   return { disabled: false };
      // }
    };
    //
    nextTick(() => {
      setProps(selectionOptions);
    });
    // 新增
    function handleCreate() {
      openModal(true, {
        isUpdate: false,
      });
    }
    /**
     * 浏览
     */
    function viewScene(record) {
      window.open(
        `http://192.168.119.143:8080/onemapV5.0/sceneview.html?${record.serviceid}`,
        'target',
        ''
      );
    }

    function addMethod() {
      openModal(true, {
        isUpdate: false,
      });
    }

    //查看
    async function handleView(record: Recordable) {
      const res = await queryResourceById(record?.serviceid);
      console.log('场景详情:', record);
      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 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)
          }
        }
      })
    }

    return {
      getKeywords,
      moment,
      createMessage,
      registerModal,
      authList,
      registerTable,
      // handleCreate,
      addMethod,
      viewScene,
      handleView,
      handleEdit,
      sendApprove,
      handleSuccess,
      hasBatchDelete,
      handleDelete,
      handleDeleteOrBatchDelete,
    };
  },
});
</script>