<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="供应商">
                <a-select v-model="queryParam.returnTargetSn" placeholder="请选择供应商">
                  <a-select-option v-for="item in purchaseTragetType" :key="item.purchaseTargetSn" :value="item.purchaseTargetSn">
                    {{ item.purchaseTargetName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="是否抓单">
                <v-select
                  code="FLAG"
                  id="purchaseReturnList-grabFlag"
                  v-model="queryParam.grabFlag"
                  allowClear
                  placeholder="请选择是否抓单"></v-select>
              </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_NO_SYNC_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="B_purchaseReturn-add" type="primary" v-if="$hasPermissions('B_purchaseReturn_outSnycAdd')&&($hasPermissions('B_PR_outSnycSJ')||$hasPermissions('B_PR_outSnycZB'))" class="button-error" @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"
        :scroll="{ y: tableHeight }"
        :defaultLoadData="false"
        bordered>
        <!-- 采退单号 -->
        <template slot="purchaseReturnNo" slot-scope="text, record">
          <span class="table-td-link" v-if="$hasPermissions('B_purchaseReturn_outSnycDetail')" @click="handleDetail(record)">{{ record.purchaseReturnNo }}</span>
          <span v-else>{{ record.purchaseReturnNo }}</span>
          <a-badge count="改" :offset="[10,0]" v-if="record.state=='HQ_CHANGE'"></a-badge>
        </template>
        <!-- 审核 -->
        <template slot="audit" slot-scope="text, record">
          <stateIcon :title="record.stateDictValue" v-if="record.state!='AUDIT_REJECT'" :state="record.state=='WAIT_OUT_WAREHOUSE'||record.state == 'FINISH'?'1':'2'"></stateIcon>
          <stateIcon :title="record.stateDictValue" v-else :state="0"></stateIcon>
        </template>
        <!-- 出库 -->
        <template slot="waitOut" slot-scope="text, record">
          <stateIcon :state="record.state == 'FINISH'?'1':'2'"></stateIcon>
        </template>
        <!-- 收款 -->
        <template slot="financial" slot-scope="text, record">
          <stateIcon :title="record.settleStateDictValue" :state="record.settleState == 'FINISH'?'1':'2'"></stateIcon>
        </template>
        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <div v-if="record.synchronizationType == '0'">
            <a-button
              size="small"
              type="link"
              class="button-primary"
              v-if="(record.state == 'WAIT_SUBMIT' || record.state == 'AUDIT_REJECT') && $hasPermissions('B_purchaseReturn_outSnycEdit')"
              @click="handleEdit(record,1)"
              id="purchaseReturnList-edit-btn">编辑</a-button>
            <a-button
              size="small"
              type="link"
              v-if="record.state == 'WAIT_AUDIT' && $hasPermissions('B_purchaseReturn_outSnycAudit')"
              @click="handleAudit(record)"
              class="button-primary"
              id="bulkReturnGoodsList-audit-btn">审核</a-button>
            <a-button
              size="small"
              type="link"
              v-if="record.state == 'WAIT_OUT_WAREHOUSE' && $hasPermissions('B_purchaseReturn_outSnycOut')"
              @click="handleWarehouse(record)"
              class="button-primary"
              id="bulkReturnGoodsList-out-btn">出库</a-button>
            <a-button
              size="small"
              type="link"
              class="button-error"
              v-if="(record.state == 'WAIT_SUBMIT' || record.state == 'AUDIT_REJECT') && $hasPermissions('B_purchaseReturn_outSnycDel')"
              @click="handleDel(record)"
              id="purchaseReturnList-del-btn">删除</a-button>
          </div>
          <div v-else></div>
        </template>
      </s-table>
    </a-spin>
    <!-- 选择基本信息弹框 -->
    <basic-info-modal :openModal="openModal" @load="setPurchaseTragetType" @ok="handleEdit" @close="openModal=false" />
    <!-- 审核 -->
    <auditModal
      :openModal="visibleAudit"
      :spinning="spinningAudit"
      @close="visibleAudit=false"
      @ok="auditOrder(true)"
      @fail="auditOrder(false)" />
  </a-card>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import basicInfoModal from './basicInfoModal.vue'
import getDate from '@/libs/getDate.js'
import auditModal from '@/views/common/auditModal.vue'
import stateIcon from '@/views/common/stateIcon'
import { purchaseReturnQueryNoSyncPage, purchaseReturnDel, purchaseReturnOutStock, purchaseReturnAudit } from '@/api/purchaseReturn'
export default {
  name: 'PurchaseReturnList',
  components: { STable, VSelect, rangeDate, stateIcon, basicInfoModal, auditModal },
  mixins: [commonMixin],
  data () {
    const _this = this
    return {
      spinning: false,
      advanced: true, // 高级搜索 展开/关闭
      openModal: false, // 基本信息弹框是否显示
      visibleAudit: false,
      spinningAudit: false,
      auditInfo: null,
      purchaseTragetType: [], // 供应商数据
      time: [
        getDate.getCurrMonthDays().starttime,
        getDate.getCurrMonthDays().endtime
      ],
      queryParam: { //  查询条件
        beginDate: getDate.getCurrMonthDays().starttime,
        endDate: getDate.getCurrMonthDays().endtime,
        purchaseReturnNo: '', //  退货单号
        state: undefined, //  业务状态
        settleState: undefined,
        returnTargetSn: undefined,
        grabFlag: undefined
      },
      disabled: false, //  查询、重置按钮是否可操作
      tableHeight: 0,
      columns: [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '创建时间', dataIndex: 'createDate', width: '12%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '采退单号', scopedSlots: { customRender: 'purchaseReturnNo' }, width: '12%', align: 'center' },
        { title: '供应商', dataIndex: 'returnTargetName', width: '12%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品款数', dataIndex: 'totalCategory', width: '7%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '总数量', dataIndex: 'totalQty', width: '7%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '总金额', dataIndex: 'totalAmount', width: '7%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text, 2) : '--') } },
        { title: '是否抓单', dataIndex: 'grabFlag', width: '7%', align: 'center', customRender: function (text) { return text == '1' ? '抓单' : '不抓单' } },
        { title: '出库时间', dataIndex: 'outStockTime', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '业务状态', dataIndex: 'noSyncStateDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '审核', scopedSlots: { customRender: 'audit' }, width: '3%', align: 'center' },
        { title: '出库', scopedSlots: { customRender: 'waitOut' }, width: '3%', align: 'center' },
        { title: '收款', scopedSlots: { customRender: 'financial' }, width: '3%', align: 'center' },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '10%', align: 'center' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        return purchaseReturnQueryNoSyncPage(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]
    },
    //  重置
    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.purchaseReturnNo = ''
      this.queryParam.state = undefined
      this.queryParam.settleState = undefined
      this.queryParam.returnTargetSn = undefined
      this.queryParam.grabFlag = undefined
      if (!flag) {
        this.setIsHomeNav(this.$route.name, null)
      }
    },
    // 获取供应商数据
    setPurchaseTragetType (data) {
      this.purchaseTragetType = data
    },
    //  删除
    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
            }
          })
        }
      })
    },
    // 编辑
    handleEdit (row, flag) {
      // 新增后跳转到编辑页，非列表点击的编辑，重置查询条件
      if (!flag) {
        this.resetData()
      }
      this.$router.push({ name: row.grabFlag == 1 ? 'purchaseReturnOutSyncGrapEdit' : 'purchaseReturnOutSyncEdit', params: { sn: row.purchaseReturnSn, returnTargetType: row.returnTargetType, purchaseTargetSn: row.returnTargetSn } })
    },
    // 详情
    handleDetail (row) {
      this.$router.push({ name: 'purchaseReturnOutSyncDetail', params: { sn: row.purchaseReturnSn, grabFlag: row.grabFlag } })
    },
    //  生成出库单
    handleWarehouse (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确定要出库吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          purchaseReturnOutStock({ purchaseReturnSn: row.purchaseReturnSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    auditOrder (billStatus) {
      this.spinningAudit = true
      purchaseReturnAudit({
        purchaseReturnSn: this.auditInfo.purchaseReturnSn,
        state: billStatus ? 'AUDIT_PASS' : 'AUDIT_REJECT'
      }).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
        }
      })
    },
    //  审核
    handleAudit (row) {
      this.auditInfo = row
      this.visibleAudit = true
    },
    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>
