/*
 *@description:订单管理表单
 *@author: hudw
 *@date: 2022-03-31 17:14:12
*/
<template>
  <p-grid-form selfUpdate :class="st === 1 && 'p-grid-view'" :onValuesChange="onValuesChange" :ref="formName" :items="formItems" :span="6" :labelCol="{ span: 6 }" :wrapperCol="{ span: 16 }">
    <a-alert slot="timeRule" v-if="isTimeError" message="提示：预计送达结束时间>=预计送达开始时间>=预计提货结束时间>=预计提货开始时间" type="warning" show-icon />
    <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 v-if="st !== 1" slot="extra">
        <p-button type="primary" :disabled="!cargoOwnerId" @clickSync="selectGoods" icon="plus" v-action:addGoods>新增</p-button>
        <p-button :disabled="selectedRowKeys.length === 0" @clickSync="removeItem(selectedRowKeys)" v-action:delGoods>删除</p-button>
      </a-space>
      <p-table-edit-pro
        :scroll="{ x: true }"
        :id="$route.meta.menuId + '_details_table'"
        :autoLoad="false"
        ref="table"
        :remoteUrl="remoteUrl"
        rowKey="itemId"
        :rowSelectType="st === 1 ? false : 2"
        :selectedRowKeys.sync="selectedRowKeys"
        :columns="columns"
        :dataSource.sync="details"
        :remoteBefore="remoteBefore"
        :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 :span="24" v-if="parcelTable" itemHeight="auto" :wrapperCol="{ span: 24 }">
      <p-card title="包裹信息" style="margin-top: 20px">
        <p-table-edit-pro
          :scroll="{ x: true }"
          :id="$route.meta.menuId + '_details_table_2'"
          :autoLoad="false"
          rowKey="_row_count"
          ref="table_2"
          :remoteUrl="remoteUrl_2"
          :remoteBefore="remoteBefore"
          :rowSelectType="st === 1 ? false : 2"
          :columns="columns_2"
          :dataSource.sync="details_2"
          :pagination="20"
          dragle
        >
        </p-table-edit-pro>
        <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="总拼箱数" 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="总整件数" 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>
    <slot slot="table-2" />
  </p-grid-form>
</template>
<script>
const titleArr = ['', '查看', '新建', '修改', '复制'];
import { mainGetFormList } from './config.js';
import { goodsModalConfig, setGoogColumns } from './goods.js';
import {  mainSaveData, childrenTableInfoUrl, mainSaveDataSubmit, packageTableUrl } from '../../api';
import { setMainColumns as setParcelColumns } from '@/views/TMS/transportation/$common/parcelTable/tableConfig.js';
// import { getComputedParameter } from '@/blocks/utils'
import { getItemUnit } from '../../api';

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

export default {
  props: {
    load: false,
    options: {
      //字典
      type: Object,
      default: () => {
        return {};
      },
    },
    parcelTable: {
      type: Boolean,
      default: false,
    },
    remoteBefore: {
      type: Function,
    },
    record: {
      //当前行数据
      type: Object,
    },
    mainId: {
      //主表ID
      type: null,
    },
    formName: {
      //主表：main，表细表：children
      type: null,
      default: 'main',
    },
    st: {
      type: Number,
      default: 0 /**0=不显示,1=查看,2=新建,3=修改,4=复制 */,
    },
    goods: {
      type: null,
    },
    parcel: {
      type: null,
    },
    formExtendedField: {
      type: Object,
      default() {
        return {
          form: [],
          formTable: [],
        };
      },
    },
    goodsExtendedField: {
      type: Array,
    },
  },
  data() {
    return {
      isTimeError: false,
      goodsModalConfig: goodsModalConfig(this),
      showModal: false,
      columns: setGoogColumns(this, this.formExtendedField.formTable),
      columns_2: setParcelColumns(this),
      selectedRowKeys: [],
      cargoOwnerId: '',
      shipperType: 2, //发货商默认类型，
      consigneeType: 1, //收货商默认类型
      confirmLoading: false,
      // details: this.isDev ? moke : [],//商品数据
      details: [], //商品数据
      details_2: [], //包果数据
      formItems: mainGetFormList(this, this.formExtendedField.form),
      remoteUrl: {
        method: 'post',
        url: childrenTableInfoUrl,
        ...this.goods,
      },
      remoteUrl_2: {
        method: 'post',
        url: packageTableUrl,
        ...this.parcel,
      },
      cache:null
    };
  },
  watch: {
    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 = mainGetFormList(this, value);
      }
    },
    'formExtendedField.formTable'(value) {
      if (value.length > 0) {
        this.columns = setGoogColumns(this, value);
      }
    },
  },
  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 _record = data || this.record;
        if (_record) {
          const { shipperName, consigneeName, shipbillId, shipperType, consigneeType, cargoOwnerId, shipbillDetailViewByIdDTOS, packages } = _record;
          let obj = {};
          let data = _record;

          if (value !== 1) {
            if (data.estimatedPickupStartTime) {
              let m = this.moment(data.estimatedPickupStartTime);
              obj.estimatedPickupStartTime_time = m.format('HH:mm:ss');
              obj.estimatedPickupStartTime = m.format('YYYY-MM-DD');
            }
            if (data.estimatedDeliveryStartTime) {
              let m = this.moment(data.estimatedDeliveryStartTime);
              obj.estimatedDeliveryStartTime_time = m.format('HH:mm:ss');
              obj.estimatedDeliveryStartTime = m.format('YYYY-MM-DD');
            }

            if (data.estimatedPickupEndTime) {
              let m = this.moment(data.estimatedPickupEndTime);
              obj.estimatedPickupEndTime_time = m.format('HH:mm:ss');
              obj.estimatedPickupEndTime = m.format('YYYY-MM-DD');
            }
            if (data.estimatedDeliveryEndTime) {
              let m = this.moment(data.estimatedDeliveryEndTime);
              obj.estimatedDeliveryEndTime_time = m.format('HH:mm:ss');
              obj.estimatedDeliveryEndTime = m.format('YYYY-MM-DD');
            }
          }
          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.$nextTick(() => {
            if (shipbillDetailViewByIdDTOS && packages) {
              this.details = shipbillDetailViewByIdDTOS;
              this.details_2 = packages;
              if (this.details.length > 0) {
                let obj = {};
                shipbillDetailViewByIdDTOS.map((item) => {
                  obj[item.itemId] = item;
                });
                let id = this.details.map((item) => item.itemId);

                getItemUnit(this, id).then((res) => {
                  if (res.success) {
                    let obj = {};
                    res.data.map((item) => {
                      obj[item.itemId] = item;
                    });
                    res.data.length > 0 &&
                      this.details.forEach((item) => {
                        const { volume, weight } = obj[item.itemId];
                        item.unitVolume = volume || 0;
                        item.unitWeight = weight || 0;
                      });
                  } 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.reload({ data: { shipbillId } });
            }

            if (value === 3) {
              //修改
            } else if (value === 1) {
              //查看
            } else if (value === 4) {
              //复制
              obj.shipbillId = '';
              obj.shipbillNo = '运单号自动生成';
              obj.orderNo = '';
              obj.wmsOrderNo = '';
            }
            obj = { ..._record, ...obj };
            delete obj.totalPcs;
            delete obj.totalWeight;
            delete obj.totalVolume;
            this.cache = _record

            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);
        },
      });
    },
    reload(args) {
      if (this.parcelTable) {
        this.$refs.table_2.reload(args);
      }
      return this.$refs.table.reload(args).then(() => {
        let form = this.form();
        this.counterTotal(['pcs', 'weight', 'volume'], form, this.details);
        // const { totalPcs, totalWeight, totalVolume } = form.getFieldsValue()
        // form.setFieldsValue({totalWeight:totalWeight*totalPcs,totalVolume:totalVolume*totalPcs})
      });
    },
    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);
      });
    },
    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);
      }
    },
    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]));

              //  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.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(() => {});
      }
    },
    handleChange({ name, record, value }) {
      //件数
      if (name == 'pcs') {
        // console.log(this.BigJs(value).times(record.unitWeight))
        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());
    },
    //商品选择
    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];
      let timeArr = ['estimatedPickupEndTime', 'estimatedPickupEndTime_time', 'estimatedDeliveryEndTime', 'estimatedDeliveryEndTime_time'];
      let countTime = this.moment(new Date()).format('HH:mm');
      switch (key) {
        case 'estimatedPickupStartTime':
          //a1
          if (!values.estimatedPickupStartTime) {
            countTime = '';
          }
          form.setFieldsValue({ estimatedPickupStartTime_time: countTime });
          break;
        case 'estimatedPickupEndTime':
          //a2
          if (!values.estimatedPickupEndTime) {
            countTime = '';
          }
          form.setFieldsValue({ estimatedPickupEndTime_time: countTime });
          break;
        case 'estimatedDeliveryStartTime':
          //b1
          if (!values.estimatedDeliveryStartTime) {
            countTime = '';
          }
          form.setFieldsValue({ estimatedDeliveryStartTime_time: countTime });
          break;
        case 'estimatedDeliveryEndTime':
          //b2
          if (!values.estimatedDeliveryEndTime) {
            countTime = '';
          }
          form.setFieldsValue({ estimatedDeliveryEndTime_time: countTime });
          break;
      }

      if (timeArr.indexOf(key) > -1) {
        let valueTime = { ...form.getFieldsValue(timeArr), ...values };
        let transportAging = this.countTime(valueTime).transportAging;
        form.setFieldsValue({ transportAging });
      }
    },

    //计算时间
    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) {
        //提货时间
        let _estimatedPickupEndTime = this.moment(estimatedPickupEndTime + (estimatedPickupEndTime_time ? 'T' + estimatedPickupEndTime_time : '')).format('YYYY-MM-DD HH:mm:ss');
        //送达时间
        let _estimatedDeliveryEndTime = this.moment(estimatedDeliveryEndTime + (estimatedDeliveryEndTime_time ? 'T' + estimatedDeliveryEndTime_time : '')).format('YYYY-MM-DD HH:mm:ss');
        //转时间戳
        _estimatedPickupEndTime = +new Date(_estimatedPickupEndTime);
        _estimatedDeliveryEndTime = +new Date(_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');

      obj.estimatedPickupEndTime = estimatedPickupEndTime && this.moment(estimatedPickupEndTime + (estimatedPickupEndTime_time ? 'T' + estimatedPickupEndTime_time : '')).format('YYYY-MM-DD HH:mm:ss');
      obj.estimatedDeliveryEndTime =
        estimatedDeliveryEndTime && this.moment(estimatedDeliveryEndTime + (estimatedDeliveryEndTime_time ? 'T' + estimatedDeliveryEndTime_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;
    },
    save(number) {
      let _this = this
      let form = this.form()

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

        value = this.returnFormValue(value)

        let fn = [mainSaveData, mainSaveDataSubmit]
        // if (number === 0) this.$emit('loading', true)
        fn[number](this, value, this.st).then((res) => {
          this.$emit('loading', false)
          if (res.success) {
            this.back(res.data || value.shipbillId, true)
          }
        })
      })
    },


    back(id, isReload = true) {
      this.$emit('back', this.formName, id, isReload);
      // this.formItems = []
      // let form = this.form()
      // form.resetFields()
      this.details = [];
      this.cache=null

    },
  },
};
</script>
<style lang="less" >
.p-grid-view {
  .plg-grid-from .form-item-flex-wrapper .form-item-children-wrapper {
    flex: 0;
  }

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