<template>
  <div class="descriptions-edit">
    <el-form ref="form" v-loading="loading" :model="form" :rules="rules" :show-message="false" v-enterboard>
      <el-descriptions :column="2" border>
        <el-descriptions-item>
          <template slot="label">订单号
            <rq />
          </template>
          <MyFormItem prop="orderNo" :value="form.orderNo" :readonly="orderReadonly">
            <BillNumberInput v-model="form.orderNo" title="订单编号" type="CY"></BillNumberInput>
          </MyFormItem>
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">状态</template>
          <el-tag :type="form.status == '1' ? 'success' : ''">{{ form.status == 1 ? '已完成' : '未完成'
            }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item v-if="!orderReadonly || !!form.sourceNo">
          <template slot="label">关联托运订单</template>
          <MyFormItem prop="sourceNo" :value="form.sourceNo" :readonly="orderReadonly">
            <OrderInput width="100%" orderType="0" :value="form.sourceNo" :readonly="readonly" :label="form.sourceNo"
              @change="handleUnionOrderChange"></OrderInput>
          </MyFormItem>
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">货物名称
            <rq />
          </template>
          <MyFormItem prop="cargoInfo" :value="form.cargoInfo" :readonly="readonly">
            <el-input v-model="form.cargoInfo" placeholder="请输入货物名称" />
          </MyFormItem>
        </el-descriptions-item>
        <el-descriptions-item>

          <template slot="label">承运企业
            <rq />
          </template>
          <MyFormItem prop="custId" :value="form.custName" :readonly="readonly">
            <CustInput width="100%" custType="1" :value="form.custId" :readonly="readonly" :label="form.custName"
              @change="handleCustChange" />
          </MyFormItem>
        </el-descriptions-item>
        <el-descriptions-item>

          <template slot="label">承运价</template>
          <MyFormItem prop="freightRates" :value="form.freightRates" :readonly="readonly">
            <el-input v-model="form.freightRates" placeholder="请输入托运价" />
          </MyFormItem>
        </el-descriptions-item>
        <el-descriptions-item>

          <template slot="label">币种</template>
          <MyFormItem prop="currency" :value="form.currency" :readonly="readonly">
            <template slot="readonly">
              <dict-tag :options="dict.type.sys_curr_type" :value="form.currency" />
            </template>
            <el-select v-model="form.currency" placeholder="请选择币种" clearable>
              <el-option v-for="dict in dict.type.sys_curr_type" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </MyFormItem>
        </el-descriptions-item>
        <!-- <el-descriptions-item>

          <template slot="label">状态</template>
          <MyFormItem prop="status" :value="form.status" :readonly="readonly">
            <el-select v-model="form.status" placeholder="请选择订单状态" clearable>
              <el-option v-for="dict in dict.type.order_status" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </MyFormItem>
        </el-descriptions-item> -->
        <el-descriptions-item>
          <template slot="label">订单时间</template>
            <MyFormItem prop="orderDate" :value="form.orderDate" :readonly="readonly">
              <el-date-picker class="el-date-picker" v-model="form.orderDate" value-format="yyyy-MM-dd" type="date" placeholder="请选择订单时间">
              </el-date-picker>
            </MyFormItem>
        </el-descriptions-item>
        <el-descriptions-item>

          <template slot="label">备注</template>
          <MyFormItem prop="remark" :value="form.remark" :readonly="readonly">
            <el-input v-model="form.remark" placeholder="请输入备注" />
          </MyFormItem>
        </el-descriptions-item>
      </el-descriptions>
      <div class="cargo-header">
        <span class="cargo-title">货物明细</span>
        <el-button v-if="!readonly" icon="el-icon-plus" type="primary" size="small" plain @click="addCargo">新增货物</el-button>
        <el-popconfirm
          title="确定删除选中的货物吗？"
          @confirm="deleteCargo"
        >
          <el-button slot="reference" v-if="!readonly" icon="el-icon-delete" :disabled="selectCargos.length === 0" type="warning" size="small" plain >删除货物</el-button>
        </el-popconfirm>
      </div>
      <el-table v-if="!loading" class="cargo-table" highlight-current-row ref="table" max-height="400px" :data="form.orderCargoList" :summary-method="getCargoSummaries"
          show-summary @selection-change="cargoSelectionChange" border stripe>
          <el-table-column v-if="!readonly" type="selection" width="30" align="center" />
          <el-table-column type="index" width="30" align="center" />
          <el-table-column label="货物名称" prop="cargoInfo" align="center">
            <template slot-scope="scope">
              <MyFormItem :prop="'orderCargoList.' + scope.$index + '.cargoInfo'" :value="scope.row.cargoInfo" :readonly="readonly" :rules="rules.cargoInfo">
                <el-input v-model="scope.row.cargoInfo" placeholder="请输入货物名称" />
              </MyFormItem>
            </template>
          </el-table-column>
          <el-table-column label="重量(吨)" prop="cargoWeight" align="center">
            <template slot-scope="scope">
              <MyFormItem :prop="'orderCargoList.' + scope.$index + '.cargoWeight'" :value="scope.row.cargoWeight" :readonly="readonly" :rules="rules.cargoWeight">
                <el-input v-model="scope.row.cargoWeight" placeholder="请输入重量(吨)" />
              </MyFormItem>
            </template>
          </el-table-column>
          <el-table-column label="体积(m³)" prop="cargoVol" align="center">
            <template slot-scope="scope">
              <MyFormItem :prop="'orderCargoList.' + scope.$index + '.cargoVol'" :value="scope.row.cargoVol" :readonly="readonly">
                <el-input v-model="scope.row.cargoVol" placeholder="请输入体积(m³)" />
              </MyFormItem>
            </template>
          </el-table-column>
          <el-table-column label="件数" prop="cargoNum" align="center">
            <template slot-scope="scope">
              <MyFormItem :prop="'orderCargoList.' + scope.$index + '.cargoNum'" :value="scope.row.cargoNum" :readonly="readonly">
                <el-input v-model="scope.row.cargoNum" placeholder="请输入件数" />
              </MyFormItem>
            </template>
          </el-table-column>
          <el-table-column label="价值" prop="cargoWorth" align="center">
            <template slot-scope="scope">
              <MyFormItem :prop="'orderCargoList.' + scope.$index + '.cargoWorth'" :value="scope.row.cargoWorth" :readonly="readonly">
                <el-input v-model="scope.row.cargoWorth" placeholder="请输入价值" />
              </MyFormItem>
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" align="center">
            <template slot-scope="scope">
              <MyFormItem :prop="'orderCargoList.' + scope.$index + '.remark'" :value="scope.row.remark" :readonly="readonly">
                <el-input v-model="scope.row.remark" placeholder="请输入备注" />
              </MyFormItem>
            </template>
          </el-table-column>
      </el-table>
    </el-form>
    <div class="trans-footer">
      <el-button type="primary" style="margin-right: 10px;" @click="submitForm('trans')" v-if="showSaveGoPlan" plain>保存并去添加运输计划</el-button>
      <el-button type="primary" style="margin-right: 10px;" @click="goTransPlan" v-else plain>运输计划</el-button>
      <el-popconfirm
        v-if="form.status === '1'"
        v-hasPermi="['carriage_order:finished:edit']"
        title="确定撤销为未完成吗？"
        @confirm="submitForm('recall')"
        >
        <el-button slot="reference" style="margin-right: 10px;" type="success" plain>撤销订单</el-button>
      </el-popconfirm>
      <el-popconfirm
        v-if="!readonly"
        title="确定完成订单吗？"
        @confirm="submitForm('submit')"
        >
        <el-button slot="reference" style="margin-right: 10px;" type="success" plain>完成订单</el-button>
      </el-popconfirm>
      <el-button type="primary" @click="submitForm()" v-if="!readonly">保 存</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>

<script>
import { getOrder, addOrder, updateOrder, revokeOrder } from "@/api/tm/order";
import { listDetail } from "@/api/cargo/detail";
import CustInput from "@/views/tm/components/CustInput";
import DriverInput from "@/views/tm/components/DriverInput";
import VehicleInput from '@/views/tm/components/VehicleInput';
import OrderInput from '@/views/tm/components/OrderInput';
import { getToken } from "@/utils/auth";

export default {
  name: 'CarriageOrderEdit',
  components: {
    CustInput,
    DriverInput,
    VehicleInput,
    OrderInput
  },
  dicts: ['sys_curr_type'],
  props: {
    bid: [String, Number, Array],
    readonly: Boolean,
  },
  data() {
    return {
      loading: false,
      form: this.defaultForm(),
      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" }
        ],
        cargoWt: [
          { 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"
      },
      // 选择的车辆
      selectVehicles: [],
      // 选择的货物
      selectCargos: [],
    }
  },
  computed: {
    orderReadonly() {
      return this.readonly || this.$validate.hasValue(this.form.id);
    },
    showSaveGoPlan() {
      return !this.$validate.hasValue(this.form.id);
    }
  },
  watch: {
    bid: {
      immediate: true,
      handler(val) {
        this.getDetail();
      }
    },
  },
  methods: {
    // 订单选择
    handleUnionOrderChange(orders) {
      const order = orders[0] || {};
      
      listDetail({ cargoId: order.id }).then(res => {
        const list = res.data || [];
        this.form.orderCargoList.push(...list.map(item => {
          return {
            cargoInfo: item.detailName,
            cargoWeight: item.detailWeight,
            cargoVol: item.detailVol,
            cargoNum: item.detailNum,
            cargoWorth: item.detailWorth,
            remark: item.remark,
          }
        }));
        this.form.sourceId = order.id;
        this.form.sourceNo = order.orderNo;
      });
    },
    // 添加货物
    addCargo() {
      if (!this.form.orderCargoList) {
        this.form.orderCargoList = [];
      }
      this.form.orderCargoList.push(this.defaultCargoForm());
      this.$refs.table.doLayout();
    },
    // 删除货物
    deleteCargo() {
      this.form.orderCargoList = this.form.orderCargoList.filter(item => {
        return this.selectCargos.indexOf(item) === -1;
      });
      if (this.$refs['cargo-table' + index]) {
        this.$refs['cargo-table' + index].clearSelection();
      }
    },
    // 修改客户
    handleCustChange(custs) {
      const cust = custs.length > 0 ? custs[0] : {};
      this.form.custId = cust.id;
      this.form.custCode = cust.custCode;
      this.form.custName = cust.custName;
    },
    // 货物选择
    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 (!['cargoWeight', 'cargoVol', 'cargoNum', 'cargoWorth'].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;
    },
    // 获取详情
    getDetail() {
      this.form = this.defaultForm();
      this.resetForm("form");
      this.selectVehicles = [];
      if (!this.bid) {
        return;
      }
      this.loading = true;
      getOrder(this.bid).then((res) => {
        this.loading = false;
        this.form = this.defaultForm(res.data);
      }).catch((err) => {
        this.loading = false;
      });
    },
    // 默认表单
    defaultForm(data) {
      if (data) {
        if (!data.orderCargoList) {
          data.orderCargoList = [];
        }
        
        data.orderCargoList = data.orderCargoList.map(item => {
          return this.defaultCargoForm(item);
        });
      }
      
      return {
        orderNo: null,
        sourceId: null, // 关联订单ID
        sourceNo: null, // 关联订单号
        cargoInfo: null,
        custId: null,
        custCode: null,
        custName: null,
        freightRates: null,
        currency: '142', //142 人民币
        orderDate: null,
        status: '0',
        remark: null,
        orderCargoList: [],
        ...data,
      };
    },
    // 货物默认表单
    defaultCargoForm(data) {
      return {
        cargoInfo: '',
        cargoWeight: '',
        cargoVol: '',
        cargoNum: '',
        cargoWorth: '',
        remark: '',
        ...data,
      };
    },
    // 提交表单
    submitForm(type) {
      const params = {
        ...this.form
      }
      if (type === 'submit') {
        params.status = '1';
      } else if (type === 'recall') {
        revokeOrder({id: this.form.id}).then(res => {
          this.$modal.msgSuccess("撤销成功");
          this.$emit('saved', false);
        });
        return;
      }
      this.$refs.form.validate((valid, rules) => {
        if (!valid) {
          this.$modal.formWarning(rules);
          return;
        }
        if (this.$validate.hasValue(this.form.id)) {
          updateOrder(params).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.$emit('saved', false);
          });
        } else {
          addOrder(params).then(response => {
            this.$modal.msgSuccess("新增成功");
            if (type === 'trans') {
              this.goTransPlan();
            }
            this.$emit('saved', true);
          });
        }
      });
    },
    // 去运输计划
    goTransPlan() {
      this.$router.push({ path: '/tm/carriage_order/plan?orderNo=' + this.form.orderNo });
      this.cancel();
    },
    cancel() {
      this.$emit('cancel');
    }
  }
}
</script>

<style scoped lang="scss">
.descriptions-edit {
  height: calc(100vh - 210px);
  overflow-y: auto;
  padding: 0 15px 80px;
}

.trans-footer {
  position: absolute;
  bottom: 5px;
  right: 30px;
  z-index: 100;
}

.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;

  .vehicle-title {
    font-size: 17px;
    font-weight: 500;
    margin-right: 20px;
  }

  .el-button {
    margin-left: 10px;
  }
}

.cargo-header {
  display: flex;
  align-items: center;
  margin: 10px 0;

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


.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>