/*
 *@description:订单管理表单
 *@author: hudw
 *@date: 2022-03-31 17:14:12
*/
<template>
  <p-grid-form selfUpdate :onValuesChange="onValuesChange" :ref="formName" :items="formItems" :span="6" :labelCol="{ span: 6 }" :wrapperCol="{ span: 16 }">
    <p-card slot="table" title="商品信息" style="margin-top: 20px">
      <p-search-modal v-show="false" :open="showModal" @cancel="() => (showModal = false)" @change="handleDataAutoChange" v-bind="goodsModalConfig" />
      <a-space slot="extra">
        <p-button type="primary" :disabled="!cargoOwnerId" @clickSync="selectGoods" icon="plus">新增</p-button>
        <p-button :disabled="selectedRowKeys.length === 0" @clickSync="removeItem(selectedRowKeys)">删除</p-button>
      </a-space>
      <p-table-edit-pro
        :id="$route.meta.menuId + '_details_table'"
        :autoLoad="false"
        ref="table"
        rowKey="itemId"
        :rowSelectType="2"
        :scroll="{x:true}"
        :selectedRowKeys.sync="selectedRowKeys"
        :columns="columns"
        :dataSource.sync="details"
        :pagination="false"
        dragle
      >
      </p-table-edit-pro>
      <template slot="actions">
        <p-grid-form-item :wrapperCol="{ span: 7 }" :span="24" name="totalPcs" label="总件数" :value="0" unit="件" readOnly :type="st == 1 ? 'txt' : 'input'" />
        <p-grid-form-item :wrapperCol="{ span: 7 }" :span="24" name="totalWeight" label="总重量" :value="0" @change="handleChange" unit="公斤" readOnly :type="st == 1 ? 'txt' : 'input'">
        </p-grid-form-item>
        <p-grid-form-item :wrapperCol="{ span: 7 }" :span="24" name="totalVolume" label="总体积" :value="0" unit="立方" readOnly :type="st == 1 ? 'txt' : 'input'" @change="handleChange" />
      </template>
    </p-card>
  </p-grid-form>
</template>
<script>
const titleArr = ['', '查看', '新建', '修改', '复制']
import { mainGetFormList } from './config.js'
import { goodsModalConfig, setGoogColumns } from './goods.js'
import { mainSaveData, mainSaveDataSubmit } from '../../api'
import { getItemUnit } from '../../api'
import debounce from 'lodash/debounce'
import { getComputedParameter } from '@/blocks/utils/index.js'


const pageName = {
  main: '订单信息',
  children: '商品信息',
}

export default {
  props: {
    load: false,
    options: {
      //字典
      type: Object,
      default: () => {
        return {}
      },
    },

    formRecord: {
      //当前行数据
      type: Object,
      // default: () => {
      //  return itemMock
      // }
    },
    mainId: {
      //主表ID
      type: null,
    },
    formName: {
      //主表：main，表细表：children
      type: null,
      default: 'main',
    },
    st: {
      type: Number,
      default: 0 /**0=不显示,1=查看,2=新建,3=修改,4=复制 */,
    },
    goods: {
      type: null,
    },

    formExtendedField: {
      type: Array,
    },
    goodsExtendedField: {
      type: Array,
    },
  },
  data() {
    return {
      isTimeError: false,
      goodsModalConfig: goodsModalConfig(this),
      showModal: false,
      columns: setGoogColumns(this, this.goodsExtendedField, this.st),
      selectedRowKeys: [],
      cargoOwnerId: '',
      shipperType: 2, //发货商默认类型，
      consigneeType: 1, //收货商默认类型
      carrierType: 1, //承运商默认类型
      confirmLoading: false,
      // details: this.isDev ? moke : [],//商品数据
      details: [], //商品数据
      formItems: mainGetFormList(this, this.formExtendedField),
    }
  },
  watch: {
    details(data) {
      data.forEach((item) => {
        if (item.id) {
          item.itemId = item.id
        } else if (item.itemId) {
          item.id = item.itemId
        }
      })
    },
    shipperType(v) {
      let form = this.form()
      let baseName = 'shipper'
      let arr = { [baseName + 'UnitName']: '', [baseName + 'UnitId']: '', [baseName + 'UnitCode']: '' }

      if (v === 2) {
        //  form.setFieldsValue(arr)
        form.enableItem(baseName + 'Name')
        return form.hiddenItem(Object.keys(arr)[0])
      }
      form.disableItem(baseName + 'Name')
      return form.unhiddenItem(Object.keys(arr)[0])
    },

    consigneeType(v) {
      let form = this.form()
      let baseName = 'consignee'
      let arr = { [baseName + 'UnitName']: '', [baseName + 'UnitId']: '', [baseName + 'UnitCode']: '' }
      if (v === 2) {
        // form.setFieldsValue(arr)
        form.enableItem(baseName + 'Name')
        return form.hiddenItem(Object.keys(arr)[0])
      }
      form.disableItem(baseName + 'Name')
      return form.unhiddenItem(Object.keys(arr)[0])
    },

    formExtendedField(value) {
      if (value.length > 0) {
        this.formItems = mainGetFormList(this, value)
      }
    },
    goodsExtendedField(value) {
      if (value.length > 0) {
        this.columns = setGoogColumns(this, value, this.st)
      }
    },
  },
  computed: {
    disableItemId() {
      return this.details.map((item) => item.itemCode + item.itemName)
    },
    title() {
      return titleArr[this.st] + pageName[this.formName]
    },
  },
  mounted() {
    this.init(this.st)
  },
  methods: {
    init(value, data = null) {
      let form = this.form()
      this.isTimeError = false
      if (value > 0) {
        this.selectedRowKeys = []
        this.cargoOwnerId = ''
        this.shipperType = 2
        this.consigneeType = 1

        this.details = []
        if (value === 2) {
          form.resetFields()
          return
        }
        let _formRecord = data || this.formRecord
        if (_formRecord) {
          const { shipperName, consigneeName, shipperType, consigneeType, cargoOwnerId } = _formRecord
          let obj = {}
          let data = _formRecord

          let baseNameArr = ['consignee', 'shipper']
          baseNameArr.forEach((baseName) => {
            let arr = [data[baseName + 'Province'], data[baseName + 'City'], data[baseName + 'District']]
            obj[baseName + 'ProvinceCity'] = arr
          })

          //发货商默认类型，收货商默认类型
          this.cargoOwnerId = cargoOwnerId
          this.shipperType = shipperType
          this.consigneeType = consigneeType
          this.carrierType = _formRecord.carrierType

          this.$nextTick(() => {
            // this.reload({ data: { shipbillId } })
            this.details = _formRecord.list
            if (this.details.length > 0) {
              let id = this.details.map((item) => item.itemId)

              getItemUnit(this, id).then((res) => {
                if (res.success) {
                  let obj2 = {}
                  res.data.map((item) => {
                    obj2[item.itemId] = item
                  })

                  this.details.forEach((item) => {
                    const { volume, weight } = obj2[item.itemId]
                    item.unitVolume = volume || 0
                    item.unitWeight = weight || 0
                  })
                } else {
                  this.$exception(res)
                }
              })
            }

            if (value === 4) {
              //复制
              obj.id = ''
              obj.shipbillNo = '运单号自动生成'
              obj.orderNo = ''
              obj.wmsOrderNo = ''
            }
            obj = { ..._formRecord, ...obj }
            delete obj.totalPcs
            delete obj.totalWeight
            delete obj.totalVolume
            this.counterTotal(['pcs', 'weight', 'volume'], form, this.details)
            form.setFieldsValue(obj)
            cargoOwnerId && shipperName && form.enableItem('shipperName')
            cargoOwnerId && consigneeName && form.enableItem('consigneeName')
          })
        }
      }
    },
    removeItem(args) {
      let _this = this
      return this.$confirm({
        title: '是否删除选中的商品',
        onOk(clear) {
          _this.$nextTick(() => {
            _this.selectedRowKeys = []
            clear()
          })
          return _this.$refs.table.removeRow(args)
        },
      })
    },

    handleDataAutoChange(event, value, dataArr) {
      dataArr.forEach((item) => {
        item.unitVolume = item.volume || 0
        item.unitWeight = item.weight || 0
        item.volume = 0
        item.weight = 0
        for (let key in item) {
          if (key.indexOf('ext') > -1) {
            item[key] = ''
          }
        }
        delete item._row_count
        this.$refs.table.createRow(item, false)
      })

      this.showModal = false
      this.$nextTick(() => {
        this.counterTotal(['pcs', 'weight', 'volume'], this.form(), this.details)
      })
    },

    tableDone(dataArr) {
      dataArr.data.list.forEach((item) => {
        if (item.id) {
          item.itemId = item.id
        } else if (item.itemId) {
          item.id = item.itemId
        }
      })

      return dataArr
    },
    counterTotal(arr, form, data = null) {
      if (this.st > 0) {
        let obj = {}
        let details = data || this.details
        let str = arr
        if (details.length > 0) {
          details.forEach((item) => {
            let str = arr
            str.forEach((_key) => {
              let key = 'total' + _key[0].toLocaleUpperCase() + _key.slice(1)
              if (typeof obj[key] === 'undefined') {
                obj[key] = 0
              }
              let count = item[_key] || 0;
              // obj[key] = Math.round((count + obj[key] + Number.EPSILON) * 1000) / 1000
              obj[key] = parseFloat(this.BigJs(count).plus(obj[key]))

              //  parseFloat(this.BigJs(count).plus(obj[key]))
            })
          })
          console.log(obj)
        } else {
          str.forEach((_key) => {
            obj['total' + _key[0].toLocaleUpperCase() + _key.slice(1)] = 0
          })
        }
        form.setFieldsValue(obj)
        this.$nextTick(() => {})
      }
    },


    handleChange: debounce(function ({ name, record, value }) {
      if (name == 'weight' || name == 'volume') {
        record[name] = getComputedParameter(value, name)

      }
      if (name == 'pcs') {
        record.weight = parseFloat(this.BigJs(value).times(record.unitWeight)) //BigJs((value * record.unitWeight)
        record.volume = parseFloat(this.BigJs(value).times(record.unitVolume)) //  getComputedParameter(value * record.unitVolume, 'volume')
        return this.counterTotal(['pcs', 'weight', 'volume'], this.form())
      }


      this.counterTotal([name], this.form())

    }, 200),
    //商品选择
    selectGoods() {
      this.showModal = true
    },
    getFieldsValue() {
      return this.$refs[this.formName].form.getFieldsValue()
    },
    form() {
      if (this.$refs[this.formName]) {
        return this.$refs[this.formName].form
      }
      return undefined
    },

    onValuesChange({ form }, values) {
      let key = Object.keys(values)[0]
    },
    returnFormValue(value) {
      delete value.provinceCityDistrict
      delete value.estimatedPickupEndTime_time
      delete value.estimatedPickupStartTime_time
      delete value.estimatedDeliveryStartTime_time
      delete value.estimatedDeliveryEndTime_time
      delete value.shipperConsigneeProvinceCity
      delete value.consigneeConsigneeProvinceCity
      value.list = this.details
      return value
    },
    save(number) {
      let _this = this
      let form = this.form()

      form.validateFieldsAndScroll((error, value) => {
        if (error) return

        value = this.returnFormValue(value)

        let fn = [mainSaveData, mainSaveDataSubmit]
        if (number === 0) this.$emit('loading', true, number)

        if (value.carrierType == 2) {
          const {affiliationId,affiliationCode,affiliationName } =value
            value.carrierId=affiliationId
            value.carrierCode=affiliationCode
            value.carrierName=affiliationName
        }
        fn[number](this, value, this.st).then((res) => {
          this.$emit('loading', false, number)
          if (res.success) {
            setTimeout(() => {
              this.back(res.data || value.shipbillId, true)
            }, 1000)
          }
        })
      })
    },

    back(id, isReload = true) {
      this.$emit('back', this.formName, id, isReload)
      //  let form = this.form()
      //  form.resetFields()
      //  this.details = []
    },
  },
}
</script>
<style lang="less" >
.p-grid-view {
  .plg-grid-from .form-item-flex-wrapper .form-item-children-wrapper {
    flex: 0;
  }

  .time {
    display: none;
  }
}
</style>
