<!--
 @description: 采购员/采购执行人-创建采购单-第二步发布采购公告编辑
 @author: gmy
 @date: 2020-6-21 14:36:58
 @routerPath: /procurement/procurementProject/proPublishNoticeContent
-->
<template>
  <div class="p0-16">
    <el-form ref="form" :model="ruleData" :inline-message="true">
      <p class="page-title">
        1.项目规则
      </p>
      <!--    询价 采购方式为11 招标 采购方式为00-->
      <projecctRule-Enquiry
        v-if="tenderMethod==='11'"
        ref="ruleDatas"
        :data-rule="ruleData"
        :tender-type="tenderType"
        :tender-id="tenderId"
      />
      <!--    单一来源 采购方式为12-->
      <projectRule-SingSource v-if="tenderMethod==='12'" ref="ruleDatas" :data-rule="ruleData" :tender-method="tenderMethod" />
      <!--   竞争性谈判 采购方式为13-->
      <projectRule-Competitive v-if="tenderMethod==='13'" ref="ruleDatas" :data-rule="ruleData" :tender-method="tenderMethod" />
      <!--    竞价 采购方式为14-->
      <projectRule-Bidding v-if="tenderMethod==='14'" ref="ruleDatas" :data-rule="ruleData" />
      <!--    招标 采购方式为00-->
      <projectBidsRuleAdd v-if="tenderMethod==='00'" ref="ruleDatas" :data-rule="ruleData" />
      <!--  添加供应商组件 项目类型 00 公开隐藏 01 邀请显示    -->
      <div v-if="tenderType === '01'">
        <el-row :gutter="40">
          <el-col :md="24" :lg="24" class="mt10 mb10">
            <span class="page-title">2.邀请供应商</span>
            <!-- <el-button style="margin-left: 10px" type="primary" @click="addSupplier">
                添加供应商
              </el-button> -->
          </el-col>
        </el-row>
        <div>
          <proAdd-Supplier
            :data-rule="ruleData"
            :supplist="procurementSupplierList"
            @deleteSupplier="deleteSupplier"
          />
          <!--分页组件-->
          <pagination :pagination-data="paginationData" @change="initSupplier" />
        </div>
      </div>
      <!--  补充说明  -->
      <p v-if="tenderType === '01'" class="page-title">
        3.补充说明
      </p>
      <p v-else class="page-title">
        2.补充说明
      </p>
      <!-- 补充说明组件 -->
      <project-supplement ref="proSupplement" :save-notice-data="saveNotice" :updata-files-data="supplementaryData" @fileListType="fileListType" />
    </el-form>
    <!--保存按钮-->
    <div class="but_footer">
      <div class="but_footer-h">
        <div class="but_footer-but">
          <!-- 上一步 -->
          <el-button :loading="confirmLoading" @click="prevStep">
            上一步
          </el-button>
          <!-- 保存 -->
          <el-button :loading="confirmLoading" @click="saveData('form')">
            {{ language.keep }}
          </el-button>
          <!-- 发布公告 -->
          <el-button :loading="confirmLoading" type="primary" @click="nextStep('form')">
            {{ tenderMethod==='00'?'提交' : '发布公告' }}
          </el-button>
        </div>
      </div>
    </div>
    <!-- 添加供应商弹框   -->
    <addSupplier-dialog
      :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 } from '@/api/procurement/procurementProject'// 获取项目信息
import { saveProcurementRuleRecord, queryProcurementRuleRecord, deleteConditionById } from '@/api/procurement/procurementProject' // 获取项目信息 获取项目规则
import { procurementProcfileTakeEffect, deleteProtProcfile } from '@api/procurement/procurementProtdoc'
import { queryBaseProcurementBulletinInfo, saveBaseProcurementBulletinInfo } from '@/api/procurement/procurementBulletin'
import { queryProcurementInvitatinByTenderId, queryProcurementInvitatinDetailPage, saveProcurementInvitatinDetailSupplierList, removeProcurementInvitatinDetailSupplier, saveProcurementInvitatin } from '@/api/procurement/procurementInvitation' // 保存供应商
/* 公共方法*/
import { mapGetters } from 'vuex' // 文件上传路径
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 projecctRuleEnquiry from '../procurementProjectRule/projectRuleEnquiry/projecctRuleEnquiry-add' // 询价
import projectRuleSingSource from '../procurementProjectRule/projectRuleSingleSource/projectRuleSingSource-add' // 单一来源
import projectRuleCompetitive from '../procurementProjectRule/projectRuleCompetitive/projectRuleCompetitive-add' // 竞争性谈判
import projectRuleBidding from '../procurementProjectRule/projectRuleBidding/projectRuleBidding-add' // 竞价
import projectBidsRuleAdd from '../procurementProjectRule/projectBidsRule/projectBidsRule-add' // 招标
import proAddSupplier from '../procurementAddSupplier/procurementAddSupplier-list' // 供应商列表
import projectAddSupplier from '../procurementAddSupplier/procurementAddSupplier-dialog' // 添加供应商弹框
import projectSupplement from '../procurementProjectSupplement/procurementProjectSupplement-add'
/* ==========工作流===========*/
import { workCommonMixins } from '@views/work/mixins/workCommonMixins' // 工作流公共配置
import workconstant from '@/assets/js/workutils/workconstant/purProject' // 配置流程key
import processNodeCom from '@views/work/processNodeCom' // 工作流选择节点组件
import departDialog from '@views/work/depart-dialog' // 选择审核人员
/* ============================*/
export default {
  name: 'ProjectPublistNoticeAddVue',
  components: {
    'projecctRule-Enquiry': projecctRuleEnquiry, // 询价
    'projectRule-SingSource': projectRuleSingSource, // 单一来源
    'projectRule-Competitive': projectRuleCompetitive, // 竞谈
    'projectRule-Bidding': projectRuleBidding, // 竞价
    'proAdd-Supplier': proAddSupplier, // 供应商列表
    'addSupplier-dialog': projectAddSupplier, // 添加供应商弹框
    'project-supplement': projectSupplement, // 补充说明
    projectBidsRuleAdd, // 招标
    pagination, // 分页
    processNodeCom,
    departDialog
  },
  mixins: [ListMixin, procurementProjectGroupMixin, procurementProjectMixins, workCommonMixins, procurementProjectWorkMixins],
  data() {
    return {
      flowStatus: this.$route.query.flowStatus, // true 工作流进入驳回编辑
      tenderId: '', // 项目id
      tenderMethod: '', // 项目的采购方式 11 询价 12单一来源 13竞争性谈判 14 竞价 不同的采购方式展示不同的项目规则
      tenderType: '', // 项目类型 00 公开 01 邀请 控制邀请供应商列表的展示 01 显示,
      procurementSupplierList: [], // 供应商列表
      procurementBulletinConditionList: [], // 响应条件
      processDefinitionKey: '', // 工作流节点key
      // 查询供应商列表请求参数
      searchForm: {
        tenderId: this.$route.query.tenderId
      },
      loading: false, // loading效果
      isUpload: false, // 判断文件是否上传完 布尔值
      prevRouterPath: '' // 上一步路由
    }
  },
  computed: {
    /* language 国际化*/
    ...mapGetters(['language'])
  },
  created() {
    this.procurementInvitationAudit() // 保存采购邀请函基本信息工作流配置
    this.procurementBulletinAudit() // 保存公告工作流配置
    this.handelFlow()
    this.processDefinitionKey = this.tenderType === '00' ? workconstant.publishAnnouncement : workconstant.publishTenderInvitation // 工作流流程key
  },
  methods: {
    // flowStatus true 工作流进入
    handelFlow() {
      if (this.flowStatus) {
        this.tenderId = this.$route.query.id
        this.searchForm.tenderId = this.tenderId
        this.prevRouterPath = '/work/procurementProjectList/procurementBaseContentAdd'
      } else {
        this.tenderId = this.$route.query.tenderId || this.formData.tenderId
        this.searchForm.tenderId = this.tenderId
        this.prevRouterPath = '/procurement/procurementBaseContentAdd'
      }
      if (this.tenderId) {
        // 查询采购项目规则信息
        this.initData()
      }
    },
    /*
    * 获取采购项目信息方法
    * @params {tenderId: 项目id}
    */
    initData() {
      const data = { tenderId: this.tenderId }
      queryBaseProcurementProjectInfo(data).then(res => {
        // 获取项目采购方式字段
        this.tenderMethod = res.data.tenderMethod // 获取采购方式 11询价 12 单一来源 13竞争性谈判 14 竞价
        this.addSupplierDialogData.tenderMethod = this.tenderMethod
        this.saveNotice.tenderMethod = this.tenderMethod // 获取采购方式 单一来源显示 批复
        this.tenderType = res.data.tenderType // 获取项目类型 00 公开 01 邀请
        this.supplerlist.packId = res.data.packId // 获取项目标段id
        this.supplerlist.tenderId = this.tenderId // 获取项目id
        // 查询项目规则方法
        const tenterId = this.$route.query.tenderId // 采购项目信息Id
        // 查询项目规则
        this.initRuleData(tenterId)
      })
    },
    /* ======================================================页面Dom事件====================================================*/
    // 打开添加供应商弹框
    addSupplier() {
      this.addSupplierDialogData.dialog = true
    },
    // 上一步
    prevStep() {
      this.confirmLoading = true // btnLoading
      // 设置采购公告上一步字段 state 02
      this.saveNotice.state = '02'
      // 获取项目规则数据
      const data = this.$refs.ruleDatas.assemblyData()
      // 增加项目上一步字段status 02 上一步
      data.status = '02'
      // 调用保存项目规则方法
      this.saveProcurementRuleData(data, 'prev')
    },
    // 保存采购公告数据
    assetsNoticeData() {
      if (this.tenderMethod !== '12') {
        const data = {
          id: this.saveNotice.id, // id
          mattersNeedingAttention: this.saveNotice.mattersNeedingAttention, // 补充说明
          tenderId: this.searchForm.tenderId, // 项目id
          packId: this.$route.query.packId, // 标段id
          state: this.saveNotice.state, // 保存 00 提交01
          procurementConditionDtoList: this.procurementBulletinConditionList // 响应条件
        }
        return data
      }
      const data = {
        id: this.saveNotice.id, // id
        mattersNeedingAttention: this.saveNotice.mattersNeedingAttention, // 补充说明
        tenderId: this.searchForm.tenderId, // 项目id
        packId: this.$route.query.packId, // 标段id
        state: this.saveNotice.state, // 保存 00 提交01
        publicityEndTime: this.ruleData.publicityEndTime, // 公示结束时间
        workingDay: this.ruleData.workingDay, // 公示结束时间工作日
        hourMmSs: this.ruleData.hourMmSs, // 距离报价截至时间
        materialContactPerson: this.ruleData.materialContactPerson, // 物资公司联系人
        materialContactPhone: this.ruleData.materialContactPhone, // 联系电话
        materialContactEmail: this.ruleData.materialContactEmail, // 联系邮箱
        materialContactAddress: this.ruleData.materialContactAddress, // 联系地址
        procurementConditionDtoList: this.procurementBulletinConditionList // 响应条件
      }
      return data
    },
    // 保存数据
    saveData() {
      this.confirmLoading = true // btnloading
      // 设置采购公保存字段 state 00
      this.saveNotice.state = '00'
      // 获取项目规则数据
      const data = this.$refs.ruleDatas.assemblyData()
      // 增加项目保存字段status 00 保存
      data.status = '00'
      // 调用保存项目规则
      this.saveProcurementRuleData(data, 'save')
    },
    // 工作流
    subFlow() {
      const data = this.$refs.ruleDatas.assemblyData()
      // 增加项目提交字段status 01 提交
      data.status = '01'
      this.saveProcurementRuleData(data, 'next')
    },
    // 发布公告
    nextStep(formName) {
      this.$refs.proSupplement.principalFile()
      // 设置采购公告保存字段 state 01
      this.saveNotice.state = '01'
      // 校验输入内容
      this.$refs[formName].validate((valid, field) => {
        if (valid) {
          /**
         * decideSupplierNumMethods 判断采购方式对应选择的供应商家数是否符合
         * tenderMethod采购方式 11询价 12单一来源 13竞争性谈判 14 竞价
         * procurementSupplierList: 供应商列表
         * tenderType: 项目类型 00 公开 01邀请 仅有邀请下才可选择供应商
         */
          const flag = this.decideSupplierNumMethods(this.tenderMethod, this.procurementSupplierList.length, this.tenderType)
          if (flag) {
            let hint = '确认发送采购公告吗？'
            if (this.tenderMethod === '00') {
              hint = '确认提交吗？'
            }
            this.$confirm(hint, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              confirmButtonClass: 'confirmBtn',
              cancelButtonClass: 'cancelBtn',
              type: 'warning'
            })
              .then(() => {
                // 判断是否进入工作流
                if (this.procurementInvitationAuditConfig && this.procurementBulletinAuditConfig) {
                  // 判断审核人员是否是多个
                  if (JSON.stringify(this.processNode) !== '{}' && this.processNode.nodeId) {
                    this.$refs.departDialog.getUserDepart(this.processNode)
                  }
                } else {
                  // 直接提交
                  this.subFlow()
                }
              })
              .catch(() => {
                this.confirmLoading = false
                this.loading = false
              })
          }
        } else {
          this.$message.warning('请注意页面提示信息')
          this.confirmLoading = false
          this.loading = false
        }
      })
    },
    // 添加供应商的数据回调
    consignContractInfo(val) {
      // 获取添加的供应商数据
      this.supplerlist.list = val
      saveProcurementInvitatinDetailSupplierList(this.supplerlist).then(res => {
        // 调用查询采购公告方法
        this.addSupplierDialogData.excludeSupplierIds = res.data // 已被邀请供应商所有id拼接的字符串
        // 调用获取供应商；列表方法
        this.initSupplier()
        this.$message({
          message: '添加供应商成功',
          type: 'success'
        })
      })
    },
    // 删除供应商回调
    deleteSupplier(val) {
      if (val.id) {
        removeProcurementInvitatinDetailSupplier(
          val.id,
          this.$route.query.id
        ).then(res => {
          // 判断当前页数为空时将pageNo -1 阻止请求返回空的情况
          if (this.procurementSupplierList.length - 1 === 0) {
            this.paginationData.pageNo = this.paginationData.pageNo -= 1 < 0 ? 0 : this.paginationData.pageNo -= 1
          }
          // 调动获取供应商列表方法
          this.initSupplier()
          this.$message({
            message: '供应商移除成功',
            type: 'success'
          })
        })
      }
    },
    // 附件上传的回调
    fileListType(val) {
      this.$set(this.ruleData, 'principalFile', val)
    },
    /* ======================================获取页面数据方法======================================================*/
    /*
    * 获取项目规则
    * @params { tenderId: 项目id}
    * 返回项目规则数据
    */
    initRuleData(tenterId) {
      const data = { tenderId: tenterId }
      queryProcurementRuleRecord(data).then(res => {
        if (res.data.id !== null) {
          this.ruleData = {
            ...res.data
          }
          if (!this.ruleData.currency) this.ruleData.currency = '00' // 币种默认选中“人民币”
          if (!this.ruleData.quoteMethod) this.ruleData.quoteMethod = '01' // 采购单，项目规则里，询价方式，默认选中一次报价
          this.ruleData.supplierAttribute = this.ruleData.supplierAttribute ? this.ruleData.supplierAttribute.split(',') : '' // 供应商属性
          this.ruleData.supplierCategory = this.ruleData.supplierCategory ? this.ruleData.supplierCategory.split(',') : '' // 供应商分类
        }
        const tenterId = this.$route.query.tenderId // 采购项目信息Id
        // 查询公告方法
        this.queryBaseProcurementBulletinInfoData(tenterId)
      })
    },
    // 封装获取公告方法
    queryBaseProcurementBulletinInfoData(tenderId) {
      // 获取采购公告
      if (this.tenderType === '00') {
        queryBaseProcurementBulletinInfo(tenderId).then(res => {
          // 获取采购公告id
          this.saveNotice.id = res.data.id
          // 获取备注信息
          this.saveNotice.mattersNeedingAttention = res.data.mattersNeedingAttention
        })
          .catch(() => {})
      } else if (this.tenderType === '01') {
        // 获取邀请函
        queryProcurementInvitatinByTenderId(tenderId).then(response => {
          // 获取邀请函公告id
          this.saveNotice.id = response.data.id
          this.supplerlist.invitationId = this.saveNotice.id
          // 获取备注信息
          this.saveNotice.mattersNeedingAttention = response.data.mattersNeedingAttention
          // 已被邀请供应商所有id拼接的字符串
          this.addSupplierDialogData.excludeSupplierIds = response.data.excludeSupplierIds
          this.ruleData = {
            ...this.ruleData,
            publicityEndTime: response.data.publicityEndTime ? response.data.publicityEndTime : '', // 公示结束时间
            materialContactPerson: response.data.materialContactPerson ? response.data.materialContactPerson : '', // 物资公司联系人
            materialContactPhone: response.data.materialContactPhone ? response.data.materialContactPhone : '', // 联系电话
            materialContactEmail: response.data.materialContactEmail ? response.data.materialContactEmail : '', // 邮箱
            materialContactAddress: response.data.materialContactAddress ? response.data.materialContactAddress : '' // 地址
          }
          // 响应条件初始化为null默认空数组
          this.procurementBulletinConditionList = response.data.procurementInvitationConditionList ? response.data.procurementInvitationConditionList : []
          // 查询供应商列表
          this.initSupplier()
        }).catch(() => {})
      }
    },
    // 查询供应商条件
    getQueryParams() {
      const param = Object.assign({}, this.searchForm)
      param.pageNo = this.paginationData.pageNo
      param.pageSize = this.paginationData.pageSize
      return filterObj(param)
    },
    // 获取供应商列表方法
    initSupplier() {
      const data = this.getQueryParams()
      queryProcurementInvitatinDetailPage(data).then(res => {
        // 获取供应商列表数据
        this.procurementSupplierList = res.data.records
        this.$forceUpdate() // 数据强制刷新
        // 查询供应商列表id集合
        this.supplierIdData()
        this.paginationData.total = res.data.total
      })
    },
    /* ======================================保存页面数据方法======================================================*/
    // 封装保存项目规则方法
    saveProcurementRuleData(ruleData, info) {
      this.loading = true
      this.confirmLoading = true
      saveProcurementRuleRecord(ruleData).then(res => {
        // 获取公告保存数据
        const assetsNoticeData = this.assetsNoticeData()
        // 判断是否进入工作流
        if (info === 'next' && this.procurementInvitationAuditConfig && this.procurementBulletinAuditConfig) {
          assetsNoticeData.processInitDto = this.processInitDto // 审核人信息传回得信息
          assetsNoticeData.processDefinitionKey = this.processDefinitionKey
        }
        // 公开类项目的公告保存 tenderType 00 公告
        if (this.tenderType === '00' || this.tenderType === '02') {
          // 保存采购公告方法
          this.saveBaseProcurementBulletinData(assetsNoticeData, info)
          // 邀请类项目的公告保存 tenderType 01 邀请
        } else if (this.tenderType === '01') {
          // 保存邀请函方法
          this.saveProcurementInvitatinData(assetsNoticeData, info)
        }
      }).catch(() => {
        this.loading = false
        this.confirmLoading = false
      })
    },
    // 封装保存采购文件方法
    procurementProcfileTakeEffectData(supplementaryData) {
      procurementProcfileTakeEffect(supplementaryData)
        .then(res => {})
        .catch(() => {})
    },
    // 封装保存采购公告
    saveBaseProcurementBulletinData(data, info) {
      saveBaseProcurementBulletinInfo(data)
        .then(res => {
          this.loading = false
          this.confirmLoading = false
          if (info === 'prev') {
            this.$router.push({
              path: this.prevRouterPath,
              query: { ...this.$route.query }
            })
          } else if (info === 'save') {
            this.$message.success('保存成功')
            this.initRuleData(this.searchForm.tenderId)
            this.queryBaseProcurementBulletinInfoData(this.searchForm.tenderId)
          } else if (info === 'next') {
            this.confirmLoading = false
            this.handleClose()
          }
        })
        .catch(() => {
          this.loading = false
          this.confirmLoading = false
        })
    },
    // 封装保存邀请函方法
    saveProcurementInvitatinData(data, info) {
      saveProcurementInvitatin(data)
        .then(res => {
          if (info === 'prev') {
            this.$router.push({
              path: '/procurement/procurementBaseContentAdd',
              query: { ...this.$route.query }
            })
          } else if (info === 'save') {
            this.$message.success('保存成功')
            this.loading = false
            this.confirmLoading = false
            this.initRuleData(this.searchForm.tenderId)
            this.queryBaseProcurementBulletinInfoData(this.searchForm.tenderId)
          } else if (info === 'next') {
            this.confirmLoading = false
            this.handleClose()
            // this.$router.push({
            //   path: '/procurement',
            //   name: 'procurementDrive',
            //   params: { ...this.$route.query }
            // })
          }
        })
        .catch(() => {
          this.loading = false
          this.confirmLoading = false
        })
    },
    // 发布成功后跳转
    back() {
      this.$route.push(this.comType)
    },
    /* ======================================删除页面数据方法======================================================*/
    // 删除采购文件
    deleteProtProcfileData(bizId) {
      deleteProtProcfile(bizId)
        .then(res => {})
        .catch(() => {})
    },
    // 封装删除响应条件方法
    deleteConditionByData(id) {
      deleteConditionById(id)
        .then(res => {
          // 调用获取采购公告
          this.queryBaseProcurementBulletinInfoData(this.searchForm.tenderId)
        })
        .catch(() => {})
    },
    /* ======================================附件上传======================================================*/
    // 获取供应商供应商列表id集合方法
    supplierIdData() {
      const data = []
      if (this.procurementSupplierList.length > 0) {
        this.procurementSupplierList.forEach(ele => {
          data.push(ele.supplierId)
        })
        this.addSupplierDialogData.excludeSupplierIds = data.toString()
      } else {
        this.addSupplierDialogData.excludeSupplierIds = ''
      }
    },
    /* ======================================其他======================================================*/
    /**
         * decideSupplierNumMethods 判断采购方式对应选择的供应商家数是否符合
         * tenderMethod采购方式 11询价 12单一来源 13竞争性谈判 14 竞价
         * supplierNum: 供应商列表
         * tenderType: 项目类型 00 公开 01邀请 仅有邀请下才可选择供应商
         *
         */
    decideSupplierNumMethods(tenderMethod, supplierNum, tenderType) {
      // 邀请询价校验供应商至少三家
      if (tenderMethod === '11' && supplierNum < 3 && tenderType === '01') {
        this.$message.warning('至少选择三家供应商参加')
        return false
      }
      // 单一来源校验供应商必须选择一家
      if (tenderMethod === '12' && supplierNum < 1 && tenderType === '01') {
        this.$message.warning('至少选择一家供应商参加')
        return false
      }
      // 竞争性谈判校验供应商至少两家
      if (tenderMethod === '13' && supplierNum < 2 && tenderType === '01') {
        this.$message.warning('至少选择两家供应商参加')
        return false
      }
      return true
    },
    // 弹框关闭
    handleClose() {
      if (this.flowStatus) {
        const routePathStatus = sessionStorage.getItem('routePathStatus') // 工作流处理 00桌面进入 01待办列表进入
        this.$router.push({
          path: routePathStatus === '00' ? '/home' : '/work/todo'
        })
      } else {
        // 返回项目列表暂时这样后期会进入驱动
        this.$router.push({ path: this.projectMgmtList[this.tenderMethod] })
      }
    }

  }
}
</script>

<style scoped>

</style>
