<template>
  <a-card size="small" :bordered="false" class="inventoryCheckingList-wrap">
    <!-- 搜索条件 -->
    <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="inventoryCheckingList-checkWarehouseNo" v-model.trim="queryParam.checkWarehouseNo" allowClear placeholder="请输入盘点单号"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="盘点类型">
              <v-select code="CHECK_WAREHOUSE_TYPE" id="inventoryCheckingList-checkType" v-model="queryParam.checkType" allowClear placeholder="请选择盘点类型"></v-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="是否区分仓库">
              <v-select code="FLAG" id="inventoryCheckingList-warehouseFlag" v-model="queryParam.warehouseFlag" allowClear placeholder="请选择"></v-select>
            </a-form-item>
          </a-col>
          <template v-if="advanced">
            <a-col :md="6" :sm="24">
              <a-form-item label="状态">
                <v-select code="CHECK_WAREHOUSE_STATE" id="inventoryCheckingList-state" v-model="queryParam.state" allowClear placeholder="请选择状态"></v-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="创建时间">
                <rangeDate ref="rangeDate" :value="[queryParam.beginDate, queryParam.endDate]" @change="dateChange" />
              </a-form-item>
            </a-col>
          </template>
          <a-col :md="6" :sm="24">
            <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="inventoryCheckingList-refresh">查询</a-button>
            <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="inventoryCheckingList-reset">重置</a-button>
            <a @click="advanced=!advanced" style="margin-left: 5px">
              {{ advanced ? '收起' : '展开' }}
              <a-icon :type="advanced ? 'up' : 'down'"/>
            </a>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 操作按钮 -->
    <div class="table-operator">
      <a-button id="inventoryCheckingList-add" v-if="$hasPermissions('B_inventoryCheckingAdd')" 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="checkWarehouseNo" slot-scope="text, record">
        <span style="color: #ed1c24;cursor: pointer;" v-if="$hasPermissions('B_inventoryCheckingDetail')" @click="handleDetail(record)">{{ record.checkWarehouseNo }}</span>
        <span v-else>{{ record.checkWarehouseNo }}</span>
      </template>
      <!-- 监盘人审核 -->
      <template slot="dpaudit" slot-scope="text, record">
        <stateIcon v-if="record.state!='AUDIT_REJECT'" :state="record.state !== 'WAIT_SUBMIT'&&record.state !== 'WAIT_AUDIT'?'1':'2'"></stateIcon>
        <stateIcon :title="record.stateDictValue" v-else :state="0"></stateIcon>
      </template>
      <!-- 财务人审核 -->
      <template slot="cwaudit" slot-scope="text, record">
        <stateIcon :state="record.state == 'FINISH'?'1':'2'"></stateIcon>
      </template>
      <!-- 操作 -->
      <template slot="action" slot-scope="text, record">
        <a-button
          size="small"
          type="link"
          v-if="(record.state == 'WAIT_SUBMIT') || (record.state == 'AUDIT_REJECT') && $hasPermissions('B_inventoryCheckingEdit')"
          class="button-primary"
          @click="handleEdit(record)"
        >编辑</a-button>
        <a-button
          size="small"
          type="link"
          v-if="record.state == 'WAIT_AUDIT' && $hasPermissions('B_inventoryCheckingAudit')"
          class="button-primary"
          @click="handleEexamine(record)"
        >审核</a-button>
        <a-button
          size="small"
          type="link"
          v-if="record.state == 'WAIT_CHECK_WAREHOUSE' && $hasPermissions('B_inventoryCheckingInventory')"
          class="button-primary"
          @click="handleWarehouse(record)"
        >盘点</a-button>
        <a-button
          size="small"
          type="link"
          v-if="record.state == 'WAIT_CHECK_WAREHOUSE' && $hasPermissions('B_inventoryCheckingAgain')"
          class="button-primary"
          @click="handleAgain(record)"
        >重盘</a-button>
        <a-button
          size="small"
          type="link"
          v-if="(record.state == 'WAIT_SUBMIT') || (record.state == 'AUDIT_REJECT') && $hasPermissions('B_inventoryCheckingDel')"
          class="button-error"
          @click="handleDel(record)"
        >删除</a-button>
        <span
          v-if="!((record.state == 'WAIT_SUBMIT') || (record.state == 'AUDIT_REJECT') && ($hasPermissions('B_inventoryCheckingEdit') || $hasPermissions('B_inventoryCheckingDel')))
            && !(record.state == 'WAIT_AUDIT' && $hasPermissions('B_inventoryCheckingAudit'))
            && !(record.state == 'WAIT_CHECK_WAREHOUSE' && ($hasPermissions('B_inventoryCheckingInventory') || $hasPermissions('B_inventoryCheckingAgain')))">--</span>
      </template>
    </s-table>
    <!-- 基础信息 -->
    <basic-info-modal :openModal="openModal" @ok="handleOk" @close="openModal=false" />
    <!-- 审核 -->
    <auditModal :openModal="visibleAudit" :spinning="spinningAudit" @close="visibleAudit=false" @ok="auditOrder(true)" @fail="auditOrder(false)" />
    <!-- 详情 -->
    <inventoryChecking-detail-modal :openModal="openDetailModal" :itemSn="itemSn" @close="handleDetailClose" />
  </a-card>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import auditModal from '@/views/common/auditModal.vue'
import basicInfoModal from './basicInfoModal.vue'
import inventoryCheckingDetailModal from './detailModal.vue'
import stateIcon from '@/views/common/stateIcon'
import { checkWarehouseList, checkWarehouseDel, checkWarehouseAudit, checkWarehouseValidate, checkWarehouseReInventory } from '@/api/checkWarehouse'
export default {
  name: 'InventoryCheckingList',
  components: { STable, VSelect, rangeDate, auditModal, basicInfoModal, inventoryCheckingDetailModal, stateIcon },
  mixins: [commonMixin],
  data () {
    return {
      queryParam: { //  查询条件
        checkWarehouseNo: '',
        checkType: undefined,
        warehouseFlag: undefined,
        state: undefined,
        beginDate: '', //  创建时间  开始时间
        endDate: '' //  创建时间  结束时间
      },
      tableHeight: 0,
      advanced: true,
      disabled: false, //  查询、重置按钮是否可操作
      // 加载数据方法 必须为 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, //  新增编辑  弹框
      itemId: '', //  当前id
      nowData: null, //  当前记录数据
      visibleAudit: false,
      auditInfo: null,
      spinningAudit: false,
      openDetailModal: false,
      itemSn: null
    }
  },
  computed: {
    columns () {
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '盘点单号', scopedSlots: { customRender: 'checkWarehouseNo' }, width: '12%', align: 'center' },
        { title: '总款数', dataIndex: 'productTotalCategory', width: '7%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '总数量', dataIndex: 'totalStockQty', width: '7%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '总成本', dataIndex: 'totalStockCost', width: '10%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '盘点类型', dataIndex: 'checkTypeDictValue', width: '7%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '是否区分仓库', dataIndex: 'warehouseFlagDictValue', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '创建时间', dataIndex: 'createDate', width: '11%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '审核时间', dataIndex: 'checkSuperviseTime', width: '11%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '状态', dataIndex: 'stateDictValue', width: '7%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '监盘人审核', scopedSlots: { customRender: 'dpaudit' }, width: '3%', align: 'center' },
        { title: '财务人审核', scopedSlots: { customRender: 'cwaudit' }, width: '3%', align: 'center' },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '10%', align: 'center' }
      ]
      if (this.$hasPermissions('M_ShowAllCost')) {
        arr.splice(4, 0, { title: '总成本', dataIndex: 'totalStockCost', width: '10%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } })
      }
      return arr
    }
  },
  methods: {
    //  时间  change
    dateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    //  重置
    resetSearchForm () {
      this.queryParam.checkWarehouseNo = ''
      this.queryParam.checkType = undefined
      this.queryParam.warehouseFlag = undefined
      this.queryParam.state = undefined
      this.queryParam.beginDate = ''
      this.queryParam.endDate = ''
      this.$refs.rangeDate.resetDate()
      this.$refs.table.refresh(true)
    },
    // 新增
    handleAdd () {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '如果开始盘点，不能再进行其他与产品出入库相关的操作。确认开始盘点吗？',
        centered: true,
        onOk () {
          // checkWarehouseValidate({}).then(res => {
          //   if (res.status == 200) {
          //     if (res.data) {
          _this.openModal = true
          //     } else {
          //       _this.$message.info('存在未完结的盘点单，不能新增，请先完成盘点后再新增')
          //     }
          //   }
          // })
        }
      })
    },
    //  编辑
    handleEdit (row) {
      if (row.checkType == 'ALL') { // 全盘
        this.$router.push({ path: `/inventoryManagement/inventoryChecking/overall/${row.id}/${row.checkWarehouseSn}` })
      } else if (row.checkType == 'SELECT') { // 自选盘点
        this.$router.push({ path: `/inventoryManagement/inventoryChecking/selfDisk/${row.id}/${row.checkWarehouseSn}` })
      }
    },
    //  详情
    handleDetail (row) {
      this.itemSn = row.checkWarehouseSn
      this.openDetailModal = true
    },
    // 盘点
    handleWarehouse (row) {
      this.$router.push({ path: `/inventoryManagement/inventoryChecking/makeInventory/${row.id}/${row.checkWarehouseSn}` })
    },
    // 重盘
    handleAgain (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '重新盘点后，盘点单状态回退到待提交。确认重新盘点吗？',
        centered: true,
        onOk () {
          checkWarehouseReInventory({ id: row.id }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
            }
          })
        }
      })
    },
    //  基本信息  保存
    handleOk (data) {
      this.handleEdit(data)
    },
    //  删除
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '删除后不可恢复，确定要进行删除吗？',
        centered: true,
        onOk () {
          checkWarehouseDel({ id: row.id }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
            }
          })
        }
      })
    },
    //  审核
    handleEexamine (row) {
      this.auditInfo = row
      this.visibleAudit = true
    },
    auditOrder (billStatus) {
      this.spinningAudit = true
      checkWarehouseAudit({
        id: this.auditInfo.id,
        auditFlag: billStatus
      }).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
        }
      })
    },
    handleDetailClose () {
      this.itemSn = null
      this.openDetailModal = false
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    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.pageInit()
      this.resetSearchForm()
    }
    // 仅刷新列表，不重置页面
    if (this.$store.state.app.updateList) {
      this.pageInit()
      this.$refs.table.refresh()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
