/*
 *@description:计划调度
 *@author: hudw
 *@date: 2023-07-06 14:42:11
*/
<template>
  <div class="pages">
    <a-row ref="t_pages" class="pages" :gutter="12">
      <a-col :span="12" ref="span" style="height: 100%">
        <p-card style="flex: 1 1 auto" class="full-card-panel" :bodyStyle="{ padding: 0, margin: '0px -1px' }">
          <a-space slot="title">
            <a-icon type="arrow-left" style="color: #1990ff" @click="back" />
            计划调度
          </a-space>
          <a-space slot="extra">
            <p-button type="primary" :disabled="selectData.length === 0" @click.stop="addOderItem(false)">按计划配载</p-button>
          </a-space>
          <!-- @selectChange="selectChange" -->

          <mainTable
            ref="mainTable"
            title="运输计划单"
            :getForm="getForm"
            :url="mainTableInfoUrl"
            :dataSource="minDataSource"
            :actiovOrderItme="actiovOrderItme"
            :activeID="mainId"
            :loading="loading"
            :options="options"
            @selectData="(arr) => (selectData = arr)"
            :orderList="orderList"
            :disabledIds="disabledIds"
            :cache="{ addOderItem, done, groupDimensionList }"
          >
          </mainTable>
        </p-card>
      </a-col>
      <a-col :span="12" style="height: 100%">
        <p-card class="full-card-panel">
          <a-space slot="title">配载单信息</a-space>
          <a-space slot="extra">
            <p-button type="primary" @click.stop="addOderItem(true)">新建配载单</p-button>
          </a-space>

          <p-card
            ref="orderItme"
            :class="orderActive == orderItme.key ? 'order-active' : ''"
            v-for="orderItme in orderList"
            @click.stop="handleClickOrder($event, orderItme)"
            :key="orderItme.key"
            style="width: 100%; margin-bottom: 10px"
            size="small"
          >
            <!-- :title="'分组名称：' + orderItme.groupName" -->

            <a-space slot="extra">
              <p-button :disabled="orderItme.loading" type="primary" @click.stop="dataSubmit($refs[orderItme.key][0].form, orderItme)">调度</p-button>
              <p-button :disabled="orderItme.loading" type="primary" @click.stop="dataSubmitReview($refs[orderItme.key][0].form, orderItme)">调度并审核</p-button>
              <p-button :disabled="orderItme.loading" type="danger" @click.stop="removeOrder(orderItme)">删除</p-button>
            </a-space>
            <a-spin :spinning="orderItme.loading">
              <p-grid-form :ref="orderItme.key" :span="6" :getItemProps="getItemProps" class="p-grid-view" :labelCol="{ span: 10 }" :wrapperCol="{ span: 14 }" :items="formItem"></p-grid-form>
            </a-spin>
          </p-card>
        </p-card>
      </a-col>
    </a-row>
  </div>
</template>
<script>
import { queryPlanDispatchGroup, getPendingDispatch, mainTableInfoUrl, dataSubmitReview, dataSubmit } from './api';
import mainTable from './mainTable/vxe.mainTable.vue';
import { setFormItem, resultData_car } from './config/formConfig';
import { createID } from '@/blocks/utils';

export default {
  components: { mainTable },
  props: {
    options: {
      type: null,
    },
    groupDimensionList: {
      type: Array,
    },
  },
  data() {
    return {
      loading: false,
      actiovOrderItme: null, //选中的配置单
      mainId: '',
      minDataSource: [],
      selectData: [],
      // disabledIds:[],
      orderActive: '',
      mainTableInfoUrl,
      orderList: [],
      done: [],

      isReload: false,
      formItem: setFormItem(this),
    };
  },
  computed: {
    disabledIds() {
      if (this.orderList.length > 0) {
        let arr = [];
        this.orderList.forEach((item) => {
          let ids = [...item.planDetailIdsArr];
          arr = arr.concat(ids);
        });
        return arr;
      }
      return [];
    },

    //关联外网系统
    RELATION_THIRD_SYSTEM() {
      return this.$store.state?.sysParameter?.sysParameter_TMS?.RELATION_THIRD_SYSTEM?.value ?? '';
    },
  },
  mounted() {
    this.init(this.groupDimensionList);
  },
  methods: {
    back() {
      this.$emit('back', 'main', this.isReload);
    },

    init(groupDimensionList, planDetailIds = '') {
      this.loading = true;
      queryPlanDispatchGroup({
        groupDimensionList,
        planDetailIds,
      })
        .then((res) => {
          if (res.success) {
            //       "id": "24433e552d634cb593e961c54320939c",
            //       "planDetailIds": "1000000000001126,1000000000001127,1000000000001128,1000000000001129,1000000000001130,1000000000001131,1000000000001133,1000000000001135",
            //       "groupName": "南昌",
            //       "consigneeQty": 1,
            //       "carrierUnitQty": 0,
            //       "totalWeight": 0E-8,
            //       "totalPcs": 1410,
            //       "planTotalVehicleQty": 5,
            //       "transfiniteQty": 0,
            //       "totalPlanBillQty": 5,
            //       "totalShipbillQty": 6,
            //       "groupDimensionList": [
            //           "department_name",
            //           "order_no",
            //           "plan_delivery_date"
            //       ],
            //       "groupItem": "department_name,order_no,plan_delivery_date",
            //       "planBillNo": null,
            //       "shipbillNo": null,
            //       "consigneeName": null,
            //       "orderNo": "",
            //       "departmentName": "南昌",
            //       "planDeliveryDate": null,
            //       "isTransfinite": null,
            //       "carrierName": null

            this.minDataSource =
              res.data.groupQueryDTOS?.map((item) => {
                item.rootId = null;
                item.pId = null;

                item.oderQty = item.loadingPlanDetailQty;

                item.selectValue = groupDimensionList;
                item.checked = false;
                item.hasChild = true;
                return item;
              }) ?? [];
          } else {
            this.$exception(res);
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleClickOrder(event, item) {
      this.orderActive = item.key;
    },
    handleRowClick(event, key, data) {
      this.mainId = key;
    },
    getForm(name) {
      return this.$refs[name] && this.$refs[name][0]?.form;
    },
    // childrenSelect(record) {
    //   if (mainSelectedRowKeys) {
    //     this.mainSelectedRowKeys = mainSelectedRowKeys;
    //   }
    // },
    // select(record, selected, selectedRows, nativeEvent, mainSelectedRowKeys = null) {
    //   if (mainSelectedRowKeys) {
    //     this.mainSelectedRowKeys = mainSelectedRowKeys;
    //   }
    //   if (record) {
    //     record._indeterminate = false;
    //     record._checked = selected;
    //     if (selected && record._children) {
    //       record._selectedRowKeys = record._children.map((item) => {
    //         return item.id;
    //       });
    //     } else {
    //       record._selectedRowKeys = [];
    //     }
    //   }
    // },

    resultSubmitData(form, orderItme) {
      let loadingBillHeaderVO = form.getFieldsValue();
      loadingBillHeaderVO.shipbillNumber = loadingBillHeaderVO.shipbillQty;
      loadingBillHeaderVO.customerNumber = loadingBillHeaderVO.consigneeQty;
      loadingBillHeaderVO.siteNumber = loadingBillHeaderVO.totalSitQty;
      loadingBillHeaderVO.totalPcs = loadingBillHeaderVO.totalPieceQty;
      loadingBillHeaderVO.totalVolume = loadingBillHeaderVO.totalVolumeQty; //总体积
      return [
        {
          loadingBillHeaderVO,
          planDetailIds: orderItme.planDetailIds,
        },
      ];
    },

    //删除配载单
    removeOrder(orderItme, isMainRow = false) {
      let key = orderItme.key;
      for (let key in orderItme.uuData) {
        let item = orderItme.uuData[key];
        item.checked = false;
        item.disabled = false;
      }
      orderItme.uuData = {};

      this.orderList = this.orderList.filter((item) => item.key != key);
      this.orderList.sort();
      this.orderActive = null;
      this.selectData = this.$refs.mainTable.getCheckboxRecords();
      this.$nextTick(() => {
        this.$refs.mainTable.updateFooter();
      });
    },
    getDisabled(orderList) {
      if (orderList.length) {
        let arr = [];
        orderList.forEach((item) => {
          let ids = item.planDetailIds?.split(',') ?? [];
          arr = arr.concat(ids);
        });
        return arr;
      }
      return [];
    },

    addOderItem(isCreate) {
      //  [
      //  {"planBillId":"计划单1ID",
      //   "planBillDetailDTOList" [{ ... }],
      //}]
      let _this = this;
      let _m = {
        isNew: true,

        key: createID(),
        loading: false,
        itemList: [],
        planDetailIdsArr: [],
        planDetailIds: '',
        planBillLoadingVOList: null,
        uuData: {},
      };

      if (isCreate) {
        this.actiovOrderItme = _m;
        this.orderActive = _m.key;
        this.orderList.unshift(_m);

        return;
      } else {
        if (this.orderActive) {
          let _c = this.orderList.find((item) => {
            return item.key == this.orderActive;
          });
          if (_c) {
            _m = _c;
          } else {
            this.orderList.unshift(_m);
          }
        } else {
          this.actiovOrderItme = _m;
          this.orderActive = _m.key;
          this.orderList.unshift(_m);
        }
        _m.loading = true;
        let obj = {
          itemList :this.selectData,
          planDetailIdsArr: _m.planDetailIdsArr.concat()
        }
        let planDetailIdsArr = obj.planDetailIdsArr;
        this.selectData.forEach(({ planDetailIds }) => {
          planDetailIdsArr = planDetailIdsArr.concat(planDetailIds.split(','));
        });
        console.log(planDetailIdsArr);
        obj.planDetailIdsArr = Array.from(new Set(planDetailIdsArr));
        let planDetailIds = obj.planDetailIdsArr.join(',');
        obj.planDetailIds=planDetailIds
        getPendingDispatch(this, { planDetailIds })
          .then((data) => {
            _m.loading = false;
            _this.actiovOrderItme = _m;
            if (data) {
              _this.selectData.forEach((item) => {
                item.disabled = true;
                _m.uuData[item.id] = item;
              });

              for (let key in obj) {
                _m[key]=obj[key]
              }

              this.orderActive = _m.key;

              this.$nextTick(() => {
                let form = this.getForm(_m.key);
                form.setFieldsValue(data);
                this.$refs.mainTable.updateFooter();
                this.orderList.sort();
                this.carrierTypChange(data.carrierType, null, null, form, data, _m);
              });
            }
          })
          .finally(() => {
            _m.loading = false;
          });
      }
    },

    carrierTypChange(value, label, options, form, defObj = null, fieldsValue = null) {
      let volumeLoadingRate = 0,volumeRercen=0,
      weightLoadingRate = 0, weightRercent = 0;
      if (defObj && fieldsValue) {
        let _data = resultData_car(defObj, defObj);
         volumeRercen =_data.volumeRercen
         weightRercent = _data.weightRercent
         volumeLoadingRate = _data.volumeLoadingRate
         weightLoadingRate = _data.weightLoadingRate
        _data=null
      }
      let obj = {
        vehicleAscription: '',
        vehicleAscriptionName: '',
        carrierSysFlag: '',
        carrierId: '',
        carrierName: '',
        carrierCode: '',
        vehicleAffiliationId: '',
        vehicleAffiliationCode: '',
        vehicleAffiliationName: '',
        driverCode: '',
        driverId: '',
        driverName: '',
        deliverymanCode: '',
        deliverymanId: '',
        deliverymanName: '',
        vehicleTypeCode: '',
        vehicleTypeId: '',
        vehicleTypeName: '',
        vehicleId: '',
        vehiclePlateNumber: '',
        driverPhoneNumber: '',
        deliverymanPhoneNumber: '',
        volumeLoadingRate,
        weightLoadingRate,
        vehicleTypeCategory: 0,
        vehicleTypeCategoryName: '',
        vehicleDeviceId: '',
        vehicleDeviceCode: '',
        vehicleDeviceName: '',
        containerName: '',
        containerId: '',
        containerCode: '',
        ...defObj,
        weightRercent,volumeRercen,
        volumeRate: defObj &&'体积:' + volumeLoadingRate + ',重量:' + weightLoadingRate,
      };

      let name = [
        'vehicleAscriptionName',
        'vehicleAffiliationName',
        'vehicleTypeCategoryName',
        'volumeRate',
        'deliverymanPhoneNumber',
        'driverPhoneNumber',
        'vehiclePlateNumber',
        'driverName',
        'deliverymanName',
        'vehicleTypeName',
      ];
      //判断系统参数中，关联外网系统：温控系统 或 容器管理，则显示 容器号字段
      if (
        ['2', '3'].some((i) => {
          return this.RELATION_THIRD_SYSTEM.includes(i);
        })
      ) {
        name.push('containerName');
      }
      //判断系统参数中，关联外网系统：gps设备系统，则显示 设备号字段；
      if (this.RELATION_THIRD_SYSTEM.includes('1')) {
        name.push('vehicleDeviceName');
      }

      let name2 = ['carrierCode', 'carrierName'];
      if (value == 1) {
        form.hiddenItem(name);
        form.unhiddenItem(name2);
        form.setItemProps('carrierCode', {
          required: true,
        });
        form.setItemProps('driverName', {
          required: undefined,
        });
        form.setItemProps('driverPhoneNumber', {
          rules: undefined,
        });
        form.setItemProps('deliverymanPhoneNumber', {
          rules: undefined,
        });
        form.setItemProps('vehiclePlateNumber', {
          rules: undefined,
        });
      } else if (value == 2) {
        form.hiddenItem(name2);
        form.unhiddenItem(name);
        form.setItemProps('carrierCode', {
          required: undefined,
        });
        form.setItemProps('driverName', {
          required: true,
        });
        form.setItemProps('driverPhoneNumber', {
          rules: [
            {
              type: 'phone',
              required: true,
            },
          ],
        });
        form.setItemProps('deliverymanPhoneNumber', {
          rules: [
            {
              type: 'phone',
            },
          ],
        });
        form.setItemProps('vehiclePlateNumber', {
          rules: [
            {
              type: 'plateNumber',
              required: true,
            },
          ],
        });
      } else {
        form.hiddenItem([...name, ...name2]);
        form.setItemProps('carrierCode', {
          required: undefined,
        });
        form.setItemProps('driverName', {
          required: undefined,
        });
        form.setItemProps('driverPhoneNumber', {
          rules: undefined,
        });
        form.setItemProps('vehiclePlateNumber', {
          rules: undefined,
        });
        form.setItemProps('deliverymanPhoneNumber', {
          rules: undefined,
        });
      }
      form.setFieldsValue(obj);
      this.$forceUpdate();
    },

    getItemProps(name, type, form) {
      if (['vehicleDeviceName', 'containerName'].includes(name)) {
        let { vehicleId } = form.getFieldsValue();
        if (vehicleId) {
          return {
            props: {
              disabled: false,
            },
          };
        } else {
          return {
            props: {
              disabled: true,
            },
          };
        }
      }
    },
    dataSubmit(form, orderItme) {
      let _this = this;

      let params = this.resultSubmitData(form, orderItme);
      form.validateFieldsAndScroll((error, value) => {
        if (error) return;
        return dataSubmit(this, params).then((res) => {
          if (res.success) {
            _this.updtaeTable(orderItme);
          }
        });
      });
    },
    dataSubmitReview(form, orderItme) {
      form.validateFieldsAndScroll((error, value) => {
        if (error) return;
        return dataSubmitReview(this, this.resultSubmitData(form, orderItme)).then((res) => {
          if (res.success) {
            _this.updtaeTable(orderItme);
          }
        });
      });
      let _this = this;
      return;
    },
    updtaeTable(orderItme) {
      Object.values(orderItme.uuData)?.forEach((item) => {
        this.$refs.mainTable.remove(item);
      });
      this.done = this.done.concat(orderItme.planDetailIdsArr);

      this.actiovOrderItme = null;
      this.removeOrder(orderItme, true);
    },
  },
};
</script>
<style lang='less'>
</style>