<!--
 @description: 采购员/采购执行人-创建采购单-询价发布采购公告
 @author: gmy
 @date: 2020-6-21 14:36:58
 @routerPath: /procurement/procurementProject/projectPublishNotice
-->
<template>
  <div v-loading="loading">
    <div class="title title_border p0-16">
      <i class="el-icon-s-home" />采购单
    </div>
    <section class="p0-16">
      <el-form ref="form" :model="ruleData" :inline-message="true">
        <p class="page-title">
          1.项目规则
        </p>
        <!--   询价 采购方式11   -->
        <pro-enquiry :rule-datas="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 class="m10" type="primary" @click="addClick">
                添加供应商
              </el-button>
            </el-col>
          </el-row>
          <div>
            <pro-supplierList
              :supplist="queryProcurementInvitatinDetailVoList"
              @deleteSupplier="deleteSupplier"
            />
            <!--分页组件-->
            <page-nation :pagination-data="paginationData" @change="initSupplier" />
          </div>
        </div>
        <!--  报价响应条件  -->
        <!-- <el-row :gutter="40" class="mt10 mb10">
          <el-col :md="24" :lg="24" style="margin-top: 10px">
            <span v-if="tenderType === '01'" class="page-title ">3.报价需响应的条件</span>
            <span v-else class="page-title ">2.报价需响应的条件</span>
            <el-button style="margin: 0 10px" type="primary" @click="addRow">添加条件</el-button>
            <span style="font-size: 12px; color: #F42233">注：供应商报价时须对响应条件回复，否则无法完成报价</span>
          </el-col>
        </el-row>-->
        <!--  报价响应条件列表  -->
        <!-- <pro-condition :procurement-bulletin-condition-list="procurementBulletinConditionList" @delCondition="delCondition"/> -->
        <!--  补充说明  -->
        <p v-if="tenderType === '01'" class="page-title">
          3.补充说明
        </p>
        <p v-else class="page-title">
          2.补充说明
        </p>
        <table class="from_table">
          <!--  是否使用工具制作采购文件 projectFileType 00是 01 否 默认01  -->
          <tr class="singleRow">
            <td>
              <el-form-item label="使用工具制作采购文件" prop="projectFileType" />
            </td>
            <td colspan="3">
              <el-radio-group v-model="supplementaryData.makeWay">
                <el-radio
                  v-for="(item, index) in procurementFileList"
                  :key="index"
                  :label="item.typecode"
                >
                  {{ item.typename }}
                </el-radio>
              </el-radio-group>
            </td>
          </tr>
          <!--  projectFileType 00显示使用工具制作 01 否显示文件上传 默认01   -->
          <tr class="singleRow">
            <td>
              <el-form-item label="采购文件" />
            </td>
            <td v-if="supplementaryData.makeWay=== '00'" colspan="3">
              <el-button type="primary">
                使用工具制作采购文件
              </el-button>
            </td>
            <td v-if="supplementaryData.makeWay=== '01'" colspan="3">
              <upload
                ref="upload"
                :title="''"
                :on-change="principalFile"
                :data="procurementFile"
                :file-list="principalList"
                :auto-delete="true"
                :auto-upload="true"
                :action="importFileUrl"
                :success="successList"
                tip-text="上传附件格式（*.doc;*.docx;*.pdf;*.png;*.jpg;*.zip;*.jpeg;*.txt;*.xlsx;*. xls;*.ppt;*.pptx;*.rar）"
                accept=".doc, .docx, .pdf, .png, .jpg, .zip;.jpeg;.txt;.xlsx;. xls;.ppt;.pptx;.rar"
                file-ref="fileRef"
                but-text="点击上传"
              />
            </td>
          </tr>
          <!--  文字补充说明  -->
          <tr class="singleRow">
            <td>
              <el-form-item label="公告备注">
                <el-popover
                  placement="top-start"
                  popper-class="hint"
                  width="260"
                  offset="5"
                  trigger="hover"
                  content="发布公告时,给予供应商的提示信息"
                >
                  <el-button slot="reference" type="info" class="prompt">
                    <i class="iconfont icon-qm" />
                  </el-button>
                </el-popover>
              </el-form-item>
            </td>
            <td colspan="3">
              <el-input
                v-model.trim="saveNotice.mattersNeedingAttention"
                :autosize="{ minRows: 3, maxRows: 3 }"
                type="textarea"
                maxlength="800"
                show-word-limit
                style="width: 96%"
                placeholder="允许输入800个汉字，1600个字符"
              />
            </td>
          </tr>
        </table>
      </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.stop="nextStep('form')">
              发布公告
            </el-button>
          </div>
        </div>
      </div>
      <!-- 添加供应商弹框   -->
      <supplier-add
        :key="new Date()*1"
        :dialog-data="dialogData"
        @consignContractInfo="consignContractInfo"
      />
    </section>
  </div>
</template>

<script>
/* api接口*/
import {
  saveProcurementRuleRecord,
  queryProcurementRuleRecord,
  deleteConditionById
} from '@/api/procurement/procurementProject' // 获取项目信息 获取项目规则 selectProcurementCondition,
import {
  getProcurementProcfileByPackId,
  procurementProcfileTakeEffect,
  deleteProtProcfile
} from '@api/procurement/procurementProtdoc'
import {
  queryBaseProcurementBulletinInfo,
  saveBaseProcurementBulletinInfo
} from '@/api/procurement/procurementBulletin'
import {
  queryProcurementInvitatinByTenderId,
  queryProcurementInvitatinDetailPage,
  saveProcurementInvitatinDetailSupplierList,
  removeProcurementInvitatinDetailSupplier,
  saveProcurementInvitatin
} from '@/api/procurement/procurementInvitation' // 保存供应商
/* 公共方法*/
import { ListMixin } from '@/mixins/ListMixin' // 分页
import { cloneObject, randomData, filterObj } from '@assets/js/utils' // 深拷贝
import { procurementProjectGroupMixin } from '../../mixins/procurementProjectGroupMixin' // 采购立项 公共字典
import { procurementProjectMixins } from '../../mixins/procurementProjectMixins' // 采购立项 公共字典
/* 公共组件*/
import pagination from '@comp/common/pagination/pagination' // 分页组件
/* 组件*/
import projectEnquiry from '../projectRule/projectEnquiry-add' // 询价
import projectCondition from './projectCondition-add' // 报价响应条件组件
import supplierAdd from './proSuppplierAdd-dialog' // 添加供应商弹框
import projectSupplierList from './projectSupplierList-list' // 添加供应商组件
import upload from '@comp/common/updownload/upload' // 文件上传组件
import { upLoadFileUrl } from '@/api/common/uploadCenter'
import { mapGetters } from 'vuex'
export default {
  name: 'ProjectPublistNoticeAddVue',
  components: {
    'pro-enquiry': projectEnquiry, // 询价
    'pro-condition': projectCondition, // 报价响应条件编辑列表组件
    'page-nation': pagination, // 分页组件
    'pro-supplierList': projectSupplierList, // 供应商列表组件
    'supplier-add': supplierAdd, // 添加供应商
    upload // 文件上传
  },
  mixins: [ListMixin, procurementProjectGroupMixin, procurementProjectMixins],
  // 接受父组件传递的项目类型 00 公开 01 邀请
  props: {
    tenderType: {
      type: String,
      default: () => {
        return ''
      }
    }
  },
  data() {
    return {
      raidioType: false,
      importFileUrl: upLoadFileUrl, // 文件上传地址
      dialogData: {
        consignContractVisible: false, // 添加供应商
        departId: this.$route.query.buyersId, // 审核单位id
        excludeSupplierIds: '' // 已被邀请供应商所有id拼接的字符串
      },
      searchForm: {
        // 查询供应商列表
        tenderId: this.$route.query.tenderId
      },
      tenderId: this.$route.query.tenderId,
      supplerlist: {
        // 调用保存供应商接口
        list: [],
        tenderId: this.$route.query.tenderId // 项目id
      },
      // 上传采购文件
      supplementaryData: {
        tenderId: this.$route.query.tenderId, // 项目id
        packIds: this.$route.query.packId, // 标段id
        makeWay: '01', // 使用工具字段
        id: '' // 文件上传id
      },
      loading: false // loading效果
    }
  },
  computed: {
    /* language 国际化*/
    ...mapGetters(['language'])
  },
  created() {
    const tenterId = this.$route.query.tenderId // 采购项目信息Id
    const packId = this.$route.query.packId // 项目的标段id
    if (tenterId) {
      // 查询项目规则方法
      this.initRuleData(tenterId)
      // 查询公告方法
      this.queryBaseProcurementBulletinInfoData(tenterId)
      // 查询供应商列表
      this.initSupplier()
      // 查询供应商列表id集合
      this.supplierIdData()
    }
    if (packId) {
      // 调用 查询采购文件方法
      this.getProcurementProcfileData(packId)
    }
  },
  methods: {
    /* ======================================================页面Dom事件====================================================*/
    // 打开添加供应商弹框
    addClick() {
      this.dialogData.consignContractVisible = true
    },
    // 添加报价响应条件
    addRow() {
      const data = cloneObject(this.addData) // 深层拷贝
      if (this.procurementBulletinConditionList.length > 0) {
        // 校验数据不能为空
        const everType = this.procurementBulletinConditionList.every(
          item => item.conditionName && item.conditionContent
        )
        // 返回true表示都不为空
        if (everType) {
          this.procurementBulletinConditionList.push(data)
        } else {
          // 表示有某项是空值 错误提示
          this.$message.error('响应数据不可为空')
        }
      } else {
        // 初始化记载数据
        this.procurementBulletinConditionList.push(data)
      }
      // 强制刷新
      this.$forceUpdate()
    },
    // 删除报价响应回调
    delCondition(val) {
      // 有id代表数据保存过
      if (val.id) {
        this.deleteConditionByData(val.id)
      } else {
        // 有ind表初始化数据 调用删除方法
        this.procurementBulletinConditionList.splice(val.ind, 1)
        // 强制刷新
        this.$forceUpdate()
      }
    },
    // 保存规则数据信息
    assetsRuleData() {
      const data = {
        id: this.ruleData.id,
        tenderId: this.$route.query.tenderId,
        quoteEndTime: this.ruleData.quoteEndTime, // 报价截止时间
        quoteValidity: this.ruleData.quoteValidity, // 报价有效期
        isReceiveTenderBailPrice: this.ruleData.isReceiveTenderBailPrice, // 是否收取保证金
        isReceiveTenderDocumentPrice: this.ruleData.isReceiveTenderDocumentPrice, // 是否收取标书费
        protProjectDocumentPriceList: this.ruleData.protProjectDocumentPriceList, // 标书费金额
        protProjectBailPriceList: this.ruleData.protProjectBailPriceList, // 保证金金额
        isUploadReplyFile: this.ruleData.isUploadReplyFile, // 强制上传应答文件
        isContainsFreight: this.ruleData.isContainsFreight, // 是否含运费
        currency: this.ruleData.currency, // 币种
        payType: this.ruleData.payType, // 付费方式
        isEmergencyProcurement: this.ruleData.isEmergencyProcurement, // 是否紧急采购
        quoteType: this.ruleData.quoteType // 报价要求
      }
      return data
    },
    // 上一步
    prevStep() {
      // 调用保存项目规则方法
      this.confirmLoading = true
      // 设置采购公告上一步字段 state 02 代表上一步
      this.saveNotice.state = '02'
      // 获取项目规则数据
      const data = this.assetsRuleData()
      // 增加项目规则上一步字段status 02代表上一步
      data.status = '02'
      this.saveProcurementRuleData(data, 'prev')
    },
    // 保存采购公告数据
    assetsNoticeData() {
      const procurementBulletinConditionList = this.procurementBulletinConditionList.map(
        (item, index) => {
          return {
            ...item,
            sortNo: ++index // 添加序号
          }
        }
      )
      const data = {
        id: this.saveNotice.id, // id
        mattersNeedingAttention: this.saveNotice.mattersNeedingAttention, // 补充说明
        tenderId: this.$route.query.tenderId, // 项目id
        packId: this.$route.query.packId, // 标段id
        state: this.saveNotice.state, // 保存 00 提交01
        procurementConditionDtoList: procurementBulletinConditionList // 响应条件
      }
      return data
    },
    // 保存数据
    saveData(formName) {
      // 设置采购公告保存字段 state 00 代表保存
      this.saveNotice.state = '00'
      // 校验输入内容
      this.$refs[formName].validate((valid, field) => {
        if (valid) {
          this.confirmLoading = true
          // 获取项目规则数据
          const data = this.assetsRuleData()
          // 增加项目规则保存字段status 00代表保存
          data.status = '00'
          // 调用保存项目规则
          this.saveProcurementRuleData(data, 'save')
        }
      })
    },
    // 发布公告
    nextStep(formName) {
      // 校验输入内容
      this.$refs[formName].validate((valid, field) => {
        if (valid) {
          // 集团外邀请询价 校验供应商家数
          if (
            this.queryProcurementInvitatinDetailVoList.length === 0 &&
            this.tenderType === '01'
          ) {
            this.$message.error('至少选择一家供应商')
            return
          }
          if (this.procurementBulletinConditionList.length >= 0) {
            // 校验数据不能为空
            const everType = this.procurementBulletinConditionList.every(
              item => item.conditionName && item.conditionContent
            )
            // 返回true表示都不为空
            if (!everType) {
              // 表示有某项是空值 错误提示
              this.$message.error('响应数据不可为空')
              return
            }
          }
          // 设置采购公告提交字段 state 01 代表提交
          this.saveNotice.state = '01'
          // 获取项目规则数据
          const data = this.assetsRuleData()
          // 增加项目规则提交字段status 01代表提交
          data.status = '01'
          this.$confirm('确认发送公告吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            confirmButtonClass: 'confirmBtn',
            cancelButtonClass: 'cancelBtn',
            type: 'warning'
          })
            .then(() => {
              this.saveProcurementRuleData(data, 'next')
            })
            .catch(() => {
              this.confirmLoading = false
            })
        }
      })
    },
    // 添加供应商的数据回调
    consignContractInfo(val) {
      this.supplerlist.list = val
      saveProcurementInvitatinDetailSupplierList(this.supplerlist).then(res => {
        // 调用查询采购公告方法
        this.dialogData.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 => {
          // 调用回去供应商；列表方法
          this.initSupplier()
          this.$message({
            message: '供应商移除成功',
            type: 'success'
          })
        })
      }
    },
    // 查询条件
    getQueryParams() {
      const param = Object.assign({}, this.searchForm)
      param.pageNo = this.paginationData.pageNo
      param.pageSize = this.paginationData.pageSize
      return filterObj(param)
    },
    /* ======================================获取页面数据方法======================================================*/
    /*
    * 获取项目规则
    * @params { tenderId: 项目id}
    * 返回项目规则数据
    */
    initRuleData(tenterId) {
      const data = { tenderId: tenterId }
      queryProcurementRuleRecord(data).then(res => {
        if (res.data.id !== null) {
          this.ruleData = res.data
        }
      })
    },
    // 封装获取公告方法
    queryBaseProcurementBulletinInfoData(tenderId) {
      // 获取采购公告
      if (this.tenderType === '00') {
        queryBaseProcurementBulletinInfo(tenderId)
          .then(res => {
            // 获取采购公告id
            this.saveNotice.id = res.data.id
            // 获取备注信息
            this.saveNotice.mattersNeedingAttention =
              res.data.mattersNeedingAttention
            // 获取响应条件
            this.procurementBulletinConditionList = res.data
              .procurementBulletinConditionList
              ? res.data.procurementBulletinConditionList
              : []
          })
          .catch(() => {})
      } else if (this.tenderType === '01') {
        // 获取邀请函
        queryProcurementInvitatinByTenderId(tenderId)
          .then(response => {
            // 获取邀请函公告id
            this.saveNotice.id = response.data.id
            // 获取备注信息
            this.saveNotice.mattersNeedingAttention =
              response.data.mattersNeedingAttention
            // 已被邀请供应商所有id拼接的字符串
            this.dialogData.excludeSupplierIds =
              response.data.excludeSupplierIds
            // 响应条件初始化为null默认空数组
            this.procurementBulletinConditionList = response.data
              .procurementInvitationConditionList
              ? response.data.procurementInvitationConditionList
              : []
          })
          .catch(() => {})
      }
    },
    // 获取供应商列表方法
    initSupplier() {
      const data = this.getQueryParams()
      queryProcurementInvitatinDetailPage(data).then(res => {
        // 获取供应商列表数据
        this.queryProcurementInvitatinDetailVoList = res.data.records
        // 查询供应商列表id集合
        this.supplierIdData()
        this.paginationData.total = res.data.total
      })
    },
    // 封装获取采购文件方法
    getProcurementProcfileData(packId) {
      getProcurementProcfileByPackId(packId)
        .then(res => {
          // 判断是是否回显业务主键id
          if (res.data.procfileId) {
            // 保存后二次进入页面时获取业务id
            this.procurementFile.bizId = res.data.procfileId
            this.supplementaryData.id = res.data.procfileId
          } else {
            // 首次加载业务id为前端自动生成
            this.procurementFile.bizId = randomData()
          }
          // 获取采购工具字段 00 使用工具 01 上传文件
          this.supplementaryData.makeWay = res.data.makeWay
            ? res.data.makeWay
            : '01'
        })
        .catch(() => {})
    },
    /* ======================================保存页面数据方法======================================================*/
    // 封装保存项目规则方法
    saveProcurementRuleData(ruleData, info) {
      this.loading = true
      this.confirmLoading = true
      saveProcurementRuleRecord(ruleData)
        .then(res => {
          // 获取公告保存数据
          const assetsNoticeData = this.assetsNoticeData()
          if (this.tenderType === '00') {
            this.saveBaseProcurementBulletinData(assetsNoticeData, info)
          } 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
          if (info === 'prev') {
            this.$router.push({
              path: '/procurement/procurementProject/projectInfoContent',
              query: { ...this.$route.query }
            })
          } else if (info === 'save') {
            this.confirmLoading = false
            this.initRuleData(this.tenderId)
            this.queryBaseProcurementBulletinInfoData(this.tenderId)
          } else if (info === 'next') {
            this.$message({
              type: 'success',
              message: '公告发送成功',
              onClose: () => {
                // 刷新页面开启新节点
                this.confirmLoading = false
                this.$router.push({
                  path: '/procurement/procurementDrive/procurementView',
                  query: { ...this.$route.query }
                })
              }
            })
          }
        })
        .catch(() => {
          this.loading = false
          this.confirmLoading = false
        })
    },
    // 封装保存邀请函方法
    saveProcurementInvitatinData(data, info) {
      saveProcurementInvitatin(data)
        .then(res => {
          this.loading = false
          if (info === 'prev') {
            this.$router.push({
              path: '/procurement/procurementProject/projectInfoContent',
              query: { ...this.$route.query }
            })
          } else if (info === 'save') {
            this.confirmLoading = false
            this.initRuleData(this.tenderId)
            this.queryBaseProcurementBulletinInfoData(this.tenderId)
          } else if (info === 'next') {
            this.$message({
              type: 'success',
              message: '公告发送成功',
              onClose: () => {
                // 刷新页面开启新节点
                this.confirmLoading = false
                this.$router.push({
                  path: '/procurement/procurementDrive/procurementView',
                  query: { ...this.$route.query }
                })
              }
            })
          }
        })
        .catch(() => {
          this.loading = false
          this.confirmLoading = false
        })
    },
    /* ======================================删除页面数据方法======================================================*/
    // 删除采购文件
    deleteProtProcfileData(bizId) {
      deleteProtProcfile(bizId)
        .then(res => {})
        .catch(() => {})
    },
    // 封装删除响应条件方法
    deleteConditionByData(id) {
      deleteConditionById(id)
        .then(res => {
          // 调用获取采购公告
          this.queryBaseProcurementBulletinInfoData(this.tenderId)
        })
        .catch(() => {})
    },
    // 供应商方法
    initLineInfoData() {},
    /* ======================================附件上传======================================================*/
    // 附件上传
    principalFile(file, fileList) {
      this.principalList = fileList
    },
    // 附件上传成功的回调
    successList(file) {
      this.supplementaryData.id = this.procurementFile.bizId
      this.procurementProcfileTakeEffectData(this.supplementaryData)
    },
    // 获取供应商供应商列表id集合方法
    supplierIdData() {
      const data = []
      if (this.queryProcurementInvitatinDetailVoList.length > 0) {
        this.queryProcurementInvitatinDetailVoList.forEach(ele => {
          data.push(ele.supplierId)
        })
        this.dialogData.excludeSupplierIds = data.toString()
      } else {
        this.dialogData.excludeSupplierIds = ''
      }
    }
  }
}
</script>

<style scoped>
</style>
