<!--
  @description: 采购员-结果执行管理-新增采购执行结果
  @author: hdk/gmy
  @routerPath:/procurement/rstMgmtAdd
  @date： 2021-2-19 15:19:19
-->
<template>
  <div>
    <!--标题-->
    <section v-if="!flowStatus" class="title title_border p0-16">
      <i class="iconfont icon-fanhui pointer" @click="back()" />
      新增执行结果
    </section>
    <div class="p0-16">
      <!-- 执行结果基本信息 -->
      <div class="mb16">
        <p class="page-title">
          1.执行结果基本信息
          <el-button
            v-if="editMode !== '04'&&formData.executeType"
            type="primary"
            class="ml10 choose"
            @click="checkProcurementProject"
          >
            {{ addLineitemTxt[formData.executeType] }}
          </el-button>
        </p>
        <el-form ref="form" :model="formData" :rules="rules" :inline-message="true">
          <table class="from_table">
            <tr>
              <td>
                <el-form-item label="执行编号" />
              </td>
              <td colspan="3">
                <span v-if="formData.executeNo">
                  {{ formData.executeNo }}
                </span>
                <span v-else>
                  系统自动生成
                </span>
              </td>
              <!-- 物资编号 暂时隐藏 -->
              <!-- <td>
            <el-form-item label="物资编号" />
          </td>
          <td>
            <span v-if="formData.purchaseCode">
              {{ formData.purchaseCode }}
            </span>
            <span v-else>
              {{ formData.executeType === '00' ? '根据选择的打包后的行项目生成' : '根据选择的框架计划生成' }}
            </span>
          </td> -->
            </tr>
            <!-- <tr> -->
            <!-- 物资信息 暂时隐藏 -->
            <!-- <td>
            <el-form-item label="物资信息" />
          </td>
          <td>
            <span v-if="formData.purchaseName">
              {{ formData.purchaseName }}
            </span>
            <span v-else>
              {{ formData.executeType === '00' ? '根据选择的打包后的行项目生成' : '根据选择的框架计划生成' }}
            </span>
          </td> -->
            <!-- 采购单位暂时隐藏 -->
            <!-- <td>
                <el-form-item label="采购单位" prop="belongOrgName" />
              </td>
              <td colspan="3">
                <div v-if="editMode === '02'">
                  <el-input
                    v-model="formData.belongOrgName"
                    placeholder="请选择"
                    style="width: calc(100% - 254px)"
                    disabled
                  />
                  <el-button type="primary" class="ml10 choose" @click="organSelect">
                    选择采购单位
                  </el-button>
                  <el-button type="primary" plain class="ml10 choose" @click="organTree('clear')">
                    清空
                  </el-button>
                </div>
                <span v-else>
                  <span v-if="formData.belongOrgName">
                    {{ formData.belongOrgName }}
                  </span>
                  <span v-else>
                    {{ formData.executeType === '00' ? '根据选择的打包后的行项目生成' : '根据选择的框架计划生成' }}
                  </span>
                </span>
              </td> -->
            <!-- </tr> -->
            <tr>
              <td>
                <el-form-item label="成交供应商" prop="suppliersName" />
              </td>
              <td colspan="3">
                <div>
                  <el-input
                    v-model="formData.suppliersName"
                    placeholder="请选择"
                    style="width: calc(100% - 254px)"
                    disabled
                  />
                  <el-button type="primary" class="ml10 choose" @click="openSupplier">
                    选择成交供应商
                  </el-button>
                  <el-button type="primary" plain class="ml10 choose" @click="checkSupplier('clear')">
                    清空
                  </el-button>
                </div>
              </td>
            </tr>
            <tr>
              <td>
                <el-form-item label="执行方式" prop="executeType" />
              </td>
              <td>
                <!-- 00-一次谈判一次采购;01-一次谈判多次采购; -->
                {{ filterDictText(executeTypeList, formData.executeType) }}
              </td>
              <td>
                <el-form-item label="来源" />
              </td>
              <td>
                {{ filterDictText(tenderMethodList, formData.tenderMethod) }}
              </td>
            </tr>
            <tr>
              <td>
                <el-form-item label="来源编号" prop="belongTenderNo" />
              </td>
              <td>
                <el-input v-if="editMode === '01'" v-model="formData.belongTenderNo" placeholder="请输入来源编号" />
                <span v-else>
                  {{ formData.belongTenderNo }}
                </span>
              </td>
              <td>
                <el-form-item label="付款方式" prop="paymentType" />
              </td>
              <td>
                <el-select
                  v-if="editMode === '00' || editMode === '01' || flowStatus"
                  v-model="formData.paymentType"
                  popper-class="select-popper"
                  :popper-append-to-body="false"
                  placeholder="请选择"
                  style="width: 100%;"
                >
                  <el-option
                    v-for="item in paymentTypeList"
                    :key="item.typecode"
                    :title="item.typename"
                    :label="item.typename"
                    :value="item.typecode"
                  />
                </el-select>
                <span v-else>
                  {{ filterDictText(paymentTypeList, formData.paymentType) }}
                </span>
              </td>
            </tr>
            <tr>
              <td>
                <el-form-item label="采购单不含税总金额（元）" />
              </td>
              <td colspan="3">
                {{ formData.purchaseTotalBudget }}
              </td>
            </tr>
            <tr>
              <td>
                <el-form-item label="执行日期" prop="executeTime" />
              </td>
              <td>
                <el-date-picker
                  v-if="editMode === '00' || editMode === '01'"
                  v-model="formData.executeTime"
                  :value-format="elValueSaveFormat"
                  type="date"
                  placeholder="选择日期"
                />
                <span v-else>
                  {{ formData.executeTime }}
                </span>
              </td>
              <td>
                <el-form-item label="有效期至" prop="validityPeriod" />
              </td>
              <td>
                <!-- v-if="editMode === '00' || editMode === '01' || editMode === '02'" -->
                <el-date-picker
                  v-model="formData.validityPeriod"
                  :value-format="elValueSaveFormat"
                  :picker-options="disabledPickerOptions"
                  type="date"
                  placeholder="选择日期"
                />
              </td>
            </tr>
            <tr>
              <td>
                <el-form-item label="创建人" />
              </td>
              <td>
                {{ formData.exeCreateUserRealName }}
              </td>
              <td>
                <el-form-item label="创建日期" />
              </td>
              <td>
                {{ formData.createTime }}
              </td>
            </tr>
          </table>
        </el-form>
      </div>
      <div class="mb16">
        <p class="page-title">
          2.行项目信息
        </p>
        <!-- 行项目信息组件 -->
        <lineItemInfoTable
          :line-project-data="formData.detailsList"
          :execute-no="formData.executeNo"
          :execute-id="formData.executeId"
          :is-edit="true"
          @updateData="automaticGeneration"
        />
      </div>

      <!-- <div class="mt10 mb10" style="text-align: center;" /> -->
      <!--底部操作按钮-->
      <div class="but_footer">
        <div class="but_footer-h">
          <div class="but_footer-but">
            <el-button v-if="editMode !== '04'" :loading="subLoading" type="primary" class="ml10 choose" @click="saveOrSubmit('01')">
              提 交
            </el-button>
            <el-button v-if="editMode !== '04'" :loading="saveLoading" class="ml10 choose" @click="saveOrSubmit('00')">
              保 存
            </el-button>
            <el-button v-if="editMode === '04'" :loading="changeLoading" type="primary" class="ml10 choose" @click="changePurchaseResult">
              变 更
            </el-button>
          </div>
        </div>
      </div>
    </div>
    <!-- 选择采购项目 -->
    <selectPurItemDialog :dialog-data="procurementDialogData" :call-back="automaticGeneration" :is-edit="true" />
    <!-- 选择框架计划 -->
    <!-- <frameworkPlanDialog :dialog-data="frameworkDialogData" /> -->
    <!-- 代理单位弹框 -->
    <!-- <organTree-dialog ref="organTree" @call-back="organTree" /> -->
    <!--工作流选择节点组件-->
    <processNodeCom
      ref="processNode"
      :process-definition-key="processDefinitionKey"
      @processNodeData="processNodeData"
    />
    <!--工作流流程节点/获取审核用户-->
    <departDialog
      ref="departDialog"
      :process-node="processNode"
      @isSingleUser="isSingleUser"
      @processInitData="processInitData"
      @submit="submitFlow"
    />
    <!-- 供应商弹窗 -->
    <slelectSupplierDialog :dialog-data="supplierDialogData" :call-back="automaticGeneration" @checkSupplier="checkSupplier" />
  </div>
</template>

<script>
/* 接口*/
import { goPurchasePlanResultExecutePage, saveOrSubmitPurchaseResultExecute, changePurchaseResultExecuteInfo } from '@/api/procurement/purchasplan.js'
import { queryProcurementProjectRuleInitInfo } from '@/api/procurement/procurementProject' // 付款方式字典 queryProcurementProjectRuleInitInfo

/* 公共混入*/
import { rstMgmtMixins } from '../mixins/rstMgmtMixins'
/* 公共方法*/
import { filterObj, filterDictText } from '@/assets/js/utils'// 常用方法
import { characters1_auto } from '@/assets/js/validate' // 校验输入内容
/* 组件*/
// import organTreeDialog from '@/views/common/user/organizationTree/organTree-dialog' // 组织机构选择
import lineItemInfoTable from './lineItemInfoTable' // 行项目信息组件
import selectPurItemDialog from './selectPurItem-dialog' // 选择采购项目
// import frameworkPlanDialog from './rstMgmtFrameworkPlan-dialog' // 选择框架计划
import slelectSupplierDialog from './slelectSupplier-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: 'RstMgmtAdd',
  components: {
    lineItemInfoTable, // 行项目信息组件
    selectPurItemDialog, // 选择采购项目
    // organTreeDialog, // 组织机构选择
    // frameworkPlanDialog, // 选择框架计划
    processNodeCom, // 工作流节点信息组件
    departDialog, // 工作流审批人组件
    slelectSupplierDialog // 选择供应商
  },
  mixins: [rstMgmtMixins, workCommonMixins],
  data() {
    return {
      flowStatus: this.$route.query.flowStatus, // true 工作流进入驳回编辑
      resultExeType: this.$route.params.resultExeType, // 00新增采购执行结果 01新增框架执行结果
      editMode: this.$route.params.editMode, // editMode编辑模式 00新增采购执行结果 01新增框架执行结果 02变更
      procurementDialogData: { // 选择采购项目弹窗数据
        checkProjectVisible: false,
        executeId: '', // 执行单ID
        planType: '' // 区分新增招标和框架的新增结果执行 00 招标 01框架
      },
      // frameworkDialogData: { // 选择框架计划弹窗数据
      //   checkframeworkVisible: false,
      //   executeId: '', // 执行单ID
      //   planType: '' // 区分新增招标和框架的新增结果执行 00 招标 01框架
      // },
      editModeID: '',
      paymentTypeList: [], // 付款方式字典
      saveLoading: false, // 保存loading状态
      subLoading: false, // 提交loading状态
      changeLoading: false, // 变更loading状态
      formData: { // 采购项目信息
        executeId: '', // 执行单ID
        executeNo: '', // 执行编号
        purchaseCode: '', // 物资编号
        purchaseName: '', // 物资信息
        // belongOrgName: '', // 代理单位
        // belongOrgId: '', // 代理单位ID
        executeType: '', // 执行方式
        tenderMethod: '', // 来源
        belongTenderNo: '', // 来源编号
        paymentType: '', // 付款方式
        purchaseTotalBudget: '', // 采购单含税总金额（元）
        executeTime: '', // 执行日期
        validityPeriod: '', // 有效期至
        exeCreateUserRealName: '', // 创建人
        createTime: '', // 创建日期
        suppliersName: '', // 成交供应商名称
        suppliersValue: '' // 成交供应商value
      },
      processDefinitionKey: '', // 工作流流程key
      // 选择成交供货商弹窗
      supplierDialogData: {
        dialog: false, // 供应商弹窗打开状态
        singleChoice: false, // 单选
        executeId: '' // 执行表ID
      },
      addLineitemTxt: {
        '00': '选择采购项目',
        '01': '选择框架计划'
      },
      rules: {
        executeType: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 执行方式
        belongTenderNo: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 来源编号
        suppliersName: [{ required: true, validator: characters1_auto, trigger: 'blur' }] // 成交供应商
      }
    }
  },
  created() {
    this.purchasplanResultExecutionAudit() // 获取保存工作流配置
    this.purchasplanResultExecutionChangeAudit() // 获取变更工作流配置
    // 处理获取业务id方式
    this.handleFlow()
    // 工作流流程key
    this.processDefinitionKey = workconstant.purPlanExecute
    // 获取执行单详情
    this.automaticGeneration()
    // 付款方式字典请求
    this.queryRuleInitInfo()
  },
  methods: {
    // 处理获取业务id方式
    handleFlow() {
      if (this.flowStatus) {
        this.formData.executeId = this.$route.query.id
      } else {
        this.formData.executeId = this.$route.params.executeId
      }
    },
    // 字典检索
    filterDictText,
    // 付款方式字典请求
    queryRuleInitInfo() {
      queryProcurementProjectRuleInitInfo().then((res) => {
        this.paymentTypeList = res.data.protproject_payType.typeList // 支付方式
      })
    },
    /* ========================选择采购单位暂时隐藏Start================================*/
    // organSelect() {
    //   this.$refs.organTree.open({
    //     title: '选择采购单位', // 弹框标题
    //     dialog: true, // 弹窗状态
    //     selectCodes: this.formData.belongOrgId.split(',') // 当前选中的供货范围Code
    //   })
    // },
    // 选择/清空机构
    // organTree(data) {
    //   // 清空
    //   if (data === 'clear') {
    //     this.formData.belongOrgName = ''
    //     this.formData.belongOrgId = ''
    //   } else {
    //     // 选择
    //     this.$set(this.formData, 'belongOrgName', data.labels)
    //     this.$set(this.formData, 'belongOrgId', data.keys)
    //   }
    // },
    /* ========================选择采购单位暂时隐藏End================================*/

    // 选择供应商
    openSupplier() {
      if (this.formData.detailsList.length > 0) {
        this.supplierDialogData.executeId = this.formData.executeId // 执行表id
        this.supplierDialogData.dialog = true
      } else {
        this.$message.warning(`请先${this.addLineitemTxt[this.formData.executeType]}`)
      }
    },
    // 制造厂商 选择/清空
    checkSupplier(data) {
      // 清空
      if (data === 'clear') {
        // 供货商数据清空
        this.formData.suppliersName = ''
        this.formData.suppliersValue = ''
      } else {
        // 供货商数据赋值
        this.$set(this.formData, 'suppliersName', data.suppliersName)
        this.$set(this.formData, 'suppliersValue', data.suppliersValue)
      }
    },
    //  获取执行单详情
    automaticGeneration() {
      const params = {
        executeId: this.formData.executeId, // 执行单ID
        resultExeType: this.resultExeType // 00新增采购执行结果 01新增框架执行结果
      }
      // 生成执行单id（获取执行单详情）
      goPurchasePlanResultExecutePage(filterObj(params)).then(response => {
        this.formData = Object.assign({ ...this.formData }, {
          ...response.data
        })
        if (this.flowStatus) {
          this.editModeID = this.formData.executeStatus // 执行状态，00-待生效【新增】;04-变更
        }
        this.procurementDialogData.executeId = response.data.executeId
        // this.frameworkDialogData.executeId = response.data.executeId
      }).catch(() => {
      })
    },
    // 选择采购项目和选择框架采购项目 不同的项目查询入参palnType传值不同
    checkProcurementProject() {
      // 选择采购项目
      if (this.editMode === '00' || this.formData.executeType === '00') {
        this.procurementDialogData.planType = '00'
        this.procurementDialogData.checkProjectVisible = true
      } else if (this.editMode === '01' || this.formData.executeType === '01') { // 选择框架采购项目
        // this.frameworkDialogData.planType = '01'
        // this.frameworkDialogData.checkframeworkVisible = true
        this.procurementDialogData.planType = '01'
        this.procurementDialogData.checkProjectVisible = true
      }
    },
    // 选择采购项目回调
    getProcurementProject() {
      // 获取执行单详情
      this.automaticGeneration()
    },
    // 提交/保存参数
    getParamsData() {
      const params = {
        belongTenderNo: this.formData.belongTenderNo, // 来源编号
        executeId: this.formData.executeId, // 执行表ID
        executeTime: this.formData.executeTime, // 执行时间
        operation: '01', // 保存00 提交01
        paymentType: this.formData.paymentType, // 付款方式;00-货到验收后付款;01-质保金;02-货到付款;03-其他;
        validityPeriod: this.formData.validityPeriod // 有效期至
        // processDefinitionKey: this.processDefinitionKey, // 工作流节点key
        // processInitDto: this.processInitDto // 审核人信息传回得信息
      }
      // 判断是否进入工作流
      if (this.purchasplanResultExecutionAuditConfig) {
        params.processDefinitionKey = this.processDefinitionKey // 工作流节点key
        params.processInitDto = this.processInitDto // 审核人信息传回得信息
      }
      if (this.editMode === '00' || this.editModeID === '00') {
        delete params.belongTenderNo
        // params = this.delKeys(params, ['belongTenderNo'])
      }
      // else if (this.editMode === '01') {
      //   delete params.paymentType
      //   // params = this.delKeys(params, ['paymentType'])
      // }
      return params
    },
    // 审批流提交
    submitFlow() {
      if (this.editMode === '02' || this.editModeID === '04') {
        this.changeResult()
      } else {
        this.saveOrSubmitCall(this.getParamsData())
      }
    },
    // 保存提交
    saveOrSubmit(operation) {
      if (operation === '00') {
        this.saveLoading = true
        const params = this.getParamsData()
        params.operation = '00'
        this.saveOrSubmitCall(params)
      } else {
        this.saveLoading = false
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.subLoading = true
            this.$confirm('是否确定提交？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              confirmButtonClass: 'confirmBtn',
              cancelButtonClass: 'cancelBtn',
              type: 'warning'
            }).then(() => {
              this.subLoading = false
              // 判断是否进入工作流
              if (this.purchasplanResultExecutionAuditConfig) {
                // 判断审核人员是否是多个
                if (JSON.stringify(this.processNode) !== '{}' && this.processNode.nodeId) {
                  this.$refs.departDialog.getUserDepart(this.processNode)
                }
              } else {
                // 直接提交
                this.submitFlow()
              }
            }).catch(() => {
              this.subLoading = false
            })
          } else {
            this.subLoading = false
            this.$message({
              type: 'warning',
              message: '注意页面提示信息'
            })
          }
        })
      }
    },
    saveOrSubmitCall(params) {
      // 保存提交接口调用
      saveOrSubmitPurchaseResultExecute(params).then(response => {
        this.$message({
          type: 'success',
          message: '操作成功！'
        })
        this.back()
      }).catch(() => {
      })
    },
    // 变更调起
    changeResult() {
      const params = {
        // belongOrgId: this.formData.belongOrgId, // 代理单位ID
        // belongOrgName: this.formData.belongOrgName, // 代理单位名称
        executeId: this.formData.executeId // 执行表ID
        // processInitDto: this.processInitDto // 审核人信息传回得信息
      }
      // 判断是否进入工作流
      if (this.purchasplanResultExecutionChangeAudit) {
        params.processInitDto = this.processInitDto // 审核人信息传回得信息
      }
      // 变更接口调用
      changePurchaseResultExecuteInfo(params).then(response => {
        this.$message({
          type: 'success',
          message: '变更成功！'
        })
        this.back()
      }).catch(() => {
      })
    },
    // 变更
    changePurchaseResult() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.changeLoading = true
          this.$confirm('是否确定变更？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            confirmButtonClass: 'confirmBtn',
            cancelButtonClass: 'cancelBtn',
            type: 'warning'
          }).then(() => {
            this.changeLoading = false
            // 判断是否进入工作流
            if (this.purchasplanResultExecutionChangeAudit) {
              // 判断审核人员是否是多个
              if (JSON.stringify(this.processNode) !== '{}' && this.processNode.nodeId) {
                this.$refs.departDialog.getUserDepart(this.processNode)
              }
            } else {
              // 直接提交
              this.submitFlow()
            }
          }).catch(() => {
            this.changeLoading = false
          })
        } else {
          this.changeLoading = false
          this.$message({
            type: 'warning',
            message: '注意页面提示信息'
          })
        }
      })
    },
    // 批量删除属性
    delKeys(obj, keys) {
      keys.map((key) => {
        delete obj[key]
      })
      return obj
    },
    // 返回按钮
    back() {
      this.$router.push({ path: '/procurement/ProcurementPlanRstMgmtList' })
    }
  }
}
</script>
<style lang="less" scoped>
 /deep/.select-popper{
    max-width: 100%;
  }
</style>
