<template>
  <div class="descriptions-edit">
    <el-descriptions :column="4" border :labelStyle="{width: '100px'}" :contentStyle="{minWidth:'100px'}">
      <template slot="title"><span class="vehicle-title">订单信息</span></template>
      <el-descriptions-item>
        <template slot="label">订单号</template>
        {{ order.orderNo }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">状态</template>
        <el-tag :type="order.status == '1' ? 'success' : ''">{{ order.status == 1 ? '已完成' : '未完成'
          }}</el-tag>
      </el-descriptions-item>
      <el-descriptions-item v-if="order.sourceNo">
        <template slot="label">关联托运订单</template>
        {{ order.sourceNo }}
      </el-descriptions-item>
      <el-descriptions-item v-if="order.cargoInfo">
        <template slot="label">货物名称</template>
        {{ order.cargoInfo }}
      </el-descriptions-item>
      <el-descriptions-item v-if="order.custName">
        <template slot="label">承运企业</template>
        {{ order.custName }}
      </el-descriptions-item>
      <el-descriptions-item v-if="order.freightRates">
        <template slot="label">承运价</template>
        {{ order.freightRates }}
      </el-descriptions-item>
      <el-descriptions-item v-if="order.currency">
        <template slot="label">币种</template>
        <dict-tag :options="dict.type.sys_curr_type" :value="order.currency" />
      </el-descriptions-item>
      <el-descriptions-item v-if="order.orderDate">
        <template slot="label">订单时间</template>
          {{order.orderDate}}
      </el-descriptions-item>
      <el-descriptions-item v-if="order.remark">
        <template slot="label">备注</template>
        {{ order.remark }}
      </el-descriptions-item>
    </el-descriptions>
    <el-descriptions style="margin-top: 15px;" v-if="editType === TransPlanEditType.add" :column="3" border :labelStyle="{width: '100px'}" :contentStyle="{minWidth:'100px'}">
      <template slot="title"><span class="vehicle-title">运输计划车辆信息</span></template>
      <el-descriptions-item v-if="plan.vehicleNumber">
        <template slot="label">车牌号码</template>
        {{ plan.vehicleNumber }}
      </el-descriptions-item>
      <el-descriptions-item v-if="plan.vehicleBrand">
        <template slot="label">品牌型号</template>
        {{ plan.vehicleBrand }}
      </el-descriptions-item>
      <el-descriptions-item v-if="plan.driverName">
        <template slot="label">司机</template>
        {{ plan.driverName }}
      </el-descriptions-item>
      <el-descriptions-item v-if="plan.vehicleLoad">
        <template slot="label">载重(吨)</template>
        {{ plan.vehicleLoad }}
      </el-descriptions-item>
      <el-descriptions-item v-if="plan.vehicleVol">
        <template slot="label">装载体积(m³)</template>
        {{ plan.vehicleVol }}
      </el-descriptions-item>
      <el-descriptions-item v-if="plan.remark">
        <template slot="label">备注</template>
        {{ plan.remark }}
      </el-descriptions-item>
    </el-descriptions>
    <el-form ref="form" v-loading="loading" :model="form" :rules="rules" :show-message="false" v-enterboard>
      <div class="vehicle-header">
        <span class="vehicle-title">货物运输计划</span>
        <el-button v-if="editType === TransPlanEditType.add" icon="el-icon-plus" type="info" size="mini" plain
          @click="addCargo">添加货物</el-button>
        <el-popconfirm v-if="editType === TransPlanEditType.add" title="确定删除勾选中的货物吗？" @confirm="deleteCargo">
          <el-button slot="reference" icon="el-icon-delete" :disabled="selectCargos.length === 0"
            type="danger" size="mini" plain>删除勾选货物</el-button>
        </el-popconfirm>
      </div>
      <el-table class="cargo-table" highlight-current-row ref="table" max-height="500px" :data="form.lsCargos"
          @selection-change="cargoSelectionChange" border stripe :summary-method="getCargoSummaries" show-summary>
        <el-table-column v-if="editType === TransPlanEditType.add" type="selection" width="30" align="center" />
        <el-table-column type="index" width="30" align="center" />
        <el-table-column label="车牌号码" align="center" prop="vehicleNumber" min-width="100">
          <template slot-scope="scope">
            {{ editType === TransPlanEditType.add ? plan.vehicleNumber : scope.row.vehicleNumber }}
          </template>
        </el-table-column>
        <el-table-column label="司机姓名" align="center" prop="driverName" min-width="100">
          <template slot-scope="scope">
            {{ editType === TransPlanEditType.add ? plan.driverName : scope.row.driverName }}
          </template>
        </el-table-column>
        <el-table-column label="运输货物" prop="cargoName" align="center" min-width="100">
          <template slot-scope="scope">
            <MyFormItem :prop="`lsCargos.${scope.$index}.cargoName`"
              :value="scope.row.cargoName" :readonly="readonly" :rules="rules.cargoName">
              <!-- <el-input v-model="scope.row.cargoName" placeholder="请输入运输货物" /> -->
              <CarriageCargoInput :label="scope.row.cargoName" :orderId="order.id" @change="cargoChange($event, scope.row)" />
            </MyFormItem>
          </template>
        </el-table-column>
        <el-table-column label="计划装货量(吨)" prop="loadWt" align="center" min-width="100">
          <template slot-scope="scope">
            <MyFormItem :prop="`lsCargos.${scope.$index}.loadWt`"
              :value="scope.row.loadWt" :readonly="readonly" :rules="rules.loadWt">
              <el-input v-model="scope.row.loadWt" placeholder="请输入计划装货量(吨)" />
            </MyFormItem>
          </template>
        </el-table-column>
        <el-table-column label="实际装货量(吨)" prop="realLoadWt" align="center" min-width="100">
          <template slot-scope="scope">
            <MyFormItem :prop="`lsCargos.${scope.$index}.realLoadWt`"
              :readonly="readonly" :rules="rules.realLoadWt">
              <el-input v-model="scope.row.realLoadWt" placeholder="请输入实际装货量(吨)" />
            </MyFormItem>
          </template>
        </el-table-column>
        <el-table-column label="实际到货量(吨)" prop="realTransWt" align="center" min-width="100">
          <template slot-scope="scope">
            <MyFormItem :prop="`lsCargos.${scope.$index}.realTransWt`"
              :readonly="readonly" :rules="rules.realTransWt">
              <el-input v-model="scope.row.realTransWt" placeholder="请输入实际到货量(吨)" />
            </MyFormItem>
          </template>
        </el-table-column>
        <el-table-column label="计划发货时间" prop="departTime" align="center" min-width="136">
          <template slot-scope="scope">
            <MyFormItem :prop="`lsCargos.${scope.$index}.departTime`"
              :readonly="readonly" :rules="rules.departTime">
              <el-date-picker
                class="el-date-picker"
                v-model="scope.row.departTime"
                type="datetime" :clearable="false"
                value-format="yyyy-MM-dd HH:mm:ss"
                prefix-icon="n"
                placeholder="选择计划发货时间">
              </el-date-picker>
            </MyFormItem>
          </template>
        </el-table-column>
        <el-table-column label="计划到货时间" prop="arrivalTime" align="center" min-width="136">
          <template slot-scope="scope">
            <MyFormItem :prop="`lsCargos.${scope.$index}.arrivalTime`"
              :readonly="readonly" :rules="rules.arrivalTime">
              <el-date-picker
                class="el-date-picker"
                v-model="scope.row.arrivalTime"
                type="datetime" :clearable="false"
                value-format="yyyy-MM-dd HH:mm:ss"
                prefix-icon="n"
                placeholder="选择到货时间">
              </el-date-picker>
            </MyFormItem>
          </template>
        </el-table-column>
        <el-table-column label="实际发货时间" prop="realDepartTime" align="center" min-width="136">
          <template slot-scope="scope">
            <MyFormItem :prop="`lsCargos.${scope.$index}.realDepartTime`"
              :readonly="readonly" :rules="rules.realDepartTime">
              <el-date-picker
                class="el-date-picker"
                v-model="scope.row.realDepartTime"
                type="datetime" :clearable="false"
                value-format="yyyy-MM-dd HH:mm:ss"
                prefix-icon="n"
                placeholder="选择实际发货时间">
              </el-date-picker>
            </MyFormItem>
          </template>
        </el-table-column>
        <el-table-column label="实际到货时间" prop="realArrivalTime" align="center" min-width="136">
          <template slot-scope="scope">
            <MyFormItem :prop="`lsCargos.${scope.$index}.realArrivalTime`"
              :readonly="readonly" :rules="rules.realArrivalTime">
              <el-date-picker
                class="el-date-picker"
                v-model="scope.row.realArrivalTime"
                type="datetime" :clearable="false"
                value-format="yyyy-MM-dd HH:mm:ss"
                prefix-icon="n"
                placeholder="选择实际到货时间">
              </el-date-picker>
            </MyFormItem>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <!-- <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的运输计划数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
            @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog> -->
  </div>
</template>

<script>
import { getOrder, addOrder, updateOrder } from "@/api/tm/order";
import { saveTransCargo, addCargo, updateCargo } from "@/api/trans/cargo";
import CarriageCargoInput from '@/views/tm/components/CarriageCargoInput';
import { getToken } from "@/utils/auth";

const TransPlanEditType = {
  add: 'add',
  update: 'update',
};

export default {
  name: 'TransCargoPlanEdit',
  dicts: ['sys_curr_type'],
  components: {
    CarriageCargoInput
  },
  props: {
    plans: [Array],
    trans: [Array],
    readonly: Boolean,
    editType: {
      type: String,
      validator: (value) => {
        return Object.values(TransPlanEditType).includes(value);
      },
    },
  },
  computed: {
    TransPlanEditType() {
      return TransPlanEditType;
    }
  },
  data() {
    return {
      loading: false,
      // 运输计划
      plan: {},
      // 订单
      order: {},
      form: {},
      rules: {
        custId: [
          { required: true, message: "承运企业不能为空", trigger: "change" }
        ],
        cargoName: [
          { required: true, message: "货物名称不能为空", trigger: "blur" }
        ],
        cargoInfo: [
          { required: true, message: "货物名称不能为空", trigger: "blur" }
        ],
        orderNo: [
          { required: true, message: "订单号不能为空", trigger: "change" }
        ],
        loadWt: [
          { required: true, message: "预计装货量不能为空", trigger: "blur" }
        ],
        vehicleNumber: [
          { required: true, message: "车辆不能为空", trigger: "change" }
        ],
      },
      // 导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/jxc/cust/importData"
      },
      // 选择的货物
      selectCargos: [],
    }
  },
  created() {
    if (this.editType === TransPlanEditType.add) {
      this.plan = this.plans[0] || {};
      this.order = this.plan.order || {};
      this.form = this.defaultForm();
    } else {
      let cargos = this.getFilterList(this.trans) || [];
      this.order = cargos[0].order || {};
      this.form = this.defaultForm({
        lsCargos: cargos,
      });
    }
    
  },
  methods: {
    // 过滤出订单一样的数据
    getFilterList(list) {
      if (!list) {
        return [];
      }
      const tranData = {};
      list.forEach(item => {
        const order = item.order || {};
        if (!tranData[`${order.id}${order.orderNo}`]) {
          tranData[`${order.id}${order.orderNo}`] = [];
        }
        tranData[`${order.id}${order.orderNo}`].push(item);
      });
      let newList = [];
      Object.values(tranData).forEach(item => {
        if (item.length > newList.length) {
          newList = item;
        }
      });
      return newList;
    },
    // 添加货物
    addCargo() {
      this.form.lsCargos.push(this.defaultCargoForm());
      this.$refs.table.doLayout();
    },
    // 删除货物
    deleteCargo() {
      this.form.lsCargos = this.form.lsCargos.filter(item => {
        return this.selectCargos.indexOf(item) === -1;
      });
      if (this.$refs.table) {
        this.$refs.table.clearSelection();
      }
    },
    cargoChange(cargos, row) {
      const cargo = cargos[0] || {};
      row.cargoName = cargo.cargoInfo;
      row.cargoId = cargo.id;
    },
    // 货物选择
    cargoSelectionChange(sel) {
      this.selectCargos = sel || [];
    },
    // 货物合记
    getCargoSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        const property = column.property;
        if (!['loadWt', 'realLoadWt', 'realTransWt'].includes(property)) {
          return '';
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] += ' 吨';
        } else {
          sums[index] = '';
        }
      });

      return sums;
    },
    // 获取订单
    // getOrder(id) {
    //   this.loading = true;
    //   getOrder(id).then((res) => {
    //     this.loading = false;
    //     this.order = res.data || {};
    //   }).catch((err) => {
    //     this.loading = false;
    //   });
    // },
    // 默认表单
    defaultForm(data) {
      if (data) {
        if (!data.lsCargos) {
          data.lsCargos = [];
        }
        
        data.lsCargos = data.lsCargos.map(item => {
          return this.defaultCargoForm(item);
        });
      }
      
      return {
        orderId: this.order.id,
        orderNo: this.order.orderNo,
        transId: this.plan.id,
        lsCargos: [],
        ...data,
      };
    },
    // 货物默认表单
    defaultCargoForm(data) {
      return {
        cargoName: '',
        loadWt: '',
        realLoadWt: '',
        realTransWt: '',
        departTime: '',
        arrivalTime: '',
        realDepartTime: '',
        realArrivalTime: '',
        ...data,
      };
    },
    // 提交表单
    submitForm(type) {
      const params = {
        ...this.form,
        orderId: this.order.id,
        orderNo: this.order.orderNo,
        transId: this.plan.id,
      };
      
      this.$refs.form.validate((valid, rules) => {
        if (!valid) {
          this.$modal.formWarning(rules);
          return;
        }
        if (this.form.lsCargos.length === 0) {
          this.$modal.msgWarning("请添加运输货物计划");
          return;
        }
        const isAdd = this.editType === TransPlanEditType.add;
        saveTransCargo(params).then(response => {
          this.$modal.msgSuccess(isAdd ? "新增成功":"修改成功");
          this.$emit('saved', isAdd);
        });
      });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "货物运输计划导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      const fileName = `货物运输计划模板_${new Date().getTime()}.xlsx`;
      this.download(`jxc/cust/importTemplate`, {}, fileName);
    },

    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  }
}
</script>

<style scoped lang="scss">
.descriptions-edit {
  height: calc(100vh - 210px);
  overflow-y: auto;
  padding: 0 15px;
  ::v-deep .el-descriptions-item__label.is-bordered-label {
    padding: 5px !important;
    width: 100px;
  }
  ::v-deep .el-descriptions__header {
    margin-bottom: 10px;
  }
}
.go-and-come {
  display: flex;
  align-items: center;

  .el-descriptions {
    flex: 1;
  }
}

.vehicle-header {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  margin: 10px 0;
  margin-top: 15px;

  .el-button {
    margin-left: 10px;
  }
}
.vehicle-title {
    font-size: 17px;
    font-weight: 500;
    margin-right: 20px;
    color: #606266;
  }

.cargo-table {
  ::v-deep .el-table__cell {
    padding: 0px !important;

    .cell {
      padding: 2px !important;
      line-height: 18px;
    }

    .el-checkbox__label {
      padding-left: 4px;
    }
  }
  ::v-deep .el-input__inner {
    padding: 0 !important;
    text-align: center;
  }
}
.cargo-input {
  background-color: rgb(225, 243, 216);
  padding: 10px 0 20px 30px;
  .el-button {
    margin-right: 10px;
    margin-bottom: 5px;
  }
}
</style>