<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="单据来源">
                <v-select
                  v-model="queryParam.billSource"
                  ref="billSource"
                  id="purchaseReturnList-billSource"
                  code="RETURN_APPLY_BILL_SOURCE"
                  placeholder="请选择单据来源"
                  allowClear></v-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="采购退货申请单号">
                <a-input id="purchaseReturnList-purchaseReturnApplyNo" v-model.trim="queryParam.purchaseReturnApplyNo" 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="purchaseReturnList-billStatus"
                  code="RETURN_APPLY_BILL_STATUS"
                  placeholder="请选择业务状态"
                  allowClear
                ></v-select>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-item label="客服审核时间">
                  <rangeDate ref="auditDate" :value="auditTime" @change="auditDateChange" />
                </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" v-if="$hasPermissions('B_purchaseReturnApplyNew')">
        <a-button id="purchaseReturnList-add" type="primary" 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="purchaseReturnApplyNo" slot-scope="text, record">
          <span class="table-td-link" v-if="$hasPermissions('B_purchaseReturnApplyDetail')" @click="handleDetail(record)">{{ record.purchaseReturnApplyNo }}</span>
          <span v-else>{{ record.purchaseReturnApplyNo }}</span>
          <a-badge count="改" :offset="[10,0]" v-if="record.changeFlag=='1'"></a-badge>
        </template>
        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <div>
            <a-button
              size="small"
              type="link"
              class="button-primary"
              v-if="record.billStatus == 'WAIT_SUBMIT'&&$hasPermissions('B_purchaseReturnApplyEdit')"
              @click="handleEdit(record)"
            >编辑</a-button>
            <a-button
              size="small"
              type="link"
              class="button-error"
              v-if="record.billStatus == 'WAIT_SUBMIT'&&$hasPermissions('B_purchaseReturnApplyDel')"
              @click="handleDel(record)"
            >删除</a-button>
            <a-button
              size="small"
              type="link"
              v-if="record.billStatus == 'FINISH'&&$hasPermissions('B_purchaseReturnApplyCreat')"
              @click="handleWarehouse(record)"
              class="button-primary"
            >生成采购退货单</a-button>
            <a-button
              size="small"
              type="link"
              v-if="(record.billStatus == 'CANCEL'||record.billStatus == 'AUDIT_REJECT')&&$hasPermissions('B_purchaseReturnApplyAsignEdit')"
              @click="handleFinishBill(record)"
              class="button-primary"
            >再次编辑</a-button>
          </div>
        </template>
      </s-table>
    </a-spin>

    <!-- 生成采购退货单 -->
    <creatPurchaseReutn ref="creatPurchaseReutn" :openModal="openCpModal" @close="openCpModal=false" @creatOk="$refs.table.refresh()"></creatPurchaseReutn>
  </a-card>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import getDate from '@/libs/getDate.js'
import creatPurchaseReutn from './creatPurchaseReutn.vue'
import { purchaseReturnList, purchaseReturnSave, purchaseReturnDel, purchaseReturnAgainCreate } from '@/api/purchaseReturnApply'
export default {
  name: 'PurchaseReturnList',
  components: { STable, VSelect, rangeDate, creatPurchaseReutn },
  mixins: [commonMixin],
  data () {
    return {
      spinning: false,
      advanced: true, // 高级搜索 展开/关闭
      openCpModal: false,
      time: [
        getDate.getCurrMonthDays().starttime,
        getDate.getCurrMonthDays().endtime
      ],
      auditTime: [],
      queryParam: { //  查询条件
        beginDate: getDate.getCurrMonthDays().starttime,
        endDate: getDate.getCurrMonthDays().endtime,
        purchaseReturnApplyNo: '', //  退货申请单号
        billStatus: undefined, //  业务状态
        billSource: undefined, // 单据来源
        beginAuditDate: '', // 审核时间
        endAuditDate: ''
      },
      disabled: false, //  查询、重置按钮是否可操作
      tableHeight: 0,
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        delete parameter.index
        delete parameter.tableId
        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
        })
      }
    }
  },
  computed: {
    columns () {
      const arr = [
        { title: '序号', dataIndex: 'no', width: '5%', align: 'center' },
        { title: '单据来源', dataIndex: 'billSourceDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '采购退货申请单号', scopedSlots: { customRender: 'purchaseReturnApplyNo' }, width: '14%', align: 'center' },
        { title: '供应商', dataIndex: 'returnTargetName', width: '15%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '申请退货数量', dataIndex: 'totalInitialQty', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '总公司实收数量', dataIndex: 'totalReceiveQty', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '业务状态', dataIndex: 'billStatusDictValue', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '创建时间', dataIndex: 'createDate', width: '12%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '客服审核时间', dataIndex: 'auditTime', width: '12%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '12%', align: 'center' }
      ]
      return arr
    }
  },
  methods: {
    //  时间  change
    dateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    // 审核时间
    auditDateChange (date) {
      this.queryParam.beginAuditDate = date[0]
      this.queryParam.endAuditDate = date[1]
    },
    //  重置
    resetSearchForm () {
      this.resetData()
      this.$refs.table.refresh(true)
    },
    // 重置数据
    resetData (flag) {
      this.$refs.rangeDate.resetDate(flag ? '' : this.time)
      this.queryParam.beginDate = flag ? '' : getDate.getCurrMonthDays().starttime
      this.queryParam.endDate = flag ? '' : getDate.getCurrMonthDays().endtime
      this.queryParam.purchaseReturnApplyNo = ''
      this.queryParam.billStatus = undefined
      this.queryParam.billSource = undefined
      this.auditTime = []
      this.$refs.auditDate.resetDate(this.auditTime)
      this.queryParam.beginAuditDate = ''
      this.queryParam.endAuditDate = ''
      if (!flag) {
        this.setIsHomeNav(this.$route.name, null)
      }
    },
    //  删除
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '删除后不可恢复，确定要进行删除吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          purchaseReturnDel({ purchaseReturnApplySn: row.purchaseReturnApplySn }).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({ name: 'purchaseReturnApplyFormDetail', params: { sn: row.purchaseReturnApplySn } })
    },
    //  新增/编辑
    handleEdit (row) {
      const _this = this
      if (row) { //  编辑
        _this.$router.push({ name: 'purchaseReturnApplyFormEdit', params: { sn: row.purchaseReturnApplySn } })
      } else { //  新增
        this.$confirm({
          title: '提示',
          content: <div><div style="padding:10px 0;">供应商：箭冠营销中心</div><div style='color:#999;'><div>说明：</div><div>1、采购退货申请单提交后，箭冠营销中心系统将能查看到此单并进行后续处理。</div><div>2、采购退货申请单中的产品，不会占用库存。</div></div></div>,
          centered: true,
          onOk () {
            _this.spinning = true
            purchaseReturnSave({}).then(res => {
              if (res.status == 200) {
                const data = res.data
                _this.spinning = false
                // 重置查询条件
                _this.resetData()
                _this.$router.push({ name: 'purchaseReturnApplyFormEdit', params: { sn: data.purchaseReturnApplySn } })
              } else {
                _this.spinning = false
              }
            })
          }
        })
      }
    },
    // 再次编辑
    handleFinishBill (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '系统将自动生成一个新的采购退货申请单，与原单据内容相同。确认再次编辑吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          purchaseReturnAgainCreate({ sn: row.purchaseReturnApplySn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    // 生成采购单
    handleWarehouse (row) {
      this.openCpModal = true
      this.$refs.creatPurchaseReutn.setData(row)
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
      // 是否打开的页签
      const a = this.$store.state.app.isNewTab
      // 是否要刷新列表
      const b = this.$store.state.app.updateList
      // 是否从首页点击进入
      const isHomeNav = this.getIsHomeNav()[this.$route.name]
      console.log(a, b, this.getIsHomeNav(), isHomeNav, this.$route.name)

      // 从首页进入,判断式新建还式待办查询
      if (isHomeNav) {
        // 新增
        if (isHomeNav.type == 'new') {
          this.resetSearchForm()
          this.openModal = true
        }
        // 待办
        if (isHomeNav.type == 'todo') {
          this.resetData(true)
          this.queryParam = Object.assign(this.queryParam, isHomeNav.pageParams)
          this.$refs.rangeDate.resetDate([this.queryParam.beginDate, this.queryParam.endDate])
          this.$refs.table.refresh(true)
        }
      } else {
        // 如果是新页签打开，则重置当前页面
        if (a && !b) {
          this.resetSearchForm()
        }
      }
      // 仅刷新列表，不重置页面
      if (b || a == b) {
        this.$refs.table.refresh()
      }
    },
    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 () {},
  activated () {
    this.pageInit()
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
