<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="TY"></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>
          <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="custName" :value="form.custName" :readonly="readonly">
              <CustInput width="100%" custType="0" :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="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>
        </div>
      <div class="go-and-come">
        <el-descriptions :column="1" direction="vertical" border>
          <el-descriptions-item>
            <template slot="label">发货人</template>
              <MyFormItem prop="dispatchUser" :value="form.dispatchUser" :readonly="readonly">
                <el-input v-model="form.dispatchUser" placeholder="请输入发货人" />
              </MyFormItem>
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">联系方式</template>
              <MyFormItem prop="dispatchMobile" :value="form.dispatchMobile" :readonly="readonly">
                <el-input v-model="form.dispatchMobile" placeholder="请输入联系方式" />
              </MyFormItem>
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">发货地址</template>
              <MyFormItem prop="dispatchPlaceDetail" :value="form.dispatchPlaceDetail" :readonly="readonly">
                <el-input v-model="form.dispatchPlaceDetail" placeholder="请输入发货地址" />
              </MyFormItem>
          </el-descriptions-item>
        </el-descriptions>
        <i class="el-icon-right" style="font-size: 22px;"></i>
        <el-descriptions :column="1" direction="vertical" border>
          <el-descriptions-item>
            <template slot="label">收货人</template>
              <MyFormItem prop="receiveUser" :value="form.receiveUser" :readonly="readonly">
                <el-input v-model="form.receiveUser" placeholder="请输入收货人" />
              </MyFormItem>
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">联系方式</template>
              <MyFormItem prop="receiveMobile" :value="form.receiveMobile" :readonly="readonly">
                <el-input v-model="form.receiveMobile" placeholder="请输入联系方式" />
              </MyFormItem>
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">收货地址</template>
              <MyFormItem prop="receivePlaceDetail" :value="form.receivePlaceDetail" :readonly="readonly">
                <el-input v-model="form.receivePlaceDetail" placeholder="请输入收货地址" />
              </MyFormItem>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <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.cargoList" :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="detailName" align="center">
            <template slot-scope="scope">
              <MyFormItem :prop="'cargoList.' + scope.$index + '.detailName'" :value="scope.row.detailName" :readonly="readonly" :rules="rules.detailName">
                <el-input v-model="scope.row.detailName" placeholder="请输入货物名称" />
              </MyFormItem>
            </template>
          </el-table-column>
          <el-table-column label="重量(吨)" prop="detailWeight" align="center">
            <template slot-scope="scope">
              <MyFormItem :prop="'cargoList.' + scope.$index + '.detailWeight'" :value="scope.row.detailWeight" :readonly="readonly" :rules="rules.detailWeight">
                <el-input v-model="scope.row.detailWeight" placeholder="请输入重量(吨)" />
              </MyFormItem>
            </template>
          </el-table-column>
          <el-table-column label="体积(m³)" prop="detailVol" align="center">
            <template slot-scope="scope">
              <MyFormItem :prop="'cargoList.' + scope.$index + '.detailVol'" :value="scope.row.detailVol" :readonly="readonly">
                <el-input v-model="scope.row.detailVol" placeholder="请输入体积(m³)" />
              </MyFormItem>
            </template>
          </el-table-column>
          <el-table-column label="件数" prop="detailNum" align="center">
            <template slot-scope="scope">
              <MyFormItem :prop="'cargoList.' + scope.$index + '.detailNum'" :value="scope.row.detailNum" :readonly="readonly">
                <el-input v-model="scope.row.detailNum" placeholder="请输入件数" />
              </MyFormItem>
            </template>
          </el-table-column>
          <el-table-column label="价值" prop="detailWorth" align="center">
            <template slot-scope="scope">
              <MyFormItem :prop="'cargoList.' + scope.$index + '.detailWorth'" :value="scope.row.detailWorth" :readonly="readonly">
                <el-input v-model="scope.row.detailWorth" placeholder="请输入价值" />
              </MyFormItem>
            </template>
          </el-table-column>
          <el-table-column label="运价" prop="freightRates" align="center">
            <template slot-scope="scope">
              <MyFormItem :prop="'cargoList.' + scope.$index + '.freightRates'" :value="scope.row.freightRates" :readonly="readonly">
                <el-input v-model="scope.row.freightRates" placeholder="请输入运价" />
              </MyFormItem>
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" align="center">
            <template slot-scope="scope">
              <MyFormItem :prop="'cargoList.' + 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-popconfirm
        v-if="form.status === '1'"
        v-hasPermi="['consign_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="$emit('cancel')">取 消</el-button>
    </div>
  </div>
</template>

<script>
import { getSource, addSource, updateSource, revokeOrder } from "@/api/cargo/source";
import CustInput from "@/views/tm/components/CustInput";
import { formatDateToDataStr } from '@/utils';

export default {
  name: 'ConsignOrderEdit',
  components: {
    CustInput,
  },
  dicts: ['sys_curr_type'],
  props: {
    bid: [String, Number, Array],
    readonly: Boolean,
  },
  data() {
    return {
      loading: false,
      form: this.defaultForm(),
      rules: {
        cargoInfo: [
          { required: true, message: "货物名称不能为空", trigger: "blur" }
        ],
        custName: [
          { required: true, message: "客户不能为空", trigger: "change" }
        ],
        // freightRates: [
        //   { required: true, message: "运价不能为空", trigger: "blur" }
        // ],
        currency: [
          { required: true, message: "币种不能为空", trigger: "change" }
        ],
        detailName: [
          { required: true, message: "货物名称不能为空", trigger: "blur" }
        ],
        orderNo: [
          { required: true, message: "订单号不能为空", trigger: "change" }
        ],
        detailWeight: [
          { required: true, message: "货物重量不能为空", trigger: "blur" }
        ],
        // dispatchUser: [
        //   { required: true, message: "发货人不能为空", trigger: "blur" }
        // ],
        // dispatchMobile: [
        //   { required: true, message: "发货人联系方式不能为空", trigger: "blur" }
        // ],
        // dispatchPlaceDetail: [
        //   { required: true, message: "发货地址不能为空", trigger: "blur" }
        // ],
        // receiveUser: [
        //   { required: true, message: "收货人不能为空", trigger: "blur" }
        // ],
        // receiveMobile: [
        //   { required: true, message: "收货人联系方式不能为空", trigger: "blur" }
        // ],
        // receivePlaceDetail: [
        //   { required: true, message: "收货地址不能为空", trigger: "blur" }
        // ],
      },
      // 选择的货物
      selectCargos: []
    }
  },
  computed: {
    orderReadonly() {
      return this.readonly || this.$validate.hasValue(this.form.id);
    },
  },
  watch: {
    bid: {
      immediate: true,
      handler(val) {
        this.getDetail();
      }
    },
  },
  methods: {
    // 添加货物
    addCargo() {
      this.form.cargoList.push(this.defaultCargo());
    },
    // 删除货物
    deleteCargo() {
      this.form.cargoList = this.form.cargoList.filter(item => {
        return this.selectCargos.indexOf(item) === -1;
      });
      this.$refs.table.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 (!['detailWeight', 'detailVol', 'detailNum', 'detailWorth'].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.selectCargos = [];
      if (!this.bid) {
        return;
      }
      this.loading = true;
      getSource(this.bid).then((res) => {
        this.loading = false;
        this.form = this.defaultForm(res.data);
      }).catch((err) => {
        this.loading = false;
      });
    },
    // 默认表单
    defaultForm(data) {
      if (data && data.cargoList) {
        data.cargoList = data.cargoList.map(item => {
          return this.defaultCargo(item);
        });
      }
      return {
        id: null,
        orderNo: null,
        cargoInfo: null,
        custId: null,
        custCode: null,
        custName: null,
        freightRates: null,
        currency: '142', //142 人民币
        orderDate: data && data.id ? '' : formatDateToDataStr(),
        status: '0',
        remark: null,
        cargoList: [],
        dispatchUser: null,
        dispatchMobile: null,
        dispatchPlaceDetail: null,
        receiveUser: null,
        receiveMobile: null,
        receivePlaceDetail: null,
        ...data,
      };
    },
    // 货物默认表单
    defaultCargo(data) {
      return {
        detailName: '',
        detailWeight: '',
        detailWorth: '',
        detailVol: '',
        detailNum: '',
        freightRates: '',
        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)) {
          updateSource(params).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.$emit('saved', false);
          });
        } else {
          addSource(params).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.$emit('saved', true);
          });
        }
      });
    }
  }
}
</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;
  }
}

.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;
  }
}
</style>