<template>
  <div>
    <a-card size="small" :bordered="false" class="searchBoxNormal">
      <!-- 搜索条件 -->
      <div ref="tableSearch" class="table-page-search-wrapper">
        <a-form layout="inline" id="transferReturn-form" @keyup.enter.native="$refs.table.refresh(true)">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-item label="创建时间">
                <rangeDate ref="rangeDate" id="transferReturn-time" :value="time" @change="dateChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="调拨退货单号">
                <a-input id="transferReturn-allocateReturnNo" v-model.trim="queryParam.allocateReturnNo" allowClear placeholder="请输入调拨退货单号"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="调拨退货对象名称">
                <a-input id="transferReturn-targetName" v-model.trim="queryParam.targetName" allowClear placeholder="请输入调拨退货对象名称"/>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-item label="费用/调拨退货类型">
                  <AllocateType id="transferReturn-allocateReturnTypeSn" v-model="allocateTypeVal" :changeOnSelect="true" placeholder="请选择费用/调拨退货类型" @change="changeAllocatype"></AllocateType>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="调入仓库">
                  <warehouse
                    v-model="queryParam.warehouseSn"
                    id="transferReturn-warehouseSn"
                    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="transferReturn-state"
                    code="ALLOCATE_RETURN_STATE"
                    placeholder="请选择业务状态"
                    allowClear
                  ></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24" v-show="isShowCustomerSearch">
                <a-form-item label="客服">
                  <customerService id="transferReturn-bizUserSn" ref="customerName" v-model="queryParam.bizUserSn"></customerService>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="24">
              <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="transferReturn-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="transferReturn-reset">重置</a-button>
              <!-- <a-button
              style="margin-left: 5px"
              type="primary"
              class="button-warning"
              v-if="$hasPermissions('B_transferOut_export')"
              @click="handleExport"
              :disabled="disabled"
              :loading="exportLoading"
              id="transferReturn-export">导出</a-button> -->
              <a @click="advanced=!advanced" style="margin-left: 5px" id="transferReturn-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="transferReturn-wrap">
      <a-spin :spinning="spinning" tip="Loading...">
        <!-- 操作按钮 -->
        <div class="table-operator">
          <a-button v-if="$hasPermissions('B_transferReturnNew')" id="transferReturn-add" type="primary" @click="openModal=true">新增</a-button>
        </div>
        <!-- 列表 -->
        <s-table
          class="sTable fixPagination"
          ref="table"
          :style="{ height: tableHeight+84.5+'px' }"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :defaultLoadData="false"
          :scroll="{ y: tableHeight }"
          bordered>
          <!-- 单号 -->
          <template slot="allocateReturnNo" slot-scope="text, record">
            <span v-if="$hasPermissions('M_transferReturnDetail')" :id="'transferReturn-allocateReturnNo'+record.id" class="link-bule" @click="handleDetail(record)">{{ record.allocateReturnNo }}</span>
            <span v-else>{{ record.allocateReturnNo }}</span>
          </template>
          <!-- 调拨类型 -->
          <template slot="allocateType" slot-scope="text, record">
            <div>
              <span v-if="record.allocateSortName">{{ record.allocateSortName }}</span>
              <span v-if="record.allocateSortName&&record.allocateReturnTypeName">/</span>
              <span v-if="record.allocateReturnTypeName">{{ record.allocateReturnTypeName }}</span>
            </div>
          </template>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <a-button
              size="small"
              type="link"
              v-if="record.state == 'WAIT_AUDIT' && $hasPermissions('B_transferReturnAudit')"
              class="button-warning"
              @click="handleExamine(record)"
              :id="'transferReturn-audit-btn'+record.id">审核</a-button>
            <a-button
              size="small"
              type="link"
              class="button-warning"
              v-if="record.state=='WAIT_CHECK' && $hasPermissions('M_transferReturnCheck')"
              @click="handleCheck(record)"
              :id="'transferReturn-check-btn'+record.id">品检</a-button>
            <a-button
              size="small"
              type="link"
              v-if="((record.state == 'WAIT_SUBMIT') || (record.state == 'FINANCIAL_REJECT') || (record.state == 'AUDIT_REJECT')) && $hasPermissions('B_transferReturnEdit')"
              class="button-info"
              @click="handleEdit(record)"
              :id="'transferReturn-edit-btn'+record.id">编辑</a-button>
            <a-button
              size="small"
              type="link"
              v-if="((record.state == 'WAIT_SUBMIT') || (record.state == 'FINANCIAL_REJECT') || (record.state == 'AUDIT_REJECT')) && $hasPermissions('B_transferReturnDel')"
              class="button-error"
              @click="handleDel(record)"
              :id="'transferReturn-del-btn'+record.id">删除</a-button>
            <!-- 带财务确认或已完结 -->
            <span v-if="record.state == 'WAIT_FINANCIAL_AUDIT'||record.state == 'FINISH'">--</span>
          </template>
        </s-table>
      </a-spin>
      <!-- 新增 -->
      <basic-info-modal :openModal="openModal" @ok="handleEdit" @close="openModal=false" />
      <!-- 审核 -->
      <auditModal
        v-drag
        :openModal="visibleAudit"
        :spinning="spinningAudit"
        @close="visibleAudit=false"
        @ok="auditOrder('WAIT_CHECK')"
        @fail="auditOrder('AUDIT_REJECT')" />
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { hdExportExcel } from '@/libs/exportExcel'
// 组件
import { STable, VSelect } from '@/components'
import basicInfoModal from './basicInfoModal.vue'
import rangeDate from '@/views/common/rangeDate.vue'
import auditModal from '@/views/common/auditModal.vue'
import AllocateType from '@/views/common/allocateType.js'
import warehouse from '@/views/common/chooseWarehouse.js'
import customerService from '@/views/common/customerService'
// 接口
import { allocateReturnQueryPage, allocateReturnAudit, allocateReturnDelete } from '@/api/allocateReturn'
export default {
  name: 'TransferReturnList',
  mixins: [commonMixin],
  components: { STable, VSelect, basicInfoModal, rangeDate, auditModal, AllocateType, warehouse, customerService },
  data () {
    return {
      spinning: false,
      advanced: true, // 高级搜索 展开/关闭
      tableHeight: 0, // 表格高度
      time: [], // 创建时间
      allocateTypeVal: [], // 费用/调拨退货类型
      //  查询条件
      queryParam: {
        beginDate: '', // 开始时间
        endDate: '', // 结束时间
        targetName: '', //  调往对象
        costTypeSn: undefined, // 费用类型
        allocateSortSn: undefined, //  调拨类别
        allocateReturnTypeSn: undefined, // 调拨退货类型2
        state: undefined, //  业务状态
        warehouseSn: undefined, // 出库仓库
        allocateReturnNo: '', //  调拨单号
        bizUserSn: undefined// 客服
      },
      disabled: false, //  查询、重置按钮是否可操作
      exportLoading: false, // 导出按钮加载状态
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        // 获取列表数据  有分页
        return allocateReturnQueryPage(Object.assign(parameter, this.queryParam, { authWarehouseFlag: 0 })).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, // 审核按钮加载状态
      openModal: false //  新增编辑  弹框
    }
  },
  computed: {
    // 表头
    columns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', width: '3.5%', align: 'center' },
        { title: '创建时间', dataIndex: 'createDate', width: '7%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '调拨退货单号', scopedSlots: { customRender: 'allocateReturnNo' }, align: 'center', width: '8%' },
        { title: '调拨退货对象类型', dataIndex: 'targetTypeDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '调拨退货对象名称', dataIndex: 'targetName', width: '8%', align: 'left', customRender: function (text) { return text || '--' } },
        { title: '费用类型', dataIndex: 'costTypeName', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '调拨退货类型', scopedSlots: { customRender: 'allocateType' }, width: '6%', align: 'center' },
        { title: '是否抓单', dataIndex: 'grabFlagDictValue', width: '5%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '退货总数量', dataIndex: 'totalQty', width: '5%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '坏件数量', dataIndex: 'totalBadQty', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '返库数量', dataIndex: 'totalBackStockQty', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '审核时间', dataIndex: 'auditTime', width: '7%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '调入仓库', dataIndex: 'warehouseName', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '业务状态', dataIndex: 'stateDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '7%', align: 'center' }
      ]
      if (this.$hasPermissions('M_transferReturnList_salesPrice')) {
        arr.splice(11, 0, { title: '退货总金额', dataIndex: 'totalPrice', width: '5%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      return arr
    }
  },
  methods: {
    //  创建时间  change
    dateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    // 选择费用/调拨退货类型
    changeAllocatype (val, opts) {
      this.allocateTypeVal = val || []
      this.queryParam.costTypeSn = val && val[0] ? val[0] : ''
      this.queryParam.allocateSortSn = val && val[1] ? val[1] : ''
      this.queryParam.allocateReturnTypeSn = val && val[2] ? val[2] : ''
    },
    //  重置
    resetSearchForm () {
      this.$refs.rangeDate.resetDate('')
      this.queryParam.beginDate = ''
      this.queryParam.endDate = ''
      this.queryParam.targetName = ''
      this.queryParam.state = undefined
      this.queryParam.allocateReturnNo = ''
      this.queryParam.costTypeSn = undefined
      this.queryParam.allocateSortSn = undefined
      this.queryParam.allocateReturnTypeSn = undefined
      this.queryParam.warehouseSn = undefined
      this.queryParam.bizUserSn = undefined
      this.allocateTypeVal = []
      this.$refs.table.refresh(true)
    },
    //  删除
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '删除后不可恢复，确定要进行删除吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          allocateReturnDelete({ allocateReturnSn: row.allocateReturnSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    //  审核
    handleExamine (row) {
      this.auditInfo = row
      this.visibleAudit = true
    },
    // 审核成功
    auditOrder (state) {
      const _this = this
      _this.spinningAudit = true
      allocateReturnAudit({ allocateReturnSn: this.auditInfo.allocateReturnSn, state: state }).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
        }
      })
    },
    //  详情
    handleDetail (row) {
      this.$router.push({ name: 'transferReturnDetail', params: { sn: row.allocateReturnSn } })
    },
    //  编辑
    handleEdit (row) {
      this.$router.push({ name: row.grabFlag == 1 ? 'transferReturnGrpEdit' : 'transferReturnEdit', params: { sn: row.allocateReturnSn } })
    },
    // 品检
    handleCheck (row) {
      this.$router.push({ name: 'transferReturnCheck', params: { sn: row.allocateReturnSn, grabFlag: row.grabFlag } })
    },
    //  导出
    handleExport () {
      const _this = this
      const params = this.queryParam
      this.exportLoading = true
      this.spinning = true
      hdExportExcel(allocateReturnExport, params, '调拨退货列表', function () {
        _this.exportLoading = false
        _this.spinning = false
      })
    },
    // 初始化
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
      this.openModal = false
    },
    // 表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 255
    }
  },
  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>
<style lang="less" scoped>
	.active{
		color: #ed1c24;
		cursor: pointer;
	}
	.common{
		color: rgba(0, 0, 0);
	}
  /deep/.anticon.anticon-down.ant-cascader-picker-arrow{
  color:#ccc !important;
  }
</style>
