/*
 *@description:编辑
 *@author: hudw
 *@date: 2022-04-26 16:41:46
*/
<template>
  <p-card class="full-card-panel" :bordered="false" ref="card" :loading="pageLoad">
    <a-space slot="extra">
      <p-button type="primary" @clickSync="save(0)" :disabled="load">保存</p-button>
      <p-button @click="back(record && record.id, false)">取消</p-button>
    </a-space>
    <a-space slot="title">
      <a-icon type="arrow-left" @click="back(record && record.id, false)" :style="{ color: '#08c' }" />
      {{ title }}
    </a-space>
    <p-grid-form selfUpdate class="p-grid-view" ref="grid" :items="formItems" :span="6" :labelCol="{ span: 6 }" :wrapperCol="{ span: 16 }">
      <p-card slot="table" title="商品信息" style="margin-top: 20px">
        <p-table-edit-pro
          :customScrollbar="true"
          :scroll="{ x: true }"
          :id="$route.meta.menuId + '_details_table'"
          :autoLoad="false"
          ref="table"
          rowKey="_row_count"
          :rowSelectType="false"
          :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-item v-if="title !== '关闭运单'" :span="24" itemHeight="auto" :wrapperCol="{ span: 24 }">
        <p-card title="包裹信息" style="margin-top: 20px">
          <p-table
            :id="$route.meta.menuId + '_details_table_2'"
            :autoLoad="false"
            :customScrollbar="true"
            rowKey="_row_count"
            ref="table_2"
            :rowSelectType="false"
            :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="st == 1 ? 'txt' : 'input'" />
            <p-grid-form-item :wrapperCol="{ span: 7 }" :span="24" name="totalLclPiece_2" 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="totalWholePiece_2" 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="totalWeight_2" 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_2" label="总体积" :value="0" unit="立方" readOnly :type="st == 1 ? 'txt' : 'input'" @change="handleChange" />
          </template>
        </p-card>
      </p-grid-form-item>
      <a-affix v-else :offsetBottom="0" @change="schange" :target="htmlTarget" style="width: 100%">
        <div :style="{ backgroundColor: '#fff', paddingBottom: '20px' }">
          <p-card style="margin-top: 20px">
            <p-grid-form-item type="select" required :labelCol="{ span: 3 }" :span="12" style="margin-right: 50%" name="closeType" :options="options.SHIPBILL_CLOSE_TYPE" label="关闭类型" />
            <p-grid-form-item selfUpdate type="textarea" :labelCol="{ span: 3 }" :span="12" style="margin-right: 50%" name="closeReason" label="关闭原因" />
          </p-card>
        </div>
      </a-affix>
    </p-grid-form>
  </p-card>
</template>
<script>
import { mainViewUrl, mainSaveData } from '../api.js'
import { setMainColumns as setParcelColumns } from '@/views/TMS/transportation/$common/parcelTable/tableConfig.js'
import { setGoogColumns } from './goods.js'
import { setCloseGoogColumns } from './closeGoods'
import viewGetFormList from './viewGetFormList.js'
import { getItemUnit } from '@/views/TMS/order/orderManage/api'
import debounce from 'lodash/debounce'

export default {
  inheritAttrs: false,
  components: {},
  data() {
    return {
      ...this.$attrs,
      btnLoad: false,
      shipbillId: '',
      dataView: null,
      load: true,
      pageLoad: false,
      formItems: viewGetFormList(this, this.formExtendedField.form,true),
      columns: setGoogColumns(this, this.formExtendedField.formTable),
      columns_2: setParcelColumns(this),
      selectedRowKeys: [],
      details: [], //商品数据
      details_2: [], //包果数据
      affixed: true, //
    }
  },

  props: {
    options: {
      //字典
      type: Object,
      default: () => {
        return {}
      },
    },
    formExtendedField: {
      type: Object,
      default() {
        return {
          form: [],
          formTable: [],
        }
      },
    },
    goodsExtendedField: {
      type: Array,
    },
    record: {
      type: null,
    },
    st: {
      type: Number,
      default: 1,
    },
    title: {
      type: null,
    },
    formName: {
      type: null,
      default: 'main',
    },
  },
  mounted() {},
  watch: {
    'formExtendedField.form'(value) {
      if (value.length > 0) {
        this.formItems = viewGetFormList(this, value,true)
      }
    },
    'formExtendedField.formTable'(value) {
      if (value.length > 0) {
        this.columns = this.title == '关闭运单' ? setCloseGoogColumns(this, value) : setGoogColumns(this, value)
      }
    },
    record(value) {
      let form = this.form()
      form&&form.resetFields()

      if (!value) {
        this.shipbillId = ''
        return
      }
      this.getView(value.shipbillId)
    },
  },

  methods: {
    schange(affixed) {
      this.affixed = affixed
    },
    htmlTarget() {
      return this.$refs.card.$el.querySelector('.ant-card-body')
    },
    form() {
      let { st, formName } = this.$attrs
      if (this.$refs.form.$refs[formName]) {
        return this.$refs.form.$refs[formName].form
      }
      return undefined
    },
    handelRemove(record) {
      this.$refs.table.removeRow(record._row_count)
    },
    tableValidateFields(...args) {
      return this.$refs.table?.validateFields(...args)
    },

    handelCopy(record, index) {
      let data = { ...record }
      data.id = null
      data.providerPcs = ''
      data.providerId = ''
      data.providerCode = ''
      data.providerName = ''
      data.objSubBranchName = ''
      data.objSubBranchCode = ''
      data.objSubBranchId = ''
      data.applyPcs = 0
      this.$refs.table.createRow(index + 1, data)
    },
    getView(shipbillId) {
      this.pageLoad = true
      this.load = true

      let _this = this
      return this.axios({ url: mainViewUrl, method: 'post', data: { shipbillId } }).then((response) => {
        this.pageLoad = false
        this.load = false

        if (response.success) {
          this.shipbillId = shipbillId

          const {  shipperId, consigneeType, shipbillDetailViewByIdDTOS, packages } = response.data
          this.dataView = { ...response.data, ...this.record }
          const { shipperName } = this.dataView
          this.columns = this.title === '关闭运单' ? setCloseGoogColumns(_this, _this.formExtendedField.formTable) : setGoogColumns(_this, _this.formExtendedField.formTable)

          //this.columns = setGoogColumns(_this, this.formExtendedField.formTable);
          this.$nextTick(() => {
            let form = this.form()
            form && form.setFieldsValue(this.dataView)
            if (shipbillDetailViewByIdDTOS && packages) {
              this.details = shipbillDetailViewByIdDTOS
              this.details_2 = packages
              if (this.details.length > 0) {
                let obj = {}
                shipbillDetailViewByIdDTOS.map((item) => {
                  item.shipperId = shipperId
                  item.consigneeType = consigneeType
                  obj[item.itemId] = item
                })
                let id = this.details.map((item) => item.itemId)
                // this.load = true

                this.details.length > 0 &&
                  getItemUnit(this, id).then((res) => {
                    if (res.success) {
                      let obj = {}
                      if (res.data.length == 0) {
                        return this.$exception({
                          message: '商品单位信息没有找到',
                          code: 200,
                          data: `ids=${id.join()}`,
                        })
                      }
                      res.data.map((item) => {
                        obj[item.itemId] = item
                      })
                      this.details.forEach((item) => {
                        const { volume, weight } = obj[item.itemId]
                        item.unitVolume = volume || 0
                        item.unitWeight = weight || 0
                      })
                      this.load = false
                    } else {
                      this.$exception(res)
                    }
                  })
              }

              this.counterTotal(['pcs', 'weight', 'volume'], this.form(), this.details)
              this.counterTotal_2(['pcs', 'weight', 'wholePiece', 'lclPiece', 'volume'], this.form(), this.details_2)
            }
          })
        } else {
          this.$exception(response)
        }
      })
    },
    reload(args) {
      return this.$refs.form.$refs.table.reload(args)
    },
    back(id, isReload = true) {
      this.$emit('back', this.formName, id, isReload)
      let form = this.form()
      form&&form.resetFields()
      this.details = []
    },

    save(number) {
      let form = this.form()
      this.$refs.table.validateFields((error, value) => {
        if (error) return
        let params = {
          details: this.details,
          shipbillId: this.shipbillId,
        }
        // if (this.title === '关闭运单') {
        //   return form.validateFields((t_error, value) => {
        //     if (t_error) return
        //     params.closeReason = value.closeReason
        //     params.closeType = value.closeType
        //     return mainSaveData(this, params).then((res) => {
        //       if (res.success) {
        //         this.back(this.shipbillId, true)
        //       }
        //     })
        //   })
        // }

        // mainSaveData(this, params).then((res) => {
        //   if (res.success) {
        //     this.back(this.shipbillId, true)
        //   }
        // })
        return form.validateFields((t_error, value) => {
          if (t_error) return
          if (this.title === '关闭运单') {
            params.closeReason = value.closeReason
            params.closeType = value.closeType
          }
          this.formExtendedField.form.forEach(item => {
            params[item.name] = value[item.name]
          })
          return mainSaveData(this, params).then((res) => {
            if (res.success) {
              this.back(this.shipbillId, true)
            }
          })
        })
      })
    },
    handleClosePcsChange:debounce(function({ name, record, value }) {
      record.weight = parseFloat(this.BigJs(value).times(record.unitWeight)) //BigJs((value * record.unitWeight)
      record.volume = parseFloat(this.BigJs(value).times(record.unitVolume))
      return this.counterTotal([name, 'weight', 'volume'], this.form())
    },500),
    handleChange:debounce(function({ name, record, value }) {
      //件数
      if (name == 'pcs' || name == 'applyPcs') {
        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([name, 'weight', 'volume'], this.form())
      }
      this.counterTotal([name], this.form())
    }, 500),

    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 (_key == 'applyPcs') {
                key = 'totalPcs'
              }
              if (typeof obj[key] === 'undefined') {
                obj[key] = 0
              }

              let count = item[_key] || 0
              obj[key] = parseFloat(this.BigJs(count).plus(obj[key]))
            })
          })
        } else {
          str.forEach((_key) => {
            obj['total' + _key[0].toLocaleUpperCase() + _key.slice(1)] = 0
          })
        }
        form&&form.setFieldsValue(obj)
      }
    },
    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] = Math.round((+count + obj[key] + Number.EPSILON) * 1000) / 1000
            })
          })
          console.log(obj)
        } else {
          str.forEach((_key) => {
            obj['total' + _key[0].toLocaleUpperCase() + _key.slice(1)] = 0
          })
        }
        form&&form.setFieldsValue({
          totalLclPiece_2: +obj.lclPiece || 0,
          totalWholePiece_2: +obj.wholePiece || 0,
          totalPcs_2: +obj.totalPcs || 0,
          totalVolume_2: +obj.totalPcs || 0,
          totalWeight_2: +obj.totalPcs || 0,
        })
        this.$nextTick(() => {})
      }
    },
    form() {
      if (this.$refs.grid) {
        return this.$refs.grid.form
      }
      return undefined
    },
  },
}
</script>
<style lang="less" >
.p-grid-view {
  .plg-grid-from .form-item-flex-wrapper .form-item-children-wrapper {
    flex: 0;
  }

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