<template>
  <a-card size="small" :bordered="false" class="salesReturn-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 搜索条件 -->
      <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" :value="time" @change="dateChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="审核时间">
                <rangeDate ref="rangeExamineDate" @change="dateExamineChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="客户名称" :label-col="{ span:7 }" :wrapper-col="{ span:17}">
                <custList ref="custList" @change="custChange" v-model="queryParam.buyerSn"></custList>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-item label="退货单号">
                  <a-input id="salesReturn-salesReturnNo" v-model.trim="queryParam.salesReturnNo" allowClear placeholder="请输入退货单号"/>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="业务状态">
                  <v-select
                    v-model="queryParam.state"
                    ref="state"
                    id="salesManagementList-state"
                    code="SALES_RETURN_BILL_STATUS"
                    placeholder="请选择业务状态"
                    allowClear></v-select>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" :disabled="disabled" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" :disabled="disabled" @click="resetSearchForm()">重置</a-button>
                <a @click="advanced=!advanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'"/>
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!-- 操作按钮 -->
      <div class="table-operator">
        <a-button type="primary" class="button-error" v-if="$hasPermissions('B_salesReturnNew')" @click="openModal = true">新增</a-button>
      </div>
      <!-- alert -->
      <a-alert type="info" style="margin-bottom: 10px;">
        <div slot="message">
          退货总金额：<strong>{{ countData&&(countData.totalAmount || countData.totalAmount==0) ? countData.totalAmount : '--' }}</strong>元；
          总单数：<strong>{{ countData&&(countData.totalBillNumber || countData.totalBillNumber==0) ? countData.totalBillNumber : '--' }}</strong>；
          总款数：<strong>{{ countData&&(countData.totalCategory || countData.totalCategory==0) ? countData.totalCategory : '--' }}</strong>；
          总数量：<strong>{{ countData&&(countData.totalQty || countData.totalQty==0) ? countData.totalQty : '--' }}</strong>；
        </div>
      </a-alert>
      <!-- 列表 -->
      <s-table
        class="sTable fixPagination"
        ref="table"
        :style="{ height: tableHeight+84.5+'px' }"
        size="small"
        :rowKey="(record) => record.id"
        :columns="columns"
        :data="loadData"
        :scroll="{ y: tableHeight }"
        :defaultLoadData="false"
        bordered>
        <!-- 单号 -->
        <template slot="salesReturnNo" slot-scope="text, record">
          <span style="color: #ed1c24;cursor: pointer;" v-if="$hasPermissions('B_salesReturnDetail')" @click="handleDetail(record)">{{ record.salesReturnNo }}</span>
          <span v-else>{{ record.salesReturnNo }}</span>
        </template>
        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <a-button
            size="small"
            type="link"
            class="button-warning"
            v-if="record.state == 'WAIT_AUDIT'&&$hasPermissions('B_salesReturnAudit')"
            @click="handleEexamine(record)"
            id="salesReturn-eexamine-btn">审核</a-button>
          <a-button
            size="small"
            v-if="(record.state == 'WAIT_AUDIT'||record.state == 'WAIT_SUBMIT') &&$hasPermissions('B_salesReturnEdit')"
            type="link"
            class="button-info"
            @click="handleEdit(record)"
            id="salesReturn-edit-btn">编辑</a-button>
          <a-button
            size="small"
            v-if="(record.state == 'WAIT_AUDIT'||record.state == 'WAIT_SUBMIT') &&$hasPermissions('B_salesReturnDel')"
            type="link"
            class="button-error"
            @click="handleDel(record)"
            id="salesReturn-del-btn">删除</a-button>
          <span v-if="record.state == 'FINISH' || (!(record.state == 'WAIT_AUDIT'&&$hasPermissions('B_salesReturnAudit')) && !((record.state == 'WAIT_AUDIT'||record.state == 'WAIT_SUBMIT') &&$hasPermissions('B_salesReturnEdit')) && !((record.state == 'WAIT_AUDIT'||record.state == 'WAIT_SUBMIT') &&$hasPermissions('B_salesReturnDel')))">--</span>
        </template>
      </s-table>
    </a-spin>
    <!-- 选择客户弹框 -->
    <choose-custom-modal :show="openModal" @ok="handleEdit" @cancel="openModal=false"></choose-custom-modal>
  </a-card>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import getDate from '@/libs/getDate.js'
import rangeDate from '@/views/common/rangeDate.vue'
import chooseCustomModal from './chooseCustomModal.vue'
import custList from '@/views/common/custList.vue'
import { salesReturnList, salesReturnCount, salesReturnAudit, salesReturnDel } from '@/api/salesReturn'
export default {
  name: 'SalesReturnList',
  components: {
    STable,
    VSelect,
    chooseCustomModal,
    rangeDate,
    custList
  },
  mixins: [commonMixin],
  data () {
    return {
      spinning: false,
      tableHeight: 0,
      // 高级搜索 展开/关闭
      advanced: true,
      disabled: false, //  查询、重置按钮是否可操作
      openModal: false, // 选择客户弹框是否显示
      time: [
        getDate.getCurrMonthDays().starttime,
        getDate.getCurrMonthDays().endtime
      ],
      // 查询参数
      queryParam: {
        beginDate: getDate.getCurrMonthDays().starttime,
        endDate: getDate.getCurrMonthDays().endtime,
        auditBeginDate: '',
        auditEndDate: '',
        buyerSn: undefined, //  客户名称
        salesReturnNo: undefined, //  销售退货单号
        state: undefined // 业务状态
      },
      countData: null, // 统计数据
      // 表头
      columns: [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '创建时间', dataIndex: 'createDate', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '销售退货单号', scopedSlots: { customRender: 'salesReturnNo' }, width: '15%', align: 'center' },
        { title: '客户名称', dataIndex: 'buyerName', width: '15%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '退款总金额', dataIndex: 'totalAmount', width: '7%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '总款数', dataIndex: 'totalCategory', width: '5%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '总数量', dataIndex: 'totalQty', width: '5%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '是否抓单', dataIndex: 'grabFlag', width: '6%', align: 'center', customRender: function (text) { return ['否', '是'][text] } },
        { title: '审核时间', dataIndex: 'auditTime', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '业务状态', dataIndex: 'stateDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '财务状态', dataIndex: 'settleStateDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '11%', align: 'center' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        // 查询总计
        this.getQueryCount(Object.assign(parameter, this.queryParam))
        return salesReturnList(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
        })
      }
    }
  },
  methods: {
    //  时间  change
    dateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    //  审核时间  change
    dateExamineChange (date) {
      this.queryParam.auditBeginDate = date[0]
      this.queryParam.auditEndDate = date[1]
    },
    // 列表统计
    getQueryCount (params) {
      salesReturnCount(params).then(res => {
        this.countData = res.data || null
      })
    },
    // 编辑
    handleEdit (row) {
      this.$router.push({ name: row.grabFlag == 1 ? 'salesReturnGrabEdit' : 'salesReturnEdit', params: { id: row.id, sn: row.salesReturnSn, buyerSn: row.buyerSn } })
    },
    // 详情
    handleDetail (row) {
      this.$router.push({ name: 'salesReturnDetail', params: { id: row.id, sn: row.salesReturnSn } })
    },
    // 删除
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要删除吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          salesReturnDel({ sn: row.salesReturnSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    //  审核
    handleEexamine (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要审核吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          salesReturnAudit({
            sn: row.salesReturnSn
          }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    resetSearchForm () {
      this.resetData()
      this.$refs.table.refresh(true)
    },
    // 重置数据
    resetData () {
      this.$refs.rangeDate.resetDate(this.time)
      this.queryParam.beginDate = getDate.getCurrMonthDays().starttime
      this.queryParam.endDate = getDate.getCurrMonthDays().endtime
      this.$refs.rangeExamineDate.resetDate()
      this.queryParam.auditBeginDate = ''
      this.queryParam.auditEndDate = ''
      this.queryParam.buyerSn = undefined
      this.queryParam.salesReturnNo = ''
      this.queryParam.state = undefined
      this.$refs.custList.resetForm()
    },
    // 客户 change
    custChange (obj) {
      this.queryParam.buyerSn = obj.key || undefined
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 270
    }
  },
  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.resetData()
      if (this.$route.query.pageParams) {
        this.queryParam.state = this.$route.query.pageParams.state
      }
      this.pageInit()
      this.$refs.table.refresh(true)
    }
    // 仅刷新列表，不重置页面
    if (this.$store.state.app.updateList) {
      this.pageInit()
      this.$refs.table.refresh()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
