<!--
  @description:我的汇总列表--机构汇总人
  @Modifier: haofengxian
  @routerPath: /personalCenter/summaryOrderList
  @date: 2021-12-04 11:23
-->
<template>
  <div>
    <div class="shopmall-page-title">
      我的汇总列表
    </div>
    <div class="p0-16">
      <!--查询条件-->
      <div class="crud_menu_title clearfix">
        <span class="fr pointer" @click="handleToggleSearch">
          <el-link
            :underline="false"
            :class="toggleSearchStatus ? 'arrow-is-active' : ''"
            type="primary"
            class="toggleSearchStatus icon el-icon-arrow-down"
          />
          {{ toggleSearchStatus ? '收起高级查询' : '展开高级查询' }}
        </span>
      </div>
      <div class="SearchContent clearfix mb10" :class="{ SearchContent_show: toggleSearchStatus }">
        <section class="SearchContent_leftInput fl">
          <el-form ref="searchForm" :inline="true" :model="searchForm">
            <el-form-item label="申购部门">
              <el-input v-model.trim="searchForm.buyerDepartName" placeholder="请输入申购部门" @keyup.enter.native="searchList" />
            </el-form-item>
            <el-form-item label="申购人">
              <el-input v-model.trim="searchForm.buyerRealName" placeholder="请输入申购人名称" @keyup.enter.native="searchList" />
            </el-form-item>
            <el-form-item label="申购汇总编号">
              <el-input v-model.trim="searchForm.collectionNumber" placeholder="请输入申购汇总编号" @keyup.enter.native="searchList" />
            </el-form-item>
            <el-form-item label="订单编号">
              <el-input v-model.trim="searchForm.orderNo" placeholder="请输入订单编号" @keyup.enter.native="searchList" />
            </el-form-item>
            <el-form-item label="商品名称">
              <el-input v-model.trim="searchForm.goodsName" size="small" placeholder="请输入商品名称" @keyup.enter.native="searchList" />
            </el-form-item>
            <el-form-item label="申购时间">
              <el-date-picker
                v-model="searchForm.date"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="(val) => {handleDate(val, 'createStartDate', 'createEndDate');}"
              />
            </el-form-item>
            <el-form-item label="商品分类">
              <el-input v-model.trim="searchForm.classType" size="small" placeholder="请输入商品分类" @keyup.enter.native="searchList" />
            </el-form-item>
          </el-form>
        </section>
        <div class="fr">
          <el-button type="purple" @click="searchList">
            搜索
          </el-button>
          <el-button type="gray" @click="resetList">
            重置
          </el-button>
        </div>
      </div>
      <!-- tabs -->
      <el-tabs v-model="activeName" @tab-click="tabClick">
        <el-tab-pane
          v-for="(item,index) in tabsList"
          :key="index"
          :name="item.index"
          :label="item.name"
        />
      </el-tabs>
      <div class="mb10 clearfix">
        <el-button v-if="activeName==='6'" type="purple" :loading="confirmLoading" @click="printSubmitOrder">
          打印并提交
        </el-button>
        <el-button v-if="activeName!=='6'" type="purple" :loading="confirmLoading" @click="printOrder">
          打印
        </el-button>
        <template v-if="activeName==='10'">
          <el-button type="purple" :loading="confirmLoading" @click="placeOrder">
            下单
          </el-button>
          <el-button type="purple" :loading="confirmLoading" @click="orderReturn">
            退回
          </el-button>
        </template>
        <span v-if="totalMoney" class="fr total_money cursor">
          总金额：<span>{{ totalMoney }}元</span>
        </span>
      </div>
      <el-table
        ref="multipleTable"
        :key="activeName"
        v-loading="loading"
        :data="tableData"
        @select="handleSelect"
        @select-all="handleSelectAll"
      >
        <el-table-column
          :key="Math.random()"
          type="selection"
          width="55"
          align="center"
          fixed
        />
        <el-table-column
          label="序号"
          type="index"
          align="center"
          header-align="center"
        />
        <el-table-column
          label="申购部门"
          header-align="center"
          min-width="200"
        >
          <template slot-scope="scope">
            <div style="white-space:normal;">
              {{ scope.row.createUserDepartName }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="createUserName"
          label="申购人"
          header-align="center"
          min-width="100"
        />
        <el-table-column
          prop="parentOrderNo"
          label="订单编号"
          header-align="center"
          min-width="180"
        />
        <el-table-column
          prop="goodsName"
          label="商品名称"
          header-align="center"
          min-width="300"
        />
        <el-table-column
          prop="number"
          label="商品数量"
          align="right"
          header-align="center"
          width="70"
        />
        <el-table-column
          prop="unitPrice"
          label="商品单价（元）"
          align="right"
          header-align="center"
          width="110"
        />
        <el-table-column
          prop="totalPrice"
          label="商品总额（元）"
          align="right"
          width="130"
          header-align="center"
        />
        <el-table-column
          prop="productClassification"
          label="商品分类"
          align="center"
          width="100"
          header-align="center"
        />
        <el-table-column
          prop="goodsDepartName"
          label="供应商"
          align="center"
          width="100"
          header-align="center"
        />
        <el-table-column
          prop="createTime"
          label="申购时间"
          align="center"
          header-align="center"
          min-width="160"
        />
        <el-table-column
          v-if="activeName!=='6'"
          :key="Math.random()"
          prop="collectionNumberTime"
          label="打印并提交时间"
          align="center"
          header-align="center"
          min-width="160"
        />
        <el-table-column
          v-if="activeName==='9'"
          :key="Math.random()"
          prop="confirmTime"
          label="下单时间"
          align="center"
          header-align="center"
          min-width="160"
        />
        <el-table-column
          v-if="activeName!=='6'"
          :key="Math.random()"
          prop="collectionNumber"
          label="申购汇总编号"
          align="center"
          header-align="center"
          width="200"
        />
        <el-table-column
          v-if="activeName==='8'"
          :key="Math.random()"
          prop="releaseTime"
          label="退回时间"
          align="center"
          min-width="160"
          header-align="center"
        />
        <el-table-column
          v-if="activeName==='8'"
          :key="Math.random()"
          prop="releaseReason"
          label="退回意见"
          align="center"
          min-width="160"
          header-align="center"
        />
      </el-table>
      <pagination :pagination-data="paginationData" @change="initData" />
    </div>
    <!--订单退回-->
    <summaryOrderReturnDialog ref="summaryOrderReturn" @handleOrderCollection="handleOrderCollection" />
  </div>
</template>

<script>
/* api*/
import {
  getOrderCollectionList,
  orderCollectionListExport,
  auditCollectionOrders,
  orderCollectionListExportByTabType,
  getOrderCollectionTotalMoney
} from '@/api/shoppingmall/order'
/* 公共方法*/
import { download, restoreInitialValue, filterObj } from '@assets/js/utils'// 常用方法
// 组件
import pagination from '@comp/common/pagination/pagination'// 分页
import summaryOrderReturnDialog from './summaryOrderReturn-dialog' // 订单退回

export default {
  name: 'SummaryOrderList',
  components: {
    pagination, // 分页组件
    summaryOrderReturnDialog // 订单退回
  },
  data() {
    return {
      loading: false,
      confirmLoading: false, // 控制按钮重复点击Loding
      tabIndex: 0,
      activeName: '6',
      tabsList: [{
        index: '6',
        name: '已申购'
      }, {
        index: '10',
        name: '待下单'
      }, {
        index: '9',
        name: '已下单'
      }, {
        index: '8',
        name: '已退回'
      }],
      searchForm: {
        date: [],
        buyerDepartName: '', // 申购部门名称
        buyerRealName: '', // 申购人
        goodsName: '', // 商品名称
        classType: '', // 商品分类名称
        createEndDate: '', // 下单结束时间
        createStartDate: '', // 下单开始时间
        collectionNumber: '', // 申购汇总时间
        orderNo: '', // 订单号
        tabType: '' // 6 待审核(即已申购)；10 汇总过会(即待下单)； 8 被驳回（即已退回）；9 审核通过(即已下单)
      },
      tableData: [],
      selectOrderIds: [], // 已选商品id集合
      selectOrder: [], // 已选中商品
      /* 查询折叠 */
      toggleSearchStatus: false,
      /* 分页*/
      paginationData: {
        pageNo: 1, // 当前页
        pageSize: 100, // 每页显示个数
        total: 0
      },
      // 总金额
      totalMoney: null
    }
  },
  watch: {
    'selectOrder'(val) {
      // 获取选中的id数组
      this.setOrderIds()
    },
    'activeName'() {
      // 切换Tab时，重置选中数据
      this.selectOrder = []
    }
  },
  created() {
    this.initData()
  },
  methods: {
    // 获取账单列表
    initData() {
      const params = this.getQueryParams()// 查询条件
      this.loading = true
      this.getTotalMoney(params)
      getOrderCollectionList(params).then(res => {
        this.tableData = res.data.records
        this.paginationData.total = res.data.total
        this.$nextTick(() => {
          this.$refs?.multipleTable?.doLayout()
        })
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 查询条件
    getQueryParams() {
      this.searchForm.tabType = this.tabsList[this.tabIndex].index
      const param = Object.assign({}, this.searchForm)
      param.pageNo = this.paginationData.pageNo
      param.pageSize = this.paginationData.pageSize
      delete param.date
      return filterObj(param)
    },
    // 搜索
    searchList() {
      this.paginationData.pageNo = 1
      this.paginationData.pageSize = 100
      // 获取列表信息
      this.initData()
    },
    // 重置
    resetList() {
      this.paginationData.pageNo = 1
      this.paginationData.pageSize = 100
      restoreInitialValue(this.searchForm)
      this.initData()
    },
    // 处理搜索时间格式
    handleDate(val, start, end) {
      if (val) {
        this.searchForm[start] = this.$Moment(val[0]).format(this.momentDate) // 开始时间
        this.searchForm[end] = this.$Moment(val[1]).format(this.momentDate) // 结束时间
      }
    },
    // 获取选中的id数组
    setOrderIds() {
      const selectOrderIds = []
      this.selectOrder.map((item) => { selectOrderIds.push(item.id) })
      this.selectOrderIds = selectOrderIds
    },
    // 列表全选
    handleSelectAll(val) {
      this.selectOrder = val
    },
    // 勾选某行
    handleSelect(val, row) {
      // 判断是 选中 还是 取消 （-1 即取消)
      if (val.indexOf(row) === -1) {
        // 取消选择时，将取消商品的订单号从已选择列表中去掉
        val = val.filter(item => item.orderId !== row.orderId)
      }
      this.selectOrderByorderNo(val)
    },
    // 选中同订单编号下的商品
    selectOrderByorderNo(list) {
      this.$refs.multipleTable.clearSelection()
      // 已选中订单编号列表
      let orderNoList = []
      list.map(item => {
        orderNoList.push(item.orderId)
      })
      // 去重
      orderNoList = Array.from(new Set(orderNoList))
      this.tableData.forEach((item, index) => {
        // 将选中订单编号的其他商品改为选中状态
        if (orderNoList.indexOf(item.orderId) > -1) {
          // 这里需要用 table 原来绑定的数据对象 作为回显函数的参数才能正确勾选
          this.$nextTick(() => {
            this.$refs.multipleTable.toggleRowSelection(this.tableData[index], true)
          })
        } else {
          this.$nextTick(() => {
            this.$refs.multipleTable.toggleRowSelection(this.tableData[index], false)
          })
        }
      })
      this.selectOrder = this.$refs.multipleTable.selection
    },
    // 切换tab
    tabClick(tab) {
      const index = Number(tab.index)
      this.tabIndex = index
      this.activeName = tab.name
      this.paginationData.pageNo = 1
      this.searchForm.tabType = this.tabsList[index].index
      this.initData()
    },
    // 打印并提交
    printSubmitOrder() {
      // 判断是否勾选了申购单
      if (!this.selectOrderIds.length) {
        this.$message.warning('请先勾选要处理的申购单！！！')
        return
      }
      this.$confirm('确认打印并提交?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonClass: 'confirmBtn',
        cancelButtonClass: 'cancelBtn',
        type: 'warning'
      }).then(() => {
        const params = {
          orderCollectionIdList: this.selectOrderIds,
          tabType: this.tabsList[this.tabIndex].index
        }
        this.confirmLoading = true
        orderCollectionListExport(params).then(res => {
          const filename = '申购单' + '.pdf'
          download(res, filename)
          this.$message.success('申购单打印并提交成功！')
          this.initData()
        }).catch((error) => {
          this.$refs.multipleTable.clearSelection()
          throw new Error(error)
        }).finally(() => {
          this.selectOrder = []
          this.confirmLoading = false
        })
      }).catch(() => {
      })
    },
    // 打印
    printOrder() {
      // 判断是否勾选了申购单
      if (!this.selectOrderIds.length) {
        this.$message.warning('请先勾选要处理的申购单！！！')
        return
      }
      this.$confirm('确认打印？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonClass: 'confirmBtn',
        cancelButtonClass: 'cancelBtn',
        type: 'warning'
      }).then(() => {
        const params = {
          orderCollectionIdList: this.selectOrderIds,
          tabType: this.tabsList[this.tabIndex].index
        }
        this.confirmLoading = true
        orderCollectionListExportByTabType(params).then(res => {
          const filename = this.tabsList[this.tabIndex].name + '申购单' + '.pdf'
          download(res, filename)
          this.$message.success('申购单打印成功！')
          this.initData()
        }).catch((error) => {
          this.$refs.multipleTable.clearSelection()
          throw new Error(error)
        }).finally(() => {
          this.selectOrder = []
          this.confirmLoading = false
        })
      }).catch(() => {
      })
    },
    // 下单
    placeOrder() {
      // 判断是否勾选了申购单
      if (!this.selectOrderIds.length) {
        this.$message.warning('请先勾选要处理的申购单！！！')
        return
      }
      this.$confirm('确认下单?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonClass: 'confirmBtn',
        cancelButtonClass: 'cancelBtn',
        type: 'warning'
      }).then(() => {
        this.handleOrderCollection('1', '')
      }).catch(() => {
      })
    },
    // 订单退回
    orderReturn() {
      // 判断是否勾选了申购单
      if (!this.selectOrderIds.length) {
        this.$message.warning('请先勾选要处理的申购单！！！')
        return
      }
      this.$refs.summaryOrderReturn.openDialogHandleOrderReturn(this.selectOrder)
    },
    // 汇总列表-待下单tab的下单与退回操作
    handleOrderCollection(auditStatus, auditOptions) {
      const auditParams = {
        auditStatus: auditStatus, // 审核标志位 0审核驳回 1审核通过
        auditOptions: auditOptions, // 审核意见
        orderDetailIds: this.selectOrderIds // 订单汇总列表下单和退回用这个
      }
      this.confirmLoading = true
      auditCollectionOrders(auditParams).then(res => {
        this.$message.success(auditStatus === '1' ? '下单成功！' : '申购单退回成功！')
        // 退回成功关闭弹框
        if (auditParams.auditStatus === '0') {
          this.$refs.summaryOrderReturn.cancel()
        }
        this.initData()
      }).catch((err) => {
        this.$refs.multipleTable.clearSelection()
        throw new Error(err)
      }).finally(() => {
        this.selectOrder = []
        this.confirmLoading = false
      })
    },
    // 展开/折叠 查询条件
    handleToggleSearch() {
      this.toggleSearchStatus = !this.toggleSearchStatus
    },
    // 总金额
    getTotalMoney(params) {
      getOrderCollectionTotalMoney(params).then(res => {
        if (res.header.ret === '0') {
          this.totalMoney = res.data
        }
      }).catch((err) => {
        throw new Error(err)
      })
    }
  }
}
</script>

<style scoped lang="less">
.scopeNoWrap {
  white-space: normal;
}
.total_money {
  margin-right: 30px;
  font-size: 14px;
  color:#7F7F7F;
  >span {
    color:#FF0000;
  }
}
</style>
