<template>
  <a-card size="small" :bordered="false" class="inventoryCheckList-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 标签页 -->
      <a-tabs type="card" :default-active-key="queryParam.deleteFlag" @change="handleTabChange" class="inventoryCheckList-tabs">
        <a-tab-pane v-for="item in tabPaneData" :key="item.type">
          <span slot="tab">{{ item.name }}</span>
        </a-tab-pane>
      </a-tabs>
      <!-- 搜索条件 -->
      <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="盘点单号">
                <a-input id="inventoryCheckList-checkWarehouseNo" v-model.trim="queryParam.checkWarehouseNo" allowClear placeholder="请输入盘点单号"/>
              </a-form-item>
            </a-col>
            <a-col :md="4" :sm="24" v-show="isShowWarehouse">
              <a-form-item label="仓库">
                <warehouse
                  v-model="queryParam.warehouseSn"
                  isPermission
                  id="inventoryCheckList-warehouseSn"
                  placeholder="请选择仓库"
                />
              </a-form-item>
            </a-col>
            <a-col :md="4" :sm="24">
              <a-form-item label="盘点状态">
                <v-select
                  v-model="queryParam.checkState"
                  ref="checkState"
                  id="inventoryCheckList-checkState"
                  code="CHECK_WAREHOUSE_STATE"
                  placeholder="请选择盘点状态"
                  allowClear
                ></v-select>
              </a-form-item>
            </a-col>
            <a-col :md="4" :sm="24">
              <a-form-item label="监盘状态">
                <v-select
                  v-model="queryParam.checkSuperviseState"
                  ref="checkSuperviseState"
                  id="inventoryCheckList-checkSuperviseState"
                  code="CHECK_WAREHOUSE_SUPERVISE_STATE"
                  placeholder="请选择监盘状态"
                  allowClear
                ></v-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="inventoryCheckList-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="inventoryCheckList-reset">重置</a-button>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!-- 操作按钮 -->
      <div class="table-operator">
        <a-button v-if="$hasPermissions('B_inventoryCheckAdd')" id="inventoryCheckList-add" type="primary" class="button-error" @click="handleAdd">新增</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="action" slot-scope="text, record">
          <a-button
            size="small"
            type="link"
            v-if="$hasPermissions('B_inventoryCheckDetail')"
            class="button-success"
            @click="handleDetail(record)"
            id="inventoryCheckList-audit-btn">详情</a-button>
          <span v-else>--</span>
        </template>
      </s-table>
    </a-spin>
    <!-- 新增盘点单 -->
    <inventory-check-add-modal :openModal="openAddModal" @ok="handleAddOk" @close="openAddModal=false" />
    <!-- 盘点校验 -->
    <common-modal
      :openModal="openCommonModal"
      :modalHtml="modalHtml"
      okText="好的"
      :isCancel="false"
      @ok="openCommonModal=false"
      @cancel="openCommonModal=false" />
  </a-card>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import inventoryCheckAddModal from './addModal.vue'
import commonModal from '@/views/common/commonModal.vue'
import warehouse from '@/views/common/chooseWarehouse.js'
import { checkWarehouseList, checkWarehouseStartCheck } from '@/api/checkWarehouse'
export default {
  name: 'InventoryCheckList',
  mixins: [commonMixin],
  components: { STable, VSelect, inventoryCheckAddModal, commonModal, warehouse },
  data () {
    return {
      spinning: false,
      tableHeight: 0,
      queryParam: { //  查询条件
        deleteFlag: this.$route.params.type,
        checkWarehouseNo: '',
        checkState: undefined,
        warehouseSn: undefined,
        checkSuperviseState: undefined
      },
      disabled: false, //  查询、重置按钮是否可操作
      tabPaneData: [
        { name: '正常', type: '0' },
        { name: '已作废', type: '1' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        return checkWarehouseList(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
        })
      },
      openModal: false,
      itemSn: '',
      openAddModal: false,
      openCommonModal: false,
      modalHtml: ''
    }
  },
  computed: {
    columns () {
      let arr = [
          { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
          { title: '盘点单号', dataIndex: 'checkWarehouseNo', width: '10%', align: 'center' },
          // { title: '仓库', dataIndex: 'warehouseName', width: '12%', align: 'center', customRender: function (text) { return text || '--' } },
          { title: '盘点状态', dataIndex: 'checkStateDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
          { title: '监盘状态', dataIndex: 'checkSuperviseStateDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
          { title: '盘点人', dataIndex: 'checkPersonName', align: 'center', width: '8%', customRender: function (text) { return text || '--' }, ellipsis: true },
          { title: '盘点提交时间', dataIndex: 'checkTime', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
          { title: '监盘人', dataIndex: 'checkSupervisePersonName', align: 'center', width: '8%', customRender: function (text) { return text || '--' }, ellipsis: true },
          { title: '监盘提交时间', dataIndex: 'checkSuperviseTime', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        ]

      if (this.queryParam.deleteFlag == '0') { // 正常
        arr = arr.concat([
          { title: '财务确认时间', dataIndex: 'financeAuditTime', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
          { title: '盘点单创建时间', dataIndex: 'createDate', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
          { title: '操作', scopedSlots: { customRender: 'action' }, width: '6%', align: 'center' }
        ])
      } else if (this.queryParam.deleteFlag == '1') { // 已作废
        arr = arr.concat([
          { title: '盘点单创建时间', dataIndex: 'createDate', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
          { title: '盘点单作废时间', dataIndex: 'deleteTime', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
          { title: '操作', scopedSlots: { customRender: 'action' }, width: '6%', align: 'center' }
        ])
      }

      if(this.isShowWarehouse){
        arr.splice(2,0,{ title: '仓库', dataIndex: 'warehouseName', width: '12%', align: 'center', customRender: function (text) { return text || '--' } })
      }
      return arr
    }
  },
  methods: {
    // 新增
    handleAdd () {
      this.spinning = true
      checkWarehouseStartCheck({}).then(res => {
        this.spinning = false
        if (res.status == 200) {
          if (res.data && res.data.length > 0) {
            // this.modalHtml = `<div style="width: 100%">
            //   <h3 style="font-size: 15px;font-weight: bold;margin: 20px 0 5px;text-align: center;">存在以下状态的销售单，无法盘点。</h3>
            //   <h3 style="font-size: 15px;font-weight: bold;margin-bottom: 25px;text-align: center;">请先检查并处理完以下单据再试。</h3>
            //   ${res.data.indexOf('WAIT_AUDIT') != -1 ? '<p>销售单-待审核（总部自建）</p>' : ''}
            //   ${res.data.indexOf('AUDIT_REJECT') != -1 ? '<p>销售单-审核不通过（总部自建）</p>' : ''}
            //   ${res.data.indexOf('HQ_CHANGE') != -1 ? '<p>销售单-总公司改单</p>' : ''}
            //   ${res.data.indexOf('WAIT_PUSH') != -1 ? '<p>销售单-待下推</p>' : ''}
            // </div>`
            this.modalHtml = `<div style="width: 100%">
              ${res.data.indexOf('WAIT_PUSH') != -1 ? '<p>存在“待下推”状态的销售单，无法盘点。</p>' : ''}
            </div>`
            this.openCommonModal = true
          } else {
            this.openAddModal = true
          }
        }
      })
    },
    // 新增 成功
    handleAddOk (data) {
      this.$router.push({ path: `/inventoryManagement/inventoryCheck/detail/${data.checkWarehouseSn}` })
    },
    // 选择类型
    handleTabChange (key) {
      this.queryParam.deleteFlag = key
      this.$refs.table.refresh(true)
    },
    // 详情
    handleDetail (row) {
      if (this.$hasPermissions('B_inventoryCheckDetail')) {
        this.$router.push({ path: `/inventoryManagement/inventoryCheck/detail/${row.checkWarehouseSn}` })
      }
    },
    resetSearchForm () {
      this.queryParam.checkWarehouseNo = ''
      this.queryParam.checkState = undefined
      this.queryParam.checkSuperviseState = undefined
      this.queryParam.warehouseSn = undefined
      this.$refs.table.refresh(true)
    },
    closeModal () {
      this.itemSn = ''
      this.openModal = false
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    setTableH () {
      this.tableHeight = window.innerHeight - 332
    }
  },
  watch: {
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
      this.$refs.table.refresh(true)
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      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 => {
      const _this = vm
      if (_this.$route.params.type == '1') {
        setTimeout(() => {
          _this.$refs.table.refresh(true)
        }, 300)
      }
    })
  }
}
</script>

<style lang="less">
  .inventoryCheckList-wrap{
    .active{
      color: #ed1c24;
      cursor: pointer;
    }
    .common{
      color: rgba(0, 0, 0);
    }
    // tab样式
    .inventoryCheckList-tabs.ant-tabs.ant-tabs-card .ant-tabs-card-bar .ant-tabs-nav-container{
      height: 30px!important;
    }
    .inventoryCheckList-tabs.ant-tabs.ant-tabs-card .ant-tabs-card-bar .ant-tabs-tab-active{
      height: 30px!important;
    }
    .inventoryCheckList-tabs.ant-tabs.ant-tabs-card .ant-tabs-card-bar .ant-tabs-tab{
      line-height: 26px!important;
      height: 30px!important;
    }
  }
</style>
