/*
 *@description:订单管理表单
 *@author: hudw
 *@date: 2022-03-31 17:14:12
*/
<template>
  <p-grid-form selfUpdate :class="'p-grid-view'" :ref="formName" :items="formItems" :span="6" :labelCol="{ span: 6 }" :wrapperCol="{ span: 16 }">
    <p-card slot="table" title="商品信息" style="margin-top: 20px">
      <p-table
        :scroll="{ x: true }"
        :id="$route.meta.menuId + '_details_table'"
        :autoLoad="false"
        ref="table"
        rowKey="itemId"
        :rowSelectType="st === 1 ? false : 2"
        :selectedRowKeys.sync="selectedRowKeys"
        :columns="columns"
        :dataSource.sync="details"
        :pagination="false"
        dragle
      >
      </p-table>
      <template slot="actions">
        <p-grid-form-item :wrapperCol="{ span: 7 }" :span="24" name="totalPcs" label="总件数" :value="0" unit="件" readOnly type="txt" />
        <p-grid-form-item :wrapperCol="{ span: 7 }" :span="24" name="totalWeight" label="总重量" :value="0" unit="公斤" readOnly type="txt"> </p-grid-form-item>
        <p-grid-form-item :wrapperCol="{ span: 7 }" :span="24" name="totalVolume" label="总体积" :value="0" unit="立方" readOnly type="txt" />
      </template>
    </p-card>
    <p-grid-form-item :span="24" v-if="parcelTable" itemHeight="auto" :wrapperCol="{ span: 24 }">
      <p-card title="包裹信息" style="margin-top: 20px">
        <p-table
          :scroll="{ x: true }"
          :id="$route.meta.menuId + '_details_table_2'"
          :autoLoad="false"
          rowKey="_row_count"
          ref="table_2"
          :rowSelectType="st === 1 ? false : 2"
          :columns="columns_2"
          :dataSource.sync="details_2"
          :pagination="false"
          dragle
        >
        </p-table>
        <template slot="actions">
          <p-grid-form-item :wrapperCol="{ span: 7 }" :span="24" name="totalPcs_2" label="总件数" :value="0" unit="件" readOnly type="txt" />
          <p-grid-form-item :wrapperCol="{ span: 7 }" :span="24" name="totalLclPiece_2" label="总拼箱数" :value="0" unit="箱" readOnly type="txt">
          </p-grid-form-item>
          <p-grid-form-item :wrapperCol="{ span: 7 }" :span="24" name="totalWholePiece_2" label="总整件数" :value="0" unit="件" readOnly type="txt">
          </p-grid-form-item>
          <p-grid-form-item :wrapperCol="{ span: 7 }" :span="24" name="totalWeight_2" label="总重量" :value="0" unit="公斤" readOnly type="txt">
          </p-grid-form-item>
          <p-grid-form-item :wrapperCol="{ span: 7 }" :span="24" name="totalVolume_2" label="总体积" :value="0" unit="立方" readOnly type="txt" />
        </template>
      </p-card>
    </p-grid-form-item>
    <slot slot="table-2" />
  </p-grid-form>
</template>
<script>
import { viewGetFormList } from './config.js'
import {setGoogColumns} from './goods.js'
import  setParcelColumns  from './setParcelColumns.js'


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

    record: {
      //当前行数据
      type: Object,
    },

    formName: {
      //主表：main，表细表：children
      type: null,
      default: 'main',
    },
    st: {
      type: Number,
      default: 1 /**0=不显示,1=查看,2=新建,3=修改,4=复制 */,
    },
    goods: {
      type: null,
    },
    parcel: {
      type: null,
    },
    formExtendedField: {
      type: Object,
      default() {
        return {
          form: [],
          formTable: [],
        }
      },
    },
    goodsExtendedField: {
      type: Array,
    },
    goodsTableColumn: {
      type: Array
    },
  },
  data() {
    return {
      showModal: false,
      columns: this.goodsTableColumn?this.goodsTableColumn: setGoogColumns(this, this.formExtendedField.formTable),
      columns_2: setParcelColumns(this),
      selectedRowKeys: [],
      cargoOwnerId: '',
      shipperType: 2, //发货商默认类型，
      consigneeType: 1, //收货商默认类型
      confirmLoading: false,
      details: [], //商品数据
      details_2: [], //包果数据
      formItems: viewGetFormList(this, this.formExtendedField.form),


    }
  },
  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.form'(value) {
      if (value.length > 0) {
        this.formItems = viewGetFormList(this, value)
      }
    },
    goodsTableColumn(value) {
      this.columns=value

     },
    'formExtendedField.formTable'(value) {
      if (value.length > 0) {

        this.columns =this.goodsTableColumn?this.goodsTableColumn: setGoogColumns(this, this.formExtendedField.formTable)

      }
    },
  },
  computed: {
    disableItemId() {
      return this.details.map((item) => item.itemId)
    },

  },
  mounted() {
    this.init(this.st)
  },
  methods: {
    init(value, data = null) {
      let form = this.form()

      if (value > 0) {
        this.selectedRowKeys = []
        this.cargoOwnerId = ''
        this.shipperType = 1
        this.consigneeType = 1
        this.details = []


        let _record = data || this.record
        if (_record) {
          const { shipbillId, shipperType, consigneeType, cargoOwnerId, shipbillDetailViewByIdDTOS, packages } = _record
          let obj = {}
          let data = _record

          let baseNameArr = ['consignee', 'shipper']
          baseNameArr.forEach((baseName) => {
            let arr = [data[baseName + 'ProvinceName'], data[baseName + 'CityName'], data[baseName + 'DistrictName']]
            arr = arr.filter((item) => item && item)
            obj[baseName + 'ProvinceCity'] = arr.join('-')
          })

          //发货商默认类型，收货商默认类型
          this.cargoOwnerId = cargoOwnerId
          this.shipperType = shipperType
          this.consigneeType = consigneeType
          this.$nextTick(() => {
            if (shipbillDetailViewByIdDTOS && packages) {
              this.details = shipbillDetailViewByIdDTOS
              this.details_2 = packages
              this.counterTotal(['pcs', 'weight', 'volume'], this.form(), this.details)
              this.counterTotal_2(['pcs', 'weight', 'wholePiece', 'lclPiece', 'volume'], this.form(), this.details_2)
            } else {
              this.reload({ data: { shipbillId } })
            }

            obj = { ..._record, ...obj }
            delete obj.totalPcs
            delete obj.totalWeight
            delete obj.totalVolume
            form.setFieldsValue(obj)
          })
        }
      }
    },

    reload(args) {
      if (this.parcelTable) {
        this.$refs.table_2.reload(args)
      }
      return this.$refs.table.reload(args).then(() => {
        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] =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(() => {})
      }
    },
    counterTotal_2(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] =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({
          totalLclPiece_2: ~~obj.lclPiece,
          totalWholePiece_2: ~~obj.wholePiece,
          totalPcs_2: ~~obj.totalPcs,
          totalVolume_2: ~~obj.totalPcs,
          totalWeight_2: ~~obj.totalPcs,
        })
        this.$nextTick(() => {})
      }
    },

    getFieldsValue() {
      return this.$refs[this.formName].form.getFieldsValue()
    },
    form() {
      if (this.$refs[this.formName]) {
        return this.$refs[this.formName].form
      }
      return undefined
    },

    //计算时间
    countTime(valueTime) {
      let { estimatedPickupEndTime, estimatedPickupEndTime_time, estimatedDeliveryEndTime, estimatedDeliveryEndTime_time } = valueTime
      let { estimatedDeliveryStartTime, estimatedDeliveryStartTime_time, estimatedPickupStartTime, estimatedPickupStartTime_time } = valueTime

      let obj = {
        transportAging: 0,
        estimatedPickupEndTime: '',
        estimatedDeliveryEndTime: '',
        estimatedDeliveryStartTime,
        estimatedPickupStartTime,
      }
      let v = true
      if (estimatedPickupEndTime && estimatedDeliveryEndTime) {
        v = true
      } else {
        v = false
      }

      if (v) {
        //提货时间

        obj.estimatedPickupEndTime = this.moment(estimatedPickupEndTime + (estimatedPickupEndTime_time ? 'T' + estimatedPickupEndTime_time : '')).format('YYYY-MM-DD HH:mm:ss')
        //送达时间
        obj.estimatedDeliveryEndTime = this.moment(estimatedDeliveryEndTime + (estimatedDeliveryEndTime_time ? 'T' + estimatedDeliveryEndTime_time : '')).format('YYYY-MM-DD HH:mm:ss')
        //转时间戳
        let _estimatedPickupEndTime = +new Date(obj.estimatedPickupEndTime)
        let _estimatedDeliveryEndTime = +new Date(obj.estimatedDeliveryEndTime)
        // 送达时间-提货时间
        let transportAging = (_estimatedDeliveryEndTime - _estimatedPickupEndTime) / 1000 / 60 / 60
        obj.transportAging = Math.round((transportAging + Number.EPSILON) * 1000) / 1000
      }
      obj.estimatedDeliveryStartTime =
        estimatedDeliveryStartTime && this.moment(estimatedDeliveryStartTime + (estimatedDeliveryStartTime_time ? 'T' + estimatedDeliveryStartTime_time : '')).format('YYYY-MM-DD HH:mm:ss')
      obj.estimatedPickupStartTime =
        estimatedPickupStartTime && this.moment(estimatedPickupStartTime + (estimatedPickupStartTime_time ? 'T' + estimatedPickupStartTime_time : '')).format('YYYY-MM-DD HH:mm:ss')

      return obj
    },
    returnFormValue(value) {
      delete value.provinceCityDistrict
      let countTime = this.countTime(value)
      value = { ...value, ...countTime }

      delete value.estimatedPickupEndTime_time
      delete value.estimatedPickupStartTime_time
      delete value.estimatedDeliveryStartTime_time
      delete value.estimatedDeliveryEndTime_time
      delete value.shipperConsigneeProvinceCity
      delete value.consigneeConsigneeProvinceCity
      value.details = this.details
      return value
    },

    back(id, isReload = true) {
      this.$emit('back', this.formName, id, isReload)
      // this.formItems = []
      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>
