<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="导入BOM标识" prop="importFlag">
        <el-select v-model="queryParams.importFlag" placeholder="请选择导入BOM标识" clearable>
          <el-option
            v-for="dict in dict.type.import_flag"
            :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-plus"-->
      <!--          size="mini"-->
      <!--          @click="handleAdd"-->
      <!--          v-hasPermi="['mes:purchaseApplyProcess:add']"-->
      <!--        >新增</el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="success"-->
      <!--          plain-->
      <!--          icon="el-icon-edit"-->
      <!--          size="mini"-->
      <!--          :disabled="single"-->
      <!--          @click="handleUpdate"-->
      <!--          v-hasPermi="['mes:purchaseApplyProcess:edit']"-->
      <!--        >修改</el-button>-->
      <!--      </el-col>-->

      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="danger"-->
      <!--          plain-->
      <!--          icon="el-icon-delete"-->
      <!--          size="mini"-->
      <!--          :disabled="multiple"-->
      <!--          @click="handleDelete"-->
      <!--          v-hasPermi="['mes:purchaseApplyProcess:remove']"-->
      <!--        >删除</el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="warning"-->
      <!--          plain-->
      <!--          icon="el-icon-download"-->
      <!--          size="mini"-->
      <!--          @click="handleExport"-->
      <!--          v-hasPermi="['mes:purchaseApplyProcess:export']"-->
      <!--        >导出</el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['mes:purchaseApplyProcess:import']"
        >提资单导入
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="purchaseApplyProcessList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="主键标识" align="center" prop="purchaseApplyId" v-if="columns[0].visible"/>
      <el-table-column label="任务编号" align="center" prop="taskCode" v-if="columns[1].visible"/>
      <el-table-column label="提资单成品名称" align="center" prop="materialName" v-if="columns[2].visible"/>
      <el-table-column label="当前流程节点" align="center" prop="processActivityName" v-if="columns[3].visible"/>
      <el-table-column label="导入BOM标识" align="center" prop="importFlag" width="110" v-if="columns[4].visible">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.import_flag" :value="scope.row.importFlag"/>
        </template>
      </el-table-column>
      <el-table-column label="导入人" align="center" prop="createBy" width="80" v-if="columns[5].visible"/>
      <el-table-column label="导入时间" align="center" prop="createTime" width="180" v-if="columns[6].visible">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{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"
            @click="handleDetailInfo(scope.row)"
          >流程明细
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleRaiseCapitalBom(scope.row)"
            v-hasPermi="['mes:mesRaiseCapitalBom:list']"
          >提资单BOM
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-user-solid"
            @click="handlePurchaseProcess(scope.row)"
            v-if="scope.row.processActivityId === PROCESS_NODE.CREATE_ID"
            v-hasPermi="['mes:purchaseApplyProcess:purchaseEdit']"
          >采购处理
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-user-solid"
            @click="handleTechnicalProcessing(scope.row)"
            v-if="scope.row.processActivityId === PROCESS_NODE.TECHNICAL_MODIFY_ID
            || scope.row.processActivityId === PROCESS_NODE.PROCUREMENT_AUDIT_ID"
            v-hasPermi="['mes:purchaseApplyProcess:technicalEdit']"
          >技术处理
          </el-button>
          <!--          <el-button-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-delete"-->
          <!--            @click="handleDelete(scope.row)"-->
          <!--            v-hasPermi="['mes:purchaseApplyProcess:remove']"-->
          <!--          >删除</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" :rules="rules" label-width="130px">
        <el-form-item label="任务编号" prop="taskCode">
          <el-input v-model="form.taskCode" placeholder="请输入任务编号" disabled/>
        </el-form-item>
        <el-form-item label="提资单成品名称" prop="materialName">
          <el-input v-model="form.materialName" type="textarea" disabled/>
        </el-form-item>
        <el-form-item label="当前流程节点" prop="processActivityName">
          <el-input v-model="form.processActivityName" disabled/>
        </el-form-item>
        <el-form-item label="备注（通知内容）" prop="remark">
          <el-input v-model="form.remark" type="textarea"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :submitLading="submitLoading" @click="purchaseAbnormalFlow(ANOMALY_FLAG.NO)">导入BOM</el-button>
        <el-button type="warning" :submitLading="submitLoading" @click="purchaseAbnormalFlow(ANOMALY_FLAG.YES)">异常流转</el-button>
      </div>
    </el-dialog>

    <!-- 技术处理流程对话框 -->
    <el-dialog :title="title" :visible.sync="technicalOpen" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="任务编号" prop="taskCode">
          <el-input v-model="form.taskCode" placeholder="请输入任务编号" disabled/>
        </el-form-item>
        <el-form-item label="提资单成品名称" prop="materialName">
          <el-input v-model="form.materialName" type="textarea" disabled/>
        </el-form-item>
        <el-form-item label="当前流程节点" prop="processActivityName">
          <el-input v-model="form.processActivityName" disabled/>
        </el-form-item>
        <el-form-item label="备注（通知内容）" prop="remark">
          <el-input v-model="form.remark" type="textarea"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="technicalProcessingFlow(ANOMALY_FLAG.NO)">处理完成</el-button>
        <el-button type="warning" @click="technicalProcessingFlow(ANOMALY_FLAG.YES)">通知ERP</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">
          <span>仅允许导入xls、xlsx格式文件。</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="submitLoading" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="detailInfoTitle" :visible.sync="detailInfoOpen" width="1200px" append-to-body>
      <el-table :data="mesPurchaseApplyProcessDetailList" ref="mesPurchaseApplyProcessDetail">
        <el-table-column label="流程节点ID" align="center" prop="processActivityId" width="100">
          <template slot-scope="scope">
            <el-input v-model="scope.row.processActivityId" disabled/>
          </template>
        </el-table-column>
        <el-table-column label="流程节点描述" align="center" prop="processActivityName" width="200">
          <template slot-scope="scope">
            <el-input v-model="scope.row.processActivityName" disabled/>
          </template>
        </el-table-column>
        <el-table-column label="异常标识" align="center" prop="anomalyFlag" width="80">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.import_flag" :value="scope.row.anomalyFlag" disabled/>
          </template>
        </el-table-column>
<!--        <el-table-column label="更新标识" prop="updateFlag" width="150">-->
<!--          <template slot-scope="scope">-->
<!--            <dict-tag :options="dict.type.import_flag" :value="scope.row.updateFlag" disabled/>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column label="备注" align="center" prop="purchaseRemark"  >
          <template slot-scope="scope">
            <el-input v-model="scope.row.purchaseRemark" type="textarea" disabled/>
          </template>
        </el-table-column>
        <el-table-column label="通知标识" align="center" prop="noticeFlag" width="80">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.import_flag" :value="scope.row.noticeFlag" disabled/>
          </template>
        </el-table-column>
        <el-table-column label="通知用户编号" align="center" prop="noticeAuth" width="120"/>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPurchaseApplyProcess,
  getPurchaseApplyProcess,
  delPurchaseApplyProcess,
  addPurchaseApplyProcess,
  updatePurchaseApplyProcess, purchaseAbnormalFlowApi, technicalProcessingFlowApi
} from "@/api/mes/purchaseApplyProcess";
import {getToken} from "@/utils/auth";

export default {
  name: "PurchaseApplyProcess",
  dicts: ['import_flag'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedMesPurchaseApplyProcessDetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购申请流程表格数据
      purchaseApplyProcessList: [],
      // 采购申请流程明细表格数据
      mesPurchaseApplyProcessDetailList: [],
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/mes/import/raiseCapitalImportData"
      },
      submitLoading:false,
      // 弹出层标题
      title: "",
      detailInfoTitle: "采购申请流程明细",
      // 是否显示弹出层
      open: false,
      technicalOpen: false,
      detailInfoOpen: false,
      // 更新时间时间范围
      daterangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskCode: null,
        materialName: null,
        wfProcessId: null,
        importFlag: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        taskCode: [
          {required: true, message: "任务编号不能为空", trigger: "blur"}
        ],
      },
      columns: [
        {key: 0, label: `主键标识`, visible: false},
        {key: 1, label: `任务编号`, visible: true},
        {key: 2, label: `提资单成品名称`, visible: true},
        {key: 3, label: `当前流程节点`, visible: true},
        {key: 4, label: `导入BOM标识`, visible: true},
        {key: 5, label: `创建人`, visible: true},
        {key: 6, label: `导入时间`, visible: true},
      ],
      //顶级标识
      ANOMALY_FLAG: {
        YES: 1,
        NO: 0
      },
      //流程节点
      PROCESS_NODE: {
        CREATE_ID : 4011,
        PROCUREMENT_AUDIT_ID: 4012,
        TECHNICAL_MODIFY_ID: 4013,
        ERP_MODIFY_ID: 4014,
        FINISH_ID: 4015,
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询采购申请流程列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      listPurchaseApplyProcess(this.queryParams).then(response => {
        this.purchaseApplyProcessList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        purchaseApplyId: null,
        taskCode: null,
        materialName: null,
        wfProcessId: null,
        importFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.mesPurchaseApplyProcessDetailList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      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 = "添加采购申请流程";
    },
    //跳转提资单BOM页面
    handleRaiseCapitalBom(row) {
      const taskCode = row.taskCode;
      const params = {queryParams: this.queryParams, t: Date.now()};
      this.$tab.openPage("提资单BOM[" + taskCode + "]", '/mes/raise-capital-bom/index/' + taskCode, params);
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "BOM导入";
      this.upload.open = true;
      this.submitLoading = false;
    },
    // 文件上传中处理
    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();
      this.submitLoading = false;
    },
    // 提交上传文件
    submitFileForm() {
      this.submitLoading = true;
      this.$refs.upload.submit();
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.mesPurchaseApplyProcessDetailList = this.mesPurchaseApplyProcessDetailList;
          if (this.form.purchaseApplyId != null) {
            updatePurchaseApplyProcess(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPurchaseApplyProcess(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 申请流程-采购处理对话框 */
    handlePurchaseProcess(row){
      this.reset();
      const purchaseApplyId = row.purchaseApplyId || this.ids
      getPurchaseApplyProcess(purchaseApplyId).then(response => {
        this.form = response.data;
        this.mesPurchaseApplyProcessDetailList = response.data.mesPurchaseApplyProcessDetailList;
        this.open = true;
        this.title = "采购申请流程-采购处理";
      });
    },
    /** 申请流程-采购处理 */
    purchaseAbnormalFlow(anomalyFlag){
      this.submitLoading = true;
      this.form.currentAnomalyFlag = anomalyFlag
      if(anomalyFlag === this.ANOMALY_FLAG.YES){
        if(!this.form.remark || this.form.remark===null ||this.form.remark===''){
          this.$modal.msgWarning("请输入备注");
          this.submitLoading = false;
          return;
        }

      }
      purchaseAbnormalFlowApi(this.form).then(response => {
        if (anomalyFlag === this.ANOMALY_FLAG.YES){
          this.$modal.msgSuccess("通知技术人员修改成功！");
        } else {
          this.$modal.msgSuccess("BOM导入处理成功！");
        }
        this.open = false;
        this.getList();
      }).finally(e =>{
        this.submitLoading = false;
      });
    },
    /** 申请流程-技术处理对话框 */
    handleTechnicalProcessing(row){
      this.reset();
      const purchaseApplyId = row.purchaseApplyId || this.ids
      getPurchaseApplyProcess(purchaseApplyId).then(response => {
        this.form = response.data;
        this.mesPurchaseApplyProcessDetailList = response.data.mesPurchaseApplyProcessDetailList;
        this.technicalOpen = true;
        this.title = "采购申请流程-技术处理";
      });
    },
    /** 申请流程-技术处理 */
    technicalProcessingFlow(anomalyFlag){
      this.form.currentAnomalyFlag = anomalyFlag
      this.submitLoading = true;
      if(anomalyFlag === this.ANOMALY_FLAG.YES){
        if(!this.form.remark || this.form.remark===null ||this.form.remark===''){
          this.$modal.msgWarning("请输入备注");
          this.submitLoading = false;
          return;
        }
      }

      technicalProcessingFlowApi(this.form).then(response => {
        if (anomalyFlag === this.ANOMALY_FLAG.YES){
          this.$modal.msgSuccess("通知ERP人员成功！");
        } else {
          this.$modal.msgSuccess("处理成功！");
        }
        this.technicalOpen = false;
        this.getList();
      }).finally(e =>{
        this.submitLoading = false;
      });
    },
    /** 申请流程-明细信息 */
    handleDetailInfo(row){
      this.reset();
      const purchaseApplyId = row.purchaseApplyId || this.ids
      getPurchaseApplyProcess(purchaseApplyId).then(response => {
        this.mesPurchaseApplyProcessDetailList = response.data.mesPurchaseApplyProcessDetailList;
        this.detailInfoOpen = true;
        this.detailInfoTitle = "任务编号[" + row.taskCode + "]采购申请流程明细信息";
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const purchaseApplyIds = row.purchaseApplyId || this.ids;
      this.$modal.confirm('是否确认删除采购申请流程编号为"' + purchaseApplyIds + '"的数据项？').then(function () {
        return delPurchaseApplyProcess(purchaseApplyIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/purchaseApplyProcess/export', {
        ...this.queryParams
      }, `purchaseApplyProcess_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
