<template>
  <div>
    <a-card size="small" :bordered="false" class="searchBoxNormal">
      <!-- 搜索条件 -->
      <div ref="tableSearch" class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-item label="创建时间">
                <rangeDate ref="rangeDate" id="salesManagementList-rangeDate" :value="time" @change="dateChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="客户名称">
                <dealerSubareaScopeList ref="dealerSubareaScopeList" id="salesManagementList-buyerName" @change="custChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="销售单号">
                <a-input id="salesManagementList-salesBillNo" v-model.trim="queryParam.salesBillNo" allowClear placeholder="请输入销售单号"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="采购单号">
                <a-input id="salesManagementList-purchaseBillNo" v-model.trim="queryParam.purchaseBillNo" allowClear placeholder="请输入采购单号"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="备货打印状态">
                <v-select
                  v-model="queryParam.printStatus"
                  ref="printStatus"
                  id="salesManagementList-printStatus"
                  code="PRINT_STATUS"
                  placeholder="请选择打印状态"
                  allowClear></v-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="业务状态">
                <v-select
                  v-model="queryParam.billStatus"
                  ref="billStatus"
                  id="salesManagementList-billStatus"
                  code="SALES_BILL_STATUS"
                  placeholder="请选择业务状态"
                  allowClear></v-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="财务状态">
                <v-select
                  v-model="queryParam.financialStatus"
                  ref="financialStatus"
                  id="salesManagementList-financialStatus"
                  code="FINANCIAL_RECEIVE_STATUS"
                  placeholder="请选择财务状态"
                  allowClear></v-select>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-item label="单据来源">
                  <v-select
                    v-model="queryParam.salesBillSource"
                    ref="salesBillSource"
                    id="salesManagementList-salesBillSource"
                    code="SALES_SOURCE"
                    placeholder="请选择单据来源"
                    allowClear></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="所在区域">
                  <subarea ref="subarea" id="salesManagementList-subarea" @change="subareaChange"></subarea>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="地区" prop="shippingAddrProvinceSn">
                  <Area id="salesManagementList-shippingAddrProvinceSn" v-model="queryParam.shippingAddrProvinceSn" placeholder="请选择省"></Area>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="出库仓库">
                  <chooseWarehouse id="salesManagementList-warehouse" ref="warehouse" v-model="queryParam.warehouseSn"></chooseWarehouse>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="促销单">
                  <a-select v-model="queryParam.promoFlag" id="salesManagementList-promoFlag" placeholder="请选择" allowClear>
                    <a-select-option value="0">正常单</a-select-option>
                    <a-select-option value="1">促销单</a-select-option>
                    <a-select-option value="2">源单</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="发货经销商">
                  <custList id="salesManagementList-transferDealerSn" :dataAuthFlag="0" placeholder="请输入发货经销商" ref="dealerTireScopeList" @change="custTireChange" />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="转费用报销单">
                  <a-select v-model="queryParam.expenseClainFlag" id="salesManagementList-expenseClainFlag" placeholder="请选择转费用报销单状态" allowClear>
                    <a-select-option value="N">待转</a-select-option>
                    <a-select-option value="Y">已转</a-select-option>
                    <a-select-option value="ALL">全部</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24" v-show="isShowCustomerSearch">
                <a-form-item label="客服">
                  <customerService ref="customerName" id="salesManagementList-bizUserSn" v-model="queryParam.bizUserSn"></customerService>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="24">
              <a-button type="primary" :disabled="disabled" id="salesManagementList-searchButton" @click="$refs.table.refresh(true)">查询</a-button>
              <a-button style="margin-left: 10px" :disabled="disabled" id="salesManagementList-resetButton" @click="resetSearchForm()">重置</a-button>
              <a-button
                style="margin-left: 10px"
                type="primary"
                id="salesManagementList-export"
                class="button-warning"
                @click="handleExport"
                :disabled="disabled"
                :loading="exportLoading"
                v-if="$hasPermissions('B_sales_export')"
              >导出</a-button>
              <a @click="advanced=!advanced" style="margin-left: 8px" id="salesManagementList-advanced">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'"/>
              </a>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card size="small" :bordered="false" class="salesManagementList-wrap">
      <a-spin :spinning="spinning" tip="Loading...">
        <!-- 操作按钮 -->
        <div class="table-operator" style="display: flex;justify-content: space-between;align-items: center;">
          <div style="padding-right: 15px;">
            <a-button type="primary" v-if="$hasPermissions('B_salesAdd')" id="salesManagementList-handleAdd" @click="handleAdd">新增</a-button>
            <a-button type="primary" class="button-info" v-if="$hasPermissions('B_convertExpense')" id="salesManagementList-plz" @click="toWaitCostOrder">批量转</a-button>
          </div>
          <div style="flex-grow: 1;display: flex;justify-content: space-between;align-items: center;flex-wrap: wrap;">
            <div class="tongji-bar">
              <div class="tongji-bar-col">
                <div>总单数：<strong>{{ totalData&&(totalData.totalRecord || totalData.totalRecord==0) ? totalData.totalRecord : '0' }}</strong>；</div>
                <div>总款数：<strong>{{ totalData&&totalData.totalCategory || totalData.totalCategory == 0 ? totalData.totalCategory : '0' }}</strong>；</div>
              </div>
              <div class="tongji-bar-col">
                <div>总数量：<strong>{{ totalData&&(totalData.totalQty || totalData.totalQty==0) ? totalData.totalQty : '0' }}</strong>；</div>
                <div v-if="$hasPermissions('M_salesQueryList_salesPrice')">总售价：<strong>{{ totalData&&(totalData.totalAmount || totalData.totalAmount==0) ? toThousands(totalData.totalAmount) : '0' }}</strong>；</div>
              </div>
              <div class="tongji-bar-col">
                <div>待审核数量：<strong>{{ totalData&&(totalData.totalWaitAuditQty || totalData.totalWaitAuditQty==0) ? totalData.totalWaitAuditQty : '0' }}</strong>；</div>
                <div v-if="$hasPermissions('M_salesQueryList_salesPrice')">待审核金额：<strong>{{ totalData&&(totalData.totalWaitAuditAmount || totalData.totalWaitAuditAmount==0) ? toThousands(totalData.totalWaitAuditAmount) : '0' }}</strong>；</div>
              </div>
              <div class="tongji-bar-col">
                <div>待下推数量（含缺货）：<strong>{{ totalData&&(totalData.totalUnpushedQty || totalData.totalUnpushedQty==0) ? totalData.totalUnpushedQty : '0' }}</strong>；</div>
                <div v-if="$hasPermissions('M_salesQueryList_salesPrice')">待下推金额（含缺货）：<strong>{{ totalData&&(totalData.totalUnpushedAmount || totalData.totalUnpushedAmount==0) ? toThousands(totalData.totalUnpushedAmount) : '0' }}</strong>；</div>
              </div>
              <div class="tongji-bar-col">
                <div>缺货数量：<strong>{{ totalData&&(totalData.totalOosQty || totalData.totalOosQty==0) ? totalData.totalOosQty : '0' }}</strong>；</div>
                <div>缺货金额：<strong>{{ totalData&&(totalData.totalOosAmount || totalData.totalOosAmount==0) ? toThousands(totalData.totalOosAmount) : '0' }}</strong>；</div>
              </div>
              <div class="tongji-bar-col">
                <div>下推数量：<strong>{{ totalData&&(totalData.totalPushedQty || totalData.totalPushedQty==0) ? totalData.totalPushedQty : '0' }}</strong>；</div>
                <div v-if="$hasPermissions('M_salesQueryList_salesPrice')">下推金额：<strong>{{ totalData&&(totalData.totalPushedAmount || totalData.totalPushedAmount==0) ? toThousands(totalData.totalPushedAmount) : '0' }}</strong>；</div>
              </div>
              <div class="tongji-bar-col">
                <div>转单数量：<strong>{{ totalData&&(totalData.totalTransferQty || totalData.totalTransferQty==0) ? totalData.totalTransferQty : '0' }}</strong>；</div>
                <div v-if="$hasPermissions('M_salesQueryList_salesPrice')">转单金额：<strong>{{ totalData&&(totalData.totalTransferAmount || totalData.totalTransferAmount==0) ? toThousands(totalData.totalTransferAmount) : '0' }}</strong>；</div>
              </div>
            </div>
            <div>
              <hideCellMenus :defHiddenKes="colsArr" v-model="showCols"></hideCellMenus>
            </div>
          </div>
        </div>

        <!-- 列表 -->
        <v-table
          class="sTable fixPagination"
          ref="table"
          :style="{ height: tableHeight+35+'px' }"
          :pagination="{pageSize:20}"
          :columns="columns"
          :data="loadData"
          :scroll="{ y: tableHeight }"
          :defaultLoadData="false"
          bordered>
          <!-- 时间表头 -->
          <template slot="customDateTitle">
            <a-tooltip placement="top" title="第一次提交时间">提交时间&nbsp;<a-icon type="question-circle" /></a-tooltip>
          </template>
          <!-- 销售单号 -->
          <template slot="salesBillNo" slot-scope="text, record">
            <span v-if="$hasPermissions('B_salesDetail')" class="link-bule" @click="handleDetail(record,'salesNewDetail')">{{ record.salesBillNo }}</span>
            <span v-else>{{ record.salesBillNo }}</span>
            <a-badge :count="'改'+record.changeTimes" :number-style="{ zoom:'0.8' }" v-if="record.changeTimes>0"></a-badge>
            <a-badge count="促" v-if="record.promoFlag==1" :number-style="{ backgroundColor: '#52c41a', zoom:'0.8' }"></a-badge>
            <a-badge count="转" v-if="record.transferFlag==1" :number-style="{ backgroundColor: '#0055ff', zoom:'0.8' }"></a-badge>
            <a-badge count="源" v-if="record.borrowedFlag==1" :number-style="{ backgroundColor: '#aa5500', zoom:'0.8' }"></a-badge>
          </template>
          <!-- 出库仓库 -->
          <template slot="warehouseBox" slot-scope="text, record">
            <a-tooltip placement="right" v-if="record.warehouseNameSet && record.warehouseNameSet.length>0">
              <template slot="title">
                <span>{{ record.warehouseNameSet.filter(item => item != null).toString() }}</span>
              </template>
              <div class="warehouse_box">
                <span>{{ record.warehouseNameSet.filter(item => item != null).toString() }}</span>
              </div>
            </a-tooltip>
            <div v-else>--</div>
          </template>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <div>
              <a-button
                size="small"
                type="link"
                class="button-warning"
                v-if="(record.billStatus == 'WAIT_AUDIT' || record.billStatus == 'SUPERIOR_AUDIT_REJECT' || record.billStatus == 'TRANSFER_AUDIT_REJECT')&&$hasPermissions('B_salesAudit')"
                @click="handleDetail(record,'salesNewDetailAudit')"
              >审核</a-button>
              <a-button
                size="small"
                type="link"
                class="button-warning"
                v-if="record.billStatus == 'WAIT_PUSH'&&$hasPermissions('B_salesDispatch')"
                @click="handleDispatch(record)"
              >下推</a-button>
              <a-button
                size="small"
                type="link"
                class="button-info"
                v-if="(record.salesBillSource == 'SALES' && (record.billStatus == 'WAIT_SUBMIT' || record.billStatus == 'WAIT_AUDIT' || record.billStatus == 'AUDIT_REJECT' || record.billStatus == 'SUPERIOR_AUDIT_REJECT' || record.billStatus == 'HQ_CHANGE'))&&$hasPermissions('B_salesEdit')"
                @click="handleEdit(record)"
              >
                编辑
              </a-button>
              <a-button
                size="small"
                type="link"
                class="button-info"
                v-if="record.salesBillSource == 'PURCHASE' && (record.billStatus == 'WAIT_AUDIT' || record.billStatus == 'HQ_CHANGE' || record.billStatus == 'SUPERIOR_AUDIT_REJECT' || record.billStatus == 'TRANSFER_AUDIT_REJECT') && $hasPermissions('B_salesEdit')"
                @click="handleChangeOrder(record)"
              >
                改单
              </a-button>
              <!-- 转单显示条件： 业务状态  待审核;非促销单;下级提交，且产品类型是“轮胎产品”的销售单 -->
              <a-button
                size="small"
                type="link"
                class="button-success"
                v-if="$hasPermissions('B_salesTransfer')&&record.promoFlag!=1&&(record.billStatus == 'WAIT_AUDIT'||record.billStatus == 'SUPERIOR_AUDIT_REJECT' || record.billStatus == 'TRANSFER_AUDIT_REJECT')&&record.salesBillSource=='PURCHASE'&&record.orderType==='TIRE'"
                @click="handleDetail(record,'salesNewDetailTransfer')"
              >
                转单
              </a-button>
              <!-- 上级审核 -->
              <a-button
                size="small"
                type="link"
                class="button-info"
                v-if="$hasPermissions('B_higherLevelAudit')&&record.billStatus == 'SUPERIOR_WAIT_AUDIT'"
                @click="handleDetail(record,'salesNewDetaiSupLevelAudit')"
              >
                上级审核
              </a-button>
              <a-button
                size="small"
                type="link"
                class="button-error"
                v-if="(record.salesBillSource == 'SALES' && (record.billStatus == 'WAIT_SUBMIT' || record.billStatus == 'WAIT_AUDIT' || record.billStatus == 'AUDIT_REJECT' || record.billStatus == 'SUPERIOR_AUDIT_REJECT' || record.billStatus == 'HQ_CHANGE'))&&$hasPermissions('B_salesDel')"
                @click="handleDel(record)"
              >
                删除
              </a-button>
              <a-button
                size="small"
                type="link"
                class="button-error"
                v-if="record.salesBillSource == 'PURCHASE' && (record.billStatus == 'WAIT_AUDIT' || record.billStatus == 'HQ_CHANGE'||record.billStatus == 'SUPERIOR_AUDIT_REJECT' || record.billStatus == 'TRANSFER_AUDIT_REJECT') && $hasPermissions('B_salesDel')"
                @click="handleDel(record)"
              >
                取消
              </a-button>
              <a-button
                size="small"
                type="link"
                class="button-warning"
                v-if="record.printStatus=='UNABLE_PRINT'&&$hasPermissions('B_Sales_UNABLE_PRINT')"
                @click="handlePrint(record)"
              >允许备货打印</a-button>
              <a-button
                size="small"
                type="link"
                class="button-warning"
                v-if="record.billStatus=='FINISH' &&(record.expenseClainFlag == 'N' ||record.expenseClainFlag == 'M' )&&$hasPermissions('B_convertExpense')"
                @click="handleExpense(record)"
              >转费用报销单</a-button>
            </div>
          </template>
        </v-table>
      </a-spin>
      <!-- 选择客户弹框 -->
      <choose-custom-modal :show="openModal" @ok="chooseCustomOk" @cancel="openModal=false"></choose-custom-modal>
      <!-- 操作提示 -->
      <commonModal modalTit="操作提示" :width="this.tipData&&this.tipData.length == 1?'500px':'800px'" :openModal="showTipModal" @cancel="canselModal" @ok="updatePrintStatus">
        <div style="text-align: center;" v-if="this.tipData&&this.tipData.length">
          <div style="margin-bottom: 15px;font-size: 14px;"><strong>确认允许此单进行备货打印吗？</strong></div>
          <div style="line-height: 24px;" v-if="this.tipData.length == 1">
            <div>备货单号：{{ tipData[0]&&tipData[0].dispatchBillNo }}</div>
            <div>客户名称：{{ tipData[0]&&tipData[0].buyerName }}</div>
          </div>
          <div v-else>
            <a-table
              :row-selection="{ selectedRowKeys: selectedRowKeys,onChange: onSelectChange, getCheckboxProps: record => ({ props: { disabled: record.printStatus!=='UNABLE_PRINT' }})}"
              :columns="bhColumns"
              :data-source="tipData"
              :pagination="false"
            />
          </div>
        </div>
      </commonModal>
      <!-- 新增费用单 -->
      <baseDataModal ref="expenseModal" @expenseSaveOk="expenseSaveOk" :show="openBaseModal" @close="openBaseModal=false"></baseDataModal>
      <!-- 导出提示框 -->
      <reportModal :visible="showExport" @close="showExport=false"></reportModal>
      <!-- 改单 -->
      <tipModal ref="tipModal" :openModal="openTipModal" :dataList="sourceData" @close="closeTipModal" @ok="openTipModalOk"></tipModal>
    </a-card>
  </div>
</template>

<script>
import moment from 'moment'
import { commonMixin } from '@/utils/mixin'
import getDate from '@/libs/getDate.js'
import { hdExportExcel } from '@/libs/exportExcel'
// 组件
import subarea from '@/views/common/subarea.js'
import Area from '@/views/common/area.js'
import rangeDate from '@/views/common/rangeDate.vue'
import { VTable, VSelect } from '@/components'
import commonModal from '@/views/common/commonModal.vue'
import chooseCustomModal from './chooseCustomModal.vue'
import tipModal from './tipModal.vue'
import dealerSubareaScopeList from '@/views/common/dealerSubareaScopeList.vue'
import baseDataModal from '@/views/expenseManagement/expenseReimbursement/baseDataModal.vue'
import reportModal from '@/views/common/reportModal.vue'
import chooseWarehouse from '@/views/common/chooseWarehouse'
import customerService from '@/views/common/customerService'
import hideCellMenus from '@/views/common/hideCellMenus'
import custList from '@/views/common/custList.vue'
// 接口
import { dispatchBatchPrintStatus, queryBySalesBillSn } from '@/api/dispatch'
import { salesList, salesDel, salesCancle, salesCount, queryCreateBySalesBillSn, expenseAccountSave, changeBillCheckUpdatePrice, changeBillCheck } from '@/api/salesNew'
import { salesDetailExport } from '@/api/salesBillReport'

export default {
  name: 'SalesQueryList',
  mixins: [commonMixin],
  components: { VTable, VSelect, tipModal, custList, hideCellMenus, chooseCustomModal, dealerSubareaScopeList, Area, rangeDate, subarea, commonModal, reportModal, chooseWarehouse, baseDataModal, customerService },
  data () {
    return {
      spinning: false,
      advanced: true, // 高级搜索 展开/关闭
      disabled: false, //  查询、重置按钮是否可操作
      openModal: false, // 选择客户弹框是否显示
      openBaseModal: false, // 费用弹框
      showTipModal: false, // 备货打印弹框
      showExport: false, // 导出提示框
      exportLoading: false, // 导出按钮加载状态
      expenseOption: false, // 已选转费用报销单状态
      tableHeight: 0, // 表格高度
      openTipModal: false, // 改单提示弹窗
      sourceData: [], // 改单表格数据
      // 默认时间
      time: [
        moment(getDate.getThreeMonthDays().starttime, 'YYYY-MM-DD'),
        moment(getDate.getCurrMonthDays().endtime, 'YYYY-MM-DD')
      ],
      // 查询参数
      queryParam: {
        beginDate: getDate.getThreeMonthDays().starttime, // 开始时间
        endDate: getDate.getCurrMonthDays().endtime, // 结束时间
        buyerSn: undefined, //  客户名称
        salesBillNo: '', //  销售单号
        purchaseBillNo: '', // 采购单号
        printStatus: undefined, // 打印状态
        billStatus: undefined, //  业务状态
        financialStatus: undefined, //  财务状态
        salesBillSource: undefined, // 单据来源
        subareaArea: {
          subareaSn: undefined, // 区域
          subareaAreaSn: undefined // 分区
        },
        shippingAddrProvinceSn: undefined, // 省
        warehouseSn: undefined, // 仓库
        promoFlag: undefined, // 是否促销单
        expenseClainFlag: undefined, // 转费用报销单状态
        bizUserSn: undefined, // 客服
        transferDealerSn: undefined// 发货经销商
      },
      // 统计数据
      totalData: {
        totalCategory: 0, // 总款数
        totalQty: 0, // 总数量
        totalRecord: 0, // 总单数
        totalPushedQty: 0, // 已下推数量
        totalDispatchQty: 0, // 已发货数量
        totalCancelQty: 0, // 已取消数量
        totalUnpushedQty: 0, // 待下推数量
        totalAmount: 0, // 总售价
        totalPushedAmount: 0, // 已下推金额
        totalCancelAmount: 0, // 已取消金额
        totalUnpushedAmount: 0, // 待下推金额
        totalDispatchAmount: 0 // 已发货金额
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        delete parameter.tableId
        delete parameter.index
        // 如果按业务状态排序
        if (parameter.sortOrder) {
          parameter['sortAlias'] = 'sales_bill'
        } else {
          delete parameter.sortField
        }
        // 查询总计
        salesCount(Object.assign(parameter, this.queryParam)).then(res => {
          this.totalData = res.data || {}
        })
        // 查询列表
        return salesList(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
        })
      },
      // 允许备货打印弹框
      tipData: null, // 备货单信息
      tempSalesBillSn: null, // 关联的下推单sn
      selectedRowKeys: [], // 允许备货打印选项
      bhColumns: [
        {
          title: '备货单号',
          dataIndex: 'dispatchBillNo'
        },
        {
          title: '客户名称',
          dataIndex: 'buyerName'
        },
        {
          title: '备货打印状态',
          dataIndex: 'printStatusDictValue'
        }
      ],
      // 列表列显示
      showCols: [], // 已勾选的列
      colsArr: [
        {
          title: '已取消数量',
          key: 'totalCancelQty',
          disabled: false,
          checked: false
        },
        {
          title: '待下推数量',
          key: 'totalUnpushedQty',
          disabled: false,
          checked: false
        },
        {
          title: '待下推金额',
          key: 'totalUnpushedAmount',
          disabled: !this.$hasPermissions('M_salesQueryList_salesPrice')
        },
        {
          title: '转采购额数量',
          key: 'totalConvertPromoGiftsQty',
          disabled: false,
          checked: false
        },
        {
          title: '转采购额金额',
          key: 'totalConvertPromoGiftsAmount',
          disabled: !this.$hasPermissions('M_salesQueryList_salesPrice'),
          checked: false
        },
        {
          title: '发货经销商',
          key: 'transferDealerName',
          disabled: false,
          checked: false
        },
        {
          title: '转单时间',
          key: 'transferDate',
          disabled: false,
          checked: false
        }
      ]
    }
  },
  computed: {
    columns () {
      const _this = this
      const formatDate = function (text) {
        if (text) {
          const ret = text.split(' ')
          return (<div>{ret[0]}<br/>{ret[1]}</div>)
        }
        return '--'
      }
      let arr = [
        { title: '序号', dataIndex: 'no', width: '3%', align: 'center' },
        { title: '创建时间', dataIndex: 'createDate', width: '6%', align: 'center', customRender: function (text) { return formatDate(text) }, sorter: true },
        { title: '销售单号', scopedSlots: { customRender: 'salesBillNo' }, width: '10%', align: 'left' },
        { title: '提交时间', slots: { title: 'customDateTitle' }, dataIndex: 'firstSubmitDate', width: '6.5%', align: 'center', customRender: function (text) { return formatDate(text) }, sorter: true },
        { title: '客户名称', dataIndex: 'buyerName', width: '9%', align: 'left', customRender: function (text) { return text || '--' } },
        { title: '发货经销商', dataIndex: 'transferDealerName', width: '8%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '出库仓库', scopedSlots: { customRender: 'warehouseBox' }, width: '7%', align: 'center', ellipsis: true },
        { title: '总数量', dataIndex: 'totalQty', width: '4%', align: 'center' },
        { title: '总售价', dataIndex: 'totalAmount', width: '4%', align: 'right', isShow: false, customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '已下推数量', dataIndex: 'totalPushedQty', width: '5%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '下推总金额', dataIndex: 'totalPushedAmount', width: '5%', align: 'right', isShow: false, customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '待下推数量', dataIndex: 'totalUnpushedQty', width: '5%', align: 'center', isShow: false, customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '待下推金额', dataIndex: 'totalUnpushedAmount', width: '5%', align: 'right', isShow: false, customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '已发货数量', dataIndex: 'totalDispatchQty', width: '5%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '已取消数量', dataIndex: 'totalCancelQty', width: '5%', align: 'center', isShow: false, customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '转采购额数量', dataIndex: 'totalConvertPromoGiftsQty', width: '5%', align: 'center', isShow: false, customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '转采购额金额', dataIndex: 'totalConvertPromoGiftsAmount', width: '5%', align: 'right', isShow: false, customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '收款方式', dataIndex: 'settleStyleSnDictValue', width: '5%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '审核时间', dataIndex: 'auditDate', width: '6%', align: 'center', customRender: function (text) { return formatDate(text) }, sorter: true },
        { title: '业务状态', dataIndex: 'billStatusDictValue', width: '5%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '财务状态', dataIndex: 'financialStatusDictValue', width: '5%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '最近备货时间', dataIndex: 'lastStockUpDate', width: '7%', align: 'center', customRender: function (text) { return formatDate(text) }, sorter: true },
        { title: '转单时间', dataIndex: 'transferDate', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '备货打印状态', dataIndex: 'printStatusDictValue', width: '6.5%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '7%', align: 'center' }
      ]
      // 根据权限及勾选按固定顺序动态显示列
      if (!this.$hasPermissions('M_salesQueryList_salesPrice')) {
        arr = arr.filter(item => !['totalAmount', 'totalPushedAmount', 'totalUnpushedAmount', 'totalConvertPromoGiftsAmount'].includes(item.dataIndex))
      }
      return arr.filter(item => !this.showCols.includes(item.dataIndex))
    }
  },
  methods: {
    //  导出
    handleExport () {
      const _this = this
      _this.$store.state.app.curActionPermission = 'B_sales_export'
      _this.exportLoading = true
      _this.spinning = true
      hdExportExcel(salesDetailExport, _this.queryParam, '销售明细', function () {
        _this.exportLoading = false
        _this.spinning = false
        _this.showExport = true
        _this.$store.state.app.curActionPermission = ''
      })
    },
    //  选择时间  change
    dateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    // 选择客户
    custChange (val) {
      this.queryParam.buyerSn = val.key
    },
    // 选择发货经销商
    custTireChange (val) {
      this.queryParam.transferDealerSn = val.key
    },
    // 所在区域
    subareaChange (val) {
      this.queryParam.subareaArea.subareaSn = val[0] ? val[0] : undefined
      this.queryParam.subareaArea.subareaAreaSn = val[1] ? val[1] : undefined
    },
    // 打开批量转费用单页面
    toWaitCostOrder () {
      this.$router.push({ name: 'waitCostOrder' })
    },
    // 新增销售单先打开选择客户弹框
    handleAdd () {
      this.openModal = true
    },
    // 选择客户成功
    chooseCustomOk (data) {
      this.$router.push({ name: 'salesNewAdd', params: { sn: data.salesBillSn } })
    },
    // 下推
    handleDispatch (row) {
      this.$router.push({ name: 'waitDispatchNew', params: { salesBillSn: row.salesBillSn } })
    },
    // 详情 审核  转单
    handleDetail (row, name) {
      this.$router.push({ name, params: { sn: row.salesBillSn, pageType: name } })
    },
    // 编辑
    handleEdit (row) {
      this.$router.push({ name: 'salesNewEdit', params: { sn: row.salesBillSn } })
    },
    // 改单
    handleChangeOrder (row) {
      const _this = this
      _this.tempSalesBillSn = row.salesBillSn
      changeBillCheck({ salesBillSn: row.salesBillSn }).then(res => {
        let data
        if (res.status == 200) {
          data = res.data
          if (data && data.length > 0) {
            _this.sourceData = res.data
            const obj = {
              buyerName: row.buyerName,
              salesBillNo: row.salesBillNo
            }
            _this.$refs.tipModal.getShowInfo(obj)
            _this.openTipModal = true
          } else {
            _this.$router.push({ name: 'salesNewEdit', params: { sn: row.salesBillSn } })
          }
        }
      })
    },
    // 改单成功  关闭弹窗
    openTipModalOk (ajaxData) {
      ajaxData.salesBillSn = this.tempSalesBillSn
      ajaxData.detailList = this.sourceData
      changeBillCheckUpdatePrice(ajaxData).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
          this.openTipModal = false
          this.$nextTick(() => {
            this.$router.push({ name: 'salesNewEdit', params: { sn: this.tempSalesBillSn } })
          })
        }
      })
    },
    // 取消时，跳转编辑页面
    closeTipModal () {
      this.openTipModal = false
      this.$router.push({ name: 'salesNewEdit', params: { sn: this.tempSalesBillSn } })
      this.$nextTick(() => {
        this.tempSalesBillSn = null
      })
    },
    // 删除
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: row.salesBillSource == 'PURCHASE' ? '确认要取消吗？' : '确认要删除吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.spinning = true
          const fun = row.salesBillSource == 'PURCHASE' ? salesCancle : salesDel
          fun({ salesBillSn: row.salesBillSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    // 转费用单
    async handleExpense (row) {
      const _this = this
      _this.spinning = true
      const hasExpense = await queryCreateBySalesBillSn({ salesBillSn: row.salesBillSn }).then(res => res.data || [])
      const showModalFlag = []
      const optionsKey = [
        {
          id: 'balance',
          name: '采购额结余'
        },
        {
          id: 'exceed',
          name: '采购额超出'
        },
        {
          id: 'giftConvertAmount',
          name: '促销产品转采购额'
        }
      ]
      optionsKey.map(key => {
        if (hasExpense[key.id]) {
          showModalFlag.push(key)
        }
      })

      if (showModalFlag.length) {
        // 直接转费用单
        if (showModalFlag.length == 1) {
          _this.expenseSave(hasExpense[showModalFlag[0].id])
        }
        // 有2个以上采购额时
        if (showModalFlag.length > 1) {
          _this.$confirm({
            title: '转费用报销单?',
            centered: true,
            class: 'confirm-center',
            content: <div>
              <div style="padding:10px 0;text-align:center;">请选择费用报销单类型</div>
              <div style="padding:0 0 10px 0;text-align:center;">
                <aRadioGroup onChange={_this.changeDaOpt}>
                  {showModalFlag.map(item => <aRadio key={item.id} style="height: '30px';lineHeight: '30px';padding:5px 0;" value={item.id}>{item.name}</aRadio>)}
                </aRadioGroup>
              </div>
            </div>,
            onOk () {
              if (_this.expenseOption) {
                _this.expenseSave(hasExpense[_this.expenseOption])
              } else {
                _this.$message.info('请选择费用报销单类型!')
                return true
              }
            },
            onCancel () {
              _this.expenseOption = null
            }
          })
        }
      }
      _this.spinning = false
    },
    // 选择费用报销单类型
    changeDaOpt (e) {
      this.expenseOption = e.target.value
    },
    // 转费用单确定
    expenseSave (data) {
      if (data) {
        this.openBaseModal = true
        this.$refs.expenseModal.setDetail(data, 'sales')
      }
    },
    // 转费用单成功
    expenseSaveOk (params) {
      expenseAccountSave(params).then(res => {
        if (res.status == 200) {
          this.$message.info(res.message)
          this.$refs.table.refresh()
          this.openBaseModal = false
          this.expenseOption = null
          this.$refs.expenseModal.spinning = false
          this.$router.push({ name: 'expenseReimbursementEdit', params: { sn: res.data.expenseAccountSn } })
        }
      })
    },
    // 允许备货打印
    handlePrint (row) {
      // 获取关联的下推单
      this.tempSalesBillSn = row.salesBillSn
      queryBySalesBillSn({ salesBillSn: row.salesBillSn }).then(res => {
        this.tipData = res.data || []
        this.tipData.map(item => {
          item.key = item.dispatchBillSn
          if (item.printStatus == 'UNABLE_PRINT') {
            this.selectedRowKeys.push(item.dispatchBillSn)
          }
        })
        this.showTipModal = true
      })
    },
    // 关闭允许备货打印弹框
    canselModal () {
      this.tipData = null
      this.showTipModal = false
      this.tempSalesBillSn = null
      this.selectedRowKeys = []
    },
    // 选择要备货打印的
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    // 确定允许备货打印
    updatePrintStatus () {
      const isOne = this.tipData.length
      if (isOne > 1 && this.selectedRowKeys.length == 0) {
        this.$message.info('请选择备货单！')
        return
      }
      const dispatchBillSnList = []
      this.tipData.map(item => {
        dispatchBillSnList.push(item.dispatchBillSn)
      })
      const params = {
        'salesBillSn': this.tempSalesBillSn,
        'dispatchBillSnList': isOne > 1 ? this.selectedRowKeys : dispatchBillSnList,
        'printStatus': 'NO_PRINT'
      }
      dispatchBatchPrintStatus(params).then(res => {
        if (res.status == 200) {
          this.canselModal()
          this.$message.info(res.message)
          this.$refs.table.refresh()
        }
      })
    },
    // 重置列表
    resetSearchForm () {
      this.$refs.rangeDate.resetDate(this.time)
      this.queryParam.beginDate = getDate.getThreeMonthDays().starttime
      this.queryParam.endDate = getDate.getCurrMonthDays().endtime
      this.$refs.dealerSubareaScopeList.resetForm()
      this.queryParam.buyerSn = undefined
      this.queryParam.salesBillNo = ''
      this.queryParam.purchaseBillNo = ''
      this.queryParam.printStatus = undefined
      this.queryParam.billStatus = undefined
      this.queryParam.financialStatus = undefined
      this.queryParam.salesBillSource = undefined
      this.queryParam.subareaArea.subareaSn = undefined
      this.queryParam.subareaArea.subareaAreaSn = undefined
      this.queryParam.shippingAddrProvinceSn = undefined
      this.queryParam.warehouseSn = undefined
      this.queryParam.promoFlag = undefined
      this.queryParam.expenseClainFlag = undefined
      this.queryParam.bizUserSn = undefined
      this.queryParam.transferDealerSn = undefined
      if (this.advanced) {
        this.$refs.subarea.clearData()
        this.$refs.dealerTireScopeList.resetForm()
      }
      this.$refs.table.refresh(true)
    },
    // 初始化
    pageInit () {
      this.$nextTick(() => { // 页面渲染完成后的回调
        this.setTableH()
      })
    },
    // 计算表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 210
    }
  },
  watch: {
    // 展开收起
    advanced (newValue, oldValue) {
      this.pageInit()
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      console.log(newValue)
      this.setTableH()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
      this.resetSearchForm()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
      this.resetSearchForm()
    }
    // 仅刷新列表，不重置页面
    if (this.$store.state.app.updateList) {
      this.pageInit()
      this.$refs.table.refresh()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
<style lang="less" scoped>
  .salesManagementList-wrap{
    .sTable{
      .badge-con-t{
        .ant-badge-count{
          transform: scale(0.8);
          font-size: 13px;
        }
      }
    }
    .tongji-bar{
      flex:1;
      display: flex;
    }
  }
</style>
