<!--
  @description: 订单列表-编辑功能
  @author: 苏志刚/wxy
  @routerPath:/procurement/procurementOrderSubmit
  @date： 2020-07-08 11:41:12
-->
<template>
  <div v-loading="loading" class="p0-16">
    <section class="title title_border">
      <i class="iconfont icon-fanhui pointer" @click="back()" />
      编辑订单
    </section>
    <div>
      <el-form ref="formData" :model="orderInfo" :rules="rules" :inline-message="true">
        <!-- 订单基本信息 -->
        <procurementOrderBase
          :order-info-base="orderInfo"
          :order-project-click="orderProjectClick"
          :order-supplier-click="orderSupplierClick"
        />
        <!-- 行项目列表 -->
        <procurementOrderLineItemComp
          ref="procurementOrderLineItemComp"
          :line-item-info-list="tenderMaterielInfoList"
          :line-item-other="lineItemOther"
        />
        <p v-if="this.$route.params.status === '01' && procurementSignUpAuditList.length>0" class="page-title">
          6.审核消息
        </p>
        <section v-if="this.$route.params.status === '01'&& procurementSignUpAuditList.length>0" style="margin-bottom:10px">
          <!-- 审核信息组件 -->
          <procurementAuditList :audit-list="procurementSignUpAuditList" />
        </section>
      </el-form>
      <!--操作按钮-->
      <div class="but_footer">
        <div class="but_footer-h">
          <div class="but_footer-but">
            <el-button :loading="confirmLoading" @click="saveData('formData','00')">
              保存
            </el-button>
            <el-button v-if="orderInfo.sourceType === '00'" :loading="confirmLoading" type="danger" @click="callbackfn(orderInfo.sourceType)">
              退回
            </el-button>
            <!-- <el-button v-if="orderInfo.sourceType === '01'" :loading="confirmLoading" type="danger" @click="callbackfn(orderInfo.sourceType)">
              释放
            </el-button> -->
            <el-button
              :loading="confirmLoading"
              type="primary"
              @click="saveData('formData', '01')"
            >
              提交
            </el-button>
            <!-- 项目整单释放整单退回 释放说明弹框 -->
            <projectRelease v-if="dialogProjectRelease.dialog" :dialog-data="dialogProjectRelease" @projectRelease="projectRelease" />
          </div>
        </div>
      </div>
    </div>
    <!-- 查看采购单弹框 -->
    <orderProjectBase :dialog-data="orderProjectDialog" />
    <!-- 查看供应商报价弹框 -->
    <procurementSuplierOffer :dialog-data="orderSupplierDialog" />
  </div>
</template>

<script>
/* api接口*/
import {
  queryProcurementOrderInfo,
  listProcurementOrderProductPages,
  updateOrSubmitProcurementOrderInfo,
  releaseProcurementOrderProduct,
  queryProcurementOrderAudit
} from '@/api/procurement/procurementContract'
/* 公共方法 */
import { filterObj, filterDictText } from '@/assets/js/utils' // 深拷贝
import { cascaderValide, characters1_auto } from '@/assets/js/validate'// 校验输入内容
import { totalHeadCount } from '@/assets/js/utils' // 计算总价 randomData
import { commonMxin } from '@/mixins/commonMxin'
import { ListMixin } from '@/mixins/ListMixin' // 分页
import { orderManagementGroupMixin } from '../mixins/orderManagementGroupMixins'
import { orderManagementMixins } from '../mixins/orderManagementMixins'
/* 组件*/
import procurementOrderBase from './procurementOrderBaseComp' // 订单的节本信息
import procurementOrderLineItemComp from './procurementOrderLineItemTableComp' // 订单行项目列表组件
import procurementAuditList from '@/views/procurement/components/procurementAuditComp/procurementAuditComp-detail' // 审核信息公共组件
import projectRelease from './procurementOrderProjectRelease-dialog' // 项目释放退回弹框
import orderProjectBase from './procurementOrderProjectBase-dialog' // 采购单查看弹框
import procurementSuplierOffer from '@/views/procurement/components/procurementLookSupplierOffer-dialog' // 查看供应商报价弹框
export default {
  name: 'OrderManagementEdit',
  components: {
    projectRelease, // 项目释放退回弹框
    procurementOrderBase, // 订单基本信息
    procurementOrderLineItemComp, // 行项目列表组件
    procurementAuditList, // 订单审核信息
    orderProjectBase, // 订单-查看采购单弹框
    procurementSuplierOffer // 订单-查看供应商报价弹框
  },
  mixins: [
    ListMixin,
    commonMxin,
    orderManagementGroupMixin,
    orderManagementMixins
  ],
  data() {
    return {
      loading: true, // loading效果
      confirmLoading: false,
      deliveryDate: '', // 交货日期
      // 行项目搜索数据
      searchForm: {
        isOperation: '', // 业务操作
        orderBy: 0, // 排序
        orderId: this.$route.params.orderId // 订单id
      },
      tenderMaterielInfoList: [],
      // 行项目的其他数据
      lineItemOther: {
        currency: '' // 币种
      },
      procurementSignUpAuditList: [], // 审核消息列表
      // 项目释放退回弹框
      dialogProjectRelease: {
        dialog: false,
        status: '' // 区分整单释放和退回字段 00释放 01退回
      },
      // 采购单查看弹框
      orderProjectDialog: {
        dialog: false,
        tenderId: '' // 项目id
      },
      // 供应商报价单查看弹框
      orderSupplierDialog: {
        dialog: false,
        stageId: '', // 轮次id
        packId: '', // 标段id
        supplierId: '' // 供应商id
      },
      // 释放 退回参数字段
      releaseProject: {
        orderId: '', // 订单id
        ids: '', // 项目id
        reason: '' // 释放说明字段
      },
      // 校验规则
      rules: {
        quantity: [{ required: true, message: '请输入', trigger: 'blur' }], // 数量
        unitPrice: [{ required: true, message: '请输入', trigger: 'blur' }], // 金额
        deliveryTime: [{ required: true, message: '请输入', trigger: 'blur' }], // 时间
        billingType: [{ required: true, message: '请输入', trigger: 'blur' }],
        deliveryAreaName: [{ required: true, validator: cascaderValide, trigger: 'blur' }], // 地区名称
        deliveryAddress: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 详细地址
        orderName: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 订单名称
        isPushContract: [{ required: true, message: '请选择是否签合同', trigger: 'change' }] // 订单名称
      }
    }
  },
  computed: {
    // 计算总价
    totalPrice: function() {
      // 初始化数据
      const totalPriceData = []
      let totalPrice = 0
      this.tenderMaterielInfoList &&
        this.tenderMaterielInfoList.map(cur => {
          // 判断单向总价是否是数值
          if (!isNaN(cur.singleTotalPrice)) {
            // 将总价push到初始数据中
            totalPriceData.push(cur.singleTotalPrice)
            // 调用公共求和方法
            totalPrice = totalHeadCount(totalPriceData).toFixed(2)
            return
          }
          totalPrice = 0
        })
      return totalPrice
    }
  },
  watch: {
    // 行项目数据
    'tenderMaterielInfoList': {
      handler(val) {
        val && val.forEach(cur => {
          // 单价(withoutTaxNitPrice) 都有值时
          cur.singleTotalPrice = (cur.unitPrice * cur.quantity).toFixed(2) // 含税总价  cur.quantity
        })
      },
      deep: true
    }
  },
  created() {
    // 获取计量单位
    this.initUnit()
    // 查询数据字典
    this.getProcurementOderInfo()
    // 查询字典信息
    this.initWebTypeGroup()
    // 获取订单详情信息
    this.getOrderInfo()
    // 获取审核意见列表
    this.initAuditList()
  },
  methods: {
    filterDictText, // 引入字典值替换文本通用方法
    // 保存组装数据
    assemblyData() {
      const data = {
        procurementOrderProductDtoList: this.tenderMaterielInfoList, // 物资信息
        billingRemarks: this.orderInfo.billingRemarks, // 开票备注
        deliveryAddress: this.orderInfo.deliveryAddress, // 送货地址
        deliveryAreaCode: this.orderInfo.deliveryAreaCode, // 送货地区编码
        deliveryAreaName: this.orderInfo.deliveryAreaName, // 送货地区名称
        id: this.orderInfo.id, // 订单id
        internalOpinion: this.orderInfo.internalOpinion, // 意见（内部）
        orderName: this.orderInfo.orderName, // 订单名称
        orderTerms: this.orderInfo.orderTerms, // 订单条款
        orderTotalMoney: this.totalPrice = this.totalPrice === 0 ? this.orderInfo.orderTotalMoney : this.totalPrice, // 总价
        saveOrSubmit: '', // 00保存 01提交
        isPushContract: this.orderInfo.isPushContract, // 是否签合同
        billingType: this.orderInfo.billingType // 发票类型
      }
      return data
    },
    /**
     *  保存/提交事件
     *  status 00 保存 01 提交
     *  */
    saveData(formName, status) {
      this.$refs[formName].validate((valid, field) => {
        if (valid) {
          this.confirmLoading = true // btnLoding
          const data = this.assemblyData() // 组装数据
          data.saveOrSubmit = status
          if (status === '00') {
          // 调用保存方法
            this.saveOrderInfo(data, status)
            return
          }
          // 调用判断行项目为空的方法
          this.lineItemProjectIsEmpty(data, status)
        } else {
          this.confirmLoading = false // btnLoding
          this.$message.warning('注意页面提示信息')
        }
      })
    },
    // 判断行项目是否为空方法
    lineItemProjectIsEmpty(data, status) {
      // 判断行项目不为空
      if (this.tenderMaterielInfoList.length === 0) {
        this.$message.warning('行项目列表为空，不可提交订单')
        this.confirmLoading = false // btnLoding
        return
      }
      // 判断行项目列表中每一行中数量或者税率是否有空值 -1 无 有返回下标
      const lineitemIndex = this.tenderMaterielInfoList.findIndex(lineItem => {
        return lineItem.quantity === '' || lineItem.unitPrice === ''
      })
      if (lineitemIndex === -1) {
        this.$confirm('确定提交审核吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          confirmButtonClass: 'confirmBtn',
          cancelButtonClass: 'cancelBtn'
        })
          .then(() => {
            // 调用保存方法
            this.saveOrderInfo(data, status)
          })
          .catch(() => {
            this.confirmLoading = false // btnLoding
          })
      } else {
        this.$message.warning('行项目列表的第' + lineitemIndex + '行项目中的数量或者税率不可为空')
        this.confirmLoading = false // btnLoding
      }
    },
    // 释放  退回
    callbackfn(status) {
      // 获取选中行项目的id
      const { lineItemBond } = this.$refs.procurementOrderLineItemComp.getExportLineItemId()
      if (!lineItemBond) {
        this.$message.warning('请选择释放或者退回的行项目')
        return
      }
      this.releaseProject.orderId = this.orderInfo.id // 获取项目id
      this.releaseProject.ids = lineItemBond
      this.dialogProjectRelease.status = status // 区分整单释放或者整单退回字段 00 释放 01 退回
      this.dialogProjectRelease.dialog = true // 开启释放说明弹框
    },
    // 释放/退回释放说明的弹框回调
    projectRelease(releaseData) {
      this.releaseProject.reason = releaseData.reason // 获取释放说明
      setTimeout(() => {
        // 确认退回/释放并调用接口
        this.$confirm(`确认将所选行项目${releaseData.status === '00' ? '退回' : '释放'}吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          confirmButtonClass: 'confirmBtn',
          cancelButtonClass: 'cancelBtn',
          type: 'warning'
        }).then(() => {
          // 调用释放 退回请求
          this.releaseProcurementOrder(this.releaseProject)
        }).catch(() => {
        })
      }, 500)
    },
    // 订单查看采购单事件
    orderProjectClick(tenderId) {
      // 获取项目id
      this.orderProjectDialog.tenderId = tenderId
      // 打开采购单查看弹框
      this.orderProjectDialog.dialog = true
    },
    // 订单查看报价信息事件
    orderSupplierClick(supplierClickType) {
      // 点击查看报价单返回true
      if (supplierClickType) {
        // 获取轮次id
        this.orderSupplierDialog.stageId = this.orderInfo.stageId
        // 获取标段id
        this.orderSupplierDialog.packId = this.orderInfo.packId
        // 获取供应商id
        this.orderSupplierDialog.supplierId = this.orderInfo.winningDepartId
        // 开启弹框
        this.orderSupplierDialog.dialog = true
      }
    },
    // 返回按钮
    back() {
      this.$router.push({
        path: '/procurement/procurementOrderList'
      })
    },
    /**
     *  保存订单数据请求
     *  status 00 保存 01 提交
     *  */
    saveOrderInfo(data, status) {
      updateOrSubmitProcurementOrderInfo(data)
        .then(res => {
          // 保存
          if (status === '00') {
            this.$message.success('保存成功')
            this.loading = false
            this.confirmLoading = false // btnLoding
            return
          }
          // 提交
          this.$message({
            message: '提交成功',
            type: 'success',
            onClose: () => {
              this.confirmLoading = false
              this.$router.push({
                path: '/procurement/procurementOrderList'
              })
            }
          })
        })
        .catch(() => {
          this.loading = false
          this.confirmLoading = false // btnLoding
        })
    },
    // 获取订单详情信息
    getOrderInfo() {
      queryProcurementOrderInfo(this.$route.params.orderId)
        .then(res => {
          this.orderInfo = {
            ...res.data,
            // 订单条款默认空前端赋值
            orderTerms: res.data.orderTerms ? res.data.orderTerms : this.orderClauseContent
          }
          // 币种
          this.lineItemOther.currency = this.orderInfo.currency
          // 行项目信息
          this.getMaterialInfo()
        })
        .catch(() => {})
    },
    // 查询条件
    getQueryParams() {
      const param = Object.assign({}, this.searchForm)
      param.pageNo = this.paginationData.pageNo
      param.pageSize = this.paginationData.pageSize
      return filterObj(param)
    },
    // 获取行项目信息
    getMaterialInfo() {
      // 查询条件
      const params = this.getQueryParams()
      listProcurementOrderProductPages(params)
        .then(res => {
          const { records } = res.data // 行项目数据
          this.tenderMaterielInfoList = records.map(item => {
            item.singleTotalPrice = null
            return item
          })
          this.paginationData.total = res.data.total
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 释放 说明接口请求
    releaseProcurementOrder(data) {
      releaseProcurementOrderProduct(data).then(res => {
        this.$message.success('操作成功')
        // 行项目信息
        this.getMaterialInfo()
      }).catch(() => {

      })
    },
    // 获取审核意见列表
    initAuditList() {
      queryProcurementOrderAudit(this.$route.params.orderId).then(res => {
        this.procurementSignUpAuditList = res.data
      })
    }
  }
}
</script>

<style lang="less" scoped>
.tableData h4 {
  line-height: 40px;
}
</style>
