<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <BasicTable class="w-4/4 xl:w-5/5" @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="preview">预览</a-button>
        <a-button type="primary" @click="showProgress">导入进度查询</a-button>
        <a-button type="primary" @click="downloadTemplate">模板下载</a-button>
        <a-upload
          :accept="'.xlsx,.csv,.xls,.zip'"
          :showUploadList="false"
          :custom-request="customRequest"
        >
          <a-button type="primary">导入</a-button>
        </a-upload>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                label: '审核',
                onClick: () => {
                  handleAudit(record);
                },
              }
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <a-modal width="75%" style="top: 8px;" v-model:open="openModal" title="线索审核" :destroyOnClose="true" :footer="null">
      <InfoModal
        :infoData="infoData.info"
        @handleOk="handleOk"
        @closeModal="closeModal"
        :control="true"
        @closeCase="closeCase"
        @reSubmit="reSubmit"/>
    </a-modal>
    <a-modal width="75%" style="top: 33px;" v-model:open="openImportModal" title="导入" :destroyOnClose="true" :footer="null" :maskClosable="false">
      <ImportDataModal :picihao="picihao" @closeImportModal="closeImportModal"/>
    </a-modal>
    <a-modal width="75%" style="top: 33px;" v-model:open="openProgressModal" title="导入进度" :destroyOnClose="true" :footer="null">
      <ProgressModal :picihao="picihao" @closeProgressModal="closeProgressModal"/>
    </a-modal>
  </PageWrapper>
</template>
<script lang="ts" setup>
import { nextTick, onMounted, ref, h } from 'vue';
import { BasicTable, useTable, TableAction } from '@/components/Table';
import { PageWrapper } from '@/components/Page';
import InfoModal from './InfoModal/index.vue'
import ProgressModal from '@/components/Audit/ProgressModal/index.vue'
import { columns, searchFormSchema, dictionary, code, subjectKey } from './util';
import { getDetail } from '@/api/sys/WFSchemeInfo';
import { functionsaveForm, LoadFormScheme } from '@/api/demo/formScheme';
import { buildGUID } from '@/utils/uuid';
import { useUserStore } from '@/store/modules/user';
import { create, saveDraft, GetDraft } from '@/api/sys/WFProcess';
import { message, Modal, Input } from 'ant-design-vue';
import { SaveReSubmitInfo } from '@/api/demo/resubmit';
import { uploadFile } from '@/api/formrender/index';
import { MainLoadCaseInfoLists, MainGetCaseInfo, MainCloseCaseInfo, MainUpdateCaseInfoShpData } from '@/api/illegalmining/index';
import ImportDataModal from '@/components/Audit/ImportDataModal/index.vue'
import { UpdateCaseNoBySubject, LoadCaseImportInfoLast } from '@/api/audit/index';

const userStore = useUserStore();
const userInfo = userStore.getUserInfo;
const infoData = ref({})
const openModal = ref(false)
const reSubmitRemark = ref("")
const closeCaseRemark = ref("")
const picihao = ref("")
const openImportModal = ref(false)
const openProgressModal = ref(false)

const [registerTable, { reload, expandAll}] = useTable({
  title: '待审核',
  api: MainLoadCaseInfoLists,
  columns,
  rowKey: 'id',
  formConfig: {
    labelWidth: 120,
    schemas: searchFormSchema,
  },
  striped: false,
  // 序号列
  showIndexColumn: false,
  // 使用搜索表单
  useSearchForm: true,
  // 显示表格设置工具
  showTableSetting: true,
  bordered: true,
  beforeFetch(data) {
    let params = {...data}
    if(!params.nowStatus){
      params.nowStatus = '复提待审核'
    }
    return params
  },
  afterFetch(data) {
    console.log('afterFetch', data);
  },
  actionColumn: {
    width: 100,
    title: '操作',
    dataIndex: 'action',
  },
  handleSearchInfoFn(info) {
    return info;
  },
});
function handleAudit(record) {
  MainGetCaseInfo({id: record.Id}).then(res => {
    console.log(res)
    infoData.value = res
    openModal.value = true
  })
}
const handleOk = async () => {
  try {
    const { id } = infoData.value.info
    const checkValue = await GetDraft({id})
    if(checkValue.process == null){
      let data = await getDetail({ code });
      let content = JSON.parse(data.scheme.content);
      const currentNode = content.wfData.find((t) => t.type == 'bpmn:StartEvent');
      let formVerison = currentNode.formVerison
      let keyValue = ''
      const schemaData = await LoadFormScheme({
        schemeId: formVerison
      });
      const scheme = JSON.parse(schemaData.scheme);
      scheme.formInfo.tabList.forEach((tabElement) => {
        tabElement.schemas.forEach((element) => {
          if (element.field == currentNode.formRelationId) {
            keyValue = element.componentProps.fieldName;
          }
        });
      });
      let commit = {
        schemeId: currentNode.formVerison,
        pkey: keyValue,
        pkeyValue: id,
      };
      let resultQuery = {
        schemeCode: code,
        userId: userInfo.id,
        title: '',
        processId: id,
        InstanceInfo: JSON.stringify(commit),
      };
      await saveDraft(resultQuery);
      resultQuery.schemeCode = '';
      const result = await create(resultQuery);
      if(result){
        await UpdateCaseNoBySubject({id, subject: '非法采矿'})
        message.success('发起流程成功');
        reload()
        openModal.value = false
      }else{
        message.error('发起流程失败');
      }
    }else{
      message.warning('该案件已发起流程');
    }
  } catch(err) {
    console.log(err)
  }
}
const closeModal = () => {
  openModal.value = false
}
const closeCase = (id: string) => {
  Modal.confirm({
    title: '请输入关闭原因',
    content: h('input',{
      class: 'reSubmitInput',
      onChange: (e) => closeCaseRemark.value = e.target.value
    }),
    onOk: async () => {
      const result = await MainCloseCaseInfo({id, closereason: closeCaseRemark.value})
      if(result){
        message.success('关闭案件成功');
        reload()
        openModal.value = false
      }else{
        message.error('关闭案件失败');
      }
      closeCaseRemark.value = ''
    },
    onCancel() {
      closeCaseRemark.value = ''
    },
  })
}
const reSubmit = (originalcaseno: string) => {
  Modal.confirm({
    title: '请输入复提原因',
    content: h('input',{
      class: 'reSubmitInput',
      onChange: (e) => reSubmitRemark.value = e.target.value
    }),
    onOk: async () => {
      console.log(reSubmitRemark.value)
      const result = await SaveReSubmitInfo({ originalcaseno, remark: reSubmitRemark.value, subjectKey })
      if(result){
        message.success('复提成功');
        reload()
        openModal.value = false
      }else{
        message.error('复提失败');
      }
      reSubmitRemark.value = ''
    },
    onCancel() {
      reSubmitRemark.value = ''
    },
  })
}
const customRequest = (file) => {
  console.log('handleCustomRequest',file)
  // const { VITE_GLOB_API_URL } = getAppEnvConfig();
  const formData = new FormData()
  formData.append('files', file.file)
  uploadFile(formData).then(res => {
    MainUpdateCaseInfoShpData({zipFilePath: res[0].filePath.replace(/\\/g, '/'), srid: '4326', subjectname: '非法采矿'}).then(resultRes => {
      picihao.value = resultRes
      openImportModal.value = true
      reload()
    })
  })
}
const downloadTemplate = () => {
  window.open('http://120.222.154.7:6050/templates/shptest.zip')
}
const closeImportModal = () => {
  openImportModal.value = false
}
const closeProgressModal = () => {
  openProgressModal.value = false
}
const showProgress = () => {
  openProgressModal.value = true
}
const preview = () => {
  LoadCaseImportInfoLast({ subjectname: '非法采矿'}).then(res => {
    console.log(res)
    picihao.value = res
    openImportModal.value = true
  })
}

</script>
<style lang="scss">
.reSubmitInput{
  border: 1px solid;
  width: 100%;
  height: 35px;
  border-radius: 5px;
  padding: 0px 10px;
  border-color: #000;
  transition: 0.2s;
  &:focus{
    border-color: #6db8ff;
  }
}
</style>
