<template>
  <a-card size="small" :bordered="false" class="warehouseAllocationList-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 搜索条件 -->
      <div ref="tableSearch" class="table-page-search-wrapper">
        <a-form layout="inline" ref="searchForm" :model="queryParam" @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="warehousingAuditList-purchaseBillNo" v-model.trim="queryParam.purchaseBillNo" allowClear placeholder="请输入单号"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="调出仓库">
                <a-select id="warehouseAllocation-basicInfo-outWarehouseSn" allowClear placeholder="请选择调出仓库" v-model="queryParam.outWarehouseSn">
                  <a-select-option v-for="(item, index) in warehouseList" :key="index" :value="item.warehouseSn">{{ item.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-item label="调入仓库">
                  <a-select id="warehouseAllocation-basicInfo-putWarehouseSn" allowClear placeholder="请选择调入仓库" v-model="queryParam.putWarehouseSn">
                    <a-select-option v-for="(item, index) in warehouseList" :key="index" :value="item.warehouseSn">{{ 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.state"
                    ref="state"
                    id="warehouseAllocationList-state"
                    code="ALLOCATION_WAREHOUSE_STATE"
                    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="warehouseAllocationList-refresh">查询</a-button>
              <a-button style="margin-left: 8px" @click="resetSearchForm" :disabled="disabled" id="warehouseAllocationList-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="warehouseAllocationList-add" v-if="$hasPermissions('B_warehouseAllocationNews')" type="primary" class="button-error" @click="openModal = true">新增</a-button></div>
      <!-- 统计 -->
      <a-alert type="info" style="margin-bottom:10px">
        <div slot="message">
          总款数： <strong>{{ countData&&(countData.productTotalCategory || countData.productTotalCategory==0) ? countData.productTotalCategory : '--' }}</strong> ，
          总数量： <strong>{{ countData&&(countData.productTotalQty || countData.productTotalQty==0) ? countData.productTotalQty : '--' }}</strong>
          <div style="display: inline-block;" v-if="$hasPermissions('M_ShowAllCost')">
            ，总成本： <strong>{{ countData&&(countData.productTotalCost || countData.productTotalCost==0) ? toThousands(countData.productTotalCost,2) : '--' }}</strong>
          </div>
        </div>
      </a-alert>
      <!-- 列表 -->
      <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="allocationWarehouseNo" slot-scope="text, record">
          <span class="table-td-link" v-if="$hasPermissions('B_warehouseAllocationDetail')" @click="handleDetail(record)">{{ record.allocationWarehouseNo }}</span>
          <span v-else>{{ record.allocationWarehouseNo }}</span>
        </template>
        <!-- 审核 -->
        <template slot="audit" slot-scope="text, record">
          <stateIcon :title="record.stateDictValue" :state="record.state == 'FINISH'?'1':'2'"></stateIcon>
        </template>
        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <a-button
            v-if="record.state == 'WAIT_AUDIT'&&$hasPermissions('B_allocWarehouseAudit')"
            size="small"
            type="link"
            class="button-primary"
            @click="handleExamine(record)"
            id="warehouseAllocationList-examine-btn">
            审核
          </a-button>
          <a-button
            v-if="((record.state == 'WAIT_SUBMIT') || (record.state == 'WAIT_AUDIT')) && $hasPermissions('B_warehouseAllocationEdit')"
            size="small"
            type="link"
            class="button-primary"
            @click="handleEdit(record,1)"
            id="warehouseAllocationList-edit-btn">
            编辑
          </a-button>
          <a-button
            v-if="((record.state == 'WAIT_SUBMIT') || (record.state == 'WAIT_AUDIT')) && $hasPermissions('B_warehouseAllocationDel')"
            size="small"
            type="link"
            class="button-error"
            @click="handleDel(record)"
            id="warehouseAllocationList-del-btn">
            删除
          </a-button>
          <span v-if="((record.state != 'WAIT_SUBMIT') && (record.state != 'WAIT_AUDIT')) || (!(record.state == 'WAIT_AUDIT'&&$hasPermissions('B_allocWarehouseAudit')) && !(((record.state == 'WAIT_SUBMIT') || (record.state == 'WAIT_AUDIT')) && $hasPermissions('B_warehouseAllocationEdit')) &&!(((record.state == 'WAIT_SUBMIT') || (record.state == 'WAIT_AUDIT')) && $hasPermissions('B_warehouseAllocationDel'))) ">--</span>
        </template>
      </s-table>
    </a-spin>
    <!-- 新增/编辑 -->
    <basic-info-modal :openModal="openModal" @ok="handleEdit" @close="openModal=false" />
  </a-card>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { allocWarehouseList, allocWarehouseAudit, allocWarehouseDel, allocWarehouseQueryCount } from '@/api/allocWarehouse'
import { warehouseAllList } from '@/api/warehouse.js'
import { STable, VSelect } from '@/components'
import basicInfoModal from './basicInfoModal.vue'
import rangeDate from '@/views/common/rangeDate.vue'
import stateIcon from '@/views/common/stateIcon'
import getDate from '@/libs/getDate.js'
export default {
  name: 'AllocWarehouseList',
  components: { STable, VSelect, basicInfoModal, rangeDate, stateIcon },
  mixins: [commonMixin],
  data () {
    return {
      spinning: false,
      advanced: true, // 高级搜索 展开/关闭
      tableHeight: 0,
      warehouseList: [], // 仓库列表
      time: [
        getDate.getCurrMonthDays().starttime,
        getDate.getCurrMonthDays().endtime
      ],
      queryParam: { //  查询条件
        beginDate: getDate.getCurrMonthDays().starttime,
        endDate: getDate.getCurrMonthDays().endtime,
        outWarehouseSn: undefined, //  调出仓库
        putWarehouseSn: undefined, //  调入仓库
        state: undefined //  审核状态
      },
      disabled: false, //  查询、重置按钮是否可操作
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        const params = Object.assign(parameter, this.queryParam)
        return allocWarehouseList(params).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            this.getCount(params)
            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, //  新增编辑  弹框
      countData: null// 统计数据
    }
  },
  computed: {
    columns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '创建时间', dataIndex: 'createDate', width: '11%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '单号', scopedSlots: { customRender: 'allocationWarehouseNo' }, width: '15%', align: 'center' },
        { title: '调出仓库', dataIndex: 'outWarehouseName', width: '12%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '调入仓库', dataIndex: 'putWarehouseName', width: '12%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '总款数', dataIndex: 'productTotalCategory', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '总数量', dataIndex: 'productTotalQty', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '总成本', dataIndex: 'productTotalCost', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '审核时间', dataIndex: 'auditTime', width: '11%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '业务状态', dataIndex: 'stateDictValue', width: '7%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '审核', scopedSlots: { customRender: 'audit' }, width: '3%', align: 'center' },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '8%', align: 'center' }
      ]
      if (this.$hasPermissions('M_ShowAllCost')) {
        arr.splice(7, 0, { title: '总成本', dataIndex: 'productTotalCost', width: '6%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text, 2) : '--') } })
      }
      return arr
    }
  },
  methods: {
    // 统计
    getCount (params) {
      allocWarehouseQueryCount(params).then(res => {
        if (res.status == 200) {
          this.countData = res.data
        } else {
          this.countData = null
        }
      })
    },
    //  时间  change
    dateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    // 获取仓库列表
    getWarehouseList () {
      warehouseAllList({}).then(res => {
        if (res.status == 200) {
          this.warehouseList = res.data || []
        } else {
          this.warehouseList = []
        }
      })
    },
    //  重置
    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.outWarehouseSn = undefined
      this.queryParam.putWarehouseSn = undefined
      this.queryParam.state = undefined
      if (!flag) {
        this.setIsHomeNav(this.$route.name, null)
      }
    },
    //  删除
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '删除后不可恢复，确定要进行删除吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          allocWarehouseDel({ 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
            }
          })
        }
      })
    },
    //  审核
    handleExamine (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要审核通过吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          allocWarehouseAudit({ allocationWarehouseSn: row.allocationWarehouseSn }).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/warehouseAllocation/detail/${row.allocationWarehouseSn}` })
    },
    //  新增/编辑
    handleEdit (row, flag) {
      if (!flag) {
        this.resetData()
      }
      this.$router.push({ path: `/allocationManagement/warehouseAllocation/edit/${row.id}/${row.allocationWarehouseSn}` })
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
      this.getWarehouseList()

      // 是否打开的页签
      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 - 273
    }
  },
  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>
