<template>
  <div>
    <!-- 订单信息展示区域 -->
    <el-descriptions title="订单信息" class="margin-top mb8" :column="4" size="medium" border v-if="orderInfo">
      <el-descriptions-item>
        <template slot="label">
          订单编号
        </template>
        {{ orderInfo.orderCode }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          订单状态
        </template>
        <dict-tag :options="dict.type.order_status" :value="orderInfo.orderStatus"/>
      </el-descriptions-item>
    </el-descriptions>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          :disabled="!canEdit"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single || !canEdit"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple || !canEdit"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="orderDetailList">
      <el-table-column label="产品" align="center">
        <template slot-scope="scope">
          <ProductInfo :product-id="scope.row.productId">
            <template #default="{ product }">
              {{ product.productName }}<span v-if="product.productCode">({{ product.productCode }})</span>
            </template>
          </ProductInfo>
        </template>
      </el-table-column>
      <el-table-column label="BOM" align="center">
        <template slot-scope="scope">
          <BomInfoMini item-type="product" :item-id="scope.row.productId" />
        </template>
      </el-table-column>
      <el-table-column label="产品数量" align="center" prop="quantity" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="含税单价" align="center" prop="taxPrice" />
      <el-table-column label="无税单价" align="center" prop="noTaxPrice" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            :disabled="!canEdit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="handleSpec(scope.row)"
          >产品规范</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            :disabled="!canEdit"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单明细对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="订单ID" prop="orderId">
          <el-input v-model="form.orderId" placeholder="请输入订单ID" :disabled="true" />
        </el-form-item> -->
        <el-form-item label="产品" prop="productId">
          <ProductSelect :can-add="true" v-model="form.productId" placeholder="请选择产品" @change="onProductChange" />
        </el-form-item>
        <el-form-item label="产品数量" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入产品数量" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" placeholder="单位" :disabled="true" />
        </el-form-item>
        <el-form-item label="含税单价" prop="taxPrice">
          <el-input-number :controls=false controls-position="right" v-model="form.taxPrice" placeholder="请输入含税单价" />
        </el-form-item>
        <el-form-item label="无税单价" prop="noTaxPrice">
          <el-input-number :controls=false controls-position="right" v-model="form.noTaxPrice" placeholder="请输入无税单价" :min="0" :max="form.taxPrice" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="产品规范" :visible.sync="specDialogVisible" width="500px" append-to-body>
      <ProductSpec v-if="form.groupId" :groupId="form.groupId" :readonly="!canEdit"/>
      <div v-else-if="canEdit">
        <el-select placeholder="请选择产品规范" @change="handleChangeSpec">
          <el-option v-for="item in productSpecList" :key="item.groupId" :label="item.specName" :value="item.groupId" />

          <template #empty>
            <el-button type="primary" @click="handleAddSpec">新增产品规范</el-button>
          </template>
        </el-select>
      </div>
      <div v-else>
        暂无产品规范
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOrderDetail, getOrderDetail, delOrderDetail, addOrderDetail, updateOrderDetail } from "@/api/wms/orderDetail";
import { listProductSpecGroup } from "@/api/work/productSpecGroup";
import { getOrder } from "@/api/wms/order";
import ProductSelect from '@/components/KLPService/ProductSelect';
import { EOrderStatus } from "@/utils/enums";
import { ProductInfo } from '@/components/KLPService';
import BomInfoMini from '@/components/KLPService/Renderer/BomInfoMini.vue';
import ProductSpec from './spec.vue';

export default {
  name: "OrderDetailPanel",
  dicts: ['order_status'],
  props: {
    orderId: {
      type: [String, Number],
      required: true
    }
  },
  components: {
    ProductSelect,
    ProductInfo,
    BomInfoMini,
    ProductSpec
  },
  data() {
    return {
      buttonLoading: false,
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      orderDetailList: [],
      orderInfo: null, // 订单信息
      title: "",
      open: false,
      // 订单状态枚举
      EOrderStatus,
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        orderId: this.orderId,
        productId: undefined,
        quantity: undefined,
        unit: undefined,
      },
      form: {
        orderId: this.orderId
      },
      rules: {
        orderId: [
          { required: true, message: "订单ID不能为空", trigger: "blur" }
        ],
        productId: [
          { required: true, message: "产品ID不能为空", trigger: "blur" }
        ],
        quantity: [
          { required: true, message: "产品数量不能为空", trigger: "blur" },
          { pattern: /^[1-9]\d*$/, message: "产品数量必须为正整数", trigger: "blur" }
        ],
        unit: [
          { required: true, message: "单位不能为空", trigger: "blur" }
        ],
      },
      specDialogVisible: false,
      productSpecList: [],
    };
  },
  computed: {
    // 是否可以编辑（订单状态为新建时才能编辑）
    canEdit() {
      return this.orderInfo && this.orderInfo.orderStatus === EOrderStatus.NEW;
    }
  },
  watch: {
    orderId(newVal) {
      this.queryParams.orderId = newVal;
      this.form.orderId = newVal;
      this.getOrderInfo();
      this.getList();
    }
  },
  created() {
    this.getOrderInfo();
    listProductSpecGroup().then(response => {
      this.productSpecList = response.rows;
    });
    this.getList();
  },
  methods: {
    // 获取订单信息
    getOrderInfo() {
      if (this.orderId) {
        getOrder(this.orderId).then(response => {
          this.orderInfo = response.data;
        }).catch(() => {
          this.orderInfo = null;
        });
      }
    },
    getList() {
      this.loading = true;
      listOrderDetail(this.queryParams).then(response => {
        this.orderDetailList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        detailId: undefined,
        orderId: this.orderId,
        productId: undefined,
        quantity: undefined,
        taxPrice: undefined,
        noTaxPrice: undefined,
        unit: undefined,
        remark: undefined,
        delFlag: undefined,
        createTime: undefined,
        createBy: undefined,
        updateTime: undefined,
        updateBy: undefined,
      };
      this.resetForm && this.resetForm("form");
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.detailId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleAdd() {
      if (!this.canEdit) {
        this.$modal && this.$modal.msgError("当前订单状态不允许新增明细");
        return;
      }
      this.reset();
      this.open = true;
      this.title = "添加订单明细";
    },
    handleUpdate(row) {
      if (!this.canEdit) {
        this.$modal && this.$modal.msgError("当前订单状态不允许修改明细");
        return;
      }
      this.loading = true;
      this.reset();
      const detailId = row.detailId || this.ids
      getOrderDetail(detailId).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改订单明细";
      });
    },
    onProductChange(product) {
      if (product) {
        this.form.unit = product.unit;
      } else {
        this.form.unit = undefined;
      }
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.detailId != null) {
            updateOrderDetail(this.form).then(response => {
              this.$modal && this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addOrderDetail(this.form).then(response => {
              this.$modal && this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    handleDelete(row) {
      if (!this.canEdit) {
        this.$modal && this.$modal.msgError("当前订单状态不允许删除明细");
        return;
      }
      const detailIds = row.detailId || this.ids;
      this.$modal && this.$modal.confirm('是否确认删除订单明细编号为"' + detailIds + '"的数据项？').then(() => {
        this.loading = true;
        return delOrderDetail(detailIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal && this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    handleExport() {
      this.download && this.download('wms/orderDetail/export', {
        ...this.queryParams
      }, `orderDetail_${new Date().getTime()}.xlsx`)
    },
    handleSpec(row) {
      this.specDialogVisible = true;
      this.form = row;
    },
    handleChangeSpec(groupId) {
      // 确认更换
      this.$modal && this.$modal.confirm('是否确认更换产品规范？').then(() => {
        this.form.groupId = groupId;
        this.submitForm();
      });
    },
    handleAddSpec() {
      this.$router.push({
        path: '/production/pspec',
      });
    }
  },
};
</script>

<style scoped>
</style>
