<template>
  <BasicModal
    class="resultListTab"
    v-bind="$attrs"
    @register="register"
    title="新增案件"
    @visible-change="handleVisibleChange"
    @ok="handleSubmit"
    :confirmLoading="loading"
    :width="900"
    :min-height="0"
  >
    <div class="pt-2px pr-3px">
      <div class="mx-5 BasicForm flex">
        <span style="line-height: 32px; margin-right: 10px">案件名称</span>
        <div class="input">
          <a-input
            style="width: 600px"
            maxlength="100"
            showCount
            v-model:value="fileFlow.caseTitle"
            placeholder="请输入"
          />
        </div>
        <!-- <a-button type="primary" @click="handleAdd"> 新增</a-button> -->
      </div>
      <BasicTable class="zdyform" @register="registerTable">
        <template #tableTitle>
          <a-tabs class="resultListTab" v-model:activeKey="sceneType" @change="changeTable">
            <Tabs.TabPane :key="0" tab="实景三维" />
            <Tabs.TabPane :key="1" tab="共享实景三维" />
            <Tabs.TabPane :key="2" tab="多元融合" />
            <Tabs.TabPane :key="3" tab="共享多元融合" />
            <!-- <Tabs.TabPane :key="3" tab="多元融合共享" /> -->
          </a-tabs>
        </template>
        <template #href="{ record }">
          <a
            v-if="record.fusionTitle"
            target="_blank"
            :title="record.fusionTitle"
            :href="`/code/index.html?caseId=${record.fusionId}#/show`"
            >{{ record.fusionTitle || record.title }}</a
          >
          <a
            v-else-if="record.status == 1 || (record.status == -2 && record.payStatus == 1)"
            target="_blank"
            :title="record.sceneName"
            :href="record.webSite"
            >{{ record.sceneName }}</a
          >
          <span v-else-if="record.sceneName">{{ record.sceneName }}</span>
          <span v-else>-</span>
        </template>
      </BasicTable>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, nextTick, onMounted, reactive, h } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { sceneMove } from '/@/api/operate';
  import { sceneColumns, diversityColumns } from './data';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { Tabs } from 'ant-design-vue';
  import { getByKey, addOrUpdate, del } from '/@/api/media';
  import {
    BasicTable,
    useTable,
    TableAction,
    BasicColumn,
    TableImg,
    FormProps,
  } from '/@/components/Table';
  import { caseaddOrUpdateApi, operateAddSceneList } from '/@/api/operate';
  const { t } = useI18n();
  export default defineComponent({
    components: { BasicModal, BasicTable, TableAction, [Tabs.name]: Tabs },
    props: {
      userData: { type: Object },
    },
    emits: ['update', 'register'],
    setup(props, { emit }) {
      const modelRef = ref({});
      const loading = ref(false);
      const sceneType = ref(0);
      const fileFlow = reactive({
        caseTitle: '',
        file: null,
        dylist: [],
        mslist: [],
        fusionIds: [],
      });
      const searchForm: Partial<FormProps> = {
        labelWidth: 60,
        autoSubmitOnEnter: true,
        autoAdvancedLine: 1,
        schemas: [
          {
            field: 'sceneName',
            label: '名称',
            component: 'Input',
            componentProps: {
              maxLength: 100,
              placeholder: ' 请名称搜索',
            },
            colProps: {
              xl: 7,
              xxl: 7,
            },
          },
        ],
      };
      const { createMessage, createConfirm } = useMessage();
      const [registerTable, { reload, getForm, setSelectedRowKeys, setPagination, setColumns }] =
        useTable({
          api: operateAddSceneList,
          title: ``,
          showTableSetting: false,
          rowSelection: {
            type: 'checkbox',
            getCheckboxProps: getRowSelection,
            onChange: onSelectChange,
          },
          // titleHelpMessage: ['已启用expandRowByClick', '已启用stopButtonPropagation'],
          columns: sceneColumns,
          searchInfo: { isObj: '1', sceneType: sceneType },
          useSearchForm: true,
          formConfig: searchForm,
          immediate: false,
          showIndexColumn: false,
          rowKey: 'num',
          beforeFetch: (T) => {
            T.fusionTitle = T.sceneName;
            return T;
          },
          afterFetch: listAfterFetch,
          fetchSetting: {
            pageField: 'pageNum',
            sizeField: 'pageSize',
            listField: 'list',
            totalField: 'total',
          },
          canResize: true,
        });
      onMounted(() => {});
      let addListFunc = () => {};
      const [register, { closeModal }] = useModalInner((data) => {
        console.log(data);
        getForm().resetFields();
        reload();
        data && onDataReceive(data);
      });
      function getRowSelection(record) {
        return {
          disabled: !(record.fusionId || record.status == 1 || record.status == -2 ), // Column configuration not to be checked
          name: record.name,
        };
      }
      function onSelectChange(selectedRowKeys: any, selectedRows: any) {
        console.log('selectedRowKeys changed: ', selectedRowKeys, selectedRows, sceneType.value);
        let fusionIds = [], dylist = [], mslist = [];
        selectedRows.map(ele => {
          if(ele.fusionId){
            fusionIds.push(ele.fusionId);
          }else{
            mslist.push(ele.num)
          }
        })
        fileFlow.fusionIds = fusionIds;
        fileFlow.dylist = dylist;
        fileFlow.mslist = mslist;
      }
      function onDataReceive(data) {
        sceneType.value = 0;
        fileFlow.caseTitle = '';
        modelRef.value = data;
        fileFlow.dylist = [];
        fileFlow.mslist = [];
        fileFlow.fusionIds = [];
        fileFlow.caseTitle = '';
        setSelectedRowKeys([]);
      }
      function handleAdd() {
        console.log('handleAdd', fileFlow.dictName);
        let params = {
          dictName: fileFlow.dictName.trim(),
        };
        if (!fileFlow.dictName.trim()) {
          return createMessage.warning('请输入名称');
        }
        addOrUpdate(params).then((res) => {
          createMessage.success('添加成功');
          fileFlow.dictName = '';
          reload();
        });
      }
      const handleSubmit = async () => {
        if (!fileFlow.caseTitle?.trim()) {
          return createMessage.warning('请输入案件名称');
        }
        if (fileFlow.mslist.length == 0 && fileFlow.fusionIds.length == 0) {
          return createMessage.warning('至少选择一个场景或者多元融合');
        }
        try {
          loading.value = true;
          const apiData = {
            caseTitle: fileFlow.caseTitle?.trim(),
            sceneNumParam: [
              {
                type: 0,
                numList: fileFlow.dylist,
              },
              {
                type: 1,
                numList: fileFlow.mslist,
              },
              {
                type: 2,
                numList: fileFlow.fusionIds,
              },
            ],
          };
          console.log('res', apiData);
          const res = await caseaddOrUpdateApi(apiData);
          console.log('res', res);
          closeModal();
          createMessage.success('新增案件成功。');
          sceneType.value = 0;
          emit('update');
          loading.value = false;
        } catch (error) {
          loading.value = false;
          console.log('not passing', error);
        }
      };
      function handleVisibleChange(v) {
        // console.log(v);
        // v && props.userData && nextTick(() => onDataReceive(props.userData));
      }
      function changeTable(params) {
        console.log(params, 'changeTable', sceneType.value);
        setColumns(sceneType.value == 2 || sceneType.value == 3 ? diversityColumns : sceneColumns);
        setPagination({ current: 1 });
        reload();
      }
      function listAfterFetch(list) {
        console.log(list, 'changeTable', sceneType.value);
        return list.map(ele => {
          if(!ele.num){
            ele.num = ele.fusionId;
          }
          return ele;
        });
      }
      async function handleDelete(record: Recordable) {
        console.log('handleDelete', record);
        createConfirm({
          title: '删除',
          content: '确定要删除吗？',
          onOk: async () => {
            del({ id: record.id }).then(() => {
              createMessage.success({
                content: '删除成功',
              });
              reload();
            });
          },
        });
      }
      return {
        register,
        handleAdd,
        registerTable,
        model: modelRef,
        fileFlow,
        sceneType,
        changeTable,
        handleVisibleChange,
        handleSubmit,
        addListFunc,
        handleDelete,
        t,
        loading,
      };
    },
  });
</script>

<style lang="less">
  .resultListTab {
    .ant-tabs-nav {
      margin: 0;
    }
  }
  .zdyform {
    .vben-basic-form {
      margin: 0;
    }
  }
</style>
