<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    title="新增案件"
    @visible-change="handleVisibleChange"
    @ok="handleSubmit"
    :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 @register="registerTable">
        <template #href="{ record }">
          <a
            v-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 { useI18n } from '/@/hooks/web/useI18n';
  import { getByKey, addOrUpdate, del } from '/@/api/media';
  import {
    BasicTable,
    useTable,
    TableAction,
    BasicColumn,
    TableImg,
    FormProps,
  } from '/@/components/Table';
  import { caseaddOrUpdateApi, operateSceneList } from '/@/api/operate';
  const { t } = useI18n();
  export default defineComponent({
    components: { BasicModal, BasicTable, TableAction },
    props: {
      userData: { type: Object },
    },
    emits: ['update', 'register'],
    setup(props, { emit }) {
      const modelRef = ref({});
      const fileFlow = reactive({
        caseTitle: '',
        file: null,
        dylist: [],
        mslist: [],
      });
      const columns: BasicColumn[] = [
        {
          title: '场景标题',
          dataIndex: 'sceneName',
          ellipsis: true,
          slots: { customRender: 'href' },
          resizable: true,
          minWidth: 150,
          width: 150,
        },
        {
          title: '场景码',
          dataIndex: 'num',
          ellipsis: true,
          width: 180,
        },
        {
          title: '计算完成时间',
          dataIndex: 'algorithmTime',
          width: 180,
        },
        {
          title: '场景大小',
          dataIndex: 'sceneSize',
          width: 80,
          customRender: ({ record }) => {
            return record.sceneSize && record.sceneSize != 0
              ? h('span', { class: 'sceneSize' }, Math.ceil(record.sceneSize / 1024 / 1024) + 'M')
              : '-';
          },
        },
        {
          title: '状态',
          dataIndex: 'status',
          width: 80,
          customRender: ({ record }) => {
            let str;
            switch (record.status - 0) {
              case 0:
                str = '计算中';
                break;
              case 1:
                str = '计算成功';
                break;
              case -2:
                str = '计算成功';
                break;
              case -1:
                str = '计算失败';
                break;
            }
            return record.payStatus == -2 ? '封存' : str;
          },
        },
      ];
      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,
            },
          },
          {
            field: 'isObj',
            label: '场景类型',
            component: 'Select',
            labelWidth: 80,
            // labelWidth: 50,
            defaultValue: '1',
            componentProps: {
              allowClear: false,
              options: [
                {
                  label: '点云场景',
                  value: '0',
                  key: '0',
                },
                {
                  label: 'Mesh 场景',
                  value: '1',
                  key: '1',
                },
              ],
              onChange: (value) => {
                reload({
                  searchInfo: { isObj: value },
                }).then(() => {
                  setSelectedRowKeys(value == 0 ? fileFlow.dylist : fileFlow.mslist);
                });
              },
            },
            colProps: {
              xl: 7,
              xxl: 7,
            },
          },
        ],
      };
      const { createMessage, createConfirm } = useMessage();
      const [registerTable, { reload, getForm, setSelectedRowKeys }] = useTable({
        api: operateSceneList,
        title: ``,
        showTableSetting: false,
        rowSelection: { type: 'checkbox',getCheckboxProps: getRowSelection, onChange: onSelectChange },
        // titleHelpMessage: ['已启用expandRowByClick', '已启用stopButtonPropagation'],
        columns: columns,
        // searchInfo: { type: tableType },
        useSearchForm: true,
        formConfig: searchForm,
        showIndexColumn: false,
        rowKey: 'num',
        fetchSetting: {
          pageField: 'pageNum',
          sizeField: 'pageSize',
          listField: 'list',
          totalField: 'total',
        },
        canResize: true,
      });
      onMounted(() => {});
      let addListFunc = () => {};
      const [register, { closeModal }] = useModalInner((data) => {
        console.log(data);
        data && onDataReceive(data);
      });
      function getRowSelection(record) {
        return {
        disabled: !(record.status == 1 || record.status == -2), // Column configuration not to be checked
        name: record.name,}
       }
      function onSelectChange(selectedRowKeys: any, selectedRows: any) {
        const { isObj } = getForm().getFieldsValue();
        if (isObj == 0) {
          fileFlow.dylist = selectedRowKeys;
        } else if (isObj == 1) {
          fileFlow.mslist = selectedRowKeys;
        }
        console.log('isObj', isObj, fileFlow);
      }
      function onDataReceive(data) {
        modelRef.value = data;
        fileFlow.dylist = [];
        fileFlow.mslist = [];
        fileFlow.caseTitle = '';
        setSelectedRowKeys([]);
      }
      function handleAdd() {
        console.log('handleAdd', fileFlow.dictName);
        let params = {
          dictName: fileFlow.dictName,
        };
        if (!fileFlow.dictName) {
          return createMessage.warning('请输入名称');
        }
        addOrUpdate(params).then((res) => {
          createMessage.success('添加成功');
          fileFlow.dictName = '';
          reload();
        });
      }
      const handleSubmit = async () => {
        if(!fileFlow.caseTitle){
          return createMessage.warning('请输入案件名称')
        }
        try {
          const apiData = {
            caseTitle: fileFlow.caseTitle,
            sceneNumParam: [
              {
                type: 0,
                numList: fileFlow.dylist,
              },
              {
                type: 1,
                numList: fileFlow.mslist,
              },
            ],
          };
          console.log('res', apiData);
          const res = await caseaddOrUpdateApi(apiData);
          console.log('res', res);
          closeModal();
          createMessage.success('新增案件成功。');
          emit('update');
        } catch (error) {
          console.log('not passing', error);
        }
      };
      function handleVisibleChange(v) {
        // console.log(v);
        // v && props.userData && nextTick(() => onDataReceive(props.userData));
      }
      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,
        handleVisibleChange,
        handleSubmit,
        addListFunc,
        handleDelete,
        t,
      };
    },
  });
</script>
