/*
 *@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" v-if="st>1">
      <p-search-modal v-bind="modaleConfig" :modalVisible.sync="modalVisible" buttonValue="选择订单号" @click="() => (modalVisible = true)" @ok="ok"></p-search-modal>
      <p-button type="primary" @clickSync="save">保存</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

          bordered
          :editorRowTable ="st>1"
          :customScrollbar="true"
          :scroll="{ x: true }"
          :id="$route.meta.menuId + '_details_table'"
          :autoLoad="false"
          ref="table"
          rowKey="shipbillDetailId"
          :rowSelectType="false"
          :selectedRowKeys.sync="selectedRowKeys"
          :columns="columns"
          :dataSource.sync="details"
          :pagination="false"
          dragle
          :customRow="customRow"
        >
        </p-table-edit-pro>
        <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" @change="handleChange" 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" @change="handleChange" />
        </template>
      </p-card>
    </p-grid-form>
  </p-card>
</template>
<script>
import { mainViewUrl, mainSaveData } from '../api.js';
import { setGoogColumns } from './goods.js';
import modaleConfig from './modalConfig.js';
import viewGetFormList from './viewGetFormList.js';
import editGetFormList from './editGetFormList.js';
//import { getItemUnit } from '@/views/TMS/order/orderManage/api';
import debounce from 'lodash/debounce';
import { customRow } from '@/blocks/components/scheduling/js/table/tableConfig.js';

export default {
  inheritAttrs: false,
  components: {},
  data() {
    return {
      customRow,
      modaleConfig: modaleConfig(this),
      ...this.$attrs,
      btnLoad: false,
      carrierType: undefined,
      planBillId: '',
      dataView: null,
      load: true,
      pageLoad: false,
      formItems: [],
      columns: setGoogColumns(this),
      selectedRowKeys: [],
      details: [], //商品数据
      details_2: [], //包果数据
      affixed: true,
      modalVisible: false,

      //
    };
  },

  props: {
    options: {
      //字典
      type: Object,
      default: () => {
        return {};
      },
    },
    formExtendedField: {
      type: Object,
      default() {
        return {
          form: [],
          formTable: [],
        };
      },
    },
    goodsExtendedField: {
      type: Array,
    },
    record: {
      type: null,
    },
    st: {
      type: Number,
      default: 0,
      /**0=不显示,1=查看,2=新建,3=修改,4=复制 */
    },
    title: {
      type: null,
    },
    formName: {
      type: null,
      default: 'main',
    },
  },
  mounted() {},
  watch: {
    st(value) {
      if(value==0)return
      let form = this.form();
      form && form.resetFields();
      this.carrierType = undefined

      if (value === 1) {
        this.formItems = viewGetFormList(this);

      } else {
        this.formItems=editGetFormList(this)
      }

      if ( this.record) {
        this.planBillId = '';
        this.carrierType = this.record.carrierType
         this.getView(this.record.planBillId);
      }
    },
  },

  methods: {
    ok(value, label, dataArr) {
      let productName = [];
      this.details = dataArr;
      dataArr.forEach((item) => {
        item.productName&& productName.push(item.productName);
      });
      this.counterTotal(['pcs', 'weight', 'volume'], this.$refs.grid.form, dataArr);

      this.$refs.grid.form.setFieldsValue({ productName: productName.join(',') });
    },
    schange(affixed) {
      this.affixed = affixed;
    },
    htmlTarget() {
      return this.$refs.card.$el.querySelector('.ant-card-body');
    },
    form() {
      return this.$refs.grid.form;
    },
    handelRemove(record) {
      this.$refs.table.removeRow(record._row_count);
    },
    tableValidateFields(...args) {
      return this.$refs.table?.validateFields(...args);
    },

    getView(planBillId) {
      this.pageLoad = true;
      this.load = true;

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

        if (response.success) {
          this.planBillId = planBillId;

          const { planBillDetailDTOS } = response.data;
          this.dataView = { ...response.data, ...this.record };

          this.$nextTick(() => {
            let form = this.form();
            form && form.setFieldsValue(this.dataView);
            if (planBillDetailDTOS ) {
              this.details = planBillDetailDTOS;


              this.counterTotal(['pcs', 'weight', 'volume'], this.form(), this.details);
            }
          });
        } 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() {
      let form = this.form();
      // this.$refs.table.validateFields((error, value) => {
      //   if (error) return;
      //   let params = {
      //     details: this.details,
      //     planBillId: this.planBillId,
      //   };

      // });
      return form.validateFields((t_error, value) => {
        if (t_error) return;

        value.transportPlanBillDetailVOS = this.details.map(({ id, planBillId, shipbillNo, shipbillDetailId,shipbillId, planDeliveryDate }) => {
          return {
            id,
            planBillId,
            shipbillNo,
            shipbillDetailId,
            shipbillId,
            planDeliveryDate,
          };
        });
        return mainSaveData(this, value, this.st).then((res) => {
          if (res.success) {
            this.back(this.planBillId, 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 (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);
      }
    },

    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>