<!-- 文件型资源上传 -->
<template>
  <div style="height: 100%; width: 100%; margin-top: 0; padding: 0">
    <!-- 使用搜索框和表格封装组件 -->
    <BasicTable :rowSelection="{ type: 'checkbox' }" @register="registerTable" :clickToRowSelect="false">
      <!-- 表格右上角按钮 -->
      <template #toolbar v-if="props.isChild">
        <Authority>
          <a-button type="primary" @click="addMethod">新增文件</a-button>
        </Authority>
        <Authority>
          <!-- <Popconfirm title="您确定要批量删除数据" ok-text="确定" cancel-text="取消" @confirm="handleDeleteOrBatchDelete(null)"> -->
          <a-button @click="handleDelete" type="primary" 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: handleUpload.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',
            ifShow: props.isChild,
            disabled: record.status == 3 ? false : true,
            onClick: handleEdit.bind(null, record),
          },
          {
            label: '提交审核',
            //auth: 'api:yt:role:saveOrUpdateRoleInfoWithMenu:update',
            //icon: 'clarity:note-edit-line',
            color: 'warning',
            ifShow: props.isChild,
            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: props.isChild,
            disabled: record.status == 3 ? false : true,
            onClick: handleDelete.bind(null, record),
          },
        ]" />
      </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 #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 #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>
    <!-- 新增和编辑 -->
    <!-- <RoleDrawer @register="registerDrawer" @success="handleSuccess" /> -->
    <addMethod @register="registerModal" @success="handleSuccess"></addMethod>
  </div>
</template>

<script>
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 { getFileListByPage, delFileResource } from '../../api/fileUploadApi';
import { columns, searchFormSchema } from './fileUploadData';
import { useMessage } from '/@/hooks/web/useMessage';
import { list } from '/@/api/resource/files';
import { useBatchDelete } from '/@/hooks/web/useBatchDelete';
import AddMethod from './AddMethod.vue';
import Moment from 'moment';
import { getFileUrl } from '/@/api/resource/files';
import { deleteService, deleteBatchService, queryResourceById } from '/@/api/resource/map';
import { session } from '/@/utils/Memory.js';
import { queryFlowInfoPage, submitExamine } from '/@/api/resource/examine';
import { fileList } 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 },
  props: {
    isChild: {
      type: Boolean,
      default: true,
    }
  },
  setup(props) {
    //按钮的权限控制标识
    const bottomAuthority = 'api:dataresource:fileupload:';
    const authList = {
      addAuth: bottomAuthority + 'fileuploadAdd', //新增权限控制
      deleteAuth: bottomAuthority + 'fileuploadDelete', //删除权限控制
      editAuth: bottomAuthority + 'fileuploadEdit', //编辑权限控制
    };
    const moment = Moment;
    const { createMessage } = useMessage();
    // 新增和编辑界面
    const [registerModal, { openModal: openModal }] = useModal();
    // 新增和编辑界面操作函数
    function handleSuccess() {
      reload();
    }
    // 配置下方表格
    const [registerTable, { setProps, reload, setSelectedRowKeys, getSelectRows }] = useTable({
      // 表格题目
      title: '文件型资源列表',
      // 分页查询请求函数
      api: fileList,//list,
      // 表头
      columns,
      // 查询条件框配置
      formConfig: {
        labelWidth: 90,
        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 { hasBatchDelete, handleDeleteOrBatchDelete, selectionOptions, resetSelectedRowKeys } =
      useBatchDelete(deleteBatchService, handleSuccess, setProps);
    //
    selectionOptions.rowSelection.getCheckboxProps = (record) => {
      // Demo:status为1的选择框禁用
      return { disabled: record.status == 3 ? false : true };
    };
    //
    nextTick(() => {
      setProps(selectionOptions);
    });
    // 新增
    function addMethod() {
      openModal(true, {
        isUpdate: false,
      });
    }

    /**
     * 查看
     */
    async function handleView(record) {
      const res = await queryResourceById(record?.serviceid);
      if (res) {
        console.log('文件资源查看某个res:', res);
        if (res.dataVersionConf) {
          res.metadata.isnew = res.servicebase.isnew = res.dataVersionConf.active == 'Y' ? "1" : "0";
        }
        const result = Object.assign(res.metadata, res.servicebase, res.dataVersionConf || {});
        if (record.bussid) result.bussid = record.bussid;
        openModal(true, {
          record: result,
          isUpdate: true,
          isView: true,
        });
      }
    }

    /**
     * 文件下载
     */
    async function handleUpload(record) {
      console.log('下载文件', record);
      const obj = {
        id: record['fileid'],
        userid: record['userid'],
        parentId: session.getItem('sysFild').dirId,
      };
      const res = await getFileUrl(obj);
      if (res) {
        const fileName = res.fileName;
        const url = res.url;
        // fetch(url)
        //   .then((res) => res.blob())
        //   .then((blob) => {
        //     // 将链接地址字符内容转变成blob地址
        //     const a = document.createElement('a');
        //     a.href = URL.createObjectURL(blob);
        //     //测试链接console.log(a.href)
        //     a.download = fileName; // 下载文件的名字
        //     document.body.appendChild(a);
        //     a.click();
        //   });
        window.open(url);
      }
    }

    /**
     * 编辑
     */
    async function handleEdit(record) {
      const res = await queryResourceById(record?.serviceid);
      if (res) {
        console.log('文件资源查看某个res:', res);
        if (res.dataVersionConf) {
          res.metadata.isnew = res.servicebase.isnew = res.dataVersionConf.active == 'Y' ? "1" : "0";
        }
        const result = Object.assign(res.metadata, res.servicebase, res.dataVersionConf || {});
        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 {
      props,
      getKeywords,
      moment,
      createMessage,
      registerModal,
      authList,
      registerTable,
      addMethod,
      handleView,
      handleEdit,
      handleUpload,
      sendApprove,
      handleSuccess,
      hasBatchDelete,
      handleDelete,
      handleDeleteOrBatchDelete,
    };
  },
});
</script>