<template>
  <div>
    <a-card size="small" :bordered="false" class="searchBox">
      <!-- 搜索条件 -->
      <div ref="tableSearch" class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="$refs.table.refresh(true)">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-item label="创建时间">
                <rangeDate ref="rangeDate" @change="dateChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="客户名称" :label-col="{ span:7 }" :wrapper-col="{ span:17}">
                <dealerSubareaScopeList ref="dealerSubareaScopeList" id="returnConfirmationList-buyerSn" @change="custChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="销退单号">
                <a-input id="returnConfirmationList-salesReturnBillNo" v-model.trim="queryParam.salesReturnBillNo" allowClear placeholder="请输入销退单号"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="状态">
                <v-select
                  v-model="queryParam.billStatus"
                  ref="billStatus"
                  id="returnConfirmationList-billStatus"
                  code="SALES_RETURN_CONFIRM_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.salesReturnBillSource"
                    ref="salesReturnBillSource"
                    id="returnConfirmationList-salesReturnBillSource"
                    code="SALES_SOURCE"
                    placeholder="请选择单据来源"
                    allowClear></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="仓库">
                  <chooseWarehouse ref="warehouse" v-model="queryParam.warehouseSn"></chooseWarehouse>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="退货类别" prop="goodFlag">
                  <v-select
                    v-model="queryParam.goodFlag"
                    ref="goodFlag"
                    id="returnSchedule-goodFlag"
                    code="GOOD_FLAG"
                    placeholder="请选择退货类别"
                    allowClear></v-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="退货类型">
                  <v-select
                    v-model="queryParam.salesReturnType"
                    id="departUser-salesReturnType"
                    code="SALES_RETURN_TYPE"
                    placeholder="请选择退货类型"
                    allowClear></v-select>
                </a-form-model-item>
              </a-col>
            </template>
            <a-col :md="24" :sm="24" style="text-align: center;">
              <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="returnConfirmationList-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="returnConfirmationList-reset">重置</a-button>
              <a @click="advanced=!advanced" style="margin-left: 8px">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'"/>
              </a>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>

    <a-card size="small" :bordered="false" class="returnConfirmationList-wrap">
      <a-spin :spinning="spinning" tip="Loading...">
        <!-- 列表 -->
        <s-table
          class="sTable fixPagination"
          ref="table"
          :style="{ height: tableHeight+70+'px' }"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :pageSize="30"
          :data="loadData"
          :scroll="{ y: tableHeight }"
          :defaultLoadData="false"
          bordered>
          <!-- 销退单号 -->
          <template slot="salesReturnBillNo" slot-scope="text, record">
            <span v-if="$hasPermissions('B_returnConfirmation_detail')" class="link-bule" @click="handleDetail(record)">{{ record.salesReturnBillNo }}</span>
            <span v-else>{{ record.salesReturnBillNo }}</span>
          </template>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <a-button
              size="small"
              type="link"
              v-if="record.billStatus=='WAIT_FINANCIAL_AUDIT' && $hasPermissions('B_returnConfirmation_return')"
              class="button-warning"
              @click="handleAudit(record)"
              id="returnConfirmationList-audit-btn">退货确认</a-button>
            <span v-else>--</span>
          </template>
        </s-table>
      </a-spin>
      <!-- 查看 -->
      <confirmation-detail-modal v-drag :openModal="openModal" :itemSn="itemSn" @close="closeModal" />
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import rangeDate from '@/views/common/rangeDate.vue'
import { STable, VSelect } from '@/components'
import dealerSubareaScopeList from '@/views/common/dealerSubareaScopeList.vue'
import confirmationDetailModal from './detailModal.vue'
import chooseWarehouse from '@/views/common/chooseWarehouse'
import { salesReturnFinancialList, salesReturnFinancial } from '@/api/salesReturn'
export default {
  name: 'ReturnConfirmationList',
  mixins: [commonMixin],
  components: { STable, VSelect, confirmationDetailModal, dealerSubareaScopeList, rangeDate, chooseWarehouse },
  data () {
    return {
      spinning: false,
      tableHeight: 0,
      queryParam: { //  查询条件
        beginDate: '',
        endDate: '',
        salesReturnBillNo: '', //  单号
        buyerSn: undefined,
        salesReturnBillSource: undefined,
        billStatus: undefined, //  状态
        warehouseSn: undefined, //  仓库
        goodFlag: undefined,
        salesReturnType: undefined
      },
      disabled: false, //  查询、重置按钮是否可操作
      advanced: true,
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        return salesReturnFinancialList(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
        })
      },
      openModal: false,
      itemSn: ''
    }
  },
  // 根据权限显示列表字段
  computed: {
    columns () {
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '创建时间', dataIndex: 'createDate', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '单据来源', dataIndex: 'salesReturnBillSourceDictValue', width: '7%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '总部销退单号', scopedSlots: { customRender: 'salesReturnBillNo' }, width: '15%', align: 'center' },
        { title: '客户名称', dataIndex: 'buyerName', align: 'center', width: '15%', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '退货类别', dataIndex: 'goodFlagDictValue', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '退货类型', dataIndex: 'salesReturnTypeDictValue', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '仓库', dataIndex: 'warehouseName', align: 'center', width: '15%', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '申请退货数量', dataIndex: 'totalInitialQty', width: '7%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '仓库实收数量', dataIndex: 'totalReceiveQty', width: '7%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '退货金额', dataIndex: 'totalAmount', width: '7%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '确认时间', dataIndex: 'confirmTime', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '状态', dataIndex: 'billStatusDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '8%', align: 'center' }
      ]
      if (this.$hasPermissions('M_returnConfirmationList_salesPrice')) { //  售价权限
        arr.splice(8, 0, { title: '退货金额', dataIndex: 'totalAmount', width: '7%', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') })
      }
      return arr
    }
  },
  methods: {
    //  创建时间  change
    dateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    custChange (val) {
      this.queryParam.buyerSn = val.key
    },
    //  重置
    resetSearchForm () {
      this.$refs.rangeDate.resetDate()
      this.queryParam.beginDate = ''
      this.queryParam.endDate = ''
      this.queryParam.salesReturnBillNo = ''
      this.queryParam.buyerSn = undefined
      this.queryParam.salesReturnBillSource = undefined
      this.queryParam.billStatus = undefined
      this.queryParam.warehouseSn = undefined
      this.queryParam.goodFlag = undefined
      this.queryParam.salesReturnType = undefined
      this.$refs.dealerSubareaScopeList.resetForm()
      this.$refs.table.refresh(true)
    },
    // 详情
    handleDetail (row) {
      if (!this.$hasPermissions('B_returnConfirmation_detail')) { return }
      this.itemSn = row.salesReturnBillSn
      this.openModal = true
    },
    closeModal () {
      this.itemSn = ''
      this.openModal = false
    },
    // 单个审核
    handleAudit (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '请点击下方按钮确认操作',
        centered: true,
        closable: true,
        okText: '通过',
        cancelText: '不通过',
        onOk () {
          _this.auditOrder(row.salesReturnBillSn, 'FINISH')
        },
        onCancel (e) {
          if (!e.triggerCancel) {
            _this.auditOrder(row.salesReturnBillSn, 'FINANCIAL_REJECT')
          }
          _this.$destroyAll()
        }
      })
    },
    auditOrder (sn, flag) {
      const _this = this
      _this.spinning = true
      salesReturnFinancial({ salesReturnBillSn: sn, billStatus: flag }).then(res => {
        if (res.status == 200) {
          _this.$message.success(res.message)
          _this.$refs.table.refresh()
          _this.spinning = false
        } else {
          _this.spinning = false
        }
      })
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 210
    }
  },
  watch: {
    advanced (newValue, oldValue) {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      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>
