<template>
  <view class="page">
    <view v-if="ready">
      <l-select
        @input="setValue('orderData.F_CustomerId', $event)"
        :value="getValue('orderData.F_CustomerId')"
        :disabled="!edit"
        :range="dataSource.orderData.F_CustomerId"
        title="客户名称"
        required
      />
      <l-organize-picker
        @input="setValue('orderData.F_SellerId', $event)"
        :value="getValue('orderData.F_SellerId')"
        :readonly="!edit"
        type="user"
        title="销售人员"
        required
      />
      <l-date-picker
        @input="setValue('orderData.F_OrderDate', $event)"
        :value="getValue('orderData.F_OrderDate')"
        :disabled="!edit"
        title="单据日期"
        required
      />
      <l-input
        :value="getValue('orderData.F_OrderCode')"
        title="单据编号"
        required
        disabled
      />

      <view
        v-for="(tableItem, tableIndex) of current.orderProductData"
        :key="tableIndex"
        :class="edit ? '' : 'margin-bottom'"
      >
        <view class="table-item padding-lr flex align-center justify-between" style="font-size: 14px; height: 30px;">
          <view class="table-item-title">产品明细 (第{{ tableIndex + 1 }}项)</view>
          <view
            v-if="tableIndex !== 0 && edit"
            class="table-item-delete text-blue"
            @click="tableDelete('orderProductData', tableIndex)"
          >
            删除
          </view>
        </view>

        <l-layer-picker
          @input="layerSet(tableIndex, 'orderProductData', 'F_ProductName', $event)"
          :value="getValue(`orderProductData.${tableIndex}.F_ProductName`)"
          :readonly="!edit"
          :source="dataSource.orderProductData.F_ProductName"
          :layerData="scheme.orderProductData.F_ProductName.layerData"
          title="商品名称"
        />
        <l-input :value="getValue(`orderProductData.${tableIndex}.F_ProductCode`)" title="商品编号" disabled />
        <l-input
          @input="setValue(`orderProductData.${tableIndex}.F_UnitId`, $event)"
          :value="getValue(`orderProductData.${tableIndex}.F_UnitId`)"
          :disabled="!edit"
          title="单位"
        />
        <l-input
          @input="setValue(`orderProductData.${tableIndex}.F_Qty`, $event)"
          @change="calcPrice(tableIndex)"
          :value="getValue(`orderProductData.${tableIndex}.F_Qty`)"
          :disabled="!edit"
          title="数量"
        />
        <l-input
          @input="setValue(`orderProductData.${tableIndex}.F_Price`, $event)"
          @change="calcPrice(tableIndex)"
          :value="getValue(`orderProductData.${tableIndex}.F_Price`)"
          :disabled="!edit"
          title="单价"
        />
        <l-input
          @input="setValue(`orderProductData.${tableIndex}.F_TaxRate`, $event)"
          @change="calcPrice(tableIndex)"
          :value="getValue(`orderProductData.${tableIndex}.F_TaxRate`)"
          :disabled="!edit"
          title="税率 (%)"
        />
        <l-input :value="getValue(`orderProductData.${tableIndex}.F_Taxprice`)" title="含税单价" disabled />
        <l-input :value="getValue(`orderProductData.${tableIndex}.F_Tax`)" title="总税额" disabled />
        <l-input :value="getValue(`orderProductData.${tableIndex}.F_Amount`)" title="不含税总金额" disabled />
        <l-input :value="getValue(`orderProductData.${tableIndex}.F_TaxAmount`)" title="含税总金额" disabled />
        <l-input
          @input="setValue(`orderProductData.${tableIndex}.F_Description`, $event)"
          :value="getValue(`orderProductData.${tableIndex}.F_Description`)"
          :disabled="!edit"
          title="说明信息"
        />
      </view>

      <view
        v-if="edit"
        @click="tableAdd('orderProductData')"
        class="bg-white flex flex-wrap justify-center align-center margin-bottom"
      >
        <view class="add-btn text-blue padding">+ 添加一行表格</view>
      </view>

      <l-textarea
        @input="setValue('orderData.F_Description', $event)"
        :value="getValue('orderData.F_Description')"
        :readonly="!edit"
        title="备注信息"
      />
      <l-select
        @input="setValue('orderData.F_PaymentState', $event)"
        :value="getValue('orderData.F_PaymentState')"
        :disabled="!edit"
        :range="dataSource.orderData.F_PaymentState"
        title="收款状态"
        required
      />
      <l-input
        @input="setValue('orderData.F_DiscountSum', $event)"
        :value="getValue('orderData.F_DiscountSum')"
        :disabled="!edit"
        title="优惠金额"
        required
      />
      <l-input
        @input="setValue('orderData.F_Accounts', $event)"
        :value="getValue('orderData.F_Accounts')"
        :disabled="!edit"
        title="收款金额"
        required
      />
      <l-date-picker
        @input="setValue('orderData.F_PaymentDate', $event)"
        :value="getValue('orderData.F_PaymentDate')"
        :disabled="!edit"
        title="收款日期"
        required
      />
      <l-select
        @input="setValue('orderData.F_PaymentMode', $event)"
        :value="getValue('orderData.F_PaymentMode')"
        :disabled="!edit"
        :range="dataSource.orderData.F_PaymentMode"
        title="收款方式"
        required
      />
      <l-input
        @input="setValue('orderData.F_SaleCost', $event)"
        :value="getValue('orderData.F_SaleCost')"
        :disabled="!edit"
        title="销售费用"
        required
      />
      <l-organize-picker
        :value="getValue('orderData.F_CreateUserId')"
        type="user"
        title="销售人员"
        readonly
      />
      <l-input
        @input="setValue('orderData.F_ContractCode', $event)"
        :value="getValue('orderData.F_ContractCode')"
        :disabled="!edit"
        title="合同编号"
      />
      <l-textarea
        @input="setValue('orderData.F_AbstractInfo', $event)"
        :value="getValue('orderData.F_AbstractInfo')"
        :readonly="!edit"
        title="摘要信息"
      />
    </view>

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

<script>
/*
 * 版 本 Learun-ADMS V7.0.3 力软敏捷开发框架(http://www.learun.cn)
 * Copyright (c) 2013-2020 上海力软信息技术有限公司
 * 创建人：超级管理员
 * 日  期：2020-05-27 10:29
 * 描  述：1111
 */

import get from 'lodash/get'
import set from 'lodash/set'
import moment from 'moment'
import mixins from '@/common/custompage.js'

export default {
  mixins: [mixins],

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

      // 表单数据
      current: {},
      origin: {},

      // 表单项数据结构
      scheme: {
        orderData: {
          F_CustomerId: {
            type: 'select',
            title: '客户名称',
            verify: 'NotNull',
            dataSource: '1',
            dataSourceId: 'crmCustomer,f_fullname,f_customerid'
          },
          F_SellerId: { type: 'organize', title: '销售人员', verify: 'NotNull', dataType: 'user' },
          F_OrderDate: { type: 'datetime', title: '单据日期', dfvalue: '1', verify: 'NotNull', dateformat: '0' },
          F_OrderCode: { type: 'encode', title: '单据编号', rulecode: '10002' },
          F_Description: { type: 'textarea', title: '备注信息' },
          F_PaymentState: { type: 'select', title: '收款状态', verify: 'NotNull', dataSource: '0' },
          F_DiscountSum: { type: 'text', title: '优惠金额', dfvalue: '0', verify: 'Num' },
          F_Accounts: { type: 'text', title: '收款金额', dfvalue: '0', verify: 'Num' },
          F_PaymentDate: { type: 'datetime', title: '收款日期', verify: 'NotNull', dateformat: '0' },
          F_PaymentMode: {
            type: 'select',
            title: '收款方式',
            verify: 'NotNull',
            itemCode: 'Client_PaymentMode',
            dataSource: '0'
          },
          F_SaleCost: { type: 'text', title: '销售费用', dfvalue: '0', verify: 'Num' },
          F_CreateUserId: { type: 'currentInfo', title: '制单人员', dataType: 'user' },
          F_ContractCode: { type: 'text', title: '合同编号' },
          F_AbstractInfo: { type: 'textarea', title: '摘要信息' }
        },
        orderProductData: {
          __GIRDTABLE__: '产品明细',
          F_ProductName: {
            type: 'layer',
            title: '商品名称',
            itemCode: 'Client_ProductInfo',
            dataSource: '0',
            layerData: [
              { label: '商品名称', name: 'F_ItemName', value: 'F_ProductName' },
              { label: '商品编号', name: 'F_ItemValue', value: 'F_ProductCode' }
            ]
          },
          F_ProductCode: { type: 'label', title: '商品编号', dataSource: '0' },
          F_UnitId: { type: 'input', title: '单位', dataSource: '0' },
          F_Qty: { type: 'input', title: '数量', dataSource: '0' },
          F_Price: { type: 'input', title: '单价', dataSource: '0' },
          F_TaxRate: { type: 'input', title: '税率 (%)', dataSource: '0' },
          F_Taxprice: { type: 'input', title: '含税单价', dataSource: '0' },
          F_Tax: { type: 'input', title: '总税额', dataSource: '0' },
          F_Amount: { type: 'input', title: '不含税总金额', dataSource: '0' },
          F_TaxAmount: { type: 'input', title: '含税总金额', dataSource: '0' },
          F_Description: { type: 'input', title: '说明信息', dataSource: '0' }
        }
      },

      // 选单数据
      dataSource: {
        orderData: {
          F_CustomerId: [],
          F_PaymentState: [
            { text: '未收款', value: '1' },
            { text: '部分收款', value: '2' },
            { text: '全部收款', value: '3' }
          ],
          F_PaymentMode: Object.values(this.GET_GLOBAL('dataDictionary').Client_PaymentMode).map(t => ({
            value: t.value,
            text: t.text
          }))
        },
        orderProductData: {
          F_ProductName: Object.values(this.GET_GLOBAL('dataDictionary').Client_ProductInfo).map(t => ({
            F_ItemName: t.text,
            F_ItemValue: t.value
          }))
        }
      }
    }
  },

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

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

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

      // 拉取表单数据，同时拉取所有来自数据源的选单数据
      await Promise.all([
        this.FETCH_DATASOURCE('crmCustomer').then(result => {
          this.dataSource.orderData.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 = await this.getDefaultForm()
      } else {
        const result = await this.HTTP_GET('learun/adms/crm/order/form', this.id)
        this.origin = await this.formatFormData(result)
      }
      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 originPostData = await this.getPostData()
          const postData = {
            crmOrderJson: originPostData.strEntity,
            crmOrderProductJson: originPostData.strorderProductDataEntity
          }
          if (this.mode !== 'create') {
            postData.keyValue = originPostData.keyValue
          }

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

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

        case 'delete':
          if (!(await this.CONFIRM('删除项目', '确定要删除本项吗？', true))) {
            return
          }

          this.LOADING('提交删除中…')
          this.HTTP_POST('learun/adms/crm/order/delete', this.id, '删除失败').then(success => {
            this.HIDE_LOADING()
            if (!success) {
              return
            }

            this.EMIT('crm-order-list-change')
            this.NAV_BACK()
            this.TOAST('删除成功', 'success')
          })
          break

        default:
          break
      }
    },

    // 计算表单中的单价总价相关项
    calcPrice(index) {
      const listItem = this.COPY(this.current.orderProductData[index])

      const singlePrice = Number(listItem.F_Price) || 0
      const num = Number(listItem.F_Qty) || 0
      const taxRate = Number(listItem.F_TaxRate) || 0

      listItem.F_Amount = (singlePrice * num).toFixed(2)
      listItem.F_Taxprice = (singlePrice * (1 + taxRate / 100)).toFixed(2)
      listItem.F_Tax = ((singlePrice * num * taxRate) / 100).toFixed(2)
      listItem.F_TaxAmount = (singlePrice * num * (1 + taxRate / 100)).toFixed(2)

      this.$set(this.current.orderProductData, index, listItem)
    },

    // 子表格删除一行
    tableDelete(tableName, index) {
      this.current[tableName].splice(index, 1)
    },

    // 子表格添加一行
    async tableAdd(tableName) {
      const newVal = {}
      for (const [fieldName, schemeItem] of Object.entries(this.scheme[tableName])) {
        if (fieldName !== '__GIRDTABLE__') {
          newVal[fieldName] = await this.getDefaultValue(`${tableName}.${fieldName}`, schemeItem)
        }
      }
      this.current[tableName].push(newVal)
    },

    // 子表格弹层输入，可一次性设置多个字段
    layerSet(tableIndex, table, field, layerValue) {
      const layerData = get(this.scheme, `${table}.${field}.layerData`, [])
      layerData.forEach(({ name, value }) => {
        this.setValue(`${table}.${tableIndex}.${value}`, layerValue[name] || '')
      })
    },

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

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