<!--
  @description: 项目管理采购项目查看
  @author: gmy
  @routerPath: /procurement/procurementDrive/procurementView
  @routerPath:/procurement/procurementOrderBaseDetail
  /procurement/procurementDrive/procurementContentTabs/procurementProjectContentDetail
  @date: 2020-8-4 22:24:58
-->
<template>
  <div>
    <el-form ref="form" :model="ruleData" :inline-message="true">
      <!-- 项目信息 -->
      <dl class="projectInfoDetail">
        <dt>
          <p class="projectInfoDetail_icon">
            <i class="iconfont icon-xiangguanjigouxinxi" />
          </p>
          项目信息
        </dt>
        <dd>
          <!-- 项目信息 -->
          <projectBase-detail :form-data="formData" :other-data="otherData" :inside-tender-project-file-type="insideTenderProjectFileType" />
        </dd>
      </dl>
      <!-- 行项目信息组件 -->
      <dl class="projectInfoDetail">
        <dt>
          <p class="projectInfoDetail_icon">
            <i class="iconfont icon-xiangguanjigouxinxi" />
          </p>
          行项目信息
        </dt>
        <dd>
          <!-- 行项目信息 -->
          <lineItemInfo-detail :line-project-data="lineProjectData" :other-data="otherData" :subject-matter-change-list="subjectMatterChangeList" />
        </dd>
      </dl>
      <!-- 项目规则 不同的采购方式 展示不同的规则 11 询价 12 单一来源 13 竞争性谈判 14 竞价 -->
      <dl class="projectInfoDetail">
        <dt>
          <p class="projectInfoDetail_icon">
            <i class="iconfont icon-biaodeqingdan" />
          </p>项目规则
        </dt>
        <dd>
          <!-- 询价 -->
          <projecctRule-Enquiry
            v-if="tenderBase.tenderMethod === '11'"
            ref="ruleDatas"
            :tender-type="tenderBase.tenderType"
            :tender-id="tenderBase.tenderId"
            :data-rule="ruleData"
            :other-data="otherData"
          />
          <!-- 单一来源 -->
          <projectRule-SingSource
            v-if="tenderBase.tenderMethod === '12'"
            ref="ruleDatas"
            :data-rule="ruleData"
            :other-data="otherData"
          />
          <!-- 竞争性谈判 -->
          <projectRule-Competitive
            v-if="tenderBase.tenderMethod === '13'"
            ref="ruleDatas"
            :data-rule="ruleData"
            :other-data="otherData"
          />
          <!-- 竞价  -->
          <projectRule-Bidding
            v-if="tenderBase.tenderMethod === '14'"
            ref="ruleDatas"
            :data-rule="ruleData"
            :other-data="otherData"
          />
        </dd>
      </dl>
      <!-- 查看供应商列表 只有邀请才展示 -->
      <dl v-if="tenderBase.tenderType==='01'" class="projectInfoDetail">
        <dt>
          <p class="projectInfoDetail_icon">
            <i class="iconfont icon-biaoduanbaoxinxi" />
          </p>
          邀请供应商
          <!--          <gx-button v-if="tenderBase.tenderMethod!=='12'&&isAddSupplierChange" :code="'001_001_002'" :loading="confirmLoading" type="primary" @click="addSupplier">
            追加供应商
          </gx-button>-->
        </dt>
        <dd>
          <supplierList-detail v-if="formData.tenderType==='01'" :supplier-list="procurementSuplierList" />
          <!--分页组件-->
          <page-nation :pagination-data="paginationData" @change="initSupplier" />
        </dd>
      </dl>
      <!-- 补充说明 -->
      <dl class="projectInfoDetail">
        <dt>
          <p class="projectInfoDetail_icon">
            <i class="iconfont icon-xiangguanjigouxinxi" />
          </p>
          补充说明
        </dt>
        <dd>
          <!-- 补充说明 saveNotice  公告备注 loadProcurementFile  otherData其他信息-->
          <supplement-detail
            ref="proSupplement"
            :save-notice-data="saveNotice"
            :other-data="otherData"
            :load-procurement-file="loadProcurementFile"
            @fileListType="fileListType"
          />
        </dd>
      </dl>
    </el-form>
    <!--变更按钮 isChange是否显示变更栏  采购方式为单一来源的不显示 isChangeShow 控制变更是否显示字段  00 不显示 01显示 -->
    <div v-if="isChange" class="but_footer">
      <div class="but_footer-h">
        <div class="but_footer-but">
          <!-- 变更 -->
          <gx-button v-if="!otherData.isEdit" :code="'001_001_001'" :loading="confirmLoading" type="primary" @click="noticeChange">
            变 更
          </gx-button>
          <!-- 提交变更    isEdit 布尔值  点击变更后为true-->
          <template v-if="otherData.isEdit">
            <!-- 提交 isEdit 布尔值  点击变更后未true-->
            <gx-button :loading="confirmLoading" :code="'001_001_004'" type="primary" @click="nextStep('form')">
              提 交
            </gx-button>
            <gx-button :loading="confirmLoading" :code="'001_001_003'" plain @click="noticeBack">
              返 回
            </gx-button>
          </template>
        </div>
      </div>
    </div>
    <!-- 添加供应商弹框   -->
    <addSupplier-dialog
      :key="new Date()*1"
      :dialog-data="addSupplierDialogData"
      @consignContractInfo="consignContractInfo"
    />
    <!--工作流选择节点组件-->
    <processNodeCom
      ref="processNode"
      :process-definition-key="processDefinitionKey"
      @processNodeData="processNodeData"
    />
    <!--工作流流程节点/获取审核用户-->
    <departDialog
      ref="departDialog"
      :process-node="processNode"
      @isSingleUser="isSingleUser"
      @processInitData="processInitData"
      @submit="subFlow"
    />
  </div>
</template>

<script>
/* 接口*/
import { queryBaseProcurementProjectInfo, queryProcurementRuleRecord, listSubjectMatterPagesByTenderId } from '@/api/procurement/procurementProject' // 获取采购项目基本信息
import { queryBaseProcurementBulletinInfo } from '@/api/procurement/procurementBulletin'
import { getProcurementProcfileByPackId } from '@/api/procurement/procurementProtdoc'
import { queryProcurementInvitatinByTenderId, queryProcurementInvitatinDetailPage, saveProcurementInvitatinDetailSupplierList } from '@/api/procurement/procurementInvitation' // 保存供应商
import { submitChangeRecord, queryChangeRecord, getChangeBulletinInfo } from '@/api/procurement/procurementEexception' // 保存变更记录
/* 公共方法*/
import { filterObj } from '@/assets/js/utils'// 深拷贝
/* 混合开发-参数字段*/
import { ListMixin } from '@/mixins/ListMixin'// 分页
import { procurementProjectGroupMixin } from '../mixins/procurementProjectGroupMixin' // 采购立项 公共字典
import { procurementProjectMixins } from '../mixins/procurementProjectMixins' // 采购立项 公共字典
import { procurementProjectWorkMixins } from '../mixins/procurementProjectWorkMixins' // 工作流配置
/* 组件*/
import pagination from '@comp/common/pagination/pagination' // 分页组件
import projectBaseDetail from '../procurementProjectBase/procurementProjectBase-detail' // 项目信息组件
import lineItemInfoDetail from '../procurementProjectLineItemInfo/procurementProjectLineItemInfo-detail' // 行项目信息组件
import projecctRuleEnquiry from '../procurementProjectRule/projectRuleEnquiry/projectRuleEnquiry-detail' // 询价
import projectRuleSingSource from '../procurementProjectRule/projectRuleSingleSource/projectRuleSingSource-detail' // 单一来源
import projectRuleCompetitive from '../procurementProjectRule/projectRuleCompetitive/projectRuleCompetitive-detail' // 竞争性谈判
import projectRuleBidding from '../procurementProjectRule/projectRuleBidding/projectRuleBidding-detail' // 竞价
import supplierListDetail from '../procurementAddSupplier/procurementAddSupplier-detail' // 查看供应商列表
import supplementDetail from '../procurementProjectSupplement/procurementProjectSupplement-detail'
import projectAddSupplier from '../procurementAddSupplier/procurementAddSupplier-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: 'ProcurementProjectContentVue',
  components: {
    'projectBase-detail': projectBaseDetail, // 采购项目信息组件
    'lineItemInfo-detail': lineItemInfoDetail, // 行项目信息组件
    'projecctRule-Enquiry': projecctRuleEnquiry, // 询价
    'projectRule-SingSource': projectRuleSingSource, // 单一来源
    'projectRule-Competitive': projectRuleCompetitive, // 竞谈
    'projectRule-Bidding': projectRuleBidding, // 竞价
    'supplierList-detail': supplierListDetail, // 查看供应商列表
    'addSupplier-dialog': projectAddSupplier, // 添加供应商弹框
    'supplement-detail': supplementDetail, // 补充说明
    'page-nation': pagination, // 分页组件
    processNodeCom, // 工作流节点信息组件
    departDialog // 工作流审批人组件
  },
  mixins: [ListMixin, procurementProjectGroupMixin, procurementProjectMixins, workCommonMixins, procurementProjectWorkMixins],
  inject: ['driveReload', 'getTenderBase'],
  data() {
    return {
      confirmLoading: false, // loading
      procfileId: '', // 业务主键id
      lineProjectData: [], // 行项目信息数据
      procurementSuplierList: [], // 供应商列表
      processDefinitionKey: '', // 工作流流程key
      // 查询行项目信息
      searchForm: {
        createUser: '', // 物资创建人id
        orderBy: 0, // 排序
        tenderId: ''// 项目id
      },
      // 查询供应商列表请求参数
      getSupplier: {
        tenderId: ''
      },
      isChange: false, // 是否显示变更按钮
      isAddSupplierChange: false, // 是否显示追加供应商
      // ======== 变更  start===========
      subjectMatterChangeList: [], // 变更后对应的行项目数据获取新的bizId
      // 变更数据参数
      otherData: {
        newBizId: '', // 变更后新的bizid
        isEdit: false, // 是否可编辑 true 显示变更 false不显示 默认不显示
        procFrameType: '' // procFrameType 采购和框架项目 00 采购 01框架
      },
      // ======== 变更  End===========
      tenderBase: this.getTenderBase() // 获取采购采购项目信息
    }
  },
  created() {
    this.procurementChangebulletinAudit() // 提交变更公告工作流配置
    this.processDefinitionKey = workconstant.purchaseTenderChange // 变更工作流流程key
    // 获取项目信息
    this.initProjectData()
    // 获取项目规则
    this.initRule()
  },
  methods: {
    // 监听附件上传的回调
    fileListType(val) {
      this.$set(this.ruleData, 'principalFile', val)
    },
    // 打开添加供应商弹框
    addSupplier() {
      this.supplerlist.tenderId = this.tenderBase.tenderId
      this.addSupplierDialogData.dialog = true
    },
    // 添加供应商的数据回调
    consignContractInfo(val) {
      // 获取添加的供应商数据
      this.supplerlist.list = val
      this.supplerlist.packId = this.tenderBase.packId // 获取项目标段id
      this.supplerlist.tenderId = this.tenderBase.tenderId // 获取项目id
      saveProcurementInvitatinDetailSupplierList(this.supplerlist).then(res => {
        // 调用查询采购公告方法
        this.addSupplierDialogData.excludeSupplierIds = res.data // 已被邀请供应商所有id拼接的字符串
        // 调用获取供应商；列表方法
        this.initSupplier()
        this.$message({
          message: '添加供应商成功',
          type: 'success'
        })
      })
    },
    // 公告变更
    noticeChange() {
      this.confirmLoading = true
      this.saveChangeRecorData(this.tenderBase.packId)
      // 获取变更信息
      this.getChangeBulletinInfo()
      this.otherData.isEdit = true
    },
    // 设置变更按钮是否显示
    setIsChange() {
      // 采购方式单一来源 不显示变更
      if (this.tenderBase.tenderMethod === '12') {
        this.isChange = false
        this.isAddSupplierChange = this.isChange
        return
      }
      // 采购方式为询价 竞谈 竞价类时 需判断报价是否截止 来判断是否可变更
      if (this.tenderBase.tenderMethod !== '12') {
        if (this.tenderBase.isChangeShow === '01' && this.ruleData.auditStatus !== '00') {
          this.isChange = true
          this.isAddSupplierChange = this.isChange
        } else {
          this.isChange = false
          this.isAddSupplierChange = this.isChange
        }
        return
      }
    },
    // 返回
    noticeBack() {
      this.confirmLoading = false
      // 设置变更字段 isEdit false 不变更
      this.otherData.isEdit = false
      this.isAddSupplierChange = true // 保存失败显示追加供应商
      // 刷新驱动 防止编辑不保存返回数据丢失
      this.driveReload()
    },
    subFlow() {
      this.submitChangeRecordMessage()
    },
    // 校验行项目交货时间和税率情况 planType 采购项目和框架采购项目 00 采购项目 01框架采购项目
    procVerifylineItem(lineItemList) {
      if (this.formData.planType === '00') {
        // 校验行项目信中的说率和交货时间是否为空 lineItemIsEmpty 有空返回下标 不为空返回-1
        const lineItemIsEmpty = lineItemList.findIndex(lineitem => {
          return lineitem.deliveryDate === null
        })
        if (lineItemIsEmpty === -1) {
          return true
        }
        this.confirmLoading = false
        this.$message.warning('行项目列表第' + (lineItemIsEmpty + 1) + '行的税率或者交货日期不可为空')
        return false
      } else {
        return true
      }
    },
    // 提交
    nextStep(formName) {
      this.$refs.proSupplement.principalFile()
      this.$refs[formName].validate((valid, field) => {
        if (valid) {
          const data = this.changeData()
          const isLineVerifyResult = this.procVerifylineItem(data.subjectMatterChangeList)
          if (isLineVerifyResult) {
            this.$confirm('确认发送变更公告吗？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              confirmButtonClass: 'confirmBtn',
              cancelButtonClass: 'cancelBtn',
              type: 'warning'
            })
              .then(() => {
                this.confirmLoading = true
                // 判断是否进入工作流
                if (this.procurementChangebulletinAuditConfig) {
                  // 判断审核人员是否是多个
                  if (JSON.stringify(this.processNode) !== '{}' && this.processNode.nodeId) {
                    this.$refs.departDialog.getUserDepart(this.processNode)
                  }
                } else {
                  // 直接提交
                  this.subFlow()
                }

              // this.submitChangeRecordMessage()
              })
              .catch(() => {
                this.confirmLoading = false
              })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    /*
       * =======================变更-页面数据 start==============================
     * */

    // 获取变更数据
    changeData() {
      // 原始数据
      const data = {
        packId: this.tenderBase.packId, // 项目标段id
        mattersNeedingAttention: this.saveNotice.mattersNeedingAttention, // 公告备注
        quoteEndTime: this.$Moment(this.ruleData.quoteEndTime).format(this.momentSaveFormat), // 报价截止时间
        quoteValidity: this.$Moment(this.ruleData.quoteValidity).format(this.momentSaveFormat), // 报价有效期
        subjectMatterChangeList: this.matterMessageListInfo() // 原始行项目信息 (主要包括 行项目id 计划详情id 交货时间 备注)
      }
      return data
    },
    // 处理变更请求是需要的行项目数据
    matterMessageListInfo() {
      const matterMessageList = this.lineProjectData.map(item => {
        return {
          deliveryDate: item.deliveryDate ? this.$Moment(item.deliveryDate).format(this.momentSaveFormat) : '', // 交货日期
          remark: item.remark, // 备注
          subjectMatterId: item.id // 行项目id
        }
      })
      return matterMessageList
    },
    // 提交变更方法
    submitChangeRecordMessage() {
      // 获取变更数据
      const data = this.changeData()
      // 判断是否进入工作流
      if (this.procurementChangebulletinAuditConfig) {
        data.processInitDto = this.processInitDto // 审核人信息传回得信息
      }

      submitChangeRecord(data).then(res => {
        // 刷新驱动
        this.driveReload()
        this.otherData.isEdit = false
        this.confirmLoading = false
      }).catch(() => {
        this.confirmLoading = false
      })
    },
    /*
    saveChangeRecorData 保存公告变更记录方法(变更前与变更后提交是都需要调用次方法)
    changeData变更数据
    changeType变更类型 old 变更前标识 new 变更后标识
    */
    saveChangeRecorData(packId) {
      const data = {
        packId: packId
      }
      queryChangeRecord(data).then(res => {
        // 获取变更后采购文件的bizid
        this.otherData.newBizId = res.data.changeRecordId
        // 获取变更后行项目变更bizid集合
        this.subjectMatterChangeList = res.data.subjectMatterChangeList
        // loading
        this.confirmLoading = false
        // 设置变更字段 isEdit true变更 显示返回与提交按钮 变更按钮隐藏
        this.otherData.isEdit = true
        this.isAddSupplierChange = false
      }).catch(() => {
        this.otherData.isEdit = false
        this.isAddSupplierChange = true // 保存失败显示追加供应商
        this.confirmLoading = false // loading
      })
    },
    /*
       * =======================变更 End==============================
     * */
    /*
       * =======================获取-页面数据 start==============================
     * */
    // 获取项目信息
    initProjectData() {
      const data = { tenderId: this.tenderBase.tenderId }
      queryBaseProcurementProjectInfo(data).then(res => {
        // 获取项目信息
        this.formData = res.data
        this.otherData.procFrameType = this.formData.planType // 区分是否是采购或者框架项目 00 采购 01框架
        this.otherData.projectStatus = this.tenderBase.purchaseProjectStatus // 获取项目状态
        this.insideTenderProjectFileType.bizId = this.tenderBase.tenderId
      })
    },
    /*
    * 获取项目规则
    * @params { tenderId: 项目id}
    * 返回项目规则数据
    */
    initRule() {
      const data = { tenderId: this.tenderBase.tenderId }
      queryProcurementRuleRecord(data).then(res => {
        this.ruleData = { ...res.data }
        // 获取变更信息
        this.getChangeBulletinInfo()
        // 查询公告方法
        this.queryBaseProcurementBulletinInfoData(data.tenderId)
        // 查询行项目信息
        this.initLineInfoData()
        // 查询供应商列表
        this.initSupplier()
      }).catch(() => {
      })
    },
    // 获取变更信息
    getChangeBulletinInfo() {
      const data = { tenderId: this.tenderBase.tenderId }
      getChangeBulletinInfo(data).then((res) => {
        // 判断状态是否赋值最新变更数据 0代表变更中 1代表变更结束
        if (res.data && res.data.state === '0') {
          this.ruleData.auditStatus = res.data.auditStatus
          this.ruleData.workingDay = res.data.workingDay
          this.ruleData.hourMmSs = res.data.hourMmSs
          this.formData.tendermethodRemarks = res.data.tenderMethodRemarks // 变更的说明信息
          this.saveNotice.mattersNeedingAttention = res.data.mattersNeedingAttention // 变更的 公告备注
        }
        this.ruleData.supplierAttribute = this.ruleData.supplierAttribute.split(',') // 供应商属性
        this.ruleData.supplierCategory = this.ruleData.supplierCategory.split(',') // 供应商分类
        this.otherData.hisToryEndTime = this.ruleData.quoteEndTime
        // 页面初始判断变更按钮是否显示
        this.setIsChange()
      }).catch(() => {

      })
    },
    // 查询行项目信息条件
    getQueryParams() {
      // 获取项目id
      this.searchForm.tenderId = this.tenderBase.tenderId || this.tenderId
      const param = Object.assign({}, this.searchForm)
      param.pageNo = this.paginationData.pageNo
      param.pageSize = this.paginationData.pageSize
      return filterObj(param)
    },
    // 获取行项目信息方法
    initLineInfoData() {
      // 查询条件
      const params = this.getQueryParams()
      listSubjectMatterPagesByTenderId(params).then(res => {
        // 获取行项目信息
        this.lineProjectData = res.data.records
        // 获取标段id
        this.formData.packId = res.data.records[0].packId
      }).catch(() => {})
    },
    // 查询供应商条件
    getSupplierParams() {
      this.getSupplier.tenderId = this.tenderBase.tenderId
      const param = Object.assign({}, this.getSupplier)
      param.pageNo = this.paginationData.pageNo
      param.pageSize = this.paginationData.pageSize
      return filterObj(param)
    },
    // 获取供应商列表方法
    initSupplier() {
      const params = this.getSupplierParams()
      queryProcurementInvitatinDetailPage(params).then(res => {
        // 获取供应商列表数据
        this.procurementSuplierList = res.data.records
        // 获取条数
        this.paginationData.total = res.data.total
      })
    },
    // 封装获取项目公告方法
    queryBaseProcurementBulletinInfoData(tenderId) {
      // 获取采购公告
      if (this.tenderBase.tenderType === '00') {
        // 调用获取项目类型为公开的采购公告数据信息
        this.getProcurementBulletinInfoData(tenderId)
      } else if (this.tenderBase.tenderType === '01') {
        // 调用项目类型为邀请的采购公告数据信息
        this.getProcurementInvitatinInfoData(tenderId)
      }
    },
    // 获取项目类型为公开的采购公告数据信息
    getProcurementBulletinInfoData(tenderId) {
      queryBaseProcurementBulletinInfo(tenderId).then(res => {
        // 获取采购公告id
        this.saveNotice.id = res.data.id
        // 获取备注信息
        this.saveNotice.mattersNeedingAttention = res.data.mattersNeedingAttention
      }).catch(() => {})
    },
    // 获取项目类型为邀请的采购公告数据信息
    getProcurementInvitatinInfoData(tenderId) {
      // 获取邀请函
      queryProcurementInvitatinByTenderId(tenderId).then(response => {
        const { id, mattersNeedingAttention, excludeSupplierIds, publicityEndTime, materialContactPerson, materialContactPhone, materialContactEmail, materialContactAddress } = response.data
        this.ruleData = {
          ...this.ruleData,
          publicityEndTime: publicityEndTime, // 公示结束时间
          materialContactPerson: materialContactPerson, // 物资公司联系人
          materialContactPhone: materialContactPhone, // 联系电话
          materialContactEmail: materialContactEmail, // 邮箱
          materialContactAddress: materialContactAddress // 地址
        }
        // 获取邀请函公告id
        this.saveNotice.id = id
        // 获取备注信息
        this.saveNotice.mattersNeedingAttention = mattersNeedingAttention
        // 获取邀请函id
        this.supplerlist.invitationId = id
        // 已被邀请供应商所有id拼接的字符串
        this.addSupplierDialogData.excludeSupplierIds = excludeSupplierIds
        // 响应条件初始化为null默认空数组
        this.procurementBulletinConditionList = response.data.procurementInvitationConditionList ? response.data.procurementInvitationConditionList : []
      }).catch(() => {})
    },
    // 获取采购文件
    async  loadProcurementFile() {
      const packId = this.tenderBase.packId
      return await getProcurementProcfileByPackId(packId).then(res => {
        this.procfileId = res.data.procfileId
        return {
          id: res.data.procfileId, // 采购文件业务主键id
          makeWay: res.data.makeWay ? res.data.makeWay : '01', // 是否使用采购工具
          tenderId: this.tenderBase.tenderId, // 项目id
          packId: this.tenderBase.packId, // 项目id
          giveId: this.saveNotice.id, // 单一来源批复文件主键id
          tenderMethod: this.formData.tenderMethod // 采购方式
        }
      })
    }
    /*
       * =======================获取-页面数据 End==============================
     * */
  }
}
</script>

<style lang="less" scoped>

</style>
