<template>
  <div class="apply-block">
    <el-form :model="localFormData" ref="formRef" label-width="auto" :rules="rules" v-if="step!=='50'">
      <el-row>
        <el-col :span="24">
          <el-form-item label="前置流程" :required="preProcessRequired" prop="requestName">
            <div v-for="item in localFormData.preProcess" :key="item.requestId">
              <a :href="item.baseUrl" target="_blank"
                 style="color: #2a99ff;margin-right: 10px;cursor: pointer">{{ item.requestName }}</a>
            </div>
            <el-button color="#DED0B2" @click="handleShowPreTable">
              {{ localFormData.preProcess ? '更改' : '请选择' }}
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <AttachmentUpload ref="attachment" :label="getTitleName(title)+'附件'" :showTable="showTable"
                      :otherFileList="otherFileList"
                      @getAttachment="getAttachment"
                      @getOtherFile="getOtherFile" :showFileList="true" :formData="localFormData"
                      :preview="mode == 'resubmit'"/>
    <div>
      <div class="approval-record">
        <div class="approval-title">
          <baseTitle title="审批记录" v-if="mode === 'resubmit'"></baseTitle>
          <div v-else></div>
          <div class="diagram">
            <div class="base-title">流程图</div>
            <el-switch
                v-model="changeDiagram"
                style="--el-switch-on-color: #13ce66; --el-switch-off-color:#BEA266"
            />
          </div>
        </div>
        <div class="process">
          <operation-render v-if="mode === 'resubmit'&&!changeDiagram" :operation-list="data.operationList"
                            :state="data.state"/>
          <process-diagram-viewer mode="view" :idName="title" v-if="processDiagramViewer&&changeDiagram"/>
        </div>
      </div>
    </div>
    <div class="oper-page-btn">
      <el-button color="#DED0B2" v-if="mode === 'submit'" @click="handleSubmit">提交</el-button>
      <el-button color="#DED0B2" v-else-if="mode === 'resubmit'" @click="handleSubmit">重新提交</el-button>
      <el-button @click="handleBack">返回</el-button>
    </div>
    <el-dialog title="前置流程" v-model="showPreTable" width="80%">
      <el-form :model="preProcessForm" inline>
        <el-form-item label="请求名称">
          <el-input v-model="preProcessForm.requestName" placeholder="请输入请求名称" clearable>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button color="#DED0B2" @click="searchPreProcess">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="preProcessList" stripe v-loading="loading"
                @select="handleSelect" row-key="requestId">
        <el-table-column type="selection" width="55" :reserve-selection="true"/>
        <el-table-column prop="requestId" label="请求id"></el-table-column>
        <el-table-column prop="requestName" label="请求名称"></el-table-column>
        <el-table-column prop="lastOperatorName" label="最后操作人名称"></el-table-column>
        <el-table-column prop="lastOperateTime" label="最后操作时间"></el-table-column>
        <el-table-column prop="currentNodeName" label="当前节点"></el-table-column>
        <el-table-column prop="creatorName" label="创建人"></el-table-column>
        <el-table-column prop="createTime" label="创建时间"></el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <!--              <el-button type="primary" @click="choosePreProcess(scope.row)" link>选择</el-button>-->
            <a :href="scope.row.baseUrl" target="_blank" style="color: #2a99ff;margin-left: 10px">查看流程</a>
          </template>
        </el-table-column>
      </el-table>
      <paging :current-page="pageInfo.pageNum" :page-size="pageInfo.pageSize" :page-sizes="[10, 20, 30, 40,50]"
              :total="total" @changeSize="handleSizeChange" @goPage="handleCurrentChange"/>
      <div class="oper">
        <el-button color="#DED0B2" @click="choosePreProcess">确定</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="jsx">
import OperationRender from '@/views/workflow/common/OperationRender.vue'
import ProcessDiagramViewer from '@/views/workflow/common/ProcessDiagramViewer.vue';
import {ElNotification} from "element-plus";
import {
  getApplyProcess,
  getPreProcess,
  getProjectCheckProcess,
  getProjectConclusionProcess,
  projectApply,
  projectCheck,
  projectConclusion,
  resubmitApply,
  resubmitCheck,
  resubmitConclusion
} from "@/api/project-manage";
import {useProcessStore} from '@/stores/processStore.js';
import {useTagsView} from '@/stores/tagsview.js'
import Paging from "@/components/pagination/index.vue";

const router = useRouter()
const route = useRoute()
const changeDiagram = ref(false)
const emit = defineEmits(["getAttachment", "getOtherFile"])
const props = defineProps({
  title: {
    type: String,
    default: 'apply'
  },
  showTable: {
    type: Boolean,
    default: false
  },
  mode: {
    type: String,
    default: "view"
  },
  data: {
    type: Object,
    default: {}
  },
  formData: {
    type: Object,
    default: {}
  },
  step: {
    type: String,
    default: "20"
  }
})
const preProcessList = ref([])
//暂存数据
const currentList = ref([])
const preProcessRequired = ref(false)
const total = ref(0)
const preProcessForm = reactive({
  requestName: ''
})
const pageInfo = reactive({
  pageNum: 1,
  pageSize: 10,
})
const rules = reactive({
  requestName: [{required: true, message: '请选择前置流程', trigger: 'blur'}],
})
const tagsViewStore = useTagsView()
const processStore = useProcessStore()
const otherFileList = ref([])
const localFormData = ref({
  preProcess: [
    // {
    //   requestId: null,
    //   requestName: '',
    //   baseUrl: ''
    // }
  ]
})
const attachment = ref()
const deploymentData = ref({})
const showPreTable = ref(false)
const showTable = ref(true)
const loading = ref(false)
const processDiagramViewer = ref(false)
const name = ref(router.currentRoute.value.name)
const deploymentId = ref()
const selectRows = ref([])
const projectId = ref(route.query.projectId)
const getPreProcessUrl = (list) => {
  // list.map(item => {
  //   item.baseUrl = getPreProcessUrl(item.preProcess)
  // })
  // let baseUrl=
  // list.forEach(item => {
  //   baseUrl=item.baseUrl
  // })
  // return baseUrl
}
const handleSelect = async (selection) => {
  selectRows.value = selection
}
const handleCancel = () => {
  showPreTable.value = false
}
const searchPreProcess = () => {
  getPreProcessList()

}
const handleReset = () => {
  preProcessForm.requestName = ''
  getPreProcessList()
}
const handleShowPreTable = () => {
  showPreTable.value = true
  getPreProcessList()
}
const getPreProcessList = () => {
  loading.value = true
  getPreProcess().then(res => {
    loading.value = false
    let searchArray = []
    let regexPattern = ("%" + preProcessForm.requestName + "%").replace(/%/g, '.*').replace(/_/g, '.');
    let regex = new RegExp('^' + regexPattern + '$');
    res.data.filter((item) => {
      if (regex.test(item.requestName)) {
        searchArray.push(item)
      }
    })
    total.value = searchArray.length
    currentList.value = searchArray
    preProcessList.value = currentList.value.slice(0, 10)
  })
}
const choosePreProcess = () => {
  let preProcessObj = {}
  let preProcessArray = []
  selectRows.value.forEach((item) => {
    preProcessObj = {
      requestId: item.requestId,
      requestName: item.requestName,
      baseUrl: item.baseUrl
    }
    preProcessArray.push(preProcessObj)
  })
  localFormData.value.preProcess = preProcessArray
  // console.log('localFormData.value.preProcess', localFormData.value.preProcess)
  showPreTable.value = false
}

//切换每页显示条数
const handleSizeChange = (val) => {
  pageInfo.pageSize = val;
  preProcessList.value = currentList.value.slice((pageInfo.pageNum - 1) * val, pageInfo.pageNum * val)
};

//点击页码进行分页功能
const handleCurrentChange = (val) => {
  pageInfo.pageNum = val;
  preProcessList.value = currentList.value.slice((val - 1) * pageInfo.pageSize, val * pageInfo.pageSize)
};
const getTitleName = (type) => {
  switch (type) {
    case 'apply':
      return '项目立项'
    case 'check':
      return '项目验收'
    case 'filing':
      return '项目归档'
  }
}
const handleBack = () => {
  history.back()
}
const compositeParam = (item) => {
  return {
    fileId: item.id,
    size: item.size,
    originalFileName: item.originalFilename,
    fileType: item.fileType,
    url: item.url,
    newFile: true,
    tag: getTitleName(props.title)
  }
}
const getAttachment = (val) => {
  // console.log('上传文件getAttachment', val)
  localFormData.value.singleFile = compositeParam(val)
}
const getOtherFile = (val) => {
  // console.log('上传文件getOtherFile', val)
  showTable.value = false
  let fileObj = compositeParam(val)
  otherFileList.value.push(fileObj)
  nextTick(() => {
    showTable.value = true
  })
}
const getFileParam = (item) => {
  return {
    fileId: item.fileId,
    tag: item.tag
  }
}
const handleSubmit = async () => {
  if (deploymentData.value.deploymentName === '重大项目立项' || deploymentData.value.deploymentName === '重大项目验收') {
    if (localFormData.value.preProcess === undefined) {
      ElNotification({
        title: '提示',
        message: '请选择前置流程!',
        type: 'error'
      })
    }
  }
  let files = []
  if (props.mode === 'resubmit') {
    attachment.value.allFileList.forEach(item => {
      files.push(getFileParam(item))
    })
  } else {
    otherFileList.value.forEach(item => {
      files.push(getFileParam(item))
    })
  }
  // if (localFormData.value.singleFile !== undefined) {
  //   localFormData.value.singleFile = getFileParam(localFormData.value.singleFile)
  // }
  // console.log('attachment.value.singleFile', attachment.value, attachment.value.singleFile)
  // if (localFormData.value.singleFile) {
  //
  // } else {
  if (attachment.value.singleFile == null) {
    attachment.value.validate()
    ElNotification({
      title: '提示',
      message: '请上传附件',
      type: 'error'
    })
    return;
  } else {
    attachment.value.clearValidate()
  }
  // }

  let params = {
    deploymentId: deploymentId.value,
    requirementId: route.query.id,
    fileList: files,
    singleFile: attachment.value.singleFile,
    projectId: projectId.value,
    preProcess: JSON.stringify(localFormData.value.preProcess)
  }
  // console.log('params', params)
  let res
  if (props.step === '20') {
    if (props.mode === 'resubmit') {
      res = await resubmitApply(params)
    } else {
      res = await projectApply(params)
    }
  } else if (props.step === '40') {
    if (props.mode === 'resubmit') {
      res = await resubmitCheck(params)
    } else {
      res = await projectCheck(params)
    }
  } else if (props.step === '50') {
    if (props.mode === 'resubmit') {
      res = await resubmitConclusion(params)
    } else {
      res = await projectConclusion(params)
    }
  }
  ElNotification({
    title: '提示',
    message: res.msg,
    type: res.code === 1000 ? 'success' : 'error'
  })
  if (res.code === 1000) {
    tagsViewStore.delVisitedViews(router.currentRoute.value.path)
    if (props.step === '20') {
      await router.push({
        name: 'Initiation'
      })
    } else if (props.step === '40') {
      await router.push({
        name: 'Implementation'
      })
    } else if (props.step === '50') {
      await router.push({
        name: 'Filing'
      })
    }
  }
}
const init = async () => {
  let id = projectId.value
  if (!id) return;
  processDiagramViewer.value = false
  let res
  if (props.step === '20') {
    res = await getApplyProcess(id)
  } else if (props.step === '40') {
    res = await getProjectCheckProcess(id)
  } else if (props.step === '50') {
    res = await getProjectConclusionProcess(id)
  }
  if (res.code === 1000) {
    let data = res.data
    deploymentId.value = data.deploymentId
    deploymentData.value = data
    preProcessRequired.value = data.deploymentName === '重大项目立项' || data.deploymentName === '重大项目验收';
    processStore.setDesign(data)
    processStore.runningList.value = data.runningList;
    processStore.endList.value = data.endList;
    processStore.noTakeList.value = data.noTakeList;
    processStore.refuseList.value = data.refuseList;
    processStore.passList.value = data.passList;
    nextTick(() => {
      processDiagramViewer.value = true
    })
  } else {
    ElNotification({
      title: '提示',
      message: res.msg,
      type: 'error'
    })
  }
}

watchEffect(() => {
  return Object.keys(props.formData).length && (localFormData.value = props.formData)
})

onMounted(async () => {
  await init()
})
</script>

<style scoped>
.oper {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
