<template>
  <div class="salesDetail-wrap" :style="{paddingBottom:hideFooter?'0px':'45px'}">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="salesDetail-cont">
        <template slot="subTitle">
          <a href="javascript:;" @click="handleBack" id="waitCostList-back-btn"><a-icon type="left" /> 返回列表</a>
        </template>
      </a-page-header>
      <a-card size="small" :bordered="false" class="pages-wrap">
        <!-- 查询 -->
        <div class="table-page-search-wrapper" ref="searchbox">
          <div style="display: flex;justify-content: space-between;align-items: center;">
            <div style="flex-grow: 1;width: 60%;">
              <a-form layout="inline" @keyup.enter.native="searchTable">
                <a-row :gutter="15" type="flex">
                  <a-col flex="300px">
                    <a-form-item label="销售单号">
                      <a-input id="waitCostList-salesBillNo" v-model.trim="queryParam.salesBillNo" allowClear placeholder="请输入销售单号"/>
                    </a-form-item>
                  </a-col>
                  <a-col flex="300px">
                    <a-form-item label="客户名称">
                      <dealerSubareaScopeList id="waitCostList-dealerSubareaScopeList" ref="dealerSubareaScopeList" @change="custChange" />
                    </a-form-item>
                  </a-col>
                  <a-col flex="300px">
                    <a-form-item label="费用类型">
                      <v-select
                        id="waitCostList-convertExpenseAccountType"
                        v-model="queryParam.convertExpenseAccountType"
                        code="CONVERT_EXPENSE_ACCOUNT_TYPE"
                        placeholder="请选择费用类型"
                        allowClear></v-select>
                    </a-form-item>
                  </a-col>
                  <a-col flex="300px">
                    <a-form-item label="促销名称/简称">
                      <a-input id="waitCostList-promotionDescription" v-model.trim="queryParam.promotionDescription" allowClear placeholder="请输入促销名称/简称"/>
                    </a-form-item>
                  </a-col>
                  <a-col flex="300px">
                    <a-form-item label="规则简称">
                      <a-input id="waitCostList-promotionRuleDescription" v-model.trim="queryParam.promotionRuleDescription" allowClear placeholder="请输入规则简称"/>
                    </a-form-item>
                  </a-col>
                  <a-col flex="150px">
                    <a-button type="primary" id="handel-search" :disabled="disabled" @click="searchForm(false)">查询</a-button>
                    <a-button style="margin-left: 10px" id="handel-reset" :disabled="disabled" @click="resetSearchForm()">重置</a-button>
                  </a-col>
                </a-row>
              </a-form>
            </div>
          </div>
        </div>
        <!-- 产品列表 -->
        <div style="padding:0 0 5px;">
          <span>
            已选 <template v-if="rowSelectionInfo && rowSelectionInfo.selectedRowKeys.length>0">{{ rowSelectionInfo.selectedRowKeys.length }}</template><template v-else>0</template> 项
          </span>
          <span style="color:red;">（注意：费用类型不一致不能批量转费用报销单）</span>
        </div>
        <div>
          <s-table
            class="sTable fixPagination"
            ref="table"
            :style="{ height: pageHeight+67+'px' }"
            size="small"
            :rowKey="(record) => record.id"
            :columns="columns"
            :row-selection="{ columnWidth: 40, getCheckboxProps: record => ({ props: { disabled: curExpenseAccountType ? record.convertExpenseAccountType != curExpenseAccountType : false } }) }"
            @rowSelection="rowSelectionFun"
            :data="loadData"
            :scroll="{ y: pageHeight }"
            :defaultLoadData="false"
            bordered>
            <!-- 操作 -->
            <template slot="action" slot-scope="text, record">
              <div>
                <a-button
                  size="small"
                  :id="'handel-submit-'+record.no"
                  type="link"
                  class="button-warning"
                  @click="handleSave(record)"
                >转费用报销单</a-button>
              </div>
            </template>
          </s-table>
        </div>
      </a-card>
    </a-spin>
    <div class="affix-cont" :style="{padding:hideFooter?0:'7px 0 4px'}">
      <a-button
        style="width: 100px;"
        type="info"
        id="handel-views"
        @click="handleView()"
      >
        查看已选
      </a-button>
      <a-button
        type="primary"
        class="button-info"
        id="handel-submit"
        :disabled="spinning"
        style="width: 100px;margin: 0 20px;"
        @click="handleSave()"
      >
        提交
      </a-button>
      <a-button
        type="primary"
        id="handel-mergeSubmit"
        :disabled="spinning"
        style="width: 100px;"
        @click="handleMerge()"
      >
        合并提交
      </a-button>
    </div>
    <!-- 新增费用单 -->
    <baseDataModal ref="expenseModal" @expenseSaveOk="expenseSaveOk" :show="openBaseModal" @close="openBaseModal=false"></baseDataModal>
    <!-- 查看已选费用单 -->
    <viewSelectModal ref="viewModal" :openModal="showViewModal" @close="showViewModal=false" @submit="meargeSubmit"></viewSelectModal>
    <!-- 合并选项弹框 -->
    <meargeOptionModal ref="meargeModal" :openModal="showMeargeModal" @close="showMeargeModal=false" @meargeOk="meargeOk"/>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import dealerSubareaScopeList from '@/views/common/dealerSubareaScopeList.vue'
import baseDataModal from '@/views/expenseManagement/expenseReimbursement/baseDataModal.vue'
import viewSelectModal from './viewSelectModal.vue'
import meargeOptionModal from './meargeOptionModal.vue'
import { salesConvertExpenseList, expenseAccountSave, queryBatchCreateBySalesBillSn, expenseAccountSaveGroupType, queryBatchCreateBySalesPromoSnListGroupType } from '@/api/salesNew'
export default {
  name: 'WaitCostOrder',
  mixins: [commonMixin],
  components: { STable, VSelect, dealerSubareaScopeList, baseDataModal, viewSelectModal, meargeOptionModal },
  data () {
    return {
      spinning: false,
      disabled: false,
      hideFooter: false, // 隐藏页面底部
      openBaseModal: false, // 费用弹框
      showMeargeModal: false, // 合并选项弹框
      fromRouter: '', // 从那个页面打开
      authCode: '', // 数据权限码
      queryParam: {
        promotionDescription: '', // 销名称/简称
        convertExpenseAccountType: '', // 费用类型
        salesBillNo: '', // 销售单号
        promotionRuleDescription: '', // 规则简称
        buyerName: '' // 客户名称
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        delete parameter.tableId
        delete parameter.index
        this.getPageHeight() // 获取表格高度
        return salesConvertExpenseList(Object.assign(parameter, this.queryParam)).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            const no = (data.pageNo - 1) * data.pageSize
            data.list.forEach((con, i) => {
              con.no = no + i + 1
            })
            this.disabled = false
          }
          this.spinning = false
          return data
        })
      },
      rowSelectionInfo: null, // 已选行
      curExpenseAccountType: '', // 当前已选费用类型
      pageHeight: 300, // 默认页面高度
      showViewModal: false, // 查看已选费用单
      isSearch: false // 是否查询中
    }
  },
  computed: {
    // 已选数据数量
    hasSelect () {
      return this.rowSelectionInfo && this.rowSelectionInfo.selectedRowKeys.length
    },
    columns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '销售单号', dataIndex: 'salesBillNo', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '客户名称', dataIndex: 'buyerName', width: '16%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '费用类型', dataIndex: 'convertExpenseAccountTypeDictValue', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '待转金额', dataIndex: 'expense', width: '8%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '促销名称', dataIndex: 'promotionTitle', width: '17%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '促销简称', dataIndex: 'promotionDescription', width: '17%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '规则简称', dataIndex: 'promotionRuleDescription', width: '16%', align: 'left', customRender: function (text) { return text || '--' } },
        { title: '促销类型', dataIndex: 'promotionRuleTypeDictValue', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '8%', align: 'center' }
      ]
      return arr
    }
  },
  methods: {
    //  返回
    handleBack () {
      this.$router.push({ name: 'salesQueryNewList' })
    },
    // 页面高度计算
    getPageHeight () {
      this.pageHeight = window.innerHeight - 290 - (this.$refs.searchbox ? this.$refs.searchbox.clientHeight : 0)
    },
    // 表格选中项，只能选中统一费用类型的
    rowSelectionFun (obj) {
      this.rowSelectionInfo = obj || null
      if (obj.selectedRows) {
        this.curExpenseAccountType = obj.selectedRows && obj.selectedRows[0] && obj.selectedRows[0]['convertExpenseAccountType'] || ''
        // 没用勾选任何数据，刷新列表
        if (obj.selectedRows.length <= 1) {
          if (!this.isSearch) {
            this.$refs.table.refresh()
          }
          this.isSearch = false
        } else {
          // 全选，盘点是否类型一致，否则不能全选
          const ret = obj.selectedRows.filter(item => item.convertExpenseAccountType == this.curExpenseAccountType)
          if (ret.length != obj.selectedRows.length) {
            this.$message.warning('费用类型不一致，请重新勾选！')
            this.$refs.table.clearSelected()
          }
        }
      }
    },
    // 客户选择
    custChange (val) {
      this.queryParam.buyerName = val.name || ''
    },
    // 合并提交
    handleMerge () {
      if (!this.hasSelect) {
        this.$message.warning('请先勾选再合并提交！')
        return
      }
      // 打开合并选项弹框
      this.showMeargeModal = true
    },
    // 确定合并
    meargeOk (groupType) {
      // 批量合并
      const salesPromoSnList = []
      this.rowSelectionInfo.selectedRows.map(item => {
        salesPromoSnList.push(item.salesPromoSn)
      })
      const params = {
        salesPromoSnList: salesPromoSnList,
        groupType: groupType
      }
      const meargeType = { 'CUSTOMER': '相同客户名称', 'CUSTOMER_PROMO': '相同促销活动', 'CUSTOMER_PROMO_RULE': '相同活动规则' }
      // 开始合并
      queryBatchCreateBySalesPromoSnListGroupType(params).then(res => {
        // 打开已合并的待转费用报销单弹框
        if (res.status == 200) {
          const list = res.data && res.data.detailList || []
          if (list.length) {
            // 打开查看弹框
            this.showViewModal = true
            this.$refs.viewModal.title = '已合并的待转费用报销单' + '（按' + meargeType[groupType] + '合并）'
            this.$refs.viewModal.submitType = 'mearge'
            this.$refs.viewModal.setData(list, res.data)
          } else {
            this.$message.warning('没有可合并的待转费用报销单！')
          }
        }
      })
    },
    // 确定合并提交转费用单弹框
    meargeSubmit (data) {
      this.expenseSave(data, 'salesMearge')
    },
    // 直接提交（不合并）
    handleSave (row) {
      const salesPromoSnList = []
      // 单个转
      if (row) {
        salesPromoSnList.push(row.salesPromoSn)
      } else {
        // 批量转
        if (!this.hasSelect) {
          this.$message.warning('请在列表勾选后再进行提交操作！')
          return
        }
        this.rowSelectionInfo.selectedRows.map(item => {
          salesPromoSnList.push(item.salesPromoSn)
        })
      }
      // 打开转费用单弹框
      this.handleExpense(salesPromoSnList)
    },
    // 转费用单
    async handleExpense (snList) {
      const _this = this
      this.spinning = true
      const hasExpense = await queryBatchCreateBySalesBillSn({ salesPromoSnList: snList }).then(res => res.data || [])
      let result = null
      for (const key in hasExpense) {
        result = hasExpense[key]
      }
      // 转费用单弹框
      _this.expenseSave(result, 'sales')
    },
    // 新建费用单
    expenseSave (data, type) {
      if (data) {
        // 关闭查看弹框
        this.$refs.viewModal.spinning = false
        this.showViewModal = false
        // 打开新建转费用单弹框
        this.openBaseModal = true
        this.$refs.expenseModal.setDetail(data, type)
        this.spinning = false
      } else {
        this.spinning = false
      }
    },
    // 转费用单成功,并跳转到费用单详情页面
    expenseSaveOk (params, type) {
      // type：
      // sales：不合并
      // salesMearge：合并转
      const fun = type == 'sales' ? expenseAccountSave : expenseAccountSaveGroupType
      fun(params).then(res => {
        if (res.status == 200) {
          this.$message.info(res.message)
          this.openBaseModal = false
          this.searchForm(true)
          this.$router.push({ name: 'expenseReimbursementEdit', params: { sn: res.data.expenseAccountSn } })
        }
      })
    },
    // 查看
    handleView () {
      if (!this.hasSelect) {
        this.$message.warning('请先勾选！')
        return
      }
      this.showViewModal = true
      this.$refs.viewModal.title = '已选待转费用报销单'
      this.$refs.viewModal.submitType = 'noMearge'
      this.$refs.viewModal.setData(this.rowSelectionInfo && this.rowSelectionInfo.selectedRows)
    },
    //  重置
    resetSearchForm () {
      this.isSearch = true
      this.queryParam.buyerName = undefined
      this.queryParam.convertExpenseAccountType = undefined
      this.queryParam.salesBillNo = ''
      this.queryParam.promotionDescription = ''
      this.queryParam.promotionRuleDescription = ''
      this.$refs.dealerSubareaScopeList.resetForm()
      this.$refs.table.refresh(true)
      this.$refs.table.clearSelected()
    },
    searchForm (flag) {
      this.isSearch = true
      this.$refs.table.refresh(true)
      if (flag) {
        this.$refs.table.clearSelected()
      }
    }
  },
  activated () {
    // 如果是新页签打开或者进入新的子页（例：存在列表第2条数据编辑页页签时再打开第4条数据的编辑页），则重置当前页面
    if (this.$store.state.app.isNewTab || !this.$store.state.app.isNewSubTab) {
      this.resetSearchForm()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.fromRouter = from
      vm.authCode = to.meta.permission
    })
  }
}
</script>

<style lang="less">
  .salesDetail-wrap{
    position: relative;
    height: 100%;
    padding-bottom: 45px;
    box-sizing: border-box;
    >.ant-spin-nested-loading{
      overflow-y: auto;
      height: 100%;
    }
    .salesDetail-cont{
      margin-bottom: 6px;
    }
    .active-title{
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 10px;
      background: #f3f8fa;
    }
    .flexBox{
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .footer-cont{
      margin-top: 5px;
      text-align: center;
    }
    .redStyle{
      font-weight: bold;
      color: red;
    }
  }
</style>
