<template>
  <a-card size="small" :bordered="false" class="salesReturn-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 搜索条件 -->
      <div 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" @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}">
                <a-select
                  id="salesReturn-buyerSn"
                  placeholder="请选择客户"
                  allowClear
                  v-model="queryParam.buyerSn"
                  :showSearch="true"
                  option-filter-prop="children"
                  :filter-option="filterOption">
                  <a-select-option v-for="item in custAllList" :key="item.customerSn" :value="item.customerSn">{{ item.customerName }}</a-select-option>
                </a-select>
              </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: 15px;">
        <div slot="message">
          退货总金额：<strong>{{ countData&&countData.totalAmount }}</strong>元；
          总单数：<strong>{{ countData&&countData.totalBillNumber }}</strong>；
          总款数：<strong>{{ countData&&countData.totalCategory }}</strong>；
          总数量：<strong>{{ countData&&countData.totalQty }}</strong>；
        </div>
      </a-alert>
      <!-- 列表 -->
      <s-table
        class="sTable"
        ref="table"
        size="default"
        :rowKey="(record) => record.id"
        :columns="columns"
        :data="loadData"
        :scroll="{ x: 1810, y: tableHeight }"
        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="financialStatus" slot-scope="text, record">
          <a-badge :color="text=='FINISH'?'#87d068':'gold'" :text="record.settleStateDictValue" />
        </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'">--</span>
        </template>
      </s-table>
    </a-spin>
    <!-- 选择客户弹框 -->
    <choose-custom-modal :show="openModal" @ok="handleEdit" @cancel="openModal=false"></choose-custom-modal>
  </a-card>
</template>

<script>
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import chooseCustomModal from './chooseCustomModal.vue'
import { custAllList } from '@/api/customer'
import { salesReturnList, salesReturnCount, salesReturnAudit, salesReturnDel } from '@/api/salesReturn'
export default {
  name: 'TableList',
  components: {
    STable,
    VSelect,
    chooseCustomModal,
    rangeDate
  },
  data () {
    return {
      spinning: false,
      tableHeight: 0,
      // 高级搜索 展开/关闭
      advanced: false,
      disabled: false, //  查询、重置按钮是否可操作
      openModal: false, // 选择客户弹框是否显示
      custAllList: [], //  客户下拉数据
      // 查询参数
      queryParam: {
        beginDate: '',
        endDate: '',
        auditBeginDate: '',
        auditEndDate: '',
        buyerSn: undefined, //  客户名称
        salesReturnNo: undefined, //  销售退货单号
        state: undefined // 业务状态
      },
      countData: null, // 统计数据
      // 表头
      columns: [
        { title: '序号', dataIndex: 'no', width: 80, align: 'center' },
        { title: '创建时间', dataIndex: 'createDate', width: 160, align: 'center' },
        { title: '销售退货单号', scopedSlots: { customRender: 'salesReturnNo' }, width: 260, align: 'center' },
        { title: '客户名称', dataIndex: 'buyerName', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '退款总金额', dataIndex: 'totalAmount', width: 110, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '总款数', dataIndex: 'totalCategory', width: 110, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '总数量', dataIndex: 'totalQty', width: 110, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '是否抓单', dataIndex: 'grabFlag', width: 100, align: 'center', customRender: function (text) { return ['否', '是'][text] } },
        { title: '审核时间', dataIndex: 'auditTime', width: 160, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '业务状态', dataIndex: 'stateDictValue', width: 110, align: 'center' },
        { title: '财务状态', dataIndex: 'settleStateDictValue', scopedSlots: { customRender: 'financialStatus' }, width: 110, align: 'center' },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: 220, align: 'center', fixed: 'right' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        if (this.tableHeight == 0) {
          this.tableHeight = window.innerHeight - 440
        }
        // 查询总计
        this.getQueryCount(Object.assign(parameter, this.queryParam))
        return salesReturnList(Object.assign(parameter, this.queryParam)).then(res => {
          const 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
          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.$refs.rangeDate.resetDate()
      this.queryParam.beginDate = ''
      this.queryParam.endDate = ''
      this.$refs.rangeExamineDate.resetDate()
      this.queryParam.auditBeginDate = ''
      this.queryParam.auditEndDate = ''
      this.queryParam.buyerSn = undefined
      this.queryParam.salesReturnNo = ''
      this.queryParam.state = ''
      this.$refs.table.refresh(true)
    },
    // 客户无分页列表数据
    getCustAllList () {
      const _this = this
      custAllList().then(res => {
        if (res.status == 200) {
          _this.custAllList = res.data || []
        } else {
          _this.custAllList = []
        }
      })
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.getCustAllList()
    })
  }
}
</script>
