<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="任务编号" prop="taskCode">
        <el-input
          v-model="queryParams.taskCode"
          placeholder="请输入任务编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="同步ERP状态" prop="syncStatus">
        <el-select v-model="queryParams.syncStatus" placeholder="请选择销售类型" clearable>
          <el-option
            v-for="dict in dict.type.mes_purchase_apply_sync_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="purchaseApplyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="任务编号" align="center" prop="taskCode" />
      <!--el-table-column label="京源项目" align="center" prop="tondBase" /-->
      <el-table-column label="同步ERP状态" align="center" prop="syncStatus" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_purchase_apply_sync_status" :value="scope.row.syncStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="同步ERP时间" align="center" prop="syncTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.syncTime, '{y}-{m}-{d}') }}</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-info"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['mes:purchaseApply:edit']"
          >查看</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="800px" append-to-body>
      <el-form ref="form" :model="form" label-width="120px">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-form-item label="任务编号" prop="taskCode">
              <el-input v-model="form.taskCode" disabled  style="width: 220px"/>
            </el-form-item>

          </el-col>

        </el-row>



        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-form-item label="同步ERP状态" prop="syncStatus">
              <el-select v-model="form.syncStatus" disabled>
                <el-option
                  v-for="dict in dict.type.mes_purchase_apply_sync_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>

          </el-col>

          <el-col :span="1.5">
            <el-form-item label="同步ERP时间" prop="syncTime">
              <el-date-picker clearable
                              v-model="form.syncTime"
                              type="date"
                              value-format="yyyy-MM-dd" style="width: 220px" disabled
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>



        <el-divider content-position="center">采购申请单详细信息</el-divider>
        <el-table :data="mesPurchaseApplyDetailList" :row-class-name="rowMesPurchaseApplyDetailIndex" @selection-change="handleMesPurchaseApplyDetailSelectionChange" ref="mesPurchaseApplyDetail">
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="物料编码" prop="materialCode">
          </el-table-column>
          <el-table-column label="物料名称" prop="materialName">
          </el-table-column>
          <el-table-column label="产品规格型号" prop="materialSpec">
          </el-table-column>

          <el-table-column label="单位" prop="unitName">
          </el-table-column>
          <el-table-column label="原需要数量" prop="oriReqQty">
          </el-table-column>

          <el-table-column label="需要数量" prop="reqQty">
            <template slot-scope="scope">
              <el-input v-model="scope.row.reqQty" placeholder="请输入需要数量" ></el-input>
            </template>
          </el-table-column>

          <el-table-column label="生产厂家" prop="produceSupplier">
          </el-table-column>
          <el-table-column label="含税单价" prop="taxPrice">
          </el-table-column>
          <el-table-column label="含税总价" prop="taxTotalPrice">
          </el-table-column>
          <el-table-column label="京源项目" prop="tondBase">
          </el-table-column>

        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="form.syncStatus!=='1'">同 步</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>



    <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 {
  listPurchaseApply,
  getPurchaseApply,
  delPurchaseApply,
  addPurchaseApply,
  updatePurchaseApply,
  syncPurchaseApply
} from "@/api/mes/purchaseApply";
import {getToken} from "@/utils/auth";

export default {
  name: "PurchaseApply",
  dicts: ['mes_purchase_apply_sync_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedMesPurchaseApplyDetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购申请单表格数据
      purchaseApplyList: [],
      // 采购申请单详细信息;从ERP同步过来的信息，需要与物料信息关联，需要确认接口同步过来的信息内容表格数据
      mesPurchaseApplyDetailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskCode: null,
        tondBase: null,
        syncStatus: null,
        syncTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        taskCode: [
          { required: true, message: "任务编号不能为空", trigger: "blur" }
        ],
        syncStatus: [
          { required: true, message: "同步状态(0未同步1已同步)不能为空", trigger: "change" }
        ],
      },

      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/mes/import/purchaseRequisitionImportData"
      },

    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询采购申请单列表 */
    getList() {
      this.loading = true;
      listPurchaseApply(this.queryParams).then(response => {
        this.purchaseApplyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        purchaseApplyId: null,
        taskCode: null,
        tondBase: null,
        syncStatus: null,
        syncTime: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.mesPurchaseApplyDetailList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.purchaseApplyId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加采购申请单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const purchaseApplyId = row.purchaseApplyId || this.ids
      getPurchaseApply(purchaseApplyId).then(response => {
        this.form = response.data;
        this.mesPurchaseApplyDetailList = response.data.mesPurchaseApplyDetailList;
        this.open = true;
        this.title = "查看采购申请单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.mesPurchaseApplyDetailList = this.mesPurchaseApplyDetailList;
          if (this.form.purchaseApplyId != null) {
            syncPurchaseApply(this.form).then(response => {
              this.$modal.msgSuccess("同步成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const purchaseApplyIds = row.purchaseApplyId || this.ids;
      this.$modal.confirm('是否确认删除采购申请单编号为"' + purchaseApplyIds + '"的数据项？').then(function() {
        return delPurchaseApply(purchaseApplyIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
	/** 采购申请单详细信息;从ERP同步过来的信息，需要与物料信息关联，需要确认接口同步过来的信息内容序号 */
    rowMesPurchaseApplyDetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 采购申请单详细信息;从ERP同步过来的信息，需要与物料信息关联，需要确认接口同步过来的信息内容添加按钮操作 */
    handleAddMesPurchaseApplyDetail() {
      let obj = {};
      obj.erpMaterialId = "";
      obj.materialId = "";
      obj.materialCode = "";
      obj.materialName = "";
      obj.materialSpec = "";
      obj.unitCode = "";
      obj.priceUnitCode = "";
      obj.reqQty = "";
      obj.produceSupplier = "";
      obj.taxPrice = "";
      obj.taxTotalPrice = "";
      obj.oriReqQty = "";
      this.mesPurchaseApplyDetailList.push(obj);
    },
    /** 采购申请单详细信息;从ERP同步过来的信息，需要与物料信息关联，需要确认接口同步过来的信息内容删除按钮操作 */
    handleDeleteMesPurchaseApplyDetail() {
      if (this.checkedMesPurchaseApplyDetail.length == 0) {
        this.$modal.msgError("请先选择要删除的采购申请单详细信息;从ERP同步过来的信息，需要与物料信息关联，需要确认接口同步过来的信息内容数据");
      } else {
        const mesPurchaseApplyDetailList = this.mesPurchaseApplyDetailList;
        const checkedMesPurchaseApplyDetail = this.checkedMesPurchaseApplyDetail;
        this.mesPurchaseApplyDetailList = mesPurchaseApplyDetailList.filter(function(item) {
          return checkedMesPurchaseApplyDetail.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleMesPurchaseApplyDetailSelectionChange(selection) {
      this.checkedMesPurchaseApplyDetail = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/purchaseApply/export', {
        ...this.queryParams
      }, `purchaseApply_${new Date().getTime()}.xlsx`)
    },


    /** 导入按钮操作 */
    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();
      if(response.code === 200){
        this.$modal.msgSuccess("导入成功");
        this.getList();
        this.reset();
        const purchaseApplyId = response.data
        getPurchaseApply(purchaseApplyId).then(response => {
          this.form = response.data;
          this.mesPurchaseApplyDetailList = response.data.mesPurchaseApplyDetailList;
          this.open = true;
          this.title = "查看采购申请单";
        });

      }
      // this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});

    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },

  }
};
</script>
