<template>
    <hc-card class="create-project" is-action-btn scrollbar>
        <template #header>
            <div class="flex-1 text-center text-[24px] font-bold">项目信息填写</div>
        </template>
        <el-form ref="formRef" :model="baseForm" :rules="baseFormRules" label-position="left" label-width="auto" size="large">
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="项目名称:" prop="name">
                        <el-input v-model="baseForm.name" clearable placeholder="请输入" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="建设规模:" prop="buildScale">
                        <el-input v-model="baseForm.buildScale" clearable placeholder="请输入">
                            <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="12">
                    <el-form-item label="总投资:" prop="allInvestMoney">
                        <el-input v-model="baseForm.allInvestMoney" clearable placeholder="请输入">
                            <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" :formatter="formatInput" clearable placeholder="请输入">
                            <template #append>亿元</template>
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="市级重点项目:" prop="isFocusProject">
                        <el-select v-model="baseForm.isFocusProject" placeholder="请选择">
                            <el-option :value="1" label="是" />
                            <el-option :value="0" label="否" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="牵头单位:" prop="leaderUnit">
                        <el-input v-model="baseForm.leaderUnit" clearable placeholder="请输入" type="textarea" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="配合单位:" prop="assistUnit">
                        <el-input v-model="baseForm.assistUnit" clearable placeholder="请输入" type="textarea" />
                    </el-form-item>
                </el-col -->
            </el-row>
        </el-form>
        <el-form :model="baseForm" label-position="left" label-width="81" size="large">
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="开工年:" prop="startYear">
                        <el-date-picker
                            ref="startYearRef" v-model="baseForm.startYear" class="block" placeholder="请选择"
                            type="year" value-format="YYYY" :disabled="!!formInfo.id && !!baseForm.startYear"
                            @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" placeholder="请选择"
                            type="year" value-format="YYYY" :disabled="!!formInfo.id && !!baseForm.startYear"
                            @blur="endYearBlur" @change="endYearChange"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item class="is-multiple-rows" label="交通强国建设试点任务:" prop="isPilotPlan">
                        <el-select v-model="baseForm.isPilotPlan" placeholder="请选择">
                            <el-option :value="1" label="是" />
                            <el-option :value="0" label="否" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="责任单位:" prop="dutyUnit">
                        <el-input v-model="baseForm.dutyUnit" clearable placeholder="请输入" 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" class="select-year w-[100px]" placeholder="选择年份" :disabled="yearOptions.length <= 1" @change="changeYear">
                    <el-option v-for="(item) in yearOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </template>
            <el-form :disabled="!selectYear" :model="yearOptions[selectIndex].yearForm" class="mt-3" label-position="left" label-width="auto" size="large">
                <el-form-item class="w-100" label="全年计划投资:" prop="yearlyInvest">
                    <el-input v-model="yearOptions[selectIndex].yearForm.yearlyInvest" :disabled="isChangeyearlyInvest" :formatter="formatInput" clearable placeholder="请输入">
                        <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" :formatter="formatInput" clearable placeholder="请输入">
                                <template #prepend>一季度</template>
                                <template #append>亿元</template>
                            </el-input>
                        </div>
                        <div class="ml-[40px] flex">
                            <el-input v-model="yearOptions[selectIndex].yearForm.twoInvest" :formatter="formatInput" clearable placeholder="请输入">
                                <template #prepend>二季度</template>
                                <template #append>亿元</template>
                            </el-input>
                        </div>
                        <div class="ml-[40px] flex">
                            <el-input v-model="yearOptions[selectIndex].yearForm.threeInvest" :formatter="formatInput" clearable placeholder="请输入">
                                <template #prepend>三季度</template>
                                <template #append>亿元</template>
                            </el-input>
                        </div>
                        <div class="ml-[40px] flex">
                            <el-input v-model="yearOptions[selectIndex].yearForm.fourInvest" :formatter="formatInput" clearable placeholder="请输入">
                                <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" clearable placeholder="请输入" type="textarea" />
                </el-form-item>
            </el-form>
            <el-form :disabled="!selectYear" :model="yearOptions[selectIndex]?.yearForm" class="mt-3" label-position="left" label-width="auto">
                <div class="hc-form-item-title">各季度工作计划:</div>
                <el-form-item label="一季度:" prop="onePlan">
                    <el-input v-model="yearOptions[selectIndex].yearForm.onePlan" clearable placeholder="请输入" type="textarea" />
                </el-form-item>
                <el-form-item label="二季度:" prop="twoPlan">
                    <el-input v-model="yearOptions[selectIndex].yearForm.twoPlan" clearable placeholder="请输入" type="textarea" />
                </el-form-item>
                <el-form-item label="三季度:" prop="threePlan	">
                    <el-input v-model="yearOptions[selectIndex].yearForm.threePlan" clearable placeholder="请输入" type="textarea" />
                </el-form-item>
                <el-form-item label="四季度:" prop="fourPlan">
                    <el-input v-model="yearOptions[selectIndex].yearForm.fourPlan" clearable placeholder="请输入" 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" class="text-white" color="#20C98B" type="primary" @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 { arrIndex, formValidate, getArrValue, getObjValue, isNullES } from 'js-fast-way'
import mainApi from '~api/project/project'
import { getDictionaryData } from '~src/utils/tools'
import BigNumber from 'bignumber.js'

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

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

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

//渲染完成
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 = isNullES(val) ? '' : val.toString()
    endYearRef.value?.focus()
    endYearRef.value?.handleOpen()
    startYearRef.value?.handleClose()
}

//结束年
const endYearChange = (val) => {
    if (isNullES(val)) {
        baseForm.value.startYear = ''
        baseForm.value.endYear = ''
    } else {
        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([{
    value: '',
    label: '',
    yearForm: {
        yearlyInvest: '',
        oneInvest: '',
        twoInvest: '',
        threeInvest: '',
        fourInvest: '',
        yearlyTarget: '',
        onePlan: '',
        twoPlan: '',
        threePlan: '',
        fourPlan: '',
        planYear: '',
    },
}])
const selectYear = ref(null)
const changeYear = (val) => {
    selectIndex.value = arrIndex(yearOptions.value, 'value', val)
}

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

const isChangeyearlyInvest = ref(false)
//监听
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]) => {
        if (Number(key2) > 0 || Number(key3) > 0 || Number(key4) > 0 || Number(key5) > 0) {
            isChangeyearlyInvest.value = true
        } else {
            isChangeyearlyInvest.value = false
        }
        // yearOptions.value[selectIndex.value].yearForm.yearlyInvest = Number(key2) + Number(key3) + Number(key4) + Number(key5)
        yearOptions.value[selectIndex.value].yearForm.yearlyInvest = (BigNumber(Number(key2)).plus(BigNumber(Number(key3))).plus(BigNumber(Number(key4))).plus(BigNumber(Number(key5)))).toNumber()
        const totalYearlyInvest = yearOptions.value.reduce((accumulator, currentValue) => {
            // return accumulator + currentValue.yearForm.yearlyInvest
            return BigNumber(Number(accumulator)).plus(BigNumber(Number(currentValue.yearForm.yearlyInvest))).toNumber()
        }, 0)
        //baseForm.value.allInvestMoney = totalYearlyInvest
    },
)


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

//创建
const formRef = ref(null)
const creatLoading = ref(false)
const createClick = 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.add({
        ...baseForm.value,
        list,
    })
    //判断状态
    creatLoading.value = false
    if (!error && code === 200) {
        window.$message.success(msg)
        baseForm.value = {}
        yearOptions.value = [{
            value: '',
            label: '',
            yearForm: {
                yearlyInvest: '',
                oneInvest: '',
                twoInvest: '',
                threeInvest: '',
                fourInvest: '',
                yearlyTarget: '',
                onePlan: '',
                twoPlan: '',
                threePlan: '',
                fourPlan: '',
            },
        }]
    } else {
        window.$message.error(msg ?? '操作失败')
    }
}

//保存
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)
        cancelClick()
    } else {
        window.$message.error(msg ?? '操作失败')
    }
}
</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>
