<template>
  <div class="p-4">
    <div class="top-search">
      <div class="left-search-input">
        <div class="input">
          <span>关键字</span>
          <a-input allowClear v-model:value="searchValue" style="width: 200px;" placeholder="请输入资源名称"></a-input>
        </div>
        <div class="input">
          <span>资源类型</span>
          <!-- <a-select allowClear v-model:value="selectTypeValue" style="width: 200px" :options="typeOptions"></a-select> -->
          <a-select allowClear @change="handleTypeChange" v-model:value="selectTypeValue" style="width: 200px" :options="typeOptions"></a-select>
        </div>
        <div class="input" v-if="selectTypeValue != 'SR'">
          <span>应用系统</span>
          <a-select allowClear v-model:value="selectSystemValue" style="width: 200px"
            :options="sysOptions"></a-select>
        </div>
        <div class="input">
          <span>审核状态</span>
          <a-select allowClear v-model:value="selectStatusValue" style="width: 200px" :options="statusOptions">
          </a-select>
        </div>
        <!-- <div class="input">
          <span>申请时间</span>
          <a-date-picker v-model:value="searchTime" placeholder="申请时间" style="width: 200px" />
        </div> -->
      </div>
      <div class="right-btns">
        <a-button style="margin-right: 15px;" @click="handleReset">重置</a-button>
        <a-button type="primary" @click="handleSearch">查询</a-button>
      </div>
    </div>
    <div class="bottom-table">
      <BasicTable @register="registerTable" class="basic-table" @fetch-success="onFetchSuccess">
        <template #toolbar>
          <a-button style="background-color: #fc8b01;color: #fff;" :disabled="hasSelected"
            @click="handleAuditAll">批量审核</a-button>
        </template>
        <template #BLZT="{ record }">
          <a-tag :style="`color:${record.status === 3 || record.status === 3 ? 'red' : ''};`">
            {{
              record.BLZT == '在办' ? '审核中' : record.BLZT == '已办结' ? '审核完' : ''
            }}
          </a-tag>
        </template>
        <template #action="{ record }">
          <TableAction :actions="[
            {
              label: '详情',
              tooltip: '详情',
              onClick: handleDetail.bind(null, record),
            },
            {
              label: '审核',
              tooltip: '审核',
              disabled: selectStatusValue == '0' ? false : true,
              onClick: handleAudit.bind(null, record),
            }
          ]" />
        </template>

      </BasicTable>
    </div>
    <AuditModal v-if="ischect && showAuditModal" @closeModal="showAuditModal = false" :bussInfo="bussInfo"
      @onSubmit="onSubmit" />
    <map-resource-upload v-if="!ischect && selectTypeValue === 'MR'" @register="registerModal"
      @success="handleSuccess"></map-resource-upload>
    <scene-resource-upload v-if="!ischect && selectTypeValue === 'ER'" @register="registerModal"
      @success="handleSuccess"></scene-resource-upload>
    <file-resource-upload v-if="!ischect && selectTypeValue === 'DR'" @register="registerModal"
      @success="handleSuccess"></file-resource-upload>
    <ass-resource-upload v-if="!ischect && selectTypeValue === 'SR'" @register="registerModal"
      @success="handleSuccess"></ass-resource-upload>
  </div>
</template>
<script>
import { defineComponent, reactive, ref, onMounted, watch, toRefs, computed, createVNode, nextTick } from 'vue';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import AuditModal from './AuditModal.vue';
import { columns } from './map.data';
import { list } from '/@/api/authorize/authorize';
import moment from 'moment';
import { session } from '/@/utils/Memory';
import { queryTaskInfoPage, queryTaskYbInfoPage } from '/@/api/resource/examine';
import { getAppDesign } from '/@/api/oem';
import { useRouter } from 'vue-router';
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 { useModal } from '/@/components/Modal';
import { queryResourceById } from '/@/api/resource/map';
import { useAppStore } from '/@/store/modules/app';

export default defineComponent({
  name: 'Empowerment',
  components: { BasicTable, TableAction, AuditModal, MapResourceUpload, FileResourceUpload, SceneResourceUpload, AssResourceUpload },
  setup() {
    const appStore = useAppStore();
    const [registerModal, { openModal }] = useModal();
    const ischect = ref(true)
    const searchValue = ref('')
    const selectTypeValue = ref('MR')
    const selectSystemValue = ref('')
    const selectStatusValue = ref('0')
    const searchTime = ref(null)
    const { currentRoute } = useRouter();
    const currRoute = currentRoute.value;
    //mr是地图资源，dr是文件，er场景，sr组件
    const typeOptions = [
      {
        label: "地图资源",
        value: "MR"
      },
      {
        label: "场景资源",
        value: "ER"
      },
      {
        label: "文件资源",
        value: "DR"
      },
      {
        label: "组件资源",
        value: "SR"
      },
      {
        label: "接口服务",
        value: "interface"
      }
    ]

    function handleTypeChange() {

    }

    const sysOptions = ref([]);
    onMounted(() => getApp());
    function getApp() {
      list().then(r => sysOptions.value = r.map(i => { return { label: i.NAME, value: i.KEY } }))
    }
    const statusOptions = [
      {
        label: "在办",
        value: "0"
      },
      {
        label: "已办结",
        value: "1"
      }
    ]
    const showAuditModal = ref(false)
    const bussInfo = ref({
      bussInfoId: "",
      resId: ""
    })
    onMounted(() => {
      // getAllData();
    })
    //获取所有状态的资源
    const getAllData = () => {
      return new Promise(async (resolve) => {
        let params = {
          page: 1,
          rows: 10000,
          serviceType: selectTypeValue.value,
          userId: session.getItem('userId'),
          keyStr: searchValue.value
        }

        let resdb = null;
        let resyb = null;
        if (selectStatusValue.value == "0") {
          resdb = await queryTaskInfoPage(params)
          resyb = [];
        } else if (selectStatusValue.value == "1") {
          resdb = []
          resyb = await queryTaskYbInfoPage(params)
        } else {
          resdb = await queryTaskInfoPage(params)
          resyb = await queryTaskYbInfoPage(params)
        }

        let allData = removeDp(resyb, resdb)
        if (allData.length) {
          allData.filter(item => item.BUSSNAME.indexOf('授权') > -1)
          console.log("授权审核列表:", allData)
          resolve(allData)
        } else {
          resolve([])
        }
      })
    }
    //两个对象数组去重
    const removeDp = (arr1, arr2) => {
      let arr = arr1.concat(arr2)
      let obj = {}
      let newArray = arr.reduce((pre, cur) => {
        if (!obj[cur.BUSSID]) {
          obj[cur.BUSSID] = true
          pre.push(cur)
        }
        return pre
      }, [])
      return newArray;
    }
    //注册表格
    const [registerTable, { reload, getRowSelection, getSelectRowKeys, clearSelectedRowKeys, getDataSource }] = useTable({
      title: '授权资源列表',
      api: getAllData,
      // dataSource: [],
      columns,
      rowSelection: { type: 'checkbox' },
      useSearchForm: false,
      showTableSetting: true,
      bordered: false,
      striped: false,
      canResize: true,
      showIndexColumn: true,
      indexColumnProps: { fixed: 'left' },
      actionColumn: {
        width: 120,
        title: '操作',
        dataIndex: 'action',
        slots: { customRender: 'action' },
        fixed: 'right',
      },
      pagination: {
        hideOnSinglePage: false,
      },
      clickToRowSelect: false,
      tableSetting: {
        redo: true,
        size: true,
        setting: false,
        fullScreen: false
      },
    });

    //判断是否选中数据
    const hasSelected = computed(() => {
      const rowSelection = getRowSelection();
      return !(rowSelection.selectedRowKeys?.length);
    });
    //重置查询
    const handleReset = () => {
      searchValue.value = ''
      selectTypeValue.value = ''
      selectSystemValue.value = ''
      selectStatusValue.value = '0'
      searchTime.value = moment()
    }
    //条件查询
    const handleSearch = () => {
      reload();
    }
    // 批量审核
    const handleAuditAll = () => {
    }
    //资源详情
    const handleDetail = async (record) => {
      ischect.value = false;
      const res = await queryResourceById(record?.SERVICEID);
      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,
        });
      }
    }
    //单个审核，打开审核弹窗
    const handleAudit = (record) => {
      ischect.value = true;
      console.log("单个审核，打开审核弹窗:", record)
      bussInfo.value.bussInfoId = record.BUSSID;
      bussInfo.value.resId = record.SERVICEID;
      bussInfo.value.record = record;
      showAuditModal.value = true;
      appStore.setRouterPushAuditFlag(false)
    }
    //审核提交
    const onSubmit = (isPass) => {
      showAuditModal.value = false
      reload()
    }

    const onFetchSuccess = () => {
      // 请求后拿到数据，打开对应的资源审核弹窗
      nextTick(()=>{
        let dataList = getDataSource()
        if(currRoute?.query?.bussid && appStore.routerPushAuditFlag){
          dataList.forEach(item=>{
            item.BUSSID === currRoute.query.bussid && handleAudit(item)
          })
        }
      });
    }

    return {
      ischect,
      handleTypeChange,
      showAuditModal,
      bussInfo,
      searchValue,
      selectTypeValue,
      selectSystemValue,
      selectStatusValue,
      searchTime,
      typeOptions,
      sysOptions,
      statusOptions,
      hasSelected,
      registerTable,
      registerModal,
      handleReset,
      handleSearch,
      handleAuditAll,
      handleDetail,
      handleAudit,
      onSubmit,
      onFetchSuccess
    };
  },
});
</script>

<style lang="less" scoped>
.p-4 {
  height: 100%;

  .top-search {
    width: 100%;
    height: 74px;
    border-radius: 6px;
    background: #FFFFFF;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .left-search-input {
      margin-left: 20px;
      display: flex;

      .input {
        margin-right: 30px;

        span {
          margin-right: 10px;
        }
      }
    }

    .right-btns {
      margin-right: 20px;
    }
  }

  .bottom-table {
    margin-top: 24px;
    padding: 20px;
    height: calc(100% - 98px);
    background-color: #fff;

    .basic-table {
      height: 100%;

      ::v-deep .ant-table-title {
        padding: 0 !important;

        .vben-basic-title {
          font-family: '阿里巴巴普惠体 2.0';
          font-size: 16px;
          font-weight: bold;
          color: #333333;
        }

      }
    }
  }
}
</style>
