<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="96px">
      <el-form-item label="采购订单编号" prop="poNo">
        <el-input
          v-model="queryParams.poNo"
          placeholder="请输入采购订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料编码" prop="materialCode">
        <el-input
          v-model="queryParams.materialCode"
          placeholder="请输入物料编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料名称" prop="materialName">
        <el-input
          v-model="queryParams.materialName"
          placeholder="请输入物料名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="物料规格" prop="materialSpec">
        <el-input
          v-model="queryParams.materialSpec"
          placeholder="请输入物料规格"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="规格参数" prop="specificationParameter">
        <el-input
          v-model="queryParams.specificationParameter"
          placeholder="请输入规格参数"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="常备物料" prop="alwaysFlag">
        <el-select v-model="queryParams.alwaysFlag" placeholder="请选择常备物料标识" clearable>
          <el-option
            v-for="dict in dict.type.mes_material_bind_flag"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>


      <el-form-item label="订单状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable>
          <el-option
            v-for="dict in dict.type.mes_purchase_order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
        >采购申请单导入
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="purchaseOrderList" @selection-change="handleSelectionChange">
      <el-table-column label="采购订单编号" align="center" prop="poNo"/>
      <el-table-column label="物料编码" align="center" prop="materialCode"/>
      <el-table-column label="物料名称" align="center" prop="materialName"/>
      <el-table-column label="物料规格" align="center" prop="materialSpec"/>
      <el-table-column label="规格参数" align="center" prop="specificationParameter" width="200"/>
      <el-table-column label="常备物料" align="center" prop="alwaysFlag">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_material_bind_flag" :value="scope.row.alwaysFlag"/>
        </template>
      </el-table-column>

      <el-table-column label="订单数量" align="center" prop="orderAmount"/>
      <el-table-column label="完成数量" align="center" prop="completeAmount"/>
      <el-table-column label="订单状态" align="center" prop="orderStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_purchase_order_status" :value="scope.row.orderStatus"/>
        </template>
      </el-table-column>

      <el-table-column label="开始日期" align="center" prop="beginDate">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.beginDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="结束日期" align="center" prop="endDate">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="计划交货日期" align="center" prop="planDeliveryDate">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.planDeliveryDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="审核日期" align="center" prop="approveDate">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.approveDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="ERP最后修改日期" align="center" prop="erpModifyDate">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.erpModifyDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>


      <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"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['mes:purchaseOrder:bind']"
            v-if="scope.row.alwaysFlag === ALWAYS_FLAG.NO"
          >绑定
          </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="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 {
  listPurchaseOrder,
  getPurchaseOrder,
  delPurchaseOrder,
  addPurchaseOrder,
  updatePurchaseOrder
} from "@/api/mes/purchaseOrder";
import router from "@/router";
import {getToken} from "@/utils/auth";

export default {
  name: "PurchaseOrder",
  dicts: ['active_flag', 'mes_purchase_order_status', 'document_status', 'mes_safe_flag','mes_material_bind_flag'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedMesOrderBind: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购订单信息表格数据
      purchaseOrderList: [],
      // 采购销售订单绑定信息;销售订单绑定采购订单明细信息表格数据
      mesOrderBindList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        erpId: null,
        fentryId: null,
        poNo: null,
        documentStatus: null,
        materialId: null,
        materialCode: null,
        materialName: null,
        materialSpec: null,
        specificationParameter: null,
        alwaysFlag: null,
        orderAmount: null,
        completeAmount: null,
        approveDate: null,
        erpModifyDate: null,
        planDeliveryDate: null,
        beginDate: null,
        endDate: null,
        orderStatus: null,
        completeDate: null,
        isFlag: null,
        unitId: null,
        stockUnitId: null,
        priceUnitId: null,
        auxPropId: null,
        srcBillNo: null,
        purchaseOrgId: null,
        tondBase: null,
        supplierId: null,
      },
      // 表单参数
      form: {},
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/mes/import/purchaseRequisitionImportData"
      },
      // 表单校验
      rules: {
        materialCode: [
          {required: true, message: "物料编码;对应FMaterialId.FNumber不能为空", trigger: "blur"}
        ],
        orderAmount: [
          {required: true, message: "订单计划数量;对应FQty不能为空", trigger: "blur"}
        ],
        isFlag: [
          {required: true, message: "是否标识：1-是；0-否不能为空", trigger: "change"}
        ],
      },

      ALWAYS_FLAG: {
        YES: "1",
        NO: "0"
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询采购订单信息列表 */
    getList() {
      this.loading = true;
      listPurchaseOrder(this.queryParams).then(response => {
        this.purchaseOrderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        purchaseOrderId: null,
        erpId: null,
        fentryId: null,
        poNo: null,
        documentStatus: null,
        materialId: null,
        materialCode: null,
        materialName: null,
        orderAmount: null,
        completeAmount: null,
        approveDate: null,
        erpModifyDate: null,
        planDeliveryDate: null,
        beginDate: null,
        endDate: null,
        orderStatus: null,
        completeDate: null,
        isFlag: null,
        unitId: null,
        stockUnitId: null,
        priceUnitId: null,
        auxPropId: null,
        srcBillNo: null,
        purchaseOrgId: null,
        tondBase: null,
        supplierId: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.mesOrderBindList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.purchaseOrderId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/user/importTemplate', {}, `template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    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();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加采购订单信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const purchaseOrderId = row.purchaseOrderId;
      const materialSpec = row.materialSpec;
      const poNo = row.poNo;
      const params = {queryParams: this.queryParams ,t: Date.now()};

      this.$tab.openPage("订单绑定[" + poNo + "]", '/mes/purchase-order/bind/' + purchaseOrderId +'/'+materialSpec, params);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.mesOrderBindList = this.mesOrderBindList;
          if (this.form.purchaseOrderId != null) {
            updatePurchaseOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPurchaseOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const purchaseOrderIds = row.purchaseOrderId || this.ids;
      this.$modal.confirm('是否确认删除采购订单信息编号为"' + purchaseOrderIds + '"的数据项？').then(function () {
        return delPurchaseOrder(purchaseOrderIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 采购销售订单绑定信息;销售订单绑定采购订单明细信息序号 */
    rowMesOrderBindIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 采购销售订单绑定信息;销售订单绑定采购订单明细信息添加按钮操作 */
    handleAddMesOrderBind() {
      let obj = {};
      obj.safeFlag = "";
      obj.saleOrderId = "";
      obj.productId = "";
      obj.materialId = this.form.materialId;
      obj.bindAmount = "";
      obj.remark = "";
      this.mesOrderBindList.push(obj);
    },
    /** 采购销售订单绑定信息;销售订单绑定采购订单明细信息删除按钮操作 */
    handleDeleteMesOrderBind() {
      if (this.checkedMesOrderBind.length == 0) {
        this.$modal.msgError("请先选择要删除的采购销售订单绑定信息;销售订单绑定采购订单明细信息数据");
      } else {
        const mesOrderBindList = this.mesOrderBindList;
        const checkedMesOrderBind = this.checkedMesOrderBind;
        this.mesOrderBindList = mesOrderBindList.filter(function (item) {
          return checkedMesOrderBind.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleMesOrderBindSelectionChange(selection) {
      this.checkedMesOrderBind = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/purchaseOrder/export', {
        ...this.queryParams
      }, `purchaseOrder_${new Date().getTime()}.xlsx`)
    },


    handleSaleOrderAdd() {

    }

  }
};
</script>
