<!-- 商务方案 -->
<template>
  <div>
    <Collapse v-if="planData.length" v-model="activeNames">
      <CollapseItem v-for="(p, pi) of planData" :title="p.product_plan_id_n" :key="p.quotation_id" :name="pi">
        <list-item :item-height="44">
          <item v-for="(ele, i) of formdata" :key="ele.title">
            <div slot="name" class="font-color">{{ ele.title }}</div>
            <span v-if="ele.type == 'currency'" slot="content">{{ currency(planData[pi][ele.prop]) }}</span>
            <span v-else-if="ele.type == 'rate'" slot="content">{{ toPercent(planData[pi][ele.prop]) }}</span>
            <span v-else slot="content">{{ planData[pi][ele.prop] }}</span>
          </item>
        </list-item>
        <div v-if="editFlag || showFlag">
        <Form ref="myForm_30" >
          <Field
            v-model="p.repurchase_flag_n" :readonly="true"
            :required="editFlag" :is-link="editFlag" :rules="[{ required: editFlag,message:'请选择'}]" input-align="right"
            label="合同标识" @click="showPicker('repurchase_flag',pi)"/>
          <Field
            v-model="p.rent_invoice_type_n" :readonly="true"
            :required="editFlag" :is-link="editFlag" :rules="[{ required: editFlag,message:'请选择'}]" input-align="right"
            label="开票类型" @click="showPicker('rent_invoice_type',pi)"/>
          <!-- 主机厂是否担保 -->
          <Field
            v-model="p.factory_guarantees_flag_n" :readonly="true"
            :required="editFlag" :is-link="editFlag" :rules="[{ required: editFlag,message:'请选择'}]" input-align="right"
            label="主机厂是否担保" @click="showPicker('factory_guarantees_flag',pi)"/>
          <!-- 合同标识 -->
          <!-- <Field
            v-model="p.business_type_new_n" :readonly="true"
            :required="editFlag" :is-link="editFlag" :rules="[{ required: editFlag,message:'请选择'}]" input-align="right"
            label="业务种类" @click="showPicker('business_type_new',pi)"/> -->
          <!-- 租赁物分类 -->
          <Field
            v-model="p.lease_things_type_n" :readonly="true"
            :required="editFlag" :is-link="editFlag" :rules="[{ required: editFlag,message:'请选择'}]" input-align="right"
            label="租赁物分类" @click="showPicker('lease_things_type',pi)" />
          <!-- 是否为经销商 -->
          <Field
            v-model="p.org_is_dealer_n" :readonly="true"
            :required="editFlag" :is-link="editFlag" :rules="[{ required: editFlag,message:'请选择'}]" input-align="right"
            label="是否为经销商" @click="showPicker('org_is_dealer',pi)"/>
          <!-- 是否上牌 -->
          <!-- <Field
            v-model="p.register_flag_n" :readonly="showFlag"
            :required="editFlag" :is-link="editFlag" :rules="[{ required: editFlag,message:'请选择'}]" input-align="right"
            label="是否上牌" @click="showPicker('register_flag',pi)"/> -->
          <!-- 是否挂靠 -->
          <!-- <Field
            v-model="p.associate_flag_n" :readonly="showFlag"
            :required="editFlag" :is-link="editFlag" :rules="[{ required: editFlag,message:'请选择'}]" input-align="right"
            label="是否挂靠" @click="showPicker('associate_flag',pi)" /> -->
          <!-- 挂靠单位全称 -->
          <!-- <Field
            v-model="p.associate_company" :readonly="showFlag"
            :required="p.associate_flag==='Y' && editFlag" :rules="[{ required: p.associate_flag==='Y' && editFlag,message:'请输入'}]" input-align="right"
            label="挂靠单位全称"/> -->
          <!-- 是否提供挂靠协议 -->
          <!-- <Field
            v-model="p.associate_agreement_n" :readonly="showFlag" :is-link="editFlag" input-align="right" label="是否提供挂靠协议"
            @click="showPicker('associate_agreement',pi)" /> -->
          <!-- 租赁物是否办理抵押 -->
          <!-- <Field
            v-model="p.lease_mortgage_n" :readonly="showFlag" :is-link="editFlag" input-align="right" label="租赁物是否办理抵押"
            @click="showPicker('lease_mortgage',pi)" /> -->
          <!-- 是否特批中登网不公示  为是 附件信息则必须同步上传审批报告 -->
          <Field
            v-model="p.special_approval_flag_n" :readonly="true"
            :required="editFlag" :is-link="editFlag" :rules="[{ required: editFlag,message:'请选择'}]" input-align="right"
            label="是否特批中登网不公示" @click="showPicker('special_approval_flag',pi)"/>
          <Field
            v-model="p.special_policy_flag_n" :readonly="true"
            :required="editFlag" :is-link="editFlag" :rules="[{ required: editFlag,message:'请选择'}]" input-align="right"
            label="是否特殊政策" @click="showPicker('special_policy_flag',pi)"/>
          <Field
            v-model="p.payer_n" :readonly="true"
            :required="editFlag" :is-link="editFlag" :rules="[{ required: editFlag,message:'请选择'}]" input-align="right"
            label="付款方" @click="showPicker('business_plan_payer',pi)"/>
          <Field
            v-model="p.payer_name" :readonly="payerNameFlag" :required="editFlag" label="付款方名称"
              input-align="right"/>
          <!-- GPS是否未安装（必填） -->
          <!-- <Field
            v-model="p.gps_flag_n" :readonly="showFlag"
            :required="editFlag" :is-link="editFlag" :rules="[{ required: editFlag,message:'请选择'}]" input-align="right"
            label="GPS是否未安装" @click="showPicker('gps_flag',pi)"/> -->
          <!-- 设备是否购买保险（不必填且无默认值） -->
          <!-- <Field
            v-model="p.insurance_flag_n" :readonly="showFlag" :is-link="editFlag" input-align="right" label="设备是否购买保险"
            @click="showPicker('insurance_flag',pi)" /> -->
        </Form>
      </div>
        <!-- 查看还款计划 -->
        <router-link :to="toPath(p.cash_lists, p)">查看还款计划</router-link>
      </CollapseItem>
    </Collapse>
    <div v-if="editFlag" class="foot-bottom" >
      <button native-type="submit" class="success" @click="save">保存</button>
    </div>
    <ActionSheet
      v-model="picker_show" :actions="actions" :title="actionTitle" :close-on-click-action="true"
      :closeable="false" @select="onSelect" />
  </div>
</template>

<script>
import { Collapse, CollapseItem, Cell, ActionSheet, Field, Form } from 'vant'
import 'vant/lib/collapse/style'
import 'vant/lib/collapse-item/style'
import 'vant/lib/action-sheet/style'
import 'vant/lib/field/style'
import 'vant/lib/form/style'
import 'vant/lib/cell/style'

export default {
  components: {
    Collapse, CollapseItem, Cell, ActionSheet, Field, Form},
  props: ['planData', 'editFlag', 'showFlag'],
  data () {
    return {
      activeNames: [0],
      formdata: [],
      actions: [], // 下拉框
      contractType: [], // 合同类型下拉框
      ticketType: [], // 开票类型下拉框
      factoryType: [], // 是否主机厂担保
      businessNewType: [], // 合同标识
      leaseType: [], // 租赁物类型
      YesNoType: [], // 是否类型
      businessPlanPayer: [], // 付款方
      picker_show: false,
      now_location: '',
      now_nodeName: '',
      actionTitle: '',
      now_specialFlag: false,
      payerNameFlag: true,
    }
  },
  // watch: {
  //   planData: {
  //     deep: true,
  //     handler (n, o) {
  //       console.log('xin', n)
  //       console.log('jiu', o)
  //       if(o.length!==0) window.localStorage.setItem('myform_30_isSave', false)
  //     },

  //   },
  // },
  created () {
    this.createForm()
    this.getDropBox()
    console.log(this.editFlag, this.showFlag)
  },
  methods: {
    getData(){
      return this.now_specialFlag
    },
    validate () { // 验证表单项是否必填
      return this.$refs.myForm_30[0].validate().then(async (res) => {
        return true
      }).catch((err) => {
        return false
      })
    },
    async save () {
      let flag = await this.validate()
      if (!flag) return hlsPopup.showLongCenter('请将必填项填写完整')
      let url = process.env.basePath + 'prj_wfl_quotation_save'
      let param = {
        'master': {
          quotation_lists: this.planData,
        },
      }
      console.log(param)

      hlsPopup.showLoading('请稍候')
      let res = await this.$post(url, param)
      this.hlsPopup.hideLoading()
      if (res.result === 'S') {
        hlsPopup.showLongCenter('保存成功')
        window.localStorage.setItem('myform_30_isSave', true)
      } else {
        hlsPopup.showLongCenter('保存失败')
      }
    },
    onSelect (value) {
      let val = value.name
      if (this.now_nodeName === 'repurchase_flag') { // 合同类型
        this.planData[this.now_location].repurchase_flag_n = val
        let arr = this.contractType.filter(item => item.code_name === val)
        this.planData[this.now_location].repurchase_flag = arr[0].code
      } else if (this.now_nodeName === 'rent_invoice_type') { // 开票类型
        this.planData[this.now_location].rent_invoice_type_n = val
        let arr = this.ticketType.filter(item => item.code_name === val)
        this.planData[this.now_location].rent_invoice_type = arr[0].code
      } else if (this.now_nodeName === 'factory_guarantees_flag') { // 是否主机厂担保
        this.planData[this.now_location].factory_guarantees_flag_n = val
        let arr = this.factoryType.filter(item => item.code_name === val)
        this.planData[this.now_location].factory_guarantees_flag = arr[0].code
      } else if (this.now_nodeName === 'business_type_new') { // 合同标识
        this.planData[this.now_location].business_type_new_n = val
        let arr = this.businessNewType.filter(item => item.code_name === val)
        this.planData[this.now_location].business_type_new = arr[0].code
      } else if (this.now_nodeName === 'lease_things_type') { // 租赁物分类
        this.planData[this.now_location].lease_things_type_n = val
        let arr = this.leaseType.filter(item => item.code_name === val)
        this.planData[this.now_location].lease_things_type = arr[0].code
      } else if (this.now_nodeName === 'business_plan_payer') { // 付款方
        this.planData[this.now_location].payer_n = val
        let arr = this.businessPlanPayer.filter(item => item.code_name === val)
        this.planData[this.now_location].payer = arr[0].code
        if (this.planData[this.now_location].payer === 'FACTORY') {
          this.payerNameFlag = true
          this.planData[this.now_location].payer_name = this.planData.factory_n
        } else if (this.planData[this.now_location].payer === 'TENANT') {
          this.payerNameFlag = true
          this.planData[this.now_location].payer_name = this.planData.bp_id_tenant_n
        } else if (this.planData[this.now_location].payer === 'AGENT') {
          this.payerNameFlag = true
          this.planData[this.now_location].payer_name = this.planData.bp_id_agent_n
        } else if (this.planData[this.now_location].payer === 'OTHER') {
          this.payerNameFlag = false
          this.planData[this.now_location].payer_name = ''
        }
      } else {
        this.planData[this.now_location][this.now_nodeName + '_n'] = val
        let arr = this.YesNoType.filter(item => item.code_name === val)
        this.planData[this.now_location][this.now_nodeName] = arr[0].code
        if(this.now_nodeName==='special_approval_flag'){
          this.now_specialFlag=arr[0].code
        }
      }
      window.localStorage.setItem('myform_30_isSave', false)
    },
    showPicker (flag, index) {
      if (!this.editFlag) return
      if (flag === 'repurchase_flag') {
        this.actions = this.contractType.map(item => ({name: item.code_name}))
        this.now_nodeName = 'repurchase_flag'
        this.actionTitle = '选择合同类型'
      } else if (flag === 'rent_invoice_type') {
        this.now_nodeName = 'rent_invoice_type'
        this.actions = this.ticketType.map(item => ({name: item.code_name}))
        this.actionTitle = '选择开票类型'
      } else if (flag === 'factory_guarantees_flag') {
        this.now_nodeName = 'factory_guarantees_flag'
        this.actions = this.factoryType.map(item => ({name: item.code_name}))
        this.actionTitle = '请选择'
      } else if (flag === 'business_type_new') {
        this.now_nodeName = 'business_type_new'
        this.actions = this.businessNewType.map(item => ({name: item.code_name}))
        this.actionTitle = '请选择'
      } else if (flag === 'lease_things_type') {
        this.now_nodeName = 'lease_things_type'
        this.actions = this.leaseType.map(item => ({name: item.code_name}))
        this.actionTitle = '请选择'
      } else if (flag === 'business_plan_payer') {
        this.now_nodeName = 'business_plan_payer'
        this.actions = this.businessPlanPayer.map(item => ({name: item.code_name}))
        this.actionTitle = '请选择'
      } else {
        this.now_nodeName = flag
        this.actions = this.YesNoType.map(item => ({name: item.code_name}))
        this.actionTitle = '请选择'
      }
      this.now_location = index
      this.picker_show = true
    },
    // 下拉框数据获取
    async  getDropBox () {
      let url = process.env.basePath + 'app_get_syscode'
      let param = {
        'REPURCHASE_FLAG': 'PRJ501A.REPURCHASE_FLAG',
        'RENT_INVOICE_TYPE': 'PRJ501A.RENT_INVOICE_TYPE',
        'FACTORY_GUARANTEES_TYPE': 'FACTORY_GUARANTEES_TYPE',
        // 'BUSINESS_TYPE_NEW': 'BUSINESS_TYPE_NEW',
        'LEASE_THINGS_TYPE': 'LEASE_THINGS_TYPE',
        'YES_NO': 'YES_NO',
        'BUSINESS_PLAN_PAYER': 'BUSINESS_PLAN_PAYER',

      }

      hlsPopup.showLoading('请稍候')
      let res = await this.$post(url, param)
      this.hlsPopup.hideLoading()
      if (res.return_status === 'S') {
        this.contractType = res.REPURCHASE_FLAG
        this.ticketType = res.RENT_INVOICE_TYPE
        this.factoryType = res.FACTORY_GUARANTEES_TYPE
        this.businessNewType = res.BUSINESS_TYPE_NEW
        this.leaseType = res.LEASE_THINGS_TYPE
        this.YesNoType = res.YES_NO
        this.businessPlanPayer = res.BUSINESS_PLAN_PAYER
      }
    },

    toPath (cash_lists, p) {
      let headInfo = JSON.stringify({
        lease_times: p.lease_times,
        financing_num: p.financing_num,
        lease_charge: p.lease_charge,
        down_payment: p.down_payment,
        deposit: p.deposit,
      })
      return { name: 'financingApplyFinancing', params: { cash_lists: JSON.stringify(cash_lists), headInfo } }
    },
    factory (arr) {
      // 接收二维数组,产生 formdata
      if (arr.length) {
        arr.forEach(ele => {
          let [title, prop, type] = ele
          this.formdata.push({
            title: title || '',
            prop: prop || '',
            type: type || 'text',
          })
        })
      }
    },
    createForm () {
      let formArr = [
        ['商务政策', 'product_plan_id_n', 'text'],
        ['数量', 'product_num', 'text'],
        ['首付款比例', 'down_payment_ratio', 'rate'],
        ['首付款(单台)', 'down_payment', 'currency'],
        ['产品名称', 'division_n', 'text'],

        ['单价设备', 'equip_price', 'currency'],
        ['保证金比例(%)', 'deposit_ratio', 'rate'],
        ['保证金(单台)', 'deposit', 'currency'],
        ['设备型号', 'product_id_n', 'text'],
        ['合同金额', 'total_price', 'currency'],

        ['手续费(%)', 'lease_charge_ratio', 'rate'],
        ['手续费(单台)', 'lease_charge', 'currency'],
        ['首期租金付款日期', 'lease_start_date', 'text'],
        ['租赁利率', 'int_rate', 'rate'],
        ['管理费(单台)', 'management_money', 'currency'],

        ['首付款合计', 'first_pay', 'currency'],
        ['保证金抵扣方式', 'deposit_deduction_n', 'text'],
        ['还款周期', 'annual_pay_times_n', 'text'],
        ['名义货价(单台)', 'residual_value', 'currency'],
        ['每期还款', 'per_repay_num', 'currency'],

        ['支付方式', 'pay_type_n', 'text'],
        ['报价方式', 'price_list_n', 'text'],
        ['GPS费金额', 'gps_fee', 'currency'],
        ['融资金额', 'financing_num', 'currency'],
        ['手续费政策', 'handling_policy_n', 'text'],
        ['租赁期数', 'lease_times', 'text'],

        ['保险押金', 'insurance_fee', 'currency'],
        ['利息总额', 'total_interest', 'currency'],
        ['逾期日利率', 'penalty_rate', 'rate'],
        ['首x期-起始期', 'lease_times_x_f', 'text'],
        ['首x期-截至期', 'lease_times_x', 'text'],

        ['租金总额', 'total_rental_sum', 'currency'],
        ['冬歇/雨歇起始月份', 'fallow_date_f', 'text'],
        ['冬歇/雨歇结束月份', 'fallow_date_t', 'text'],
      ]
      this.factory(formArr)
    },
    currency (num, dotNum = 2) {
      if (num === null || num === undefined || isNaN(+num)) return num
      return (+num).toLocaleString('en-US', { style: 'decimal', minimumFractionDigits: dotNum, maximumFractionDigits: dotNum })
    },
    toPercent (val, needSign = true, dotNum = 2) {
      if (!val || isNaN(+val)) return '0.00%'
      let res = (+val).toLocaleString('zh-CN', { style: 'percent', minimumFractionDigits: dotNum })
      return needSign ? res : res.replace('%', '')
    },
  },
}
</script>

<style lang="less" scoped>
  /deep/ .van-cell{
    background: none !important;
  }

  /deep/ .van-cell__title {
    color: #333333 !important
  }
</style>
