<template>
  <a-card size="small" :bordered="false" class="purchaseReturnList-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="退货单号">
                <a-input id="purchaseReturnList-purchaseReturnNo" v-model.trim="queryParam.purchaseReturnNo" 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="purchaseReturnList-state"
                  code="PURCHASE_RETURN_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.settleState"
                    ref="settleState"
                    id="chainTransferOutList-settleState"
                    code="FINANCIAL_RECEIVE_STATUS"
                    placeholder="请选择财务状态"
                    allowClear></v-select>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
              <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="purchaseReturnList-refresh">查询</a-button>
              <a-button style="margin-left: 8px" @click="resetSearchForm" :disabled="disabled" id="purchaseReturnList-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>
      <!-- 操作按钮 -->
      <div class="table-operator">
        <a-button id="purchaseReturnList-add" type="primary" v-if="$hasPermissions('B_purchaseReturnNew')" class="button-error" @click="handleEdit()">新增</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"
        :scroll="{ y: tableHeight }"
        :defaultLoadData="false"
        bordered>
        <!-- 采退单号 -->
        <template slot="purchaseReturnNo" slot-scope="text, record">
          <span style="color: #ed1c24;cursor: pointer;" v-if="$hasPermissions('B_purchaseReturnDetail')" @click="handleDetail(record)">{{ record.purchaseReturnNo }}</span>
          <span v-else>{{ record.purchaseReturnNo }}</span>
        </template>
        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <a-button
            size="small"
            type="link"
            class="button-info"
            v-if="(record.state == 'WAIT_SUBMIT' || record.state == 'AUDIT_REJECT') && $hasPermissions('B_purchaseReturnEdit')"
            @click="handleEdit(record)"
            id="purchaseReturnList-edit-btn">编辑</a-button>
          <a-button
            size="small"
            type="link"
            v-if="record.state == 'CHECKED' && $hasPermissions('B_purchaseReturnOutStock')"
            @click="handleWarehouse(record)"
            class="button-primary"
            id="bulkReturnGoodsList-warehouse-btn">生成出库单</a-button>
          <a-button
            size="small"
            type="link"
            v-if="record.state == 'CHECKED' && $hasPermissions('B_purchaseReturnFinishBill')"
            @click="handleFinishBill(record)"
            class="button-primary"
            id="bulkReturnGoodsList-warehouse-btn">完结单据</a-button>
          <a-button
            size="small"
            type="link"
            class="button-error"
            v-if="(record.state == 'WAIT_SUBMIT' || record.state == 'AUDIT_REJECT') && $hasPermissions('B_purchaseReturnDel')"
            @click="handleDel(record)"
            id="purchaseReturnList-del-btn">删除</a-button>
          <span v-if="!((record.state == 'WAIT_SUBMIT' || record.state == 'AUDIT_REJECT') && ($hasPermissions('B_purchaseReturnEdit') || $hasPermissions('B_purchaseReturnDel'))) && !(record.state == 'CHECKED' && ($hasPermissions('B_purchaseReturnOutStock') || $hasPermissions('B_purchaseReturnFinishBill')))">--</span>
        </template>
      </s-table>
    </a-spin>
  </a-card>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import { purchaseTargetList } from '@/api/purchase'
import getDate from '@/libs/getDate.js'
import { purchaseReturnList, purchaseReturnSave, purchaseReturnDel, purchaseReturnOutStockBill, purchaseReturnFinishBill } from '@/api/purchaseReturn'
export default {
  name: 'PurchaseReturnList',
  components: { STable, VSelect, rangeDate },
  mixins: [commonMixin],
  data () {
    return {
      spinning: false,
      advanced: true, // 高级搜索 展开/关闭
      time: [
        getDate.getCurrMonthDays().starttime,
        getDate.getCurrMonthDays().endtime
      ],
      queryParam: { //  查询条件
        beginDate: getDate.getCurrMonthDays().starttime,
        endDate: getDate.getCurrMonthDays().endtime,
        purchaseReturnNo: '', //  退货单号
        state: undefined, //  业务状态
        settleState: undefined
      },
      disabled: false, //  查询、重置按钮是否可操作
      tableHeight: 0,
      columns: [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '创建时间', dataIndex: 'createDate', width: '14%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '采退单号', scopedSlots: { customRender: 'purchaseReturnNo' }, width: '17%', align: 'center' },
        { title: '退货数量', dataIndex: 'totalQty', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '退款金额', dataIndex: 'totalAmount', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '审核时间', dataIndex: 'auditTime', width: '14%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '扣减库存', dataIndex: 'hasStockBill', width: '6%', align: 'center', customRender: function (text) { return ['否', '是'][text] } },
        { title: '业务状态', dataIndex: 'stateDictValue', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '财务状态', dataIndex: 'settleStateDictValue', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '13%', align: 'center' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        return purchaseReturnList(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
        })
      },
      purchaseTragetType: []
    }
  },
  methods: {
    //  时间  change
    dateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    //  重置
    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.queryParam.purchaseReturnNo = ''
      this.queryParam.state = undefined
      this.queryParam.settleState = undefined
    },
    //  删除
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '删除后不可恢复，确定要进行删除吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          purchaseReturnDel({ id: row.id }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    //  详情
    handleDetail (row) {
      this.$router.push({ path: `/purchasingManagement/purchaseReturn/detail/${row.purchaseReturnSn}` })
    },
    //  新增/编辑
    handleEdit (row) {
      const _this = this
      if (row) { //  编辑
        _this.$router.push({ path: `/purchasingManagement/purchaseReturn/edit/${row.id}/${row.purchaseReturnSn}/${row.returnTargetName}` })
      } else { //  新增
        let content
        if (this.purchaseTragetType.length > 0) {
          content = '退货供应商：' + this.purchaseTragetType[0].purchaseTargetName
        } else {
          content = '退货供应商：--'
        }
        this.$confirm({
          title: '提示',
          content: content,
          centered: true,
          onOk () {
            const params = {
              returnTargetSn: _this.purchaseTragetType[0].purchaseTargetSn,
              returnTargetName: _this.purchaseTragetType[0].purchaseTargetName,
              returnTargetType: _this.purchaseTragetType[0].purchaseTargetType
            }
            _this.spinning = true
            purchaseReturnSave(params).then(res => {
              if (res.status == 200) {
                const data = res.data
                _this.spinning = false
                _this.$router.push({ path: `/purchasingManagement/purchaseReturn/add/${data.id}/${data.purchaseReturnSn}/${data.returnTargetName}` })
              } else {
                _this.spinning = false
              }
            })
          }
        })
      }
    },
    //  生成出库单
    handleWarehouse (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确定要生成出库单吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          purchaseReturnOutStockBill({ sn: row.purchaseReturnSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    //  完结单据
    handleFinishBill (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确定要完结该单据吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          purchaseReturnFinishBill({ sn: row.purchaseReturnSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    getParentDealer () {
      purchaseTargetList({ purchaseTargetType: 'SUPPLIER_SYS' }).then(res => {
        if (res.status == 200) {
          this.purchaseTragetType = res.data
        } else {
          this.purchaseTragetType = []
        }
      })
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
      this.getParentDealer()
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 235
    }
  },
  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>
