<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,.shp,.zip'"
          :showUploadList="false"
          :custom-request="customRequest"
        >
          <a-button type="primary">导入</a-button>
        </a-upload>
        <a-button type="primary" @click="downloadSHP" v-if="['违法用地','非法采矿'].includes(type)">SHP导出</a-button>
      </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: 30px;" v-model:open="openModal" title="线索审核" :destroyOnClose="true" :footer="null">
      <InfoModal
        :type="type"
        :infoData="infoData.info"
        @handleOk="handleOk"
        @closeModal="closeModal"
        :control="true"
        @closeCase="closeCase"
        @reSubmit="reSubmit"
        :modalLoading="modalLoading"
        @changeLoading="changeLoading"/>
    </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 '@/components/Audit/InfoModal/index.vue'
import ImportDataModal from '@/components/Audit/ImportDataModal/index.vue'
import ProgressModal from '@/components/Audit/ProgressModal/index.vue'
import { columns, searchFormSchemaFunction, codeObj, SubjectKeyObj } from '@/views/demo/audit/util';
import { getDetail } from '@/api/sys/WFSchemeInfo';
import { LoadFormScheme } from '@/api/demo/formScheme';
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 { 
  LoadCaseInfoLists,
  GetCaseInfo,
  CloseCaseInfo,
  ImportCaseInfoShpData,
  UpdateCaseNoBySubject,
  LoadCaseImportInfoLast,
  ExportapprovalCaseInfoShapefile,
  UpdateCaseInfoBySubject
} from '@/api/audit/index';
import { useRouter } from 'vue-router';

const router = useRouter()
let type = router.currentRoute.value.params.id
const searchFormSchema = searchFormSchemaFunction(type, true)
const code = codeObj[type]
const subjectKey = SubjectKeyObj[type]


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

const [registerTable, { reload, expandAll, getForm}] = useTable({
  title: '待审核',
  api: (params) => LoadCaseInfoLists(type,params),
  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) {
  GetCaseInfo(type, {id: record.Id}).then(res => {
    console.log(res)
    infoData.value = res
    openModal.value = true
  })
}
const handleOk = async (params) => {
  changeLoading(true)
  try {
    const { id, case_description } = infoData.value.info
    const checkValue = await GetDraft({id})
    if(checkValue.process == null){
      await UpdateCaseInfoBySubject(params)
      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: case_description,
        processId: id,
        InstanceInfo: JSON.stringify(commit),
      };
      await saveDraft(resultQuery);
      resultQuery.schemeCode = '';
      const result = await create(resultQuery);
      if(result){
        await UpdateCaseNoBySubject({subject: type, id})
        message.success('发起流程成功');
        changeLoading(false)
        reload()
        openModal.value = false
      }else{
        message.error('发起流程失败');
        changeLoading(false)
      }
    }else{
      message.warning('该案件已发起流程');
      changeLoading(false)
    }
  } catch(err) {
    console.log(err)
    changeLoading(false)
  }
}
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 () => {
      if(closeCaseRemark.value.trim().length <=0){
        message.warning('关闭原因不能为空')
        return Promise.reject()
      }
      changeLoading(true)
      try{
        const result = await CloseCaseInfo(type, {id, closereason: closeCaseRemark.value})
        changeLoading(false)
        if(result){
          message.success('关闭案件成功');
          reload()
          openModal.value = false
        }
        closeCaseRemark.value = ''
      } catch (error){
        changeLoading(false)
        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 () => {
      changeLoading(true)
      try{
        console.log(reSubmitRemark.value)
        const result = await SaveReSubmitInfo({ originalcaseno, remark: reSubmitRemark.value, subjectKey })
        changeLoading(false)
        if(result){
          message.success('复提成功');
          reload()
          openModal.value = false
        }else{
          message.error('复提失败');
        }
        reSubmitRemark.value = ''
      }catch (error){
        changeLoading(false)
      }
    },
    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 => {
    ImportCaseInfoShpData({zipFilePath: res[0].filePath.replace(/\\/g, '/'), srid: '4326', subjectname: type}).then(resultRes => {
      console.log('resultRes',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: type}).then(res => {
    console.log(res)
    if(res == "") return message.warning("当前没有未导入数据")
    picihao.value = res
    openImportModal.value = true
  })
}
const downloadSHP = () => {
  const form = getForm();
  const filterValues = form.getFieldsValue();
  ExportapprovalCaseInfoShapefile(type,filterValues).then(res => {
    const elink = document.createElement('a');
    elink.download = '待审核矢量数据' + new Date().getTime() + '.zip';
    elink.style.display = 'none';
    elink.href = URL.createObjectURL(res);
    document.body.appendChild(elink);
    elink.click();
    URL.revokeObjectURL(elink.href);
    document.body.removeChild(elink);
  })
}
const changeLoading = (type: boolean) => {
  modalLoading.value = type
}

</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>
