<template>
  <div style="padding: 0 30px ">
    <baseTitle title="项目基本信息"></baseTitle>
    <fvForm :schema="schema" @getInstance="(e)=>baseForm = e" label-position="left" label-width="left"
            style="margin-left: 15px"></fvForm>
    <el-form :model="tableForm" ref="form">
      <el-table :data="tableForm.tableData">
        <el-table-column prop="time" label="时间" min-width="180">
          <template #default="scope">
            <el-form-item prop="time" :rules="scope.row.time?'1':rules.time">
              <el-date-picker
                  v-model="scope.row.time"
                  type="month"
                  format="YYYY-MM"
                  value-format="YYYY-MM"
                  placeholder="选择时间"
              >
              </el-date-picker>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="projectCost" label="项目费用" min-width="220">
          <template #default="scope">
            <el-form-item prop="projectCost" :rules="scope.row.projectCost?'1':rules.projectCost">
              <el-select v-model="scope.row.projectCost" placeholder="请选择费用性质" clearable filterable style="width: 100%">
                <el-option
                    v-for="item in cacheStore.getDict('project_cost')"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="researchStage" label="研发阶段" min-width="220">
          <template #default="scope">
            <el-form-item prop="researchStage" :rules="scope.row.researchStage?'1':rules.researchStage">
              <el-select v-model="scope.row.researchStage" placeholder="请选择研发阶段" clearable filterable>
                <el-option
                    v-for="item in cacheStore.getDict('fee_stage')"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="digest" label="摘要" min-width="220">
          <template #default="scope">
            <el-form-item prop="digest" :rules="scope.row.digest?'1':rules.digest">
              <el-input v-model="scope.row.digest" placeholder="请输入摘要" clearable>
              </el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="afterTax" label="税后余额(元)" min-width="220">
          <template #default="scope">
            <el-form-item prop="afterTax" :rules="scope.row.afterTax?'1':rules.afterTax">
              <el-input
                  v-model="scope.row.afterTax"
                  placeholder="请输入税后余额"
                  clearable
                  :formatter="(value) => value.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                  :parser="(value) => value.replace(/\$\s?|(,*)+[^0-9.]/g, '')"
              />
<!--              <el-input-number v-model="scope.row.afterTax" placeholder="请输入税后余额" :controls="false">-->
<!--              </el-input-number>-->
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="oper" label="操作">
          <template #default="scope">
            <el-button type="primary" @click="handleDelete(scope.$index)" link style="font-size: 16px">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <div style="width:100%;text-align: center;padding: 10px">
      <el-button type="primary" @click="handleAdd" link style="font-size: 16px">添加一行</el-button>
    </div>
    <div class="oper-page-btn">
      <el-button color="#DED0B2" @click="handleSubmit(form)">提交</el-button>
      <el-button @click="handleBack">返回</el-button>
    </div>
  </div>
</template>

<script setup lang="jsx">
import {ElNotification} from "element-plus";
import {addLedger} from "@/api/project-manage";
import {useTagsView} from '@/stores/tagsview.js'
import {useRoute} from "vue-router";
import {useCacheStore} from '@/stores/cache.js'
import {getBaseInfoApi} from "@/components/steps/api";
import {toThousands} from '@/utils/changePrice.js'

const baseFormData = ref([])
const cacheStore = useCacheStore()
const route = useRoute()
const router = useRouter()
const tagsViewStore = useTagsView()
const formData = ref({})
const form = ref()
const projectName = ref()
const schema = computed(() => {
  return [
    // {
    //   label: '征集公司',
    //   prop: 'affiliatedCompany',
    //   colProps: {
    //     span: 6
    //   }
    // },
    // {
    //   label: '征集名称',
    //   prop: 'requirementName',
    //   colProps: {
    //     span: 6
    //   }
    // },
    // {
    //   label: '征集说明',
    //   prop: 'collectExplain',
    //   colProps: {
    //     span: 24
    //   }
    // },
    {
      label: '承办单位',
      prop: 'affiliatedCompany',
      colProps: {
        span: 6
      }
    },
    {
      label: '项目名称',
      prop: 'projectName',
      colProps: {
        span: 6
      }
    },

    {
      label: '开始时间',
      prop: 'startTime',
      colProps: {
        span: 6
      }
    },
    {
      label: '结束时间',
      prop: 'endTime',
      colProps: {
        span: 6
      }
    },
    {
      label: '项目类型',
      prop: 'projectType',
      colProps: {
        span: 6
      },
      component: () => (
          <div>
            {
              baseFormData.value?.projectType ?
                  <span>{filterDict(cacheStore.getDict('project_type'), baseFormData.value?.projectType)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    {
      label: '研发主体',
      prop: 'rdSubject',
      colProps: {
        span: 6
      },
      component: () => (
          <div>
            {
              baseFormData.value?.rdSubject ?
                  <span>{filterDict(cacheStore.getDict('rd_subject'), baseFormData.value?.rdSubject)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    {
      label: '出资类型',
      prop: 'investmentType',
      colProps: {
        span: 6
      },
      component: () => (
          <div>
            {
              baseFormData.value?.investmentType ?
                  <span>{filterDict(cacheStore.getDict('invest_type'), baseFormData.value?.investmentType)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    {
      label: '所属业务板块',
      prop: 'businessSegment',
      colProps: {
        span: 6
      },
      component: () => (
          <div>
            {
              baseFormData.value?.businessSegment ?
                  <span>{filterDict(cacheStore.getDict('business_segment'), baseFormData.value?.businessSegment)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    {
      label: '标准制定',
      prop: 'technicalStandard',
      colProps: {
        span: 6
      },
      component: () => (
          <div>
            {
              baseFormData.value?.technicalStandard ?
                  <span>{filterDict(cacheStore.getDict('technical_standard'), baseFormData.value?.technicalStandard)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    {
      label: '项目影响',
      prop: 'projectImpact',
      colProps: {
        span: 6
      },
      component: () => (
          <div>
            {
              baseFormData.value?.projectImpact ?
                  <span>{filterDict(cacheStore.getDict('project_impact'), baseFormData.value?.projectImpact)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    {
      label: '预估经费预算',
      prop: 'economicEstimate',
      colProps: {
        span: 6
      },
      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: 6
      },
      component: () => (
          <div>
            {
              baseFormData.value?.industryUniversityResearch ?
                  <span>{filterDict(cacheStore.getDict('industry_university'), baseFormData.value?.industryUniversityResearch)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    {
      label: '开展政府申报',
      prop: 'governmentDeclaration',
      colProps: {
        span: 6
      },
      component: () => (
          <div>
            {
              baseFormData.value?.governmentDeclaration ?
                  <span>{filterDict(cacheStore.getDict('government_declaration'), baseFormData.value?.governmentDeclaration)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    // {
    //   label: '是否专项资金项目',
    //   prop: 'isSpecialFund',
    //   colProps: {
    //     span: 6
    //   }
    // },
    {
      label: '所属专项资金项目',
      prop: 'specialFund',
      colProps: {
        span: 6
      }
    },
    {
      label: '预估专项资金(元)',
      prop: 'forecastSpecialFundAmount',
      colProps: {
        span: 6
      },
      component: () => (
          <div>
            {
              baseFormData.value?.forecastSpecialFundAmount ?
                  <span>{toThousands(baseFormData.value?.forecastSpecialFundAmount)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    {
      label: '实际专项资金(元)',
      prop: 'specialFundAmount',
      colProps: {
        span: 6
      },
      component: () => (
          <div>
            {
              baseFormData.value?.specialFundAmount ?
                  <span>{toThousands(baseFormData.value?.specialFundAmount)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    {
      label: '是否在预算内',
      prop: 'isWithinBudget',
      colProps: {
        span: 6
      },
      component: () => (
          <div>
            {
              baseFormData.value?.isWithinBudget!=null ? baseFormData.value?.isWithinBudget?
                  <span>{'预算内'}</span>
                  : <span>{'预算外'}</span>:'--'
            }
          </div>
      )
    },
    {
      label: '部门分管领导',
      prop: 'optionalChargeLeadership',
      colProps: {
        span: 6
      }
    },
    {
      label: '主项目',
      prop: 'masterProjectName',
      colProps: {
        span: 6
      }
    }
  ]
})

const baseForm = ref()
const rules = reactive({
  time: [{required: true, message: '请选择时间', trigger: 'blur'}],
  projectCost: [{required: true, message: '请选择项目费用', trigger: 'blur'}],
  researchStage: [{required: true, message: '请选择研发阶段', trigger: 'blur'}],
  digest: [{required: true, message: '请输入摘要', trigger: 'blur'}],
  afterTax: [{required: true, message: '请输入税后余额', trigger: 'blur'}]
})
const tableForm = ref({
  tableData: [
    {
      projectId: route.query.id,
      time: '',
      projectCost: '',
      researchStage: '',
      digest: '',
      afterTax: null
    }
  ]
})
//匹配字典值,返回对应值的字典标签
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 () => {
  try {
    const {code, data} = await getBaseInfoApi(route.query.id)
    baseForm.value.setValues(data)
    baseFormData.value = data
  } catch {
  }
}

getBaseInfo()

const handleAdd = () => {
  let row = {
    projectId: route.query.id,
    time: '',
    projectCost: '',
    researchStage: '',
    digest: '',
    afterTax: null
  }
  tableForm.value.tableData.push(row)
}
const handleDelete = (index) => {
  tableForm.value.tableData.splice(index, 1)
}
const handleSubmit = (instance) => {
  if (!instance) return
  instance.validate(async (valid) => {
    if (!valid) {
      ElNotification({
        title: '提示',
        message: '请完善数据,再提交!',
        type: 'error'
      })
      return;
    }
    instance.clearValidate()
    tableForm.value.tableData.forEach(item => {
      item.projectName = projectName.value
    })
    const res = await addLedger(tableForm.value.tableData)
    ElNotification({
      title: '提示',
      message: res.msg,
      type: res.code === 1000 ? 'success' : 'error'
    })
    if (res.code === 1000) {
      tagsViewStore.delVisitedViews(router.currentRoute.value.path)
      router.push({
        name: 'Implementation/account',
        query: {
          id: route.query.id
        }
      })
    }
  })
}
const handleBack = () => {
  history.back()
}
onActivated(() => {
  tableForm.value = {
    tableData: [
      {
        projectId: route.query.id,
        time: '',
        projectCost: '',
        researchStage: '',
        digest: '',
        afterTax: null
      }
    ]
  }
})
</script>
<style scoped lang="scss">
:deep(.el-table--enable-row-transition) {
  .el-table__body td.el-table__cell {
    .cell {
      .el-form-item {
        margin-top: 20px;
      }
    }
  }
}

:deep(.el-date-editor--month) {
  width: 100%;
}

:deep(.el-input-number) {
  width: 100%;

  .el-input__inner {
    text-align: left;
  }
}
</style>

