<template>
 <div id="printBox">
   <div style="display: flex;justify-content: space-between">
     <baseTitle title="项目基本信息"></baseTitle>
     <el-button v-print="print"  color="#ded0b2" icon="Printer" style="margin-top: 15px" @click="handlePrint(print)"> 打印</el-button>
   </div>
   <fvForm :schema="schema" @getInstance="(e)=>baseForm = e" label-position="left" label-width="left" style="margin-left: 15px"></fvForm>
   <div class="steps-box">
     <el-steps :active="localActive" finish-status="success">
       <el-step
           v-for="(item, index) in localSteps"
           :key="item.key"
           :title="item.title"
           :class="stepClass(index)"
           @click="handleStep(item.key, index)"
       >
         <template #icon>
           <el-icon style="font-size: 20px;" :class="index == localActive ? 'is-active' : 'is-end'" v-if="localStepSuccess.includes(index)"><SuccessFilled /></el-icon>
           <el-icon style="font-size: 20px; color: gray;" v-else><WarningFilled /></el-icon>
         </template>
       </el-step>
     </el-steps>
   </div>

   <!-- 步骤内容 -->
   <div>
     <slot name="content" :localActive="localActive"></slot>
     <!-- <template v-for="(item, index) in stepList" :key="item.key">
       <component v-if="localActive == index" v-bind="item.props || {}" :is="item.component" />
     </template> -->
   </div>
 </div>
</template>

<script setup lang="jsx">
import {ElLoading, ElNotification} from 'element-plus';
import {getBaseInfoApi} from './api';
import {useCacheStore} from '@/stores/cache.js'

import {toThousands} from '@/utils/changePrice.js'
const cacheStore = useCacheStore()
const props = defineProps({
  // 步骤对应内容list
  stepList: {
    type: Array,
    default: []
  },
  // 当前显示步骤
  active: {
    type: Number,
    default: 0
  },
  // 已完成的工作流步骤
  stepSuccess: {
    type: Array,
    default: ['00']
  },
  //直接上报/需求征集
  reportType: {
    type: String,
    default: ''
  }
})
const print = ref({
  id: 'printBox',//这里的id就是上面我们的打印区域id，实现指哪打哪
  popTitle: '配置页眉标题', // 打印配置页上方的标题
  extraHead: '', // 最上方的头部文字，附加在head标签上的额外标签，使用逗号分割
  preview: false, // 是否启动预览模式，默认是false
  previewTitle: '预览的标题', // 打印预览的标题
  previewPrintBtnLabel: '预览结束，开始打印', // 打印预览的标题下方的按钮文本，点击可进入打印
  zIndex: 20002, // 预览窗口的z-index，默认是20002，最好比默认值更高
  previewBeforeOpenCallback() {
    console.log('正在加载预览窗口！');
  }, // 预览窗口打开之前的callback
  previewOpenCallback() {
    console.log('已经加载完预览窗口，预览打开了！')
  }, // 预览窗口打开时的callback
  beforeOpenCallback() {
    console.log('开始打印之前！')
  }, // 开始打印之前的callback
  openCallback() {
    console.log('执行打印了！')
  }, // 调用打印时的callback
  closeCallback() {
    console.log('关闭了打印工具！')
    emits('closePrint')
  }, // 关闭打印的callback(无法区分确认or取消)
  clickMounted() {
    console.log('点击v-print绑定的按钮了！')
  },
})
const route = useRoute()

const emits = defineEmits(['stepChange', 'setDetail'])

const localData = reactive({})

const localActive = ref(0) // 当前激活步骤

const localSteps = ref([
  {
    title: '需求征集',
    key: 'collect',
  },
  {
    title: '需求上报',
    key: 'report',
  },
  {
    title: '项目立项',
    key: 'approve',
  },
  {
    title: '项目实施',
    key: 'implement',
  },
  {
    title: '项目验收',
    key: 'execute',
  },
  {
    title: '项目归档',
    key: 'archivist',
  },
  // {
  //   title: '项目结项',
  //   key: 'end',
  // },
])

const baseForm = ref()
const baseFormData = ref([])

const schema = computed(() => {
  return [
    {
      label: '承办单位',
      prop: 'affiliatedCompany',
      colProps: {
        span: 24
      }
    },
    {
      label: '项目名称',
      prop: 'projectName',
      colProps: {
        span: 24
      }
    },

    {
      label: '开始时间',
      prop: 'startTime',
      colProps: {
        span: 24
      }
    },
    {
      label: '结束时间',
      prop: 'endTime',
      colProps: {
        span: 24
      }
    },
    {
      label: '项目类型',
      prop: 'projectType',
      colProps: {
        span: 24
      },
      component: () => (
          <div>
            {
              baseFormData.value?.projectType ?
                  <span>{filterDict(cacheStore.getDict('project_type'), baseFormData.value?.projectType)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    {
      label: '研发主体',
      prop: 'rdSubject',
      colProps: {
        span: 24
      },
      component: () => (
          <div>
            {
              baseFormData.value?.rdSubject ?
                  <span>{filterDict(cacheStore.getDict('rd_subject'), baseFormData.value?.rdSubject)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    {
      label: '出资类型',
      prop: 'investmentType',
      colProps: {
        span: 24
      },
      component: () => (
          <div>
            {
              baseFormData.value?.investmentType ?
                  <span>{filterDict(cacheStore.getDict('invest_type'), baseFormData.value?.investmentType)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    {
      label: '业务板块',
      prop: 'businessSegment',
      colProps: {
        span: 24
      },
      component: () => (
          <div>
            {
              baseFormData.value?.businessSegment ?
                  <span>{filterDict(cacheStore.getDict('business_segment'), baseFormData.value?.businessSegment)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    {
      label: '标准制定',
      prop: 'technicalStandard',
      colProps: {
        span: 24
      },
      component: () => (
          <div>
            {
              baseFormData.value?.technicalStandard ?
                  <span>{filterDict(cacheStore.getDict('technical_standard'), baseFormData.value?.technicalStandard)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    {
      label: '项目影响',
      prop: 'projectImpact',
      colProps: {
        span: 24
      },
      component: () => (
          <div>
            {
              baseFormData.value?.projectImpact ?
                  <span>{filterDict(cacheStore.getDict('project_impact'), baseFormData.value?.projectImpact)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },

    {
      label: '预估经费预算',
      prop: 'economicEstimate',
      colProps: {
        span: 24
      },
      component: () => (
          <div>
            {
              baseFormData.value?.economicEstimate ?
                  <span>{ toThousands(baseFormData.value?.economicEstimate )}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    {
      label: '实际经费预算',
      prop: 'actualEconomicEstimate',
      colProps: {
        span: 6
      },
      component: () => (
          <div>
            {
              baseFormData.value?.actualEconomicEstimate ?
                  <span>{toThousands(baseFormData.value?.actualEconomicEstimate)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    {
      label: '产学研联合',
      prop: 'industryUniversityResearch',
      colProps: {
        span: 24
      },
      component: () => (
          <div>
            {
              baseFormData.value?.industryUniversityResearch ?
                  <span>{filterDict(cacheStore.getDict('industry_university'), baseFormData.value?.industryUniversityResearch)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    {
      label: '开展政府申报',
      prop: 'governmentDeclaration',
      colProps: {
        span: 24
      },
      component: () => (
          <div>
            {
              baseFormData.value?.governmentDeclaration ?
                  <span>{filterDict(cacheStore.getDict('government_declaration'), baseFormData.value?.governmentDeclaration)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    // {
    //   label: '是否专项资金项目',
    //   prop: 'isSpecialFund',
    //   colProps: {
    //     span: 24
    //   }
    // },
    {
      label: '所属专项资金',
      prop: 'specialFund',
      colProps: {
        span: 24
      }
    },

    {
      label: '预估专项资金(元)',
      prop: 'forecastSpecialFundAmount',
      colProps: {
        span: 24
      },
      component: () => (
          <div>
            {
              baseFormData.value?.forecastSpecialFundAmount ?
                  <span>{toThousands(baseFormData.value?.forecastSpecialFundAmount)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },

    {
      label: '实际专项资金(元)',
      prop: 'forecastSpecialFundAmount',
      colProps: {
        span: 24
      },
      component: () => (
          <div>
            {
              baseFormData.value?.specialFundAmount ?
                  <span>{toThousands(baseFormData.value?.specialFundAmount)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },

    {
      label: '是否在预算内',
      prop: 'isWithinBudget',
      colProps: {
        span: 24
      },
      component: () => (
          <div>
            {
              baseFormData.value?.isWithinBudget!=null ? baseFormData.value?.isWithinBudget?
                  <span>{'预算内'}</span>
                  : <span>{'预算外'}</span>:'--'
            }
          </div>
      )
    },
    {
      label: '部门分管领导',
      prop: 'optionalChargeLeadership',
      colProps: {
        span: 24
      }
    },
    {
      label: '主项目',
      prop: 'masterProjectName',
      colProps: {
        span: 24
      }
    }
  ]
})

const localStepSuccess = ref([])
const handlePrint=(print)=>{
  emits('openPrint',print)
}
// 格式化详情步骤条
const formatProcedure = (data) => {
  console.info("🚀 ~method:formatProcedure -----", data)
  let arr = []
  if (data instanceof Array) {
    data.forEach(item => {
      if (props.reportType === 'direct') {
        switch (item) {
          case '10':
            arr.push(0)
            break
          case '20':
            arr.push(1)
            break
          case '30':
            arr.push(2)
            break
          case '40':
            arr.push(3)
            break
          case '50':
            arr.push(4)
            break
        }
      } else {
        switch (item) {
          case '00':
            arr.push(0)
            break
          case '10':
            arr.push(1)
            break
          case '20':
            arr.push(2)
            break
          case '30':
            arr.push(3)
            break
          case '40':
            arr.push(4)
            break
          case '50':
            arr.push(5)
            break
        }
      }

    })
  }
  return arr
}

// 反向格式化
const formatReProcedure = (data) => {
  let arr = []
  if (data instanceof Array) {
    data.forEach(item => {
      switch (item) {
        case 0:
          arr.push('00')
          break
        case 1:
          arr.push('10')
          break
        case 2:
          arr.push('20')
          break
          // case 3: arr.push('30')
          //   break
        case 3:
          arr.push('40')
          break
        case 4:
          arr.push('50')
          break
      }
    })
  }
}

const formatActive = (val) => {
  let newVal
  if (props.reportType === 'direct') {
    newVal = val + 1
  } else {
    newVal = val
  }
  let active = ''
  newVal == 0 && (active = '00')
  newVal == 1 && (active = '10')
  newVal == 2 && (active = '20')
  newVal == 3 && (active = '30')
  newVal == 4 && (active = '40')
  newVal == 5 && (active = '50')
  return active
}

const stepClass = (val) => {
  if (localStepSuccess.value.includes(val)) {
    return 'step-success'
  }
  return 'step-error'
}

const handleStep = (key, index) => {
  if (localStepSuccess.value.includes(index)) {
    let active = ''
    localActive.value = index
    if (props.reportType === 'direct') {
      switch (index) {
        case 0:
          active = '10'
          break
        case 1:
          active = '20'
          break
        case 2:
          active = '30'
          break
        case 3:
          active = '40'
          break
        case 4:
          active = '50'
          break
      }
    } else {
      switch (index) {
        case 0:
          active = '00'
          break
        case 1:
          active = '10'
          break
        case 2:
          active = '20'
          break
        case 3:
          active = '30'
          break
        case 4:
          active = '40'
          break
        case 5:
          active = '50'
          break
      }
    }
    emits('stepChange', {key, active})
    return
  }
  ElNotification({
    title: '提示',
    message: '不能查看未完成的工作流信息',
    type: 'warning'
  })
}

//匹配字典值,返回对应值的字典标签
const filterDict = (data, value) => {
  if (data === undefined || value === undefined) return;
  let label = ''
  let result = []
  if (value instanceof Array) {
    value.forEach(item1 => {
      data.find(item => {
        if (item.value == item1) {
          result.push(item.label)
        }
      })
    })
    label = result.map(item => item).join('，')
  } else {
    if (data instanceof Array) {
      data.find(item => {
        if (item.value == value) {
          label = item.label
        }
      })
    }
  }
  return label
}
const getBaseInfo = async () => {
  const loading = ElLoading.service({fullscreen: true})
  try {
    const {code, data} = await getBaseInfoApi(route.query.projectId)
    // console.log('data.procedure',data.procedure,route.query.step)
    if (route.query.step === '30'||route.query.step === '40') {
      if (data.procedure.indexOf('30') == -1) {
        data.procedure.push('30')
      }
      if (data.procedure.indexOf('40') == -1) {
        data.procedure.push('40')
      }
    }else if(route.query.step==='50'){
      if(data.procedure.indexOf('50')==-1){
        data.procedure.push('50')
      }
    }
    localStepSuccess.value = formatProcedure(data.procedure)
    baseForm.value.setValues(data)
    baseFormData.value = data
    emits('setDetail', formatActive(localActive.value))
    loading.close()
  } catch {
    loading.close()
  }
}

getBaseInfo()

watchEffect(() => {
  localActive.value = props.active
})
watchEffect(() => {
  if (props.reportType === 'direct') {
    let steps = []
    for (const step of localSteps.value) {
      if (step.key !== 'collect') {
        steps.push(step)
      }
    }
    localSteps.value = steps
  }
})
</script>

<style lang="scss" scoped>
:deep(.el-step__title){
  font-size: 14px;
}
.steps-box {
  padding: 10px 0;
}

.step-success {
  cursor: pointer;
}

.step-error {
  cursor: not-allowed;
}
.is-active {
  color: #67c23a;
}
.is-end {
  color: #BEA266;
}
:deep(.el-step__title.is-success) {
  color: #A8abb2;
}

:deep(.el-step__head.is-success) {
  border-color: #A8abb2;
}
</style>
