<template>
  <a-card size="small" :bordered="false" class="chainTransferOutList-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-select
                  placeholder="请选择调往对象"
                  allowClear
                  id="chainTransferOutList-putTenantSn"
                  v-model="queryParam.putTenantSn"
                  :showSearch="true"
                  option-filter-prop="children"
                  :filter-option="filterOption">
                  <a-select-option v-for="item in putTenantSnData" :key="item.sn" :value="item.sn">{{ item.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="调出产品类型">
                <v-select
                  v-model="queryParam.allocationType"
                  ref="allocationType"
                  id="chainTransferOutList-allocationType"
                  code="ALLOCATION_LINKAGE_PRODUCT_TYPE"
                  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.state"
                    ref="state"
                    id="chainTransferOutList-state"
                    code="ALLOCATION_LINKAGE_OUT_STATUS"
                    placeholder="请选择业务状态"
                    allowClear></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="财务状态">
                  <v-select
                    v-model="queryParam.settleState"
                    ref="settleState"
                    id="chainTransferOutList-settleState"
                    code="FINANCIAL_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="chainTransferOutList-refresh">查询</a-button>
              <a-button style="margin-left: 8px" @click="resetSearchForm" :disabled="disabled" id="chainTransferOutList-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="chainTransferOutList-add" v-if="$hasPermissions('B_allocLinkageOutNew')" type="primary" 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="allocationLinkageOutNo" slot-scope="text, record">
          <span style="color: #ed1c24;cursor: pointer;" v-if="$hasPermissions('B_allocLinkageOutDetail')" @click="handleDetail(record)">{{ record.allocationLinkageOutNo }}</span>
          <span v-else>{{ record.allocationLinkageOutNo }}</span>
        </template>
        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <a-button
            size="small"
            type="link"
            v-if="record.state == 'WAIT_AUDIT'&&$hasPermissions('B_allocLinkageOutAudit')"
            class="button-warning"
            @click="handleExamine(record)"
            id="chainTransferOutList-examine-btn">审核</a-button>
          <a-button
            size="small"
            type="link"
            v-if="(record.state == 'WAIT_SUBMIT' || record.state == 'WAIT_AUDIT') &&$hasPermissions('B_allocLinkageOutEdit')"
            class="button-info"
            @click="handleEdit(record)"
            id="chainTransferOutList-edit-btn">编辑</a-button>
          <a-button
            size="small"
            type="link"
            v-if="record.state == 'WAIT_OUT_WAREHOUSE'&&$hasPermissions('B_allocLinkageOutStock')"
            class="button-primary"
            @click="handleOut(record)"
            id="chainTransferOutList-out-btn">出库</a-button>
          <a-button
            size="small"
            type="link"
            v-if="(record.state == 'WAIT_SUBMIT' || record.state == 'WAIT_AUDIT' || record.state == 'WAIT_OUT_WAREHOUSE') &&$hasPermissions('B_allocLinkageOutDel')"
            class="button-error"
            @click="handleDel(record)"
            id="chainTransferOutList-del-btn">删除</a-button>
          <span v-if="(record.state != 'WAIT_SUBMIT' && record.state != 'WAIT_AUDIT' && record.state != 'WAIT_OUT_WAREHOUSE')|| (!(record.state == 'WAIT_AUDIT'&&$hasPermissions('B_allocLinkageOutAudit')) && !((record.state == 'WAIT_SUBMIT' || record.state == 'WAIT_AUDIT') &&$hasPermissions('B_allocLinkageOutEdit')) && !(record.state == 'WAIT_OUT_WAREHOUSE'&&$hasPermissions('B_allocLinkageOutStock')))">--</span>
        </template>
      </s-table>
    </a-spin>
    <!-- 新增/编辑 -->
    <basic-info-modal :openModal="openModal" @ok="handleOk" @close="openModal=false" />
  </a-card>
</template>

<script>
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import basicInfoModal from './basicInfoModal.vue'
import getDate from '@/libs/getDate.js'
import { allocLinkageOutList, allocLinkageAudit, allocLinkageOutDel, allocLinkageOutStock, getTenantList } from '@/api/allocLinkageOut'
export default {
  components: { STable, VSelect, basicInfoModal, rangeDate },
  data () {
    return {
      spinning: false,
      tableHeight: 0,
      advanced: true, // 高级搜索 展开/关闭
      time: [
        getDate.getCurrMonthDays().starttime,
        getDate.getCurrMonthDays().endtime
      ],
      queryParam: { //  查询条件
        beginDate: getDate.getCurrMonthDays().starttime,
        endDate: getDate.getCurrMonthDays().endtime,
        putTenantSn: undefined, //  调往对象
        allocationType: undefined, //  调出产品类型
        state: undefined, //  业务状态
        settleState: undefined
      },
      disabled: false, //  查询、重置按钮是否可操作
      columns: [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '创建时间', dataIndex: 'createDate', width: '11%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '连锁调出单号', scopedSlots: { customRender: 'allocationLinkageOutNo' }, width: '16%', align: 'center' },
        { title: '调往对象', dataIndex: 'putTenantName', width: '12%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '总款数', dataIndex: 'productTotalCategory', width: '5%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '总数量', dataIndex: 'productTotalQty', width: '5%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '总成本', dataIndex: 'productTotalCost', width: '5%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '审核时间', dataIndex: 'auditTime', width: '11%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '调拨类型', dataIndex: 'allocationTypeDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '业务状态', dataIndex: 'stateDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '财务状态', dataIndex: 'settleStateDictValue', width: '6%', 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 allocLinkageOutList(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
        })
      },
      putTenantSnData: [],
      openModal: false, //  新增编辑  弹框
      itemId: '' //  当前品牌id
    }
  },
  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.putTenantSn = undefined
      this.queryParam.allocationType = undefined
      this.queryParam.state = undefined
      this.queryParam.settleState = undefined
    },
    //  基本信息  保存
    handleOk (data) {
      this.$router.push({ path: `/allocationManagement/chainTransferOut/add/${data.id}/${data.allocationLinkageOutSn}` })
    },
    //  删除
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '删除后不可恢复，确定要进行删除吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          allocLinkageOutDel({ sn: row.allocationLinkageOutSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    //  出库
    handleOut (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要出库吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          allocLinkageOutStock({ sn: row.allocationLinkageOutSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    //  审核
    handleExamine (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要审核通过吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          allocLinkageAudit({ sn: row.allocationLinkageOutSn }).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: `/allocationManagement/chainTransferOut/detail/${row.allocationLinkageOutSn}` })
    },
    //  新增/编辑
    handleEdit (row) {
      this.$router.push({ path: `/allocationManagement/chainTransferOut/edit/${row.id}/${row.allocationLinkageOutSn}` })
    },
    // 调往对象
    getPutTenantList () {
      getTenantList({}).then(res => {
        if (res.status == 200) {
          this.putTenantSnData = res.data
        } else {
          this.putTenantSnData = []
        }
      })
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
      this.openModal = false
      this.getPutTenantList()
    },
    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>
