<script setup name='planList'>
import ElTree from '@/components/elTree/index.vue'
import { useRouter } from 'vue-router'
import { onMounted, reactive, ref, h, getCurrentInstance, watch } from 'vue'
import { fileFormatVerification, handleFileSuccess, handleFileError } from '@/utils/uploadAction.js'
import {
  defer,
  list,
  startDeclare,
  exportAnnualPlanEditTable, projectExcel
} from '@/http/apis/projectStoreManage/annualPlanStore'
import store from '@/store'
import ApprovalDialog from './approvalDialog.vue'
import ImportProjectDialog from './importProjectDialog.vue'
import ExportFieldDialog from './exportFieldDialog.vue'
import useExportExc from '@/utils/useExportExc'
import { getIsShowRegionTree, getTreeParams } from '@/utils/getIsShowRegionTree'
const { proxy } = getCurrentInstance(),
  props = defineProps({
    isTemporaryAugment: {
      type: Number,
      default: 0
    }
  }),
  router = useRouter(),
  { statusOptions, statusOptionsCascader, projectTypeOptions } = store.dictStore.globalDicts || {},
  searchForm = reactive({
    projectName: undefined,
    buildOrg: undefined,
    projectType: undefined,
    status: undefined,
    declareAmountMin: undefined,
    declareAmountMax: undefined,
    approveAmountMin: undefined,
    approveAmountMax: undefined,
    projectYear: undefined,
    times: undefined
  }),
  tableListRef = ref(),
  total = ref(0),
  // 列表数据
  column = reactive([
    {
      type: 'selection',
      width: '50'
    },
    {
      label: '序号',
      type: 'index',
      width: '60'
    },
    {
      label: '项目名称',
      key: 'projectName',
      prop: 'projectName',
      minWidth: '200',
      showOverflowTooltip: true
    },
    {
      label: '申报单位',
      key: 'buildOrg',
      prop: 'buildOrg',
      minWidth: '200',
      showOverflowTooltip: true
    },
    {
      label: '项目类型',
      key: 'projectTypeName',
      prop: 'projectTypeName',
      width: 80
    },
    {
      label: '项目申报资金(万元)',
      key: 'declaredAmount',
      prop: 'declaredAmount',
      width: '150'
    },
    {
      label: '项目批复资金(万元)',
      key: 'approvalAmount',
      prop: 'approvalAmount',
      width: '150'
    },
    {
      label: '预算年度',
      key: 'projectYear',
      prop: 'projectYear',
      width: '80'
    },
    {
      label: '是否开启方案申报',
      key: 'isStartDeclaredProject',
      prop: 'isStartDeclaredProject',
      width: '140',
      render: row => h('span', row.isStartDeclaredProject ? '是' : '否')
    },
    {
      label: '项目状态',
      key: 'status',
      prop: 'status',
      width: '180',
      render: row => [
        h('span', {
          class: ['dot mr-4', `bg-${statusOptions[row.status]?.color}`]
        }),
        h(
          'span',
          {
            class: `text-${statusOptions[row.status]?.color}`
          },
          row.status && statusOptions[row.stage]?.name + '-' + statusOptions[row.status]?.name
        )
      ]
    },
    {
      label: '创建时间',
      key: 'createOn',
      prop: 'createOn',
      width: '180'
    },
    {
      label: '操作',
      slot: 'action',
      width: '200',
      fixed: 'right'
    }
  ]),
  data = ref([]),
  form = ref({}),
  areaCode = ref(),
  getTree = (value) => {
    areaCode.value = value.regionLevel === 3 ? value.regionCode : undefined
    tableListRef.value.pageParams.pageNumber = 1
    getTableData()
  },
  getTableData = async (pageParams = tableListRef.value.pageParams) => {
    const res = await list({
      ...pageParams,
      ...searchForm,
      status: searchForm.status?.[searchForm.status.length - 1],
      projectYear: searchForm.projectYear * 1 || undefined,
      declareAmountMin: searchForm.declareAmountMin * 1 || undefined,
      declareAmountMax: searchForm.declareAmountMax * 1 || undefined,
      approveAmountMin: searchForm.approveAmountMin * 1 || undefined,
      approveAmountMax: searchForm.approveAmountMax * 1 || undefined,
      createOnMin: searchForm.times?.[0] || undefined,
      createOnMax: searchForm.times?.[1] || undefined,
      regionCode: areaCode.value || undefined,
      isTemporaryAugment: props.isTemporaryAugment, // 非补增
      times: undefined
    })
    data.value = res.data.records
    total.value = res.data.total
  },
  selectable = (row, index) => {
    if (row.isStartDeclaredProject) {
      return false // 不可勾选
    } else {
      return true // 可勾选
    }
  },
  search = () => {
    getTableData()
  },
  reset = () => {
    searchForm.projectName = undefined
    searchForm.buildOrg = undefined
    searchForm.projectType = undefined
    searchForm.status = undefined
    searchForm.declareAmountMin = undefined
    searchForm.declareAmountMax = undefined
    searchForm.approveAmountMin = undefined
    searchForm.approveAmountMax = undefined
    searchForm.projectYear = undefined
    searchForm.times = undefined
    tableListRef.value.pageParams.pageNumber = 1
    tableListRef.value.pageParams.pageSize = 10
    getTableData()
  },
  // 选择项目
  selectProject = ref([]),
  selectionChange = (val) => {
    selectProject.value = val
  },
  // 开启方案申报
  startPlanDeclare = () => {
    if (!selectProject.value.length) {
      proxy.$message.warning('请至少选择一个项目')
      return
    }
    proxy.$messageBox
      .confirm(`是否${areaCode.value === '331181' ? '列入年度计划' : '开启方案申报'}?`, '提示！', {
        type: 'warning'
      })
      .then(async () => {
        await startDeclare({ projectIds: selectProject.value.map(i => i.projectId) })
        proxy.$message.success(`${areaCode.value === '331181' ? '列入' : '开启'}成功！`)
        getTableData()
      })
  },
  // 导入
  importProjectDialogData = reactive({
    visible: false
  }),
  // showImportProjectDialog = (data) => {
  //   importProjectDialogData.visible = true
  // },
  closeImportProjectDialog = () => {
    importProjectDialogData.visible = false
  },
  // 导出
  exportFieldDialogData = reactive({
    visible: false
  }),
  showExportFieldDialog = (data) => {
    exportFieldDialogData.visible = true
  },
  closeExportFieldDialog = () => {
    exportFieldDialogData.visible = false
  },
  { exportData } = useExportExc(),
  exportProject = async (data) => {
    await exportData(() => projectExcel({
      ...tableListRef.value.pageParams,
      ...searchForm,
      status: searchForm.status?.[searchForm.status.length - 1],
      createOnMin: searchForm.times?.[0] || undefined,
      createOnMax: searchForm.times?.[1] || undefined,
      regionCode: areaCode.value || undefined,
      isTemporaryAugment: props.isTemporaryAugment,
      times: undefined,
      exportOptionList: data
    })
    )
    closeExportFieldDialog()
  },
  // 导出编辑表
  exportEdit = async () => {
    await exportData(() => exportAnnualPlanEditTable({
      ...tableListRef.value.pageParams,
      ...searchForm,
      status: searchForm.status?.[searchForm.status.length - 1],
      createOnMin: searchForm.times?.[0] || undefined,
      createOnMax: searchForm.times?.[1] || undefined,
      regionCode: areaCode.value || undefined,
      times: undefined,
      isTemporaryAugment: props.isTemporaryAugment
      // tableFlag: 0
    })
    )
    closeExportFieldDialog()
  },
  // 编辑
  toEdit = (data) => {
    router.push({ name: 'planEdit', query: { id: data.projectId }})
  },
  // 暂缓
  projectDefer = (data) => {
    proxy.$messageBox
      .confirm(`是否暂缓【${data.projectName}】?`, '提示！', {
        type: 'warning'
      })
      .then(async () => {
        await defer({ projectId: data.projectId })
        proxy.$message.success('暂缓成功！')
        getTableData()
      })
  },
  // 立项批复
  approvalDialogData = reactive({
    visible: false,
    title: undefined,
    rowData: undefined
  }),
  showApprovalDialog = (data) => {
    approvalDialogData.visible = true
    approvalDialogData.title = `立项批复-${data.projectName}`
    approvalDialogData.rowData = data
  },
  closeApprovalDialog = (flag) => {
    approvalDialogData.visible = false
    flag && getTableData()
  }
watch(
  () => form.value.file,
  async val => {
    search()
  }
)
onMounted(async () => {
  if (!getIsShowRegionTree(['SUPER_ADMIN', 'REGION_MANAGER'])) getTableData()
})
</script>
<template>
  <el-row>
    <el-col
      v-if="getIsShowRegionTree(['SUPER_ADMIN','REGION_MANAGER'])"
      :span="4"
      class="pr-16"
    >
      <elTree :params="getTreeParams({'SUPER_ADMIN':false,'REGION_MANAGER':false})" @get-tree="getTree" />
    </el-col>
    <el-col :span="getIsShowRegionTree(['SUPER_ADMIN','REGION_MANAGER'])?20:24">
      <el-card class="w-full search">
        <el-form
          :model="searchForm"
          size="small"
          label-suffix=":"
        >
          <el-row
            :gutter="16"
            class="mb-16"
          >
            <el-col :span="8">
              <el-form-item label="项目名称">
                <el-input
                  v-model="searchForm.projectName"
                  placeholder="请输入"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="申报单位">
                <el-input
                  v-model="searchForm.buildOrg"
                  placeholder="请输入"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="项目类型">
                <el-select
                  v-model="searchForm.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-row>
          <el-row
            :gutter="16"
            class="mb-16"
          >
            <el-col :span="8">
              <el-form-item label="项目状态">
                <el-cascader
                  v-model="searchForm.status"
                  class="w-full"
                  :props="{label:'name',value:'code'}"
                  :options="statusOptionsCascader"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                class="whitespace-nowrap"
                label="申报资金(万元)"
              >
                <div class="flex">
                  <el-input-number
                    v-model="searchForm.declareAmountMin"
                    clearable
                    :controls="false"
                    @mousewheel.prevent
                  />
                  &nbsp;至&nbsp;
                  <el-input-number
                    v-model="searchForm.declareAmountMax"
                    clearable
                    :controls="false"
                    @mousewheel.prevent
                  />
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                class="whitespace-nowrap"
                label="批复资金(万元)"
              >
                <div class="flex">
                  <el-input-number
                    v-model="searchForm.approveAmountMin"
                    :controls="false"
                    clearable
                    @mousewheel.prevent
                  /> &nbsp;至&nbsp;
                  <el-input-number
                    v-model="searchForm.approveAmountMax"
                    :controls="false"
                    clearable
                    @mousewheel.prevent
                  />
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            :gutter="16"
            class="mb-16"
          >
            <el-col :span="8">
              <el-form-item label="预算年度">
                <el-date-picker
                  v-model="searchForm.projectYear"
                  type="year"
                  value-format="YYYY"
                  placeholder="请选择"
                />
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="创建时间">
                <el-date-picker
                  v-model="searchForm.times"
                  type="datetimerange"
                  :editable="false"
                  format="YYYY-MM-DD HH:mm"
                  value-format="YYYY-MM-DD HH:mm"
                  range-separator="-"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item class="btn">
                <div class="flex">
                  <el-button
                    type="primary"
                    @click="search"
                  >查询</el-button>
                  <el-button
                    @click="reset"
                  >重置</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 items-center">
            <div class="flex items-center">
              <span class="mr-24">列表</span>
              <el-button
                type="primary"
                size="small"
                @click="startPlanDeclare"
              >{{ areaCode==='331181'?'列入年度计划':'开启方案申报' }}</el-button>
            </div>
            <div class="flex items-center relative">
              <!-- <el-button
                type="primary"
                plain
                size="small"
                @click="showImportProjectDialog"
              >导入</el-button> -->
              <el-upload
                v-model:file-list="form.file"
                class="absolute -left-70 -top-2"
                :show-file-list="false"
                :data="{importFlag:$route.name==='annualPlanStore'?'ANNUAL_PLAN':'ANNUAL_PLAN_SUPPLEMENT'}"
                action="/pm/api/v1/annualPlan/importAnnualPlan"
                :on-success="res => handleFileSuccess(res, form.file, true,search)"
                :on-error="handleFileError"
                :limit="1"
                :before-upload="
                  file =>
                    fileFormatVerification(file, {
                      types: [
                        'application/vnd.ms-excel',
                        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                      ]
                    })
                "
                accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
              >
                <el-button
                  type="primary"
                  plain
                  size="small"
                >导入</el-button>
                <!-- <template #tip>
                  <div class="el-upload__tip">支持.xlsx、.xls</div>
                </template> -->
              </el-upload>
              <el-button
                type="primary"
                class="ml-10"
                plain
                size="small"
                @click="exportEdit"
              >导出编辑表</el-button>
              <el-button
                type="primary"
                plain
                size="small"
                @click="showExportFieldDialog"
              >导出</el-button>
            </div>
          </div>
        </template>
        <table-list
          ref="tableListRef"
          :column="column"
          :data="data"
          :total="total"
          :selectable="selectable"
          @selection-change="selectionChange"
          @get-table-data="getTableData"
        >
          <template #action="{ scope }">
            <a v-if="scope.row.status===10010" @click="toEdit(scope.row)">编辑</a>
            <a v-if="scope.row.status===10010" @click="projectDefer(scope.row)">暂缓</a>
            <a v-if="scope.row.status===10014" @click="showApprovalDialog(scope.row)">立项批复</a>
            <a @click="router.push({name:'projectDetail',query:{id:scope.row.projectId}})">详情</a>
          </template>
        </table-list>
      </el-card>
    </el-col>
  </el-row>
  <approval-dialog
    :visible="approvalDialogData.visible"
    :title="approvalDialogData.title"
    :data="approvalDialogData.rowData"
    @close="closeApprovalDialog"
  />
  <import-project-dialog
    :visible="importProjectDialogData.visible"
    :data="importProjectDialogData.rowData"
    @close="closeImportProjectDialog"
  />
  <export-field-dialog
    :visible="exportFieldDialogData.visible"
    :data="exportFieldDialogData.rowData"
    @close="closeExportFieldDialog"
    @export-project="exportProject"
  />
</template>
