<template>
  <div class="necessary-container">
    <p style="border-bottom: 1px solid #ebedf0" class="fs15 fwb pl10 pv12">基本信息</p>
    <van-field
      readonly
      label="第一顺位需求"
      name="第一顺位需求"
      right-icon="arrow"
      placeholder="请选择"
      @click="necessaryFieldClick(1)"
      :value="getNecessaryText(form.firstCostRequirements)"
    ></van-field>
    <van-field
      readonly
      label="第二顺位需求"
      name="第二顺位需求"
      right-icon="arrow"
      placeholder="请选择"
      @click="necessaryFieldClick(2)"
      :value="getNecessaryText(form.secondCostRequirements)"
    ></van-field>
    <van-field
      readonly
      label="第三顺位需求"
      name="第三顺位需求"
      right-icon="arrow"
      placeholder="请选择"
      @click="necessaryFieldClick(3)"
      :value="getNecessaryText(form.thirdCostRequirements)"
    ></van-field>
    <p style="border-bottom: 1px solid #ebedf0" class="fs15 fwb pl10 pv12">生活费用</p>
    <van-field clearable label="每月生活费（元）" name="每月生活费（元）" placeholder="请输入" v-model="form.livingCosts"></van-field>
    <van-field clearable label="子女抚养至（岁）" name="子女抚养至（岁）" placeholder="请输入" v-model="form.raisingAge" v-if="childNum > 0"></van-field>
    <p style="border-bottom: 1px solid #ebedf0" class="fs15 fwb pl10 pv12">房贷/房租费用</p>
    <van-field clearable label="贷款余额（万元）" name="贷款余额（万元）" placeholder="请输入" v-model="form.loanBalance"></van-field>
    <van-field clearable label="剩余还款期间（年）" name="剩余还款期间（年）" placeholder="请输入" v-model="form.remainRepaymentTime"></van-field>
    <van-field clearable label="租金（元/月）" name="租金（元/月）" placeholder="请输入" v-model="form.charterMoney"></van-field>
    <van-field clearable label="租屋年数（年）" name="租屋年数（年）" placeholder="请输入" v-model="form.rentHouseNumber"></van-field>
    <p style="border-bottom: 1px solid #ebedf0" class="fs15 fwb pl10 pv12">父母孝养金</p>
    <van-field clearable label="本人父亲年龄" name="本人父亲年龄" placeholder="请输入" v-model="form.myParentsAge"></van-field>
    <van-field clearable label="本人母亲年龄" name="本人母亲年龄" placeholder="请输入" v-model="form.myMotherAge"></van-field>
    <van-field clearable label="孝养金（元/月）" name="孝养金（元/月）" placeholder="请输入" v-model="form.myParentsRaisemoney"></van-field>
    <template v-if="hasWife">
      <van-field clearable label="配偶父亲年龄" name="配偶父亲年龄" placeholder="请输入" v-model="form.wifeParentsAge"></van-field>
      <van-field clearable label="配偶母亲年龄" name="配偶母亲年龄" placeholder="请输入" v-model="form.wifeMotherAge"></van-field>
      <van-field clearable label="孝养金（元/月）" name="孝养金（元/月）" placeholder="请输入" v-model="form.wifeParentsRaisemoney"></van-field>
    </template>
    <template v-if="childNum >= 1">
      <p style="border-bottom: 1px solid #ebedf0" class="fs15 fwb pl10 pv12">教育费用</p>
      <p style="border-bottom: 1px solid #ebedf0" class="fs15 fwb pl15 pv12">子女1（{{children[0].familyName}}）</p>
      <van-field clearable label="费用总计（万元）" name="费用总计（万元）" placeholder="请输入" v-model="form.educationalCostOne"></van-field>
      <van-field clearable label="教育年龄" name="教育年龄" placeholder="请输入" v-model="form.educationalAgeOne" @change="eduAge(form.educationalAgeOne,children[0].familyAge)"></van-field>
    </template>
    <template v-if="childNum >= 2">
      <p style="border-bottom: 1px solid #ebedf0" class="fs15 fwb pl15 pv12">子女2（{{children[1].familyName}}）</p>
      <van-field clearable label="费用总计（万元）" name="费用总计（万元）" placeholder="请输入" v-model="form.educationalCostTwo"></van-field>
      <van-field clearable label="教育年龄" name="教育年龄" placeholder="请输入" v-model="form.educationalAgeTwo" @change="eduAge(form.educationalCostTwo,children[1].familyAge)"></van-field>
    </template>
    <template v-if="childNum === 3">
      <p style="border-bottom: 1px solid #ebedf0" class="fs15 fwb pl15 pv12">子女3（{{children[2].familyName}}）</p>
      <van-field clearable label="费用总计（万元）" name="费用总计（万元）" placeholder="请输入" v-model="form.educationalCostThree"></van-field>
      <van-field clearable label="教育年龄" name="教育年龄" placeholder="请输入" v-model="form.educationalAgeThree" @change="eduAge(form.educationalCostThree,children[2].familyAge)"></van-field>
    </template>
    <p style="border-bottom: 1px solid #ebedf0" class="fs15 fwb pl15 pv12">医疗费用</p>
    <van-field clearable label="往来医院" name="往来医院" placeholder="请输入" v-model="form.hospitalizationCost"></van-field>
    <p style="border-bottom: 1px solid #ebedf0" class="fs15 fwb pl15 pv12">最后费用</p>
    <van-field clearable label="本人身故丧葬费用（万元）" name="本人身故丧葬费用（万元）" placeholder="请输入" v-model="form.myFuneralExpenses"></van-field>
    <van-field
      clearable
      label="配偶身故丧葬费用（万元）"
      name="配偶身故丧葬费用（万元）"
      placeholder="请输入"
      v-model="form.wifeFuneralExpenses"
      v-if="hasWife"
    ></van-field>
    <p style="border-bottom: 1px solid #ebedf0" class="fs15 fwb pl15 pv12">资产传承</p>
    <van-field clearable label="本人预估资产总额（万元）" name="本人预估资产总额（万元）" placeholder="请输入" v-model="form.myEstimateTotalassets"></van-field>
    <van-field
      clearable
      label="配偶预估资产总额（万元）"
      name="配偶预估资产总额（万元）"
      placeholder="请输入"
      v-model="form.wifeEstimateTotalassets"
      v-if="hasWife"
    ></van-field>
    <p style="border-bottom: 1px solid #ebedf0" class="fs15 fwb pl10 pv12">其它费用</p>
    <div v-for="(item, index) in form.proposalNbsProjectCostInfoDTOLst" :key="index">
      <template v-if="item">
        <van-field
          clearable
          readonly
          label="对象"
          name="对象"
          right-icon="arrow"
          placeholder="请选择"
          @click="targetFieldClick(index)"
          :value="getTargetText(item.object)"
        ></van-field>
        <van-field clearable label="项目" name="项目" placeholder="请输入" v-model="item.projectName"></van-field>
        <van-field clearable label="金额（元/月）" name="金额（元/月）" placeholder="请输入" v-model="item.projectCost"></van-field>
        <!-- 起始年月和终止年月只能选择本月及以后 -->
        <FieldDatePicter
          label="起始年月"
          name="起始年月"
          type="year-month"
          :flag="true"
          :value.sync="item.startDate"
          :formatter="dateFormatter"
          :min-date="new Date()"
        ></FieldDatePicter>
        <FieldDatePicter
          label="终止年月"
          name="终止年月"
          type="year-month"
          :flag="true"
          :value.sync="item.endDate"
          :formatter="dateFormatter"
          :min-date="new Date()"
        ></FieldDatePicter>
        <div class="nbs-del" @click="del(index)"><van-icon name="delete"></van-icon></div>
      </template>
    </div>
    <div class="nbs-add" @click="add">+ 添加其它费用</div>
    <van-button type="danger" class="bottom-btn" @click="submit" v-no-more-click="1000">完成</van-button>

    <!-- 顺位需求选择 -->
    <van-popup v-model="isNecessaryPickerShow" position="bottom">
      <van-picker show-toolbar :columns="necessaryArr" @confirm="onNecessaryConfirm" @cancel="onNecessaryCancel" />
    </van-popup>
    <!-- 对象选择 -->
    <van-popup v-model="isTargetPickerShow" position="bottom">
      <van-picker show-toolbar :columns="targetArr" @confirm="onTargetConfirm" @cancel="onTargetCancel" />
    </van-popup>
  </div>
</template>
<script>
import { Field, Popup, Picker } from 'vant'
import FieldDatePicter from '@/components/ebiz/FieldDatePicter'
import dataDictionary from '@/assets/js/utils/data-dictionary'
import { saveForm, nbsDetail } from '@/api/ebiz/nbs'
import utils from '@/assets/js/common'
import utils2 from '@/assets/js/business-common'

//顺位需求字典
let necessaryDictionary = dataDictionary.necessaryDictionary

//对象字典
let targetDictionary = dataDictionary.targetDictionary

//其它费用
let otherCost = {
  object: '',
  projectName: '',
  projectCost: '',
  startDate: '',
  endDate: '',
  //这两个必传，写死
  isDelete: '0',
  projectinfoId: ''
}

export default {
  components: {
    [Field.name]: Field,
    [Popup.name]: Popup,
    [Picker.name]: Picker,
    FieldDatePicter
  },
  created() {
    //回填
    let id = localStorage.getItem('nbsId')
    let state = localStorage.getItem('nbsState')
    if (id && state) {
      nbsDetail({
        orderNo: id,
        nbsState: state
      }).then(res => {
        let obj = res.content

        //取得有无配偶、子女数量
        let hasWife = false,
          childNum = 0
        obj.proposalNbsFamilyDTOLst.forEach(v => {
          if (v.relation === '00') hasWife = true
          else if (v.relation === '01') {
            this.children.push(v)
            childNum++
          }
        })
        this.hasWife = hasWife
        this.childNum = childNum

        //如果没有填配偶，其他费用的对象不能选择配偶
        if (!hasWife) {
          targetDictionary.forEach((v, i) => {
            if (v.code === '01') targetDictionary.splice(i, 1)
          })
          this.targetArr = targetDictionary.map(v => v.value)
        }

        let keys = Object.keys(this.form)
        for (let i in obj) {
          if (!keys.includes(i)) {
            delete obj[i]
          }
        }

        if (!obj.proposalNbsProjectCostInfoDTOLst) obj.proposalNbsProjectCostInfoDTOLst = [{ ...otherCost }]

        this.form = obj
        this.filterSelectedList()
      })
    }
  },
  data() {
    return {
      necessaryArr: necessaryDictionary.map(v => v.value),
      targetArr: targetDictionary.map(v => v.value),
      isNecessaryPickerShow: false,
      clickedNecessaryIndex: null,
      isTargetPickerShow: false,
      clickedTargetIndex: null,
      form: {
        firstCostRequirements: '',
        secondCostRequirements: '',
        thirdCostRequirements: '',
        livingCosts: '',
        raisingAge: '',
        loanBalance: '',
        remainRepaymentTime: '',
        charterMoney: '',
        rentHouseNumber: '',
        myParentsAge: '',
        myMotherAge: '',
        myParentsRaisemoney: '',
        wifeParentsAge: '',
        wifeMotherAge: '',
        wifeParentsRaisemoney: '',
        educationalCostOne: '',
        educationalCostTwo: '',
        educationalCostThree: '',
        educationalAgeOne:'',
        educationalAgeTwo:'',
        educationalAgeThree:'',
        hospitalizationCost: '',
        myFuneralExpenses: '',
        wifeFuneralExpenses: '',
        myEstimateTotalassets: '',
        wifeEstimateTotalassets: '',
        proposalNbsProjectCostInfoDTOLst: [{ ...otherCost }],
        isDelete: '0',
        customerId: ''
      },
      children:[],
      hasWife: false,
      childNum: 0
    }
  },
  methods: {
    necessaryFieldClick(index) {
      this.isNecessaryPickerShow = true
      this.clickedNecessaryIndex = index
    },
    onNecessaryConfirm(v) {
      this.isNecessaryPickerShow = false

      let form = this.form
      //van-picker不能传字符串数组，所以这里根据选择的项的文本，找到它的code码来保存
      let selectedCode
      necessaryDictionary.forEach(value => {
        if (value.value === v) {
          selectedCode = value.code
        }
      })
      switch (this.clickedNecessaryIndex) {
        case 1:
          form.firstCostRequirements = selectedCode
          break
        case 2:
          form.secondCostRequirements = selectedCode
          break
        case 3:
          form.thirdCostRequirements = selectedCode
          break
      }

      //已经选过的，就不能再次选了。所以每当选择时，把所有已选过的剔除出列表
      this.filterSelectedList()
    },
    filterSelectedList() {
      //已经选过的，就不能再次选了。把所有已选过的剔除出列表
      let form = this.form
      let selectedArr = [form.firstCostRequirements, form.secondCostRequirements, form.thirdCostRequirements]
      let necessaryArr = []
      necessaryDictionary.forEach(v => {
        if (selectedArr.indexOf(v.code) === -1) {
          necessaryArr.push(v.value)
        }
      })
      this.necessaryArr = necessaryArr
    },
    onNecessaryCancel() {
      this.isNecessaryPickerShow = false
    },
    getNecessaryText(code) {
      for (let i of necessaryDictionary) {
        if (i.code === code) {
          return i.value
        }
      }
    },
    add() {
      this.form.proposalNbsProjectCostInfoDTOLst.push({ ...otherCost })
    },
    del(index) {
      this.$set(this.form.proposalNbsProjectCostInfoDTOLst, index, null)
    },
    dateFormatter(type, value) {
      if (type === 'year') {
        return `${value}年`
      } else if (type === 'month') {
        return `${value}月`
      }
      return value
    },
    targetFieldClick(index) {
      this.clickedTargetIndex = index
      this.isTargetPickerShow = true
    },
    getTargetText(code) {
      for (let v of targetDictionary) {
        if (v.code === code) {
          return v.value
        }
      }
    },
    onTargetConfirm(v, index) {
      this.isTargetPickerShow = false

      let list = this.form.proposalNbsProjectCostInfoDTOLst,
        value = targetDictionary[index].code
      this.$set(list[this.clickedTargetIndex], 'object', value)
    },
    onTargetCancel() {
      this.isTargetPickerShow = false
    },
    submit() {
      //终止年月必须大于起始年月
      if (
        this.form.proposalNbsProjectCostInfoDTOLst.some(v => {
          return v && v.startDate > v.endDate
        })
      ) {
        this.$toast('终止年月必须大于起始年月')
        return
      }
      if(this.children[0] !== undefined && this.eduAge(this.form.educationalAgeOne,this.children[0].familyAge)){
        return false
      }
      if(this.children[1] !== undefined && this.eduAge(this.form.educationalAgeTwo,this.children[1].familyAge)){
        return false
      }
      if(this.children[2] !== undefined && this.eduAge(this.form.educationalAgeThree,this.children[2].familyAge)){
        return false
      }
      let form = utils.deepCopy(this.form)
      form.orderNo = localStorage.getItem('nbsId')
      form.type = '1'
      form.proposalNbsProjectCostInfoDTOLst = form.proposalNbsProjectCostInfoDTOLst.filter(v => v)
      form.dateOfEntry = utils2.formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss')
      form.isDelete = '0'
      form.nbsState = localStorage.getItem('nbsState')
      saveForm(form).then(res => {
        if (res.result === '0') {
          this.$toast('保存成功')

          this.$jump({
            flag: 'goBack',
            extra: {
              refresh: '1',
              index: '-1'
            },
            routerInfo: {
              path: `/nbs/nav`
            }
          })
        } else {
          this.$toast(res.resultMessage)
        }
      })
    },
    eduAge(num, age){
      num = num-0;
      if(num < age || num > 85){
        this.$toast("您子女的教育年龄不能小于她的年龄，且不能超过85岁");
        return true
      }
    }
  }
}
</script>
<style lang="scss" scoped>
@import '../../../assets/sass/nbs';
.necessary-container {
  @include container;
}
</style>
