<template>
  <a-card size="small" :bordered="false" class="salesManagementList-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 搜索条件 -->
      <div ref="tableSearch" class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="searchForm">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-item label="创建时间">
                <rangeDate
                  id="salesManagementList-date"
                  :allowClear="isByCustQuery"
                  :hasDisabledAreaTime="false"
                  ref="rangeDate"
                  :value="time"
                  @change="dateChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="客户名称" :required="isByCustQuery">
                <custList id="salesManagementList-cust" ref="custList" style="width: 100%;" @change="custChange"></custList>
              </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="单据来源">
                <v-select
                  style="width: 100%;"
                  v-model="queryParam.sourceType"
                  ref="sourceType"
                  id="salesManagementList-sourceType"
                  code="SALES_SOURCE"
                  placeholder="请选择单据来源"
                  allowClear></v-select>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-item label="出库时间">
                  <rangeDate id="salesManagementList-outWareTime" ref="outWareRangeDate" v-model="outWareTime" @change="outWareDateChange" />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="客户关系">
                  <v-select code="CUSTOMER_RELATION_TYPE" id="chainTransferOutList-buyerRelationType" v-model="queryParam.buyerRelationType" allowClear placeholder="请选择客户关系"></v-select>
                </a-form-model-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.billStatus"
                    @change="setIsHomeNav($route.name, null)"
                    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="审核时间">
                  <rangeDate id="salesManagementList-auditTime" ref="auditRangeDate" v-model="auditTime" @change="auditDateChange" />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="收款方式">
                  <v-select
                    code="SETTLE_STYLE"
                    id="salesManagementList-settleStyleSn"
                    v-model="queryParam.settleStyleSn"
                    allowClear
                    placeholder="请选择收款方式"
                  ></v-select>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-model-item label="铺货出库">
                  <v-select code="FLAG" id="salesManagementList-distributionFlag" v-model="queryParam.distributionFlag" allowClear placeholder="请选择是否铺货出库"></v-select>
                </a-form-model-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>
            <a-col :md="24" :sm="24" style="margin-bottom: 10px;text-align:center;">
              <span class="table-page-search-submitButtons">
                <a-button id="salesManagementList-searchForm" type="primary" :disabled="disabled" @click="searchForm">查询</a-button>
                <a-button id="salesManagementList-resetForm" style="margin-left: 5px" :disabled="disabled" @click="resetSearchForm()">重置</a-button>
                <a-button
                  type="primary"
                  v-if="$hasPermissions('B_salesExport')"
                  class="button-warning"
                  @click="handleExport"
                  :disabled="disabled"
                  :loading="exportLoading"
                  id="salesManagementList-export">导出</a-button>
                <a @click="advanced=!advanced" style="margin-left: 5px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'"/>
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!-- 操作按钮 -->
      <div class="table-operator" style="display:flex;align-items: center;justify-content: space-between;">
        <div>
          <a-button id="salesManagementList-new" type="primary" class="button-error" v-if="$hasPermissions('B_salesNews')" @click="handleAdd(0)">新增(零售)</a-button>
          <a-button id="salesManagementList-new1" type="primary" class="button-warning" v-if="$hasPermissions('B_salesNews')" @click="handleAdd(1)">新增(铺货)</a-button>
          <a-checkbox id="salesManagementList-custQuery" style="margin-left:10px;" v-model="isByCustQuery">按客户查询</a-checkbox>
          <a-popover placement="right">
            <template slot="content">
              使用此查询时，时间可清空，必须选择一个客户
            </template>
            <a-icon type="question-circle" />
          </a-popover>
          <a-checkbox id="salesManagementList-custQuery" style="margin-left:10px;" v-model="isAbandonOrder" >包括废弃单</a-checkbox>
          <a-popover placement="right">
            <template slot="content">
              废弃单：指【已取消】状态的订单
            </template>
            <a-icon type="question-circle" />
          </a-popover>
        </div>
        <div>
          <hideCellMenus placeholder="显示" :defHiddenKes="colsArr" v-model="showCell"></hideCellMenus>
        </div>
      </div>
      <a-alert type="info" style="margin-bottom:10px">
        <div slot="message">
          总单数：<strong>{{ totalData&&(totalData.totalRecord || totalData.totalRecord==0) ? totalData.totalRecord : '--' }}</strong>；
          总款数：<strong>{{ totalData&&(totalData.totalCategory || totalData.totalCategory==0) ? totalData.totalCategory : '--' }}</strong>；
          总数量：<strong>{{ totalData&&(totalData.totalQty || totalData.totalQty==0) ? totalData.totalQty : '--' }}</strong>；
          总售价：<strong>{{ totalData&&(totalData.totalAmount || totalData.totalAmount==0) ? toThousands(totalData.totalAmount) : '--' }}</strong>；
          <span v-if="showDiscount">
            折扣金额：<strong>{{ totalData&&(totalData.discountAmount || totalData.discountAmount==0) ? toThousands(totalData.discountAmount) : '--' }}</strong>；
            折后总售价：<strong>{{ totalData&&(totalData.discountedAmount || totalData.discountedAmount==0) ? toThousands(totalData.discountedAmount) : '--' }}</strong>；
          </span>
        </div>
      </a-alert>
      <!-- 列表 -->
      <s-table
        class="sTable fixPagination"
        ref="table"
        :style="{ height: tableHeight+65+'px' }"
        size="small"
        :rowKey="(record) => record.id"
        :columns="columns"
        :data="loadData"
        :scroll="{ y:tableHeight - 20 }"
        :defaultLoadData="false"
        bordered>
        <!-- 销售单号 -->
        <template slot="salesBillNo" slot-scope="text, record">
          <span id="salesManagementList-viewDetail" class="table-td-link" v-if="$hasPermissions('B_salesDetail')" @click="handleDetail(record)">{{ record.salesBillNo }}</span>
          <span v-else>{{ record.salesBillNo }}</span>
          <a-badge count="改" :number-style="{ zoom:'80%',marginLeft:'5px' }" v-if="record.billStatus=='SUPERIOR_CHANGE'"></a-badge>
        </template>
        <!-- 审核 -->
        <template slot="audit" slot-scope="text, record">
          <stateIcon :title="record.billStatusDictValue" v-if="record.billStatus!='AUDIT_REJECT'" :state="record.billStatus == 'WAIT_OUT_WAREHOUSE'||record.billStatus == 'FINISH'?'1':'2'"></stateIcon>
          <stateIcon :title="record.billStatusDictValue" v-else :state="0"></stateIcon>
        </template>
        <!-- 急件 -->
        <template slot="oosFlag" slot-scope="text, record">
          <stateIcon :state="record.oosFlag==1?'1':'2'"></stateIcon>
        </template>
        <!-- 出库 -->
        <template slot="waitOut" slot-scope="text, record">
          <stateIcon :state="record.billStatus == 'FINISH'?'1':'2'"></stateIcon>
        </template>
        <!-- 收款 -->
        <template slot="financial" slot-scope="text, record">
          <stateIcon :title="record.financialStatusDictValue" :state="record.financialStatus == 'FINISH'?'1':'2'"></stateIcon>
        </template>
        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <a-button
            size="small"
            type="link"
            class="button-primary"
            :id="'salesManagementList-audit-'+record.salesBillNo"
            v-if="record.billStatus == 'WAIT_AUDIT' && $hasPermissions('B_salesAudit')"
            @click="handleEexamine(record)"
          >审核</a-button>
          <a-button
            size="small"
            type="link"
            :id="'salesManagementList-sendOut-'+record.salesBillNo"
            v-if="record.billStatus == 'WAIT_OUT_WAREHOUSE' && $hasPermissions('B_salesStockOut')"
            class="button-primary"
            @click="handleSend(record)"
          >出库</a-button>
          <a-button
            size="small"
            type="link"
            :id="'salesManagementList-edit-'+record.salesBillNo"
            class="button-primary"
            v-if="(((record.sourceType == 'SATELLITE' || record.sourceType == 'SALES' || record.sourceType == 'TEMPORARY_DISPATCHING') && (record.billStatus == 'WAIT_AUDIT' || record.billStatus == 'WAIT_SUBMIT' ||record.billStatus == 'AUDIT_REJECT'))||(record.sourceType === 'TRANSFER_ORDER'&&record.billStatus == 'WAIT_AUDIT')||(record.sourceType == 'XPRH_PURCHASE'&&record.billStatus != 'AUDIT_REJECT')) && $hasPermissions('B_salesEdit')"
            @click="handleEdit(record)"
          >
            编辑
          </a-button>
          <a-button
            size="small"
            type="link"
            :id="'salesManagementList-del-'+record.salesBillNo"
            class="button-error"
            v-if="((record.sourceType == 'SATELLITE' || record.sourceType == 'SALES' ) && record.billStatus != 'FINISH')||(record.sourceType == 'TEMPORARY_DISPATCHING'&&record.billStatus != 'FINISH'&&record.billStatus != 'WAIT_OUT_WAREHOUSE') && $hasPermissions('B_salesDel')"
            @click="handleDel(record)"
          >
            删除
          </a-button>
          <a-button
            size="small"
            type="link"
            :id="'salesManagementList-edit1-'+record.salesBillNo"
            class="button-primary"
            v-if="((record.sourceType == 'CHILD_PURCHASE'||record.sourceType == 'DEALER_PURCHASE') && (record.billStatus == 'WAIT_AUDIT' || record.billStatus == 'SUPERIOR_CHANGE')) && $hasPermissions('B_salesEdit')"
            @click="handleEdit(record)"
          >
            改单
          </a-button>
          <a-button
            size="small"
            type="link"
            :id="'salesManagementList-cancel-'+record.salesBillNo"
            class="button-error"
            v-if="((record.sourceType == 'CHILD_PURCHASE'||record.sourceType == 'DEALER_PURCHASE'||record.sourceType =='XPRH_PURCHASE') && (record.billStatus == 'WAIT_AUDIT' || record.billStatus == 'SUPERIOR_CHANGE')) && record.sourceType != 'TRANSFER_ORDER'&& $hasPermissions('B_salesDel')"
            @click="handleDel(record, 'cancel')"
          >
            取消
          </a-button>
          <span v-if="!(record.billStatus == 'WAIT_AUDIT' && $hasPermissions('B_salesAudit')) && !(record.billStatus == 'WAIT_OUT_WAREHOUSE' && $hasPermissions('B_salesStockOut')) && !(((record.sourceType == 'SATELLITE' || record.sourceType == 'SALES' || record.sourceType == 'TEMPORARY_DISPATCHING') && (record.billStatus == 'WAIT_AUDIT' || record.billStatus == 'WAIT_SUBMIT' ||record.billStatus == 'AUDIT_REJECT'))||(record.sourceType === 'TRANSFER_ORDER'&&record.billStatus == 'WAIT_AUDIT')||(record.sourceType == 'XPRH_PURCHASE'&&record.billStatus != 'AUDIT_REJECT')) && $hasPermissions('B_salesEdit') && !(((record.sourceType == 'SATELLITE' || record.sourceType == 'SALES' || record.sourceType == 'TEMPORARY_DISPATCHING') && record.billStatus != 'FINISH') && $hasPermissions('B_salesDel'))">
            <span v-if="!(((record.sourceType == 'CHILD_PURCHASE'||record.sourceType == 'DEALER_PURCHASE') && (record.billStatus == 'WAIT_AUDIT' || record.billStatus == 'SUPERIOR_CHANGE')) &&$hasPermissions('B_salesEdit')) && !(((record.sourceType == 'CHILD_PURCHASE'||record.sourceType == 'DEALER_PURCHASE') && (record.billStatus == 'WAIT_AUDIT' || record.billStatus == 'SUPERIOR_CHANGE')) && $hasPermissions('B_salesDel'))">--</span>
          </span>
        </template>
      </s-table>
    </a-spin>
    <!-- 选择客户弹框 -->
    <choose-custom-modal :show="openModal" :distributionFlag="distributionFlag" @ok="chooseCustomOk" @cancel="openModal=false"></choose-custom-modal>
    <!-- 审核 -->
    <auditModal :openModal="visibleAudit" :spinning="spinningAudit" @close="visibleAudit=false" @ok="auditOrder('WAIT_OUT_WAREHOUSE')" @fail="auditOrder('AUDIT_REJECT')" />
  </a-card>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import moment from 'moment'
import getDate from '@/libs/getDate.js'
import { downloadExcel } from '@/libs/JGPrint.js'
// 组件
import { STable, VSelect } from '@/components'
import chooseCustomModal from './chooseCustomModal.vue'
import auditModal from '@/views/common/auditModal.vue'
import rangeDate from '@/views/common/rangeDate.vue'
import custList from '@/views/common/custList.vue'
import stateIcon from '@/views/common/stateIcon'
import hideCellMenus from '@/views/common/hideCellMenus'
// 接口
import { salesList, salesDel, salesWriteAudit, salesWriteStockOut, salesCount, salesExport } from '@/api/sales'
export default {
  name: 'SalesList',
  components: { STable, VSelect, chooseCustomModal, rangeDate, auditModal, custList, stateIcon, hideCellMenus },
  mixins: [commonMixin],
  data () {
    return {
      spinning: false,
      tableHeight: 0, // 表格高度
      advanced: true, // 高级搜索 展开/关闭
      disabled: false, //  查询、重置按钮是否可操作
      exportLoading: false, // 导出loading
      openModal: false, // 选择客户弹框是否显示
      isByCustQuery: false, // 是否按客户查询
      showDiscount: false, // 显示折后总售价
      time: [ // 创建时间
        getDate.getMonthDays(3).starttime,
        getDate.getMonthDays(3).endtime
      ],
      auditTime: [], // 审核时间
      outWareTime: [], // 出库时间
      // 查询参数
      queryParam: {
        beginDate: getDate.getMonthDays(3).starttime, // 开始时间
        endDate: getDate.getMonthDays(3).endtime, // 结束时间
        auditBeginDate: '', // 审核开始时间
        auditEndDate: '', // 审核结束时间
        outWarehouseBeginDate: '', // 出库开始时间
        outWarehouseEndDate: '', // 出库结束时间
        buyerNameCurrent: undefined, //  客户名称
        buyerSn: undefined, // 客户sn
        salesBillNo: '', //  销售单号
        purchaseBillNo: '', //  采购单号
        payType: undefined, //  支付方式
        settleStyleSn: undefined, //  收款方式
        billStatus: undefined, //  业务状态
        financialStatus: undefined, //  财务状态
        sourceType: undefined, // 单据来源
        distributionFlag: undefined, // 是否铺货出库
        buyerRelationType: undefined, // 客户关系
        payOnlineFlag: 0
      },
      totalData: {
        totalAmount: 0, // 总金额
        totalCategory: 0, // 总类目
        totalQty: 0, // 总数量
        totalRecord: 0 // 总条数
      },
      selType: '0', // 0零售 1铺货
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        // 是否包含废弃单
        this.queryParam.disuseFlag = this.isAbandonOrder ? '1' : '0'
        // 查询总计
        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
            for (var i = 0; i < data.list.length; i++) {
              data.list[i].no = no + i + 1
            }
            this.disabled = false
          }
          this.spinning = false
          return data
        })
      },
      visibleAudit: false, // 审核弹框
      auditInfo: null, // 当前审核的数据
      spinningAudit: false, // 审核loading
      distributionFlag: '0', //  是否铺货出库
      isAbandonOrder: true, // 包含废弃单
      colsArr: [// 需要显示的列
        {
          title: '折后总售价',
          key: 'discountedAmount',
          disabled: false,
          checked: false
        },
        {
          title: '客户关系',
          key: 'buyerRelationTypeDictValue',
          disabled: false,
          checked: false
        },
        {
          title: '采购单号',
          key: 'purchaseBillNo',
          disabled: false,
          checked: false
        }
      ],
      showCell: []// 已选要显示的列
    }
  },
  computed: {
    columns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', align: 'center', width: '4%' },
        { title: '来源', dataIndex: 'sourceTypeDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '销售单号', scopedSlots: { customRender: 'salesBillNo' }, width: '8%', align: 'center' },
        { title: '采购单号', dataIndex: 'purchaseBillNo', align: 'center', width: '8%', customRender: function (text) { return text || '--' } },
        { title: '客户名称', dataIndex: 'buyerNameCurrent', align: 'center', width: '13%', customRender: function (text) { return text || '--' } },
        { title: '客户关系', dataIndex: 'buyerRelationTypeDictValue', align: 'center', width: '9%', customRender: function (text) { return text || '--' } },
        { title: '总款数', dataIndex: 'totalCategory', align: 'center', width: '5%', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '总数量', dataIndex: 'totalQty', align: 'center', width: '5%', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '总售价', dataIndex: 'totalAmount', align: 'right', width: '6%', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        // { title: '折扣金额', dataIndex: 'discountAmount', align: 'right', width: '5%', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '折后总售价', dataIndex: 'discountedAmount', align: 'right', width: '6%', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '收款方式', dataIndex: 'settleStyleSnDictValue', width: '5%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '创建时间', dataIndex: 'createDate', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '审核时间', dataIndex: 'auditDate', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '业务状态', dataIndex: 'billStatusDictValue', width: '5%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '审核', scopedSlots: { customRender: 'audit' }, width: '2%', align: 'center' },
        { title: '急件', scopedSlots: { customRender: 'oosFlag' }, width: '2%', align: 'center' },
        { title: '出库', scopedSlots: { customRender: 'waitOut' }, width: '2%', align: 'center' },
        { title: '收款', scopedSlots: { customRender: 'financial' }, width: '2%', align: 'center' },
        // { title: '财务状态', dataIndex: 'financialStatusDictValue', width: '5%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '8%', align: 'center' }
      ]
      _this.showDiscount = !_this.showCell.includes('discountedAmount')
      if (!_this.showCell.includes('discountedAmount')) {
        const pos = (_this.showCell.includes('purchaseBillNo') && _this.showCell.includes('buyerRelationTypeDictValue')) ? 7 : (!_this.showCell.includes('purchaseBillNo') && !_this.showCell.includes('buyerRelationTypeDictValue')) ? 9 : 8
        arr.splice(pos, 0, { title: '折扣金额', dataIndex: 'discountAmount', align: 'right', width: '5%', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      return arr.filter(item => !_this.showCell.includes(item.dataIndex))
    }
  },
  methods: {
    // 选择创建时间
    dateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    // 选择审核时间
    auditDateChange (date) {
      this.auditTime = date
      this.queryParam.auditBeginDate = date[0]
      this.queryParam.auditEndDate = date[1]
    },
    // 选择出库时间
    outWareDateChange (date) {
      this.outWareTime = date
      this.queryParam.outWarehouseBeginDate = date[0]
      this.queryParam.outWarehouseEndDate = date[1]
    },
    // 选择客户
    custChange (v, row) {
      if (row && row.customerSn) {
        this.queryParam.buyerSn = row.customerSn
        this.queryParam.buyerNameCurrent = undefined
      } else {
        this.queryParam.buyerNameCurrent = v
        this.queryParam.buyerSn = undefined
      }
    },
    // 新增弹框
    handleAdd (flag) {
      this.openModal = true
      this.distributionFlag = flag
    },
    //  审核操作
    handleEexamine (row) {
      this.auditInfo = row
      this.visibleAudit = true
    },
    // 提交审核接口
    auditOrder (billStatus) {
      this.spinningAudit = true
      salesWriteAudit({
        id: this.auditInfo.id,
        billStatus: billStatus
      }).then(res => {
        if (res.status == 200) {
          this.visibleAudit = false
          this.$message.success(res.message)
          this.$refs.table.refresh()
          this.spinningAudit = false
        } else {
          this.visibleAudit = false
          this.spinningAudit = false
        }
      })
    },
    //  出库
    handleSend (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要出库吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.spinning = true
          salesWriteStockOut({
            salesBillSn: row.salesBillSn
          }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
            }
            _this.spinning = false
          })
        }
      })
    },
    // 详情
    handleDetail (row) {
      this.$router.push({ name: 'salesDetail', params: { sn: row.salesBillSn } })
    },
    // 编辑
    handleEdit (row) {
      this.$router.push({ name: 'salesEdit', params: { id: row.id, sn: row.salesBillSn, priceType: row.priceType } })
    },
    // 选择客户成功
    chooseCustomOk (data) {
      this.$router.push({ name: 'salesAdd', params: { id: data.id, sn: data.salesBillSn, priceType: data.priceType } })
    },
    // 删除
    handleDel (row, type) {
      const _this = this
      let content = '确认要删除吗？'
      if (type == 'cancel') {
        content = '确认要取消吗？'
      }
      this.$confirm({
        title: '提示',
        content: <div><div style='font-size:16px;margin-bottom:10px;'>{content}</div><div>销售单号：{row.salesBillNo}</div><div>客户名称：{row.buyerNameCurrent}</div></div>,
        centered: true,
        closable: true,
        onOk () {
          _this.spinning = true
          salesDel({ id: row.id, mainFlag: 1 }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    // 查询按钮
    searchForm () {
      // 是否按客户查询
      if (!this.isByCustQuery) {
        const a = moment(this.queryParam.beginDate)
        const b = moment(this.queryParam.endDate)
        if (b.diff(a, 'days') > 730) {
          this.$message.info('最多只能选择2年的时间区间')
          return false
        }
        this.$refs.table.refresh(true)
      } else {
        if (this.queryParam.buyerSn) {
          this.$refs.table.refresh(true)
        } else {
          this.$message.info('请选择客户')
          return false
        }
      }
    },
    // 重置
    resetSearchForm () {
      this.resetData()
      this.$refs.table.refresh(true)
    },
    // 重置数据
    resetData (flag) {
      this.$refs.rangeDate.resetDate(flag ? '' : this.time)
      this.queryParam.beginDate = flag ? '' : getDate.getMonthDays(3).starttime
      this.queryParam.endDate = flag ? '' : getDate.getMonthDays(3).endtime

      this.queryParam.auditBeginDate = ''
      this.queryParam.auditEndDate = ''
      this.queryParam.outWarehouseBeginDate = ''
      this.queryParam.outWarehouseEndDate = ''
      this.auditTime = []
      this.outWareTime = []
      if (this.advanced) {
        this.$refs.auditRangeDate.resetDate('')
        this.$refs.outWareRangeDate.resetDate('')
      }

      this.queryParam.buyerNameCurrent = undefined
      this.queryParam.buyerSn = undefined
      this.queryParam.salesBillNo = ''
      this.queryParam.purchaseBillNo = ''
      this.queryParam.payType = undefined
      this.queryParam.settleStyleSn = undefined
      this.queryParam.billStatus = undefined
      this.queryParam.financialStatus = undefined
      this.queryParam.sourceType = undefined
      this.queryParam.distributionFlag = undefined
      this.queryParam.buyerRelationType = undefined
      this.$refs.custList.resetForm()
      if (!flag) {
        // 重置单据状态
        this.setIsHomeNav(this.$route.name, null)
      }
    },
    //  导出
    handleExport () {
      const _this = this
      const params = this.queryParam
      params.showDiscountAmountFlag = this.showDiscount ? 1 : 0
      this.exportLoading = true
      _this.spinning = true
      salesExport(params).then(res => {
        this.exportLoading = false
        _this.spinning = false
        if (res.type == 'application/json') {
          var reader = new FileReader()
          reader.addEventListener('loadend', function () {
            const obj = JSON.parse(reader.result)
            _this.$notification.error({
              message: '提示',
              description: obj.message
            })
          })
          reader.readAsText(res)
        } else {
          downloadExcel(res, '销售列表')
        }
      })
    },
    // 表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 255
    },
    // 页面初始
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
      // 是否打开的页签
      const a = this.$store.state.app.isNewTab
      // 是否要刷新列表
      const b = this.$store.state.app.updateList
      // 是否从首页点击进入
      const isHomeNav = this.getIsHomeNav()[this.$route.name]
      // 从首页进入,判断式新建还式待办查询
      if (isHomeNav) {
        // 新增
        if (isHomeNav.type == 'new') {
          this.resetSearchForm()
          this.openModal = true
        }
        // 待办
        if (isHomeNav.type == 'todo') {
          this.$refs.rangeDate.resetDate([isHomeNav.pageParams.beginDate, isHomeNav.pageParams.endDate])
          this.queryParam = Object.assign(this.queryParam, isHomeNav.pageParams)
          this.$refs.table.refresh(true)
        }
      } else {
        // 如果是新页签打开，则重置当前页面
        if (a && !b) {
          this.resetSearchForm()
        }
        // 仅刷新列表，不重置页面
        if (b || a == b) {
          this.$refs.table.refresh()
        }
      }
    }
  },
  watch: {
    advanced (newValue, oldValue) {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    },
    isByCustQuery (newValue, oldValue) {
      if (!newValue) {
        this.resetSearchForm()
      }
    },
    isAbandonOrder (newVal, oldVal) {
      this.resetSearchForm()
    }
  },
  activated () {
    this.pageInit()
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
    })
  }
}
</script>
