<template>
  <div>
    <el-empty v-if="!orderId || orderId == ''" description="未选中订单" />

    <div v-else>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
            v-if="editable">新增</el-button>
          <!-- <el-button type="primary" plain icon="el-icon-printer" size="mini" @click="handlePrint">打印</el-button> -->
          <el-button type="primary" plain icon="el-icon-refresh" size="mini" @click="getList">刷新</el-button>
        </el-col>
      </el-row>

      <el-table v-loading="loading" :data="orderItemList">
        <el-table-column label="产品类型" align="center" prop="productType" />
        <el-table-column label="成品宽度" align="center" prop="width" />
        <el-table-column label="成品厚度" align="center" prop="thickness" />
        <el-table-column label="成品规格" align="center" prop="finishedProductSpec" />
        <!-- <el-table-column label="原料规格" align="center" prop="rawMaterialSpec" /> -->
        <el-table-column label="宽度公差" align="center" prop="widthTolerance" />
        <el-table-column label="厚度公差" align="center" prop="thicknessTolerance" />
        
        <el-table-column label="材质" align="center" prop="material" />
        <el-table-column label="重量" align="center" prop="weight" />
        <el-table-column label="含税单价（元/吨）" align="center" prop="contractPrice" />
        <el-table-column label="含税总额" align="center">
          <template slot-scope="scope">             
            {{ scope.row.weight * scope.row.contractPrice }}
          </template>
        </el-table-column>
        <el-table-column label="无税单价（元/吨）" align="center" prop="itemAmount" />
        <el-table-column label="卷数" align="center" prop="productNum" />
        <el-table-column label="表面处理" align="center" prop="surfaceTreatment" />
        <el-table-column label="包装要求" align="center" prop="packagingReq" />
        <el-table-column label="切边要求" align="center" prop="edgeCuttingReq" />
        <el-table-column label="用途" align="center" prop="purpose" />

        
        <el-table-column label="特殊要求" align="center" prop="specialRequire" />
        
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="editable">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @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" />
    </div>

    <!-- 添加或修改正式订单明细对话框 -->
    <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="产品类型" prop="productType">
          <el-input v-model="form.productType" placeholder="请输入产品类型" />
        </el-form-item>
        <el-form-item label="成品规格" prop="finishedProductSpec">
          <el-input v-model="form.finishedProductSpec" placeholder="请输入成品规格" />
        </el-form-item>
        <el-form-item label="成品宽度" prop="width">
          <el-input v-model="form.width" placeholder="请输入宽度" />
        </el-form-item>
        <el-form-item label="成品厚度" prop="thickness">
          <el-input v-model="form.thickness" placeholder="请输入厚度" />
        </el-form-item>
        <el-form-item label="宽度公差" prop="widthTolerance">
          <el-input v-model="form.widthTolerance" placeholder="请输入宽度公差" />
        </el-form-item>
        <el-form-item label="厚度公差" prop="thicknessTolerance">
          <el-input v-model="form.thicknessTolerance" placeholder="请输入厚度公差" />
        </el-form-item>
        <el-form-item label="材质" prop="material">
          <el-input v-model="form.material" placeholder="请输入材质" />
        </el-form-item>
        <el-form-item label="重量" prop="weight">
          <el-input v-model="form.weight" placeholder="请输入重量" />
        </el-form-item>
        <el-form-item label="含税单价（元/吨）" prop="contractPrice">
          <el-input v-model="form.contractPrice" placeholder="请输入含税单价" />
        </el-form-item>
        <el-form-item label="无税单价（元/吨）" prop="itemAmount">
          <el-input v-model="form.itemAmount" placeholder="请输入无税单价" />
        </el-form-item>
        
        <el-form-item label="卷数" prop="productNum">
          <el-input v-model="form.productNum" placeholder="请输入卷数" />
        </el-form-item>
        <el-form-item label="表面处理" prop="surfaceTreatment">
          <el-input v-model="form.surfaceTreatment" placeholder="请输入表面处理" />
        </el-form-item>
        <el-form-item label="包装要求" prop="packagingReq">
          <el-input v-model="form.packagingReq" placeholder="请输入包装要求" />
        </el-form-item>
        <el-form-item label="切边要求" prop="edgeCuttingReq">
          <el-input v-model="form.edgeCuttingReq" placeholder="请输入切边要求" />
        </el-form-item>
        <el-form-item label="用途" prop="purpose">
          <el-input v-model="form.purpose" placeholder="请输入用途" />
        </el-form-item>

        <el-form-item label="特殊要求" prop="specialRequire">
          <el-input v-model="form.specialRequire" placeholder="请输入特殊要求" />
        </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="打印结算单" :loading="orderLoading" :visible.sync="orderOpen" width="1000px" append-to-body>
      <OrderPrinter ref="printer" :orderContent="orderContent" :orderList="orderItemList" />

      <el-button slot="footer">
        <el-button :loading="buttonLoading" @click="printOrder">打印</el-button>
      </el-button>
    </el-dialog>
  </div>
</template>

<script>
import { listOrderItem, getOrderItem } from "@/api/crm/orderItem";
import { actions, ORDER_ACTIONS } from "../js/actions";
import { getOrder } from "@/api/crm/order";
import OrderPrinter from "./OrderPrinter.vue";

export default {
  name: "OrderItem",
  props: {
    orderId: {
      required: true
    },
    editable: {
      type: Boolean,
      default: true
    },
  },
  components: {
    OrderPrinter
  },
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 正式订单明细表格数据
      orderItemList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderId: undefined,
        productType: undefined,
        specRequire: undefined,
        productNum: undefined,
        specialRequire: undefined,
        itemAmount: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        productType: [
          { required: true, message: "请输入产品类型", trigger: "blur" }
        ],
        // productNum: [
        //   { required: true, message: "请输入产品数量", trigger: "blur" }
        // ],
        // rawMaterialSpec: [
        //   { required: true, message: "请输入原料规格", trigger: "blur" }
        // ],
        // finishedProductSpec: [
        //   { required: true, message: "请输入成品规格", trigger: "blur" }
        // ],
        // 重量和合同定价不能为空，且必须是数字，最多两位小数
        // weight: [
        //   { required: true, message: "请输入重量", trigger: "blur" },
        //   // 必须是数字，最多两位小数，使用自定义的校验规则
        //   {
        //     validator: (rule, value, callback) => {
        //       if (!/^\d+(\.\d{1,2,3})?$/.test(value)) {
        //         callback(new Error("请输入最多三位小数的数字"));
        //       } else {
        //         callback();
        //       }
        //     }, trigger: "change"
        //   }
        // ],
        contractPrice: [
          { required: true, message: "请输入合同定价", trigger: "blur" },
          // 必须是数字，最多两位小数，使用自定义的校验规则
          {
            validator: (rule, value, callback) => {
              if (!/^\d+(\.\d{1,2,3})?$/.test(value)) {
                callback(new Error("请输入最多三位小数的数字"));
              } else {
                callback();
              }
            }, trigger: "change"
          }
        ],
      },
      orderContent: {},
      orderLoading: false,
      orderOpen: false,
    };
  },
  watch: {
    orderId: {
      handler(newVal, oldVal) {
        // if (newVal !== oldVal) {
        this.queryParams.orderId = newVal;
        this.getList();
        // }
      },
      immediate: true
    }
  },
  methods: {
    /** 查询正式订单明细列表 */
    getList() {
      if (!this.queryParams.orderId) {
        this.orderItemList = [];
        this.total = 0;
        return;
      }
      this.loading = true;
      listOrderItem(this.queryParams).then(response => {
        this.orderItemList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        itemId: undefined,
        orderId: this.orderId,
        productType: undefined,
        rawMaterialSpec: undefined,
        finishedProductSpec: undefined,
        material: undefined,
        grade: undefined,
        weight: undefined,
        contractPrice: undefined,
        customizer: undefined,
        shipper: undefined,
        productionBatch: undefined,
        productNum: undefined,
        specialRequire: undefined,
        itemAmount: undefined,
        remark: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 打印按钮操作 */
    handlePrint() {
      // 正在准备打印内容
      this.orderLoading = true;
      this.orderOpen = true;
      getOrder(this.orderId).then(response => {
        this.orderContent = response.data;
        this.orderLoading = false;
      });
    },
    printOrder() {
      this.$refs["printer"].print();
      this.orderOpen = false;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.itemId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单明细";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const itemId = row.itemId || this.ids
      getOrderItem(itemId).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改订单明细";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.itemId != null) {
            actions[ORDER_ACTIONS.updateOrderdetail].handler(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            actions[ORDER_ACTIONS.createOrderdetail].handler(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const itemIds = row.itemId || this.ids;
      const orderId = this.orderId;
      this.$modal.confirm('是否确认删除正式订单明细编号为"' + itemIds + '"的数据项？').then(() => {
        this.loading = true;
        return actions[ORDER_ACTIONS.deleteOrderDetail].handler(itemIds, orderId)
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('crm/orderItem/export', {
        ...this.queryParams
      }, `orderItem_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
