<!--
  @description: 新增物料采购方式弹框/驳回共用
  @author: hdk/lxl
  @date： 2020-11-02 16:16:26
-->
<template>
  <div>
    <el-form ref="form" :model="formData" :rules="rules" :inline-message="true">
      <table class="from_table">
        <tr class="singleRow">
          <td>
            <el-form-item label="品牌" prop="purchaseBrand" />
          </td>
          <td colspan="3">
            <gx-input
              v-model.trim="formData.purchaseBrand"
              clearable
              placeholder="请输入品牌(最多输入50个汉字)"
              gx-maxlength="varchar50"
              style="width: calc(100% - 36px)"
            />
          </td>
        </tr>
        <tr class="singleRow">
          <td>
            <el-form-item label="制造厂商" prop="manufacturerName" />
          </td>
          <td colspan="3">
            <gx-input
              v-model.trim="formData.manufacturerName"
              clearable
              placeholder="最多允许输入100个汉字"
              gx-maxlength="varchar100"
              style="width: calc(100% - 36px)"
            />
          </td>
        </tr>
        <tr class="singleRow">
          <td>
            <el-form-item label="物资编码" prop="purchaseCode" />
          </td>
          <td colspan="3">
            <el-input
              v-model="formData.purchaseCode"
              placeholder="请选择"
              class="mr10"
              :style="{'width':editMode !== '02'?'80%':''}"
              disabled
            />
            <template v-if="editMode !== '02'">
              <el-button type="primary" class="ml10 choose" @click="openPurchaseInfo()">
                选择
              </el-button>
              <el-button type="primary" plain @click="categoryTreeInfo('clear')">
                清空
              </el-button>
            </template>
          </td>
        </tr>
        <tr class="singleRow">
          <td>
            <el-form-item label="物资信息" prop="purchaseName" />
          </td>
          <td colspan="3">
            <el-input
              v-model="formData.purchaseName"
              disabled
            />
          </td>
        </tr>
        <tr class="singleRow">
          <td>
            <el-form-item label="采购方式" prop="purchaseMethodValue" />
          </td>
          <td colspan="3">
            <el-select v-model="formData.purchaseMethodValue" filterable style="width:15vw" placeholder="请选择" @change="changeMethod">
              <el-option
                v-for="item in tenderMethodList"
                :key="item.typename"
                :label="item.typename"
                :value="item.typecode"
              />
            </el-select>
          </td>
        </tr>
        <tr class="singleRow">
          <td>
            <el-form-item label="供货厂商" :prop="formData.purchaseMethodValue === '12'?'suppliersName':''" />
          </td>
          <td colspan="3">
            <div>
              <el-input
                v-model="formData.suppliersName"
                placeholder="请选择"
                class="mr10"
                style="width: 80%"
                disabled
              />
              <el-button type="primary" class="ml10 choose" @click="openSupplier('01')">
                选择
              </el-button>
              <el-button type="primary" plain @click="checkSupplier('clear', '01')">
                清空
              </el-button>
            </div>
          </td>
        </tr>
        <tr v-if="editMode === '02' || materielType==='02'" class="singleRow">
          <td>
            <el-form-item label="变更原因" prop="updateReason" />
          </td>
          <td colspan="3">
            <gx-input
              v-model.trim="formData.updateReason"
              :autosize="{ minRows: 3, maxRows: 3 }"
              gx-placeholder="placeholderText1000"
              gx-maxlength="varchar1000"
              type="textarea"
              style="width: 96%"
            />
          </td>
        </tr>
        <tr>
          <td>
            <el-form-item label="附件信息" />
          </td>
          <td>
            <upload
              ref="ref_upload"
              :data="upLoadData"
              :auto-delete="true"
              :auto-upload="true"
              title=""
              tip-text="上传附件格式（*.doc;*.docx;*.pdf;*.png;*.jpg;*.zip;*.xlsx;*.xls;*.rar）单个文件不得超过200M"
              accept=".doc,.docx,.pdf,.png,.jpg,.zip,.jpeg,.txt,.xls,.xls,.ppt,.pptx,.rar"
              file-ref="fileRef"
            />
          </td>
        </tr>
      </table>
    </el-form>
    <div class="but_footer">
      <div class="but_footer-h">
        <div class="but_footer-but">
          <el-button type="primary" @click="submit('form')">
            提 交
          </el-button>
          <el-button @click="cancel">
            取 消
          </el-button>
        </div>
      </div>
    </div>
    <!--  物料信息弹窗 -->
    <materielChoiceDialog :dialog-data="dialogData" @categoryTreeInfo="categoryTreeInfo" />
    <!-- 供应商弹窗 -->
    <materielSupplierDialog :dialog-data="supplierDialogData" @consignContractInfo="checkSupplier" />

    <!--工作流选择节点组件-->
    <processNodeCom
      ref="processNode"
      :process-definition-key="processDefinitionKey"
      @processNodeData="processNodeData"
    />
    <!--工作流流程节点/获取审核用户-->
    <departDialog
      ref="departDialog"
      :process-node="processNode"
      @isSingleUser="isSingleUser"
      @processInitData="processInitData"
      @submit="submitFlow"
    />
  </div>
</template>

<script>
/* api*/
import { alterPlanPurchaseMaintenanceInfo, saveOrUpdatePlanPurchaseMaintenanceList, getProcurementMaintenanceInfo } from '@/api/procurement/purchasplan'
/* 公共混入*/
import { materielMixins } from '../mixins/materielMixins'
/* 公共方法 */
import { characters1_auto } from '@/assets/js/validate' // 校验输入内容
import { randomData } from '@/assets/js/utils/index'
import upload from '@comp/common/updownload/upload' // 附件上传组件

/* 组件 */
import materielChoiceDialog from './materielChoice-dialog' // 物料信息弹窗
import materielSupplierDialog from './materielSupplier-dialog' // 供应商弹窗

/* ==========工作流===========*/
import { workCommonMixins } from '@views/work/mixins/workCommonMixins' // 工作流公共配置
import workconstant from '@/assets/js/workutils/workconstant/procurement' // 配置流程key
import processNodeCom from '@views/work/processNodeCom' // 工作流选择节点组件
import departDialog from '@views/work/depart-dialog' // 选择审核人员
export default {
  name: 'PurPlanMaterielAdd',
  components: {
    materielChoiceDialog, // 物料信息弹窗
    materielSupplierDialog, // 供应商弹窗
    departDialog, // 选择审核人员
    processNodeCom, // 工作流选择节点组件
    upload
  },
  mixins: [materielMixins, workCommonMixins],
  props: {
    // 弹窗打开状态
    materielAddVisible: {
      type: Boolean,
      default: false
    },
    // 编辑模式 00新增 01编辑 02变更
    editMode: {
      type: String,
      default: '00'
    },
    // 编辑数据源
    editRowData: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  data() {
    return {
      flowStatus: this.$route.query.flowStatus, // true 工作流进入驳回编辑
      materielType: this.$route.meta.materielType, // 工作流进入参数
      editModeType: '', // 工作流进入参数
      dialogData: {
        dialog: false, // 弹窗状态
        onlyOneSelected: true, // 是否只能选最后一级且是单选
        multipleChoice: true, // 多选
        selectCodes: [] // 当前选中的供货范围Code
      },
      supplierDialogData: { // 供货商弹窗参数
        dialog: false, // 供应商弹窗打开状态
        supplierCheckMode: '00', // 00制造厂商 01供货厂商
        singleChoice: false // 单选
      },
      // 附件上传参数
      upLoadData: {
        bizId: '',
        fileType: 'purchase_maintenance_file_'
      },
      formData: { // 表单数据
        purchaseBrand: '', // 品牌
        manufacturerName: '', // 制造厂商
        manufacturerValue: '', // 制造厂商id
        purchaseCode: '', // 物资编码
        purchaseName: '', // 物资信息
        purchaseMethodValue: '', // 采购方式
        suppliersName: '', // 供货厂商
        suppliersValue: '', // 供货厂商id
        updateReason: '', // 变更原因
        explainFileId: ''
      },
      processDefinitionKey: '', // 工作流流程key
      rules: { // 校验
        suppliersName: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 供货厂商
        purchaseCode: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 物资编码
        purchaseName: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 物资信息
        purchaseMethodValue: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 采购方式
        updateReason: [{ required: true, validator: characters1_auto, trigger: 'blur' }] // 变更原因
      }
    }
  },
  watch: {
  },
  created() {
    this.purchasplanMethodSubmitAudit() // 保存修改物料采购获取工作流配置
    this.purchasplanMethodChangeAudit() // 变更物料采购获取工作流配置
    // 工作流流程key
    this.processDefinitionKey = this.editMode === '00' ? workconstant.purPlanTypeAdd : this.editMode === '02' ? workconstant.purPlanUpdate : workconstant.purPlanTypeAdd
    // 数据初始化
    if (this.flowStatus) {
      this.rejectReload()
    } else {
      this.pageDataInit()
    }
  },
  methods: {
    pageDataInit() {
      if (JSON.stringify(this.editRowData) !== '{}') {
        this.formData = JSON.parse(JSON.stringify(this.editRowData))
      }
      this.formData.explainFileId = this.editMode === '01' ? this.formData.bizAuditId : randomData()// 新增时随机生成ID
      this.upLoadData.bizId = this.formData.explainFileId
    },
    // 工作流进入初始化
    rejectReload() {
      const materielType = this.$route.meta.materielType
      this.editModeType = materielType
      this.upLoadData.bizId = this.$route.query.packId
      const params = {
        purchaseMaintenanceId: this.$route.query.id
      }
      this.processDefinitionKey = materielType === '01' ? workconstant.purPlanTypeAdd : workconstant.purPlanUpdate
      getProcurementMaintenanceInfo(params).then((res) => {
        this.formData = res.data
      })
    },
    changeMethod(code) {
      // 单一来源添加供货厂商校验
      if (code === '12') {
        // 供货厂商校验
        this.rules.supplier = [{ required: true, validator: characters1_auto, trigger: 'blur' }]
        // 单选
        this.supplierDialogData.singleChoice = true
      } else {
        delete this.rules.supplier
      }
    },
    // 物资编码 选择/清空
    categoryTreeInfo(data) {
      // 清空
      if (data === 'clear') {
        this.formData.purchaseCode = ''
        this.formData.purchaseName = ''
      } else {
        // 选择
        this.$set(this.formData, 'purchaseCode', data.keys)
        this.$set(this.formData, 'purchaseName', data.labels)
      }
    },
    // 制造厂商 选择/清空
    checkSupplier(data, mode) {
      // 清空
      if (data === 'clear') {
        // 制造商数据清空
        if (mode === '00') {
          this.formData.manufacturerName = ''
          this.formData.manufacturerValue = ''
        } else {
          // 供货商数据清空
          this.formData.suppliersName = ''
          this.formData.suppliersValue = ''
        }
      } else {
        // 选择
        if (this.supplierDialogData.supplierCheckMode === '00') {
          // 制造商数据赋值
          this.$set(this.formData, 'manufacturerName', data.labels)
          this.$set(this.formData, 'manufacturerValue', data.keys)
        } else {
          // 供货商数据赋值
          this.$set(this.formData, 'suppliersName', data.labels)
          this.$set(this.formData, 'suppliersValue', data.keys)
        }
      }
    },
    openPurchaseInfo() {
      // 打开物资信息
      this.dialogData.dialog = true
    },
    openSupplier(mode) {
      // 供应商弹窗 00制造厂商 01供货厂商
      this.supplierDialogData.supplierCheckMode = mode
      this.supplierDialogData.dialog = true
      if (mode === '00' || this.formData.purchaseMethodValue === '12') {
        // 单选
        this.supplierDialogData.singleChoice = true
      } else {
        // 多选
        this.supplierDialogData.singleChoice = false
      }
    },
    cancel() {
      // 取消
      // this.$emit('closeDialog')
      this.backLog()
    },
    // 关闭退回处理
    backLog() {
      if (this.flowStatus) {
        const routePathStatus = sessionStorage.getItem('routePathStatus') // 工作流处理 00桌面进入 01待办列表进入
        this.$router.push({
          path: routePathStatus === '00' ? '/home' : '/work/todo'
        })
      } else {
        this.$emit('closeDialog')
      }
    },
    // 审批流提交
    submitFlow() {
      this.subFrom()
    },
    subFrom() {
      const params = Object.assign({ ...this.formData }, {
        // processDefinitionKey: this.processDefinitionKey, // 工作流节点key
        // processInitDto: this.processInitDto, // 审核人信息传回得信息
        operationType: this.flowStatus ? this.editModeType : this.editMode
      })
      if (this.purchasplanMethodSubmitAuditConfig || this.purchasplanMethodChangeAuditConfig) {
        params.processDefinitionKey = this.processDefinitionKey // 工作流节点key
        params.processInitDto = this.processInitDto // 审核人信息传回得信息
      }
      if (this.flowStatus) {
        params.explainFileId = this.formData.bizAuditId
        params.bizId = this.$route.query.bizId
        params.purchaseMaintenanceId = this.$route.query.id
      }

      if (this.editMode === '02' || this.materielType === '02') {
        // 变更调用
        alterPlanPurchaseMaintenanceInfo(params).then(response => {
          this.$message({
            type: 'success',
            message: '变更成功'
          })
          this.backLog()
        }).catch(() => {
        })
      } else {
        // 新增调用
        saveOrUpdatePlanPurchaseMaintenanceList(params).then(response => {
          this.$message({
            type: 'success',
            message: '提交成功'
          })
          this.backLog()
        }).catch(() => {
        })
      }
    },
    submit(formName) {
      // 提交
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.formData.purchaseMethodValue === '12' && !this.formData.suppliersName) {
            this.$message({
              type: 'warning',
              message: '请选择供货厂商'
            })
            return false
          }
          this.$confirm('是否确定提交？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            confirmButtonClass: 'confirmBtn',
            cancelButtonClass: 'cancelBtn',
            type: 'warning'
          }).then(() => {
            if (this.purchasplanMethodSubmitAuditConfig || this.purchasplanMethodChangeAuditConfig) {
              // 判断审核人员是否是多个
              if (JSON.stringify(this.processNode) !== '{}' && this.processNode.nodeId) {
                this.$refs.departDialog.getUserDepart(this.processNode)
              }
            } else {
              this.submitFlow()
            }
          }).catch(() => {
          })
        }
      })
    }
  }
}
</script>

<style>

</style>
