<template>
    <hc-card scrollbar is-action-btn class="create-project">
        <template #header>
            <div class="flex-1 text-center text-[24px] font-bold">项目信息填写</div>
        </template>
        <el-form ref="formRef" :model="baseForm" label-width="auto" :rules="baseFormRules" size="large" label-position="left">
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="项目名称:" prop="name">
                        <el-input v-model="baseForm.name" placeholder="请输入" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="建设规模:" prop="buildScale">
                        <el-input v-model="baseForm.buildScale" placeholder="请输入" clearable>
                            <template #append>
                                <el-select v-model="baseForm.buildScaleUnit" placeholder="单位" style="width: 80px">
                                    <el-option label="公里" value="1" />
                                    <el-option label="无" value="2" />
                                </el-select>
                            </template>
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="项目阶段:" prop="projectStage">
                        <el-select v-model="baseForm.projectStage" placeholder="请选择">
                            <el-option v-for="item in stateOptions" :key="item.value" :label="item.label" :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="项目类型:" prop="projectType">
                        <el-select v-model="baseForm.projectType" placeholder="请选择">
                            <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="总投资:" prop="allInvestMoney">
                        <el-input
                            v-model="baseForm.allInvestMoney" placeholder="请输入" clearable
                            :formatter="formatInput"
                        >
                            <template #append>亿元</template>
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="十四五计划投资:" prop="fourteenFiveInvest">
                        <el-input
                            v-model="baseForm.fourteenFiveInvest" placeholder="请输入" clearable
                            :formatter="formatInput"
                        >
                            <template #append>亿元</template>
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="开工年:" prop="startYear">
                        <el-date-picker ref="startYearRef" v-model="baseForm.startYear" class="block" type="year" placeholder="请选择" value-format="YYYY" @change="startYearChange" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="完工年:" prop="endYear">
                        <el-date-picker ref="endYearRef" v-model="baseForm.endYear" class="block" type="year" placeholder="请选择" value-format="YYYY" @change="endYearChange" @blur="endYearBlur" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="市级重点项目:" prop="isFocusProject">
                        <el-select v-model="baseForm.isFocusProject" placeholder="请选择">
                            <el-option label="是" :value="1" />
                            <el-option label="否" :value="0" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="交通强国建设试点任务:" prop="isPilotPlan">
                        <el-select v-model="baseForm.isPilotPlan" placeholder="请选择">
                            <el-option label="是" :value="1" />
                            <el-option label="否" :value="0" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="牵头单位:" prop="leaderUnit">
                        <el-input v-model="baseForm.leaderUnit" placeholder="请输入" clearable type="textarea" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="配合单位:" prop="assistUnit">
                        <el-input v-model="baseForm.assistUnit" placeholder="请输入" clearable type="textarea" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="责任单位:" prop="dutyUnit">
                        <el-input v-model="baseForm.dutyUnit" placeholder="请输入" clearable type="textarea" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <hc-card-item class="year-detail mt-3">
            <template #header>
                <el-select v-model="selectYear" placeholder="选择年份" class="select-year w-[100px]" @change="changeYear">
                    <el-option v-for="(item, index) in yearOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </template>
            <el-form :model="yearOptions[selectIndex].yearForm" label-width="auto" class="mt-3" label-position="left" size="large">
                <el-form-item label="全年计划投资:" prop="yearlyInvest" class="w-100">
                    <el-input
                        v-model="yearOptions[selectIndex].yearForm.yearlyInvest" placeholder="请输入" clearable
                        :formatter="formatInput"
                    >
                        <template #append>亿元</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="预计完成投资额:" prop="key1">
                    <div class="quarter-box w-full flex">
                        <div class="flex">
                            <el-input v-model="yearOptions[selectIndex].yearForm.oneInvest" placeholder="请输入" clearable :formatter="formatInput">
                                <template #prepend>一季度</template>
                                <template #append>亿元</template>
                            </el-input>
                        </div>
                        <div class="ml-[40px] flex">
                            <el-input v-model="yearOptions[selectIndex].yearForm.twoInvest" placeholder="请输入" clearable :formatter="formatInput">
                                <template #prepend>二季度</template>
                                <template #append>亿元</template>
                            </el-input>
                        </div>
                        <div class="ml-[40px] flex">
                            <el-input v-model="yearOptions[selectIndex].yearForm.threeInvest" placeholder="请输入" clearable :formatter="formatInput">
                                <template #prepend>三季度</template>
                                <template #append>亿元</template>
                            </el-input>
                        </div>
                        <div class="ml-[40px] flex">
                            <el-input v-model="yearOptions[selectIndex].yearForm.fourInvest" placeholder="请输入" clearable :formatter="formatInput">
                                <template #prepend>四季度</template>
                                <template #append>亿元</template>
                            </el-input>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="全年目标:" prop="yearlyTarget">
                    <el-input v-model="yearOptions[selectIndex].yearForm.yearlyTarget" placeholder="请输入" clearable type="textarea" />
                </el-form-item>
            </el-form>
            <el-form :model="yearOptions[selectIndex]?.yearForm" label-width="auto" class="mt-3" label-position="left">
                <div class="hc-form-item-title">各季度工作计划:</div>
                <el-form-item label="一季度:" prop="onePlan">
                    <el-input v-model="yearOptions[selectIndex].yearForm.onePlan" placeholder="请输入" clearable type="textarea" />
                </el-form-item>
                <el-form-item label="二季度:" prop="twoPlan">
                    <el-input v-model="yearOptions[selectIndex].yearForm.twoPlan" placeholder="请输入" clearable type="textarea" />
                </el-form-item>
                <el-form-item label="三季度:" prop="threePlan	">
                    <el-input v-model="yearOptions[selectIndex].yearForm.threePlan" placeholder="请输入" clearable type="textarea" />
                </el-form-item>
                <el-form-item label="四季度:" prop="fourPlan">
                    <el-input v-model="yearOptions[selectIndex].yearForm.fourPlan" placeholder="请输入" clearable type="textarea" />
                </el-form-item>
            </el-form>
        </hc-card-item>
        <template #action>
            <el-button type="info" @click="cancelClick">取消</el-button>
            <el-button v-if="!formInfo.id" color="#20C98B" type="primary" class="text-white" @click="createClick">创建</el-button>
            <el-button v-else type="warning" @click="saveClick">保存</el-button>
        </template>
    </hc-card>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import { isNullES } from 'js-fast-way'
import { arrIndex, formValidate, getArrValue, getObjValue } from 'js-fast-way'
import mainApi from '~api/project/project'
import { getDictionaryData } from '~src/utils/tools'

const props = defineProps({
    form: {
        type: Object,
        default: () => ({}),
    },
})

//事件
const emit = defineEmits(['back'])

//监听权限
const formInfo = ref(props.form)
watch(() => props.form, (data) => {
    formInfo.value = data
  
})

//渲染完成
onMounted(async () => {
  
   await getProStation()
   await getProType()
   getDataApi()
})
const getDataApi = async () => {
    const form = getObjValue(formInfo.value)
    if (!isNullES(form.id)) {
        getProDetail(form.id)
    }
}
const getProDetail = async (id)=>{
    const { error, code, data } = await mainApi.detail(id)
    //处理数据
 
    if (!error && code === 200) {
        baseForm.value = getObjValue(data)
        let list = getArrValue(baseForm.value?.list)
        if (list.length > 0) {
            selectYear.value = list[0].planYear
        }
        baseForm.value.startYear = data.startYear.toString()
        baseForm.value.endYear = data.endYear.toString()
        yearOptions.value = []
        list.forEach((ele)=>{
            yearOptions.value.push({
                value:ele.planYear,
                label:ele.planYear,
                yearForm:ele,
            })
        
        })
    
        
    } else {
        baseForm.value = {}
    }
}
const baseForm = ref({ buildScaleUnit:'1' })
const baseFormRules = {
    name: {
        required: true,
        trigger: 'blur',
        message: '请输入项目名称',
    },
    projectStage: {
        required: true,
        trigger: 'blur',
        message: '请选择项目阶段',
    },
    projectType: {
        required: true,
        trigger: 'blur',
        message: '请选择项目类型',
    },

}
const unitSelect = ref('')

//项目阶段
const stateOptions = ref([])

const getProStation = async () => {
    stateOptions.value = await getDictionaryData('projectStage', true)
    
}
//项目类型
const typeOptions = ref([])
const getProType = async () => {
    typeOptions.value = await getDictionaryData('projectType', true)
  }
  const endYearRef = ref(null)
  const startYearRef = ref(null)
//开始年
const startYearChange = (val) => {
    baseForm.value.startYear = val.toString()
    endYearRef.value?.focus()
    endYearRef.value?.handleOpen()
    startYearRef.value?.handleClose()
}

//结束年
const endYearChange = (val) => {
    if (isNullES(val)) {
        baseForm.value.startYear = ''
    }
    baseForm.value.endYear = val.toString()

}
//失去焦点
const endYearBlur = () => {
    if (isNullES(baseForm.value.startYear) || isNullES(baseForm.value.endYear)) {
        baseForm.value.startYear = ''
        baseForm.value.endYear = ''
        window.$message.warning('请重新选择完整的范围年份')
    } 

  let years = []
  let startYear = baseForm.value.startYear
  let endYear = baseForm.value.endYear
  for (let year = startYear; year <= endYear; year++) {
    years.push(
        {
            value:year,
            label:year,
            yearForm:{
                planYear:year,
                oneInvest:'',
                twoInvest:'',
                threeInvest:'',
                fourInvest:'',
                yearlyTarget:'',
                onePlan:'',
                twoPlan:'',
                threePlan:'',
                fourPlan:'',
               
            },
        },
    )
  }
  yearOptions.value = years
  selectYear.value = yearOptions.value[0].value
}
//选择年份
const selectIndex = ref(0)
const yearOptions = ref([{
     yearForm:{
        yearlyInvest:'',
        oneInvest:'',
        twoInvest:'',
        threeInvest:'',
        fourInvest:'',
        yearlyTarget:'',
        onePlan:'',
        twoPlan:'',
        threePlan:'',
        fourPlan:'',
        planYear:'',
     }, 
    }])
const selectYear = ref('')
const changeYear = (val)=>{
    selectIndex.value = arrIndex(yearOptions.value, 'value', val)
    console.log( selectIndex.value, '111111')
}


const formatInput = (value)=>{
  // 如果输入为空，则直接返回空字符串
  if (!value) {
        return ''
      }
      // 使用正则表达式匹配输入是否合法
      const regExp = /^\d+(\.\d{0,2})?$/
      if (regExp.test(value)) {
        return value // 如果输入合法，则返回原始值
      } else {
        // 如果输入不合法，则移除非法字符，并返回处理后的值
        return value.slice(0, -1)
      } 
}


//监听
watch(() => [
yearOptions.value[selectIndex.value].yearForm.oneInvest,
yearOptions.value[selectIndex.value].yearForm.twoInvest,
yearOptions.value[selectIndex.value].yearForm.threeInvest,
yearOptions.value[selectIndex.value].yearForm.fourInvest,
], ([key2, key3, key4, key5]) => {
    yearOptions.value[selectIndex.value].yearForm.yearlyInvest = Number(key2) + Number(key3) + Number(key4) + Number(key5)
},
)



//取消
const cancelClick = () => {
    emit('back')
}

//创建
const formRef = ref(null)
const creatLoading = ref(false)
const createClick = async () => {
    const form = formInfo.value
    console.log(form)
    // if (isNullES(form.id)) cancelClick()
    console.log(baseForm.value, 'baseForm.value')
    console.log(yearOptions.value, '111111')
    let list = []
    yearOptions.value.forEach((ele)=>{
        let yearForm = ele.yearForm
        list.push(yearForm)
    })
    const isValidate = await formValidate(formRef.value)
    if (!isValidate) return false
    creatLoading.value = true
        //发起请求
        const { error, code, msg } = await mainApi.add({
            ...baseForm.value,
            list,
    })
    //判断状态
    creatLoading.value = false
    if (!error && code === 200) {
        window?.$message?.success(msg)
        console.log(form.id, 'form.id')
        if (isNullES(form.id)) {
            baseForm.value = {}
            yearOptions.value = [{
                yearForm:{
                yearlyInvest:'',
                oneInvest:'',
                twoInvest:'',
                threeInvest:'',
                fourInvest:'',
                yearlyTarget:'',
                onePlan:'',
                twoPlan:'',
                threePlan:'',
                fourPlan:'',
            },
            }]
            // cancelClick()
        }
    } else {
        window.$message.error(msg ?? '操作失败')
    }

    console.log('创建')
}

//保存
const saveClick = async () => {
    let list = []
    yearOptions.value.forEach((ele)=>{
        let yearForm = ele.yearForm
        list.push(yearForm)
    })
    const isValidate = await formValidate(formRef.value)
    if (!isValidate) return false
    creatLoading.value = true
        //发起请求
        const { error, code, msg } = await mainApi.update({
            ...baseForm.value,
            list,
    })
    //判断状态
    creatLoading.value = false
    if (!error && code === 200) {
        window?.$message?.success(msg)
     
    } else {
        window.$message.error(msg ?? '操作失败')
    }

    console.log('创建')
}
</script>

<style lang="scss">
.create-project .el-card .el-card__body .hc-card-main-body {
    padding: 14px;
    .el-scrollbar__bar.is-vertical {
        right: -16px;
    }
}
.hc-card-item-box.year-detail {
    padding: 20px;
    background: #f7f7f7;
    border-radius: 5px;
    .hc-card-item-header {
        border-bottom: 1px solid #ecebeb;
        padding-bottom: 16px;
        .item-header {
            justify-content: center;
        }
    }
    .hc-form-item-title {
        position: relative;
        padding: 10px 0;
        margin-bottom: 14px;
    }
}
.quarter-box {
    position: relative;
    justify-content: space-around;
}
.form-text {
    white-space: nowrap;
    color:var(--el-text-color-regular) ;
    font-size: var(--el-form-label-font-size);
}
</style>
