<script setup name = 'constructionPlanDeclare'>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { useRouter } from 'vue-router'
import { genFileId } from 'element-plus'
import store from '@/store'
import {
  getConstructionDeclarePlan,
  declareConstructionScheme,
  declareExport
} from '@/http/apis/declareMange'
import { fileFormatVerification, handleFileSuccess, fileTypes, fileDesc, handleFilePreview } from '@/utils/uploadAction.js'
import useExportExc from '@/utils/useExportExc'
const { projectTypeOptions } = store.dictStore.globalDicts || {}
// 搜索栏表单数据
const { proxy } = getCurrentInstance(),
  formInline = reactive({
    projectName: '',
    projectType: '',
    projectYear: null,
    startTime: '',
    endTime: '',
    createTimeArr: []
  }),
  router = useRouter(),
  tableListRef = ref(),
  selectData = ref([]),
  getTableData = async (pageParams = tableListRef.value.pageParams) => {
    const res = await getConstructionDeclarePlan({
      ...pageParams,
      ...formInline,
      startTime: formInline.createTimeArr?.length
        ? formInline.createTimeArr[0]
        : undefined,
      endTime: formInline.createTimeArr?.length
        ? formInline.createTimeArr[0]
        : undefined,
      createTimeArr: undefined
    })
    selectData.value = res.data.records
    total.value = res.data.total
  },
  column = reactive([
    {
      label: '序号',
      type: 'index',
      width: '80'
    },
    {
      label: '项目名称',
      key: 'projectName',
      prop: 'projectName',
      minWidth: '200',
      showOverflowTooltip: true
    },
    {
      label: '项目类型',
      key: 'projectTypeName',
      prop: 'projectTypeName',
      width: 80
    },
    {
      label: '申报金额(万元)',
      key: 'declaredAmount',
      prop: 'declaredAmount',
      width: '200'
    },
    {
      label: '预算年度',
      key: 'projectYear',
      prop: 'projectYear',
      width: '100'
    },
    {
      label: '创建时间',
      key: 'createOn',
      prop: 'createOn',
      width: '250'
    },
    {
      label: '操作',
      slot: 'action',
      width: '140',
      fixed: 'right'
    }
  ]),
  // projectData = reactive([]),
  rules = reactive({
    constructionPlanFile: [
      { required: true, message: '请上传建设方案', trigger: 'blur' }
    ] }),
  // 数据总数
  total = ref(2),
  checkDetail = (detailData) => {
    // console.log('detailData', detailData)
    router.push({ name: 'projectDeclareDetail', query: { id: detailData.id }})
  },
  // 提交查询
  onSubmit = () => {
    getTableData()
  },
  formReset = () => {
    formInline.projectName = null
    formInline.projectType = null
    formInline.projectYear = null
    formInline.startTime = null
    formInline.endTime = null
    formInline.createTimeArr = null
    getTableData()
  },
  // 导出excel文件
  tableDom = ref(),
  handleTable = (value) => {
    tableDom.value = value
  },
  // handleExcel = () => {
  //   exportExcel(tableDom.value)
  // },
  // 申报方案
  // declarePlan = (val) => {
  //   projectId.value = val.id
  //   dialogVisible.value = true
  //   if (upload.value)upload.value.clearFiles()
  // },
  dialogVisible = ref(false),
  handleClose = (done) => {
    done()
  },
  // 文件上传
  uploadUrl = store.dictStore.uploadUrl,
  ruleForm = reactive({
    constructionPlanFile: []
  }),
  upload = ref(),
  planUploadRef = ref(),
  constructionPlanRef = ref(),
  handleExceed = (files) => {
    upload.value.clearFiles()
    const file = files[0]
    file.uid = genFileId()
    upload.value.handleStart(file)
  },
  projectId = ref(),
  submitUpload = async (formEl) => {
    if (!formEl) return
    formEl.validate((valid) => {
      if (valid) {
        declareConstructionSchemeFunction()
      } else {
        console.log('error submit!')
      }
    })
  },
  declareConstructionSchemeFunction = async () => {
    await declareConstructionScheme({
      projectInfo: {
        id: projectId.value,
        constructionPlanFile: JSON.stringify(ruleForm.constructionPlanFile && ruleForm.constructionPlanFile.map(i => {
          return {
            fileId: i.response.data.id,
            fileName: i.response.data.originalFileName
          }
        })[0])
      }
    })
    dialogVisible.value = false
    ruleForm.constructionPlanFile = []
    proxy.$message.success('提交成功')
    getTableData()
  },
  // 导出excel文件
  { exportLoading, exportData } = useExportExc(),
  handleExcel = () => {
    exportData(() => declareExport(3, {
      ...formInline,
      year: formInline.year * 1,
      startTime: formInline.createTimeArr?.length
        ? formInline.createTimeArr[0]
        : undefined,
      endTime: formInline.createTimeArr?.length
        ? formInline.createTimeArr[0]
        : undefined,
      createTimeArr: undefined
    }))
  }
onMounted(async () => {
  getTableData()
})
</script>
<template>
  <el-card class="w-full search">
    <el-form :model="formInline" size="small" label-suffix=":">
      <el-row :gutter="16" class="mb-16">
        <el-col :span="8">
          <el-form-item label="项目名称">
            <el-input v-model="formInline.projectName" maxlength="50" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目类型">
            <el-select v-model="formInline.projectType" placeholder="全部" class="w-full">
              <el-option
                v-for="(v,k) in projectTypeOptions"
                :key="k"
                :label="v"
                :value="k"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="预算年度">
            <el-date-picker
              v-model="formInline.projectYear"
              type="year"
              placeholder="请选择"
              format="YYYY"
              value-format="YYYY"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="10">
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="formInline.createTimeArr"
              type="datetimerange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm"
              value-format="YYYY-MM-DD HH:mm"
            />
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item class="btn">
            <div class="flex">
              <el-button type="primary" @click="onSubmit">查询</el-button>
              <el-button @click="formReset">重置</el-button>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-card>
  <el-card class="w-full mt-8">
    <template #header>
      <div class="flex justify-between">
        <span>待申报的项目</span>
        <div>
          <el-button
            type="primary"
            plain
            size="small"
            :loading="exportLoading"
            @click="handleExcel"
          >导出</el-button>
        </div>
      </div>
    </template>
    <table-list
      ref="tableListRef"
      :column="column"
      :data="selectData"
      :total="total"
      @handle-table="handleTable"
      @get-table-data="getTableData"
    >
      <template #action="{ scope }">
        <a @click="$router.push({name:'declarePlan',query:{id:scope.row.id}})">申报方案</a>
        <a @click="checkDetail(scope.row)">详情</a>
      </template>
    </table-list>
  </el-card>
  <el-dialog
    v-model="dialogVisible"
    title="申报建设方案"
    width="35%"
    :before-close="handleClose"
  >
    <el-form
      ref="constructionPlanRef"
      :model="ruleForm"
      :rules="rules"
      label-position="right"
      label-width="auto"
      status-icon
    >
      <el-form-item label="建设方案:" prop="constructionPlanFile">
        <el-upload
          ref="planUploadRef"
          v-model:file-list="ruleForm.constructionPlanFile"
          :action="uploadUrl"
          :limit="1"
          :on-exceed="handleExceed"
          :on-success="res => handleFileSuccess(res, ruleForm.constructionPlanFile, true)"
          :before-upload="file=>fileFormatVerification(file, {types: fileTypes})"
          :accept="fileTypes.map(i=>`.${i}`).join(',')"
          :on-preview="handleFilePreview"
        >
          <el-button plain type="primary">选择文件</el-button>
          <template #tip>
            <div class="el-upload__tip">
              支持{{ fileDesc }}文件
            </div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="submitUpload(constructionPlanRef)">
          提交
        </el-button>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<style lang='less' scoped>

</style>
