<template>
  <view class="page">
    <view v-if="ready">
      <l-select
        @input="setValue('F_CustomerId', $event)"
        :value="getValue('F_CustomerId')"
        :disabled="!edit"
        :range="dataSource.lr_crm_invoice.F_CustomerId"
        title="客户名称"
        required
      />
      <l-textarea
        @input="setValue('F_InvoiceContent', $event)"
        :value="getValue('F_InvoiceContent')"
        :readonly="!edit"
        title="开票信息"
        required
      />
    </view>

    <view v-if="ready" class="padding-lr bg-white margin-tb padding-tb">
      <l-button v-if="edit" @click="action('save')" class="block" size="lg" color="green" block>提交保存</l-button>
      <l-button v-if="!edit && mode !== 'create'" @click="action('edit')" class="block" size="lg" line="orange" block>
        编辑本页
      </l-button>
      <l-button
        v-if="edit && mode !== 'create'"
        @click="action('reset')"
        class="block margin-top"
        size="lg"
        line="red"
        block
      >
        取消编辑
      </l-button>
    </view>
  </view>
</template>

<script>
import get from 'lodash/get'
import set from 'lodash/set'
import moment from 'moment'
import customPageMixins from '@/common/custompage.js'

export default {
  mixins: [customPageMixins],

  data() {
    return {
      // 页面参数
      mode: null,
      edit: null,
      ready: false,

      // 表单数据对象
      current: null,
      origin: null,

      // 表单项数据结构
      scheme: {
        lr_crm_invoice: {
          F_CustomerId: {
            type: 'select',
            title: '客户名称',
            dataSource: '1',
            dataSourceId: 'crmCustomer,f_fullname,f_customerid'
          },
          F_InvoiceContent: { type: 'texteditor', title: '开票信息' }
        }
      },

      // 数据源
      dataSource: {
        lr_crm_invoice: {
          F_CustomerId: []
        }
      }
    }
  },

  async onLoad({ type }) {
    await this.init(type)
  },

  methods: {
    // 页面初始化
    async init(type = 'create') {
      this.LOADING('加载数据中…')

      this.mode = type
      this.edit = ['create', 'edit'].includes(this.mode)

      // 加载所有数据源
      await Promise.all([
        this.FETCH_DATASOURCE('crmCustomer').then(result => {
          this.dataSource.lr_crm_invoice.F_CustomerId = result.data.map(t => ({
            text: t.f_fullname,
            value: t.f_customerid
          }))
        }),

        this.fetchForm()
      ])

      this.ready = true
      this.HIDE_LOADING()
    },

    // 加载表单数据（新建表单的场合，获取一个初始化的空表单）
    async fetchForm() {
      if (this.mode === 'create') {
        this.origin = {
          keyValue: '',
          entity: {
            F_CustomerId: '',
            F_InvoiceContent: '',
            F_CustomerName: ''
          }
        }
      } else {
        this.origin = this.GET_PARAM()
      }
      this.current = this.COPY(this.origin)
    },

    // 点击「编辑、重置、保存、删除」按钮
    async action(type) {
      switch (type) {
        case 'edit':
          this.edit = true
          break

        case 'reset':
          this.current = this.COPY(this.origin)
          this.edit = false
          break

        case 'save':
          const verifyResult = this.verifyForm()
          if (verifyResult.length > 0) {
            this.CONFIRM('表单验证失败', verifyResult.join('\n'))
            return
          }

          if (!(await this.CONFIRM('提交确认', '确定要提交本页表单内容吗？', true))) {
            return
          }

          this.LOADING('正在提交…')
          const F_CustomerName = this.dataSource.lr_crm_invoice.F_CustomerId.find(
            t => t.value === this.current.F_CustomerId
          ).text

          const postData = {
            keyValue: this.current.F_InvoiceId || '',
            entity: {
              F_CustomerId: this.current.F_CustomerId,
              F_InvoiceContent: this.current.F_InvoiceContent,
              F_CustomerName
            }
          }

          this.HTTP_POST('learun/adms/crm/invoice/save', postData, '表单提交保存失败').then(success => {
            this.HIDE_LOADING()
            if (!success) {
              return
            }

            this.EMIT('invoice-list-change')
            this.NAV_BACK()
            this.TOAST('提交保存成功', 'success')
          })
          break

        default:
          break
      }
    },

    // 获取表单值
    getValue(path) {
      return get(this.current, path)
    },

    // 设置表单值
    setValue(path, val) {
      set(this.current, path, val)
    }
  }
}
</script>
