<template>
  <div class="examine-container">
    <div class="left-container">
      <template v-for="source in sourceTypes" :key="source.SERVICETYPE">
        <div class="soure-item-row" :class="{ active: current === source.SERVICETYPE }" @click="selectHandle(source)">
          {{ source.name }}
        </div>
      </template>
    </div>
    <div class="right-container">
      <BasicTable @register="registerTable" @fetch-success="onFetchSuccess">
        <template #toolbar>
          <Authority>
            <a-button type="primary" @click="batchExamine" :disabled="hasBatchDelete">指定IP设置</a-button>
          </Authority>
        </template>

        <template #action="{ record }">
          <TableAction :actions="[
            {
              label: '浏览',
              ifShow: current == 'DR' ? false : true,
              onClick: handleVliew.bind(null, record),
            },
            {
              label: '查看',
              onClick: handleDetail.bind(null, record),
            },
            {
              label: '审核',
              disabled: statusShow == 1 ? false : true,
              color: 'warning',
              onClick: handleEdit.bind(null, record),
            },
          ]" />
        </template>
        <template #pdate="{ record }">
          <a-tag :color="'red'">
            {{ record.publishdate ? moment(record.publishdate).format('YYYY-MM-DD HH:mm:ss') : '' }}
          </a-tag>
        </template>
        <template #FLOWNAME="{ record }">
          {{ record.FLOWNAME.replace('上传', '') }}
        </template>
        <template #status="{ record }">
          <a-tag :style="`color:${record.status === 3 || record.status === 3 ? 'red' : ''};`">
            {{
              !record.status ? '待审核' : record.status == 2 ? '审核不通过' : record.status ? '审核通过' : ''
            }}
          </a-tag>
        </template>
        <template #BLZT="{ record }">
          <a-tag :style="`color:${record.status === 3 || record.status === 3 ? 'red' : ''};`">
            {{
              record.BLZT
            }}
          </a-tag>
        </template>
      </BasicTable>
      <check v-if="ischect" @register="registerModal" @success="handleSuccess" />
      <map-resource-upload v-if="!ischect && current === 'MR'" @register="registerModal"
        @success="handleSuccess"></map-resource-upload>
      <scene-resource-upload v-if="!ischect && current === 'ER'" @register="registerModal"
        @success="handleSuccess"></scene-resource-upload>
      <file-resource-upload v-if="!ischect && current === 'DR'" @register="registerModal"
        @success="handleSuccess"></file-resource-upload>
      <ass-resource-upload v-if="!ischect && current === 'SR'" @register="registerModal"
        @success="handleSuccess"></ass-resource-upload>
    </div>
  </div>
</template>
<script lang="ts">
import { defineComponent, nextTick, ref, watch } from 'vue';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { delRole, setRoleStatus } from '/@/api/system/system';
import MapResourceUpload from '/@/views/dataAdmin/dataAdmin/mapUpload/MapSourceModal.vue';
import FileResourceUpload from '/@/views/dataAdmin/dataAdmin/fileResourceUpload/AddMethod.vue';
import SceneResourceUpload from '/@/views/dataAdmin/dataAdmin/sceneResourceUpload/AddMethod.vue';
import AssResourceUpload from '/@/views/dataAdmin/assembly/MapSourceModal.vue';
import check from './check.vue';
import { getFileUrl } from '/@/api/resource/files';
import { session } from '/@/utils/Memory.js';
import {
  columns,
  searchFormSchemaMR,
  searchFormSchemaER,
  searchFormSchemaDR,
  searchFormSchemaSR,
} 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 } from 'ant-design-vue';
import { queryResourceById } from '/@/api/resource/map';
import Moment from 'moment';
import { updateExamine } from '/@/api/resource/updateExamine';
import { useModal } from '/@/components/Modal';
import { useRouter } from 'vue-router';
import { useAppStore } from '/@/store/modules/app';

export default defineComponent({
  name: 'RoleManagement',
  components: {
    BasicTable,
    check,
    TableAction,
    Authority,
    Switch,
    Popconfirm,
    MapResourceUpload,
    FileResourceUpload,
    AssResourceUpload,
    SceneResourceUpload,
  },
  setup() {
    const appStore = useAppStore();
    const { currentRoute } = useRouter();
    const currRoute = currentRoute.value;
    let current = ref(currRoute?.query?.type || 'MR');
    let statusShow = ref(1);
    const [registerTable, { getSelectRows, setProps, reload, setSelectedRowKeys, getDataSource }] = useTable({
      title: '地图资源审核列表',
      api: (param) => {
        statusShow.value = param.checkStatus;
        const data = Object.assign(param, { serviceType: current.value });
        return updateExamine(data);
      }, //求接口
      //dataSource: dataSources, //表格的数据
      columns,
      rowKey: (record) => record.BUSSID,
      formConfig: {
        labelWidth: 90,
        schemas: searchFormSchemaMR,
      },
      useSearchForm: true,
      showTableSetting: true,
      bordered: true,
      showIndexColumn: true,
      actionColumn: {
        width: 200,
        title: '操作',
        dataIndex: 'action',
        slots: { customRender: 'action' },
        fixed: 'right',
      },
      pagination: {
        hideOnSinglePage: false,
        pageSize: 10,
      },
      clickToRowSelect: true, //点击当前行多选框不选中,默认是true
      rowSelection: { type: 'checkbox' }, //是否有多选功能
      tableSetting: {
        redo: true,
        size: true,
        setting: false,
        fullScreen: false,
      },
    });

    const onFetchSuccess = () => {
      // 请求后拿到数据，打开对应的资源审核弹窗
      nextTick(() => {
        let dataList = getDataSource()
        if (currRoute?.query?.bussid && appStore.routerPushAuditFlag) {
          dataList.forEach(item => {
            item.BUSSID === currRoute.query.bussid && handleEdit(item)
          })
          let searchFormSchema = searchFormSchemaMR;
          let title = '地图资源审核列表';
          if (current.value === 'MR') {
            searchFormSchema = searchFormSchemaMR;
            title = '地图资源审核列表';
          } else if (current.value === 'ER') {
            searchFormSchema = searchFormSchemaER;
            title = '场景资源审核列表';
          } else if (current.value === 'DR') {
            searchFormSchema = searchFormSchemaDR;
            title = '文件资源审核列表';
          } else {
            searchFormSchema = searchFormSchemaSR;
            title = '组件资源审核列表';
          }
          setProps({
            title: title,
            formConfig: {
              labelWidth: 90,
              schemas: searchFormSchema,
            },
          });
        }
      });
    }

    const moment = Moment;
    const ischect = ref(true)
    const sourceTypes = ref([
      { SERVICETYPE: 'MR', name: '地图资源' },
      { SERVICETYPE: 'ER', name: '场景资源' },
      { SERVICETYPE: 'DR', name: '文件资源' },
      { SERVICETYPE: 'SR', name: '组件资源' },
    ]);
    const { hasBatchDelete, handleDeleteOrBatchDelete, selectionOptions, resetSelectedRowKeys } =
      useBatchDelete(delRole, handleSuccess, setProps);
    selectionOptions.rowSelection.getCheckboxProps = (record: Recordable) => {
      // Demo:status为1的选择框禁用
      // if (record.status === 1) {
      //   return { disabled: true };
      // } else {
      //   return { disabled: false };
      // }
    };
    const [registerModal, { openModal }] = useModal();
    watch(
      () => current.value, (val) => {
        let searchFormSchema = searchFormSchemaMR;
        let title = '地图资源审核列表';
        if (val === 'MR') {
          searchFormSchema = searchFormSchemaMR;
          title = '地图资源审核列表';
        } else if (val === 'ER') {
          searchFormSchema = searchFormSchemaER;
          title = '场景资源审核列表';
        } else if (val === 'DR') {
          searchFormSchema = searchFormSchemaDR;
          title = '文件资源审核列表';
        } else {
          searchFormSchema = searchFormSchemaSR;
          title = '组件资源审核列表';
        }
        setProps({
          title: title,
          formConfig: {
            labelWidth: 90,
            schemas: searchFormSchema,
          },
        });
        reload();
      }
    );
    nextTick(() => {
      setProps(selectionOptions);
    });

    function selectHandle(record) {
      current.value = record.SERVICETYPE;
    }

    /**
     * 详情
     */
    async function handleDetail(record: Recordable) {
      ischect.value = false;
      const res = (await queryResourceById(record?.SERVICEID)) as any;
      if (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) res.bussid = record.BUSSID;
        openModal(true, {
          record: result,
          isUpdate: true,
          isView: true,
        });
      }
    }

    /**
     * 审核
     */
    function handleEdit(record: Recordable) {
      ischect.value = true;
      setTimeout(() => {
        openModal(true, {
          record,
          isUpdate: true,
        });
        appStore.setRouterPushAuditFlag(false)
      }, 100);
    }
    /**
     * 浏览
     */
    async function handleVliew(record: Recordable) {
      //场景资源
      if (current.value === 'ER') {
        window.open(`http://192.168.119.143:8080/onemapV5.0/sceneview.html?${record.SERVICEID}`, 'target', '');
      }
      //地图资源
      if (current.value === 'MR') {
        window.open(`http://192.168.119.143:8080/onemapV5.0/mapview.html?${record.SERVICEID}`, 'target', '');
      }
      //地图资源
      if (current.value === 'SR') {
        var res = (await queryResourceById(record?.SERVICEID)) as any;
        res = Object.assign(res.metadata, res.servicebase, res.dataVersionConf || {});
        if (res) {
          window.open(`./mapview.html?onlineIde_${res.servicealiasname}`, 'target', '');
        }
      }
      //文件资源
      if (current.value === 'DR') {
        const obj = {
          id: record['fileid'],
          userid: record['userid'],
          parentId: session.getItem('sysFild').dirId,
        };
        const res = (await getFileUrl(obj)) as any;
        if (res) {
          const fileName = res.fileName;
          console.log('下载文件', fileName);
          const url = res.url;
          window.open(url);
        }
      }
      if (current.value === 'DR') {
        console.log('组件');
      }
    }

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

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


    return {
      statusShow,
      current,
      moment,
      ischect,
      sourceTypes,
      registerTable,
      registerModal,
      handleVliew,
      handleDetail,
      handleEdit,
      handleSuccess,
      RoleEnum,
      hasBatchDelete,
      handleDeleteOrBatchDelete,
      statusChange,
      batchExamine,
      selectHandle,
      onFetchSuccess
    };
  },
});
</script>
<style scoped lang="less">
.examine-container {
  display: flex;
  height: 100%;
  width: 100%;

  .left-container {
    width: 240px;
    height: calc(100% - 32px);
    margin: 16px 0 16px 10px;
    padding: 10px 20px;
    background-color: #fff;
    border-radius: 2px;

    .soure-item-row {
      height: 34px;
      width: 100%;
      margin: 20px 0;
      line-height: 34px;
      text-align: center;
      font-size: 14px;
      font-weight: normal;
      letter-spacing: 0px;
      color: #333333;
      background: #eff0f5;
      border-radius: 2px;
      cursor: pointer;
    }

    .active {
      background: #0671dd;
      color: #fff;
    }
  }

  .right-container {
    width: calc(100% - 260px);
    height: 100%;
  }
}
</style>

