<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input v-model="query.code" clearable placeholder="代码" style="width: 150px;" class="filter-item"
                  @keyup.enter.native="crud.toQuery"
        />
        <el-select
          v-model="query.status"
          clearable
          size="small"
          placeholder="状态"
          class="filter-item"
          style="width: 150px"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item in dict.use_status"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select
          v-model="query.stockTypeCode"
          clearable
          size="small"
          placeholder="容器类型"
          class="filter-item"
          style="width: 150px"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item in stockTypes"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          />
        </el-select>

        <el-select v-model="query.areaName" style="width: 120px;" clearable placeholder="库区"
                   @keyup.enter.native="crud.toQuery" class="filter-item" @change="crud.toQuery"
        >
          <el-option
            v-for="area in areas"
            :key="area.id"
            :label="area.name"
            :value="area.name"
          />
        </el-select>
        <el-input v-model="query.pointCode" clearable placeholder="点位" style="width: 150px;" class="filter-item"
                  @keyup.enter.native="crud.toQuery"
        />

        <rrOperation :crud="crud"/>
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" :tableKey="this.$options.name">

        <el-upload
          class="upload-demo"
          slot="right"
          style="float: right;padding-left: 5px"
          :headers="headers"
          :action="baseApi+'/api/stock/import_stock'"
          :file-list="fileList"
          :on-error="handleErr"
          :on-success=" (response, file, fileList) => { return handleSuccess(response, file, fileList,crud);}"
          :show-file-list="true"
        >
          <el-button size="mini" type="success" icon="el-icon-upload2">导入</el-button>
        </el-upload>
      </crudOperation>

      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0"
                 :title="crud.status.title" width="450px"
      >
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="代码" prop="code">
            <el-input v-model="form.code" style="width: 300px;"/>
          </el-form-item>
          <el-form-item label="名称" prop="name">
            <el-input v-model="form.name" style="width: 300px;"/>
          </el-form-item>
          <el-form-item label="类型" prop="stockType">
            <el-select v-model="form.stockType" value-key="id" filterable placeholder="请选择" style="width: 300px;">
              <el-option
                v-for="item in stockTypes"
                :key="item.id"
                :label="item.name"
                :value="item"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="状态" prop="status">
            <el-select
              v-model="form.status"
              clearable
              size="small"
              placeholder="状态"
              class="filter-item"
              style="width: 300px"
            >
              <el-option
                v-for="item in dict.use_status"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="点位" prop="point">
            <el-select v-model="form.point" clearable value-key="id" filterable style="width:300px"
                       placeholder="请选择点位" :filter-method="filterPoint"
            >
              <el-option
                v-for="point in pointList"
                :key="point.id"
                :label="point.code"
                :value="point"
                :disabled="point.status!=='FREE'"
              >
                <span style="float: left">{{ point.area.name }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ point.code }}</span>
              </el-option>
            </el-select>
          </el-form-item>


        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>

      <!--      容器入场弹窗界面-->
      <ContainerIn ref="containerIn"/>

      <!--      容器返空弹窗界面-->
      <ReturnContainer ref="returnContainer"/>

      <!--      呼叫容器弹窗界面-->
      <CallContainer ref="callContainer"/>

      <!--表格渲染-->
      <el-table ref="table" height="66vh" v-loading="crud.loading" :data="crud.data" size="small"
                style="width: 100%;height: 90%" @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="code" label="代码"/>
        <el-table-column :show-overflow-tooltip="true" prop="stockType" label="类型">
          <template slot-scope="scope">
            <div>{{ scope.row.stockType.name }}</div>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" prop="area" label="状态">
          <template slot-scope="scope">
            {{ dict.label.use_status[scope.row.status] }}
          </template>
        </el-table-column>
        <el-table-column label="启用" align="center" prop="enabled">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.enabled"
              active-color="#409EFF"
              inactive-color="#F56C6C"
              @change="changeEnabled(scope.row, scope.row.enabled)"
            />
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" prop="point" label="点位">
          <template slot-scope="scope">
            <span v-if="scope.row.point !=null">{{ scope.row.point.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">

            <el-button :loading="crud.status.cu === 2"
                       size="mini" type="primary" icon="el-icon-edit" @click="crud.toEdit(scope.row)"
            ></el-button>
            <el-button slot="right" size="mini"
                       type="warning" @click="toCallContainer(scope.row)"
            >呼叫
            </el-button>
            <el-button slot="right" size="mini"
                       type="success" @click="toContainerIn(scope.row)"
            >入场
            </el-button>
            <el-button slot="right" size="mini"
                       type="danger" @click="toContainerOut(scope.row)"
            >出场
            </el-button>

            <el-button slot="right" size="mini"
                       type="info" @click="toReturnEntity(scope.row)"
            >返空
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <div style="float: right;">
        <pagination/>
      </div>

    </div>

  </div>
</template>

<script>
import crudStock from '@/api/stock'
import crudArea from '@/api/area'
import crudStockType from '@/api/stockType'
import crudPoint from '@/api/point'
import crudApp from '@/api/app'
import CRUD, { presenter, header, form, crud } from '@crud/crud'

import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import { getToken } from '@/utils/auth'

import ContainerIn from '@/views/base-data/stock/containerIn.vue'
import ReturnContainer from '@/views/base-data/stock/returnContainer.vue'
import CallContainer from '@/views/base-data/stock/callContainer.vue'

import { mapGetters } from 'vuex'

const defaultForm = {
  id: null,
  status: 'FREE',
  stockType: null,
  code: null,
  pid: null,
  point: null,
  subCount: null,
  name: null,
  typeId: null,
  length: null,
  width: null,
  height: null,
  weight: null,
  size: null,
  useWeight: null,
  useSize: null,
  usageWeight: null,
  usageSize: null,
  enabled: 1,
  createBy: null,
  updateBy: null,
  createTime: null,
  updateTime: null,
  topId: null
}
export default {
  name: 'Stock',
  components: { CallContainer, ReturnContainer, ContainerIn, pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['base_staus', 'use_status'],
  cruds() {
    return CRUD({
      title: '容器', url: 'api/stock', idField: 'id', sort: 'id,desc', crudMethod: { ...crudStock },
      optShow: {
        add: true,
        edit: false,
        del: false,
        reset: true,
        download: true
      },
      queryOnPresenterCreated: true
    })
  },
  computed: {
    ...mapGetters([
      'baseApi'
    ])
  },
  data() {
    return {
      //地标点数据
      fileList: [],
      areas: [],
      pointList: [],
      ContainerIn: {
        containerCode: '',
        position: ''
      },
      headers: { 'Authorization': getToken() },
      permission: {
        add: ['admin', 'stock:add'],
        edit: ['admin', 'stock:edit'],
        del: ['admin', 'stock:del']
      },
      stockTypes: [],
      rules: {
        id: [
          { required: true, message: '容器ID不能为空', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '容器代码不能为空', trigger: 'blur' }
        ],
        stockType: [
          { required: true, message: '容器类型不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.getArea()
    this.getStockType()
    this.findByPoint()
  },
  methods: {
    handleSuccess(response, file, fileList, crud) {
      let myError = response.toString()//转字符串
      this.crud.notify(response['message'], CRUD.NOTIFICATION_TYPE.SUCCESS)
      crud.toQuery()
    },
    handleErr(err, file, fileList) {
      let myError = err.toString()//转字符串
      myError = myError.replace('Error: ', '') // 去掉前面的" Error: "
      myError = JSON.parse(myError)//转对象
      this.crud.notify(myError['message'], CRUD.NOTIFICATION_TYPE.ERROR)
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    getStockType() {
      crudStockType.queryStockTypeAll({}).then(res => {
        this.stockTypes = res
      })
    },
    // 改变状态
    changeEnabled(data, val) {
      this.$confirm('此操作将 "' + this.dict.label.base_staus[val] + '" ' + data.code + ', 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        crudStock.edit(data).then(res => {
          this.crud.notify(this.dict.label.base_staus[val] + '成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        }).catch(() => {
          data.enabled = !data.enabled
        })
      }).catch(() => {
        data.enabled = !data.enabled
      })
    },
    shuaxinContainerList() {
      this.crud.toQuery()
    },
    getArea() {
      crudArea.queryAreaAll({}).then(res => {
        this.areas = res
      })
    },
    findByPoint() {
      crudPoint.queryPointAll({}).then(res => {
        this.pointList = res
      })
    },
    //按名称或者编码检索
    filterPoint(query) {
      if (query !== '') {
        setTimeout(() => {
          const results = this.pointList.filter(point => {
            if (point.code.includes(query) || point.area.name.includes(query)) {
              return true
            }
            return false
          })
          this.pointList = results
        }, 200)
      } else {
        this.findByPoint()
      }
    },
    toContainerIn(data) {
      this.$refs.containerIn.dialogVisible = true
      this.$refs.containerIn.containerInClick(data)
    },
    toContainerOut(data) {
      this.ContainerIn.containerCode = data.code
      this.ContainerIn.position = data.point.code
      crudApp.containerOut(this.ContainerIn).then(res => {
        if (res.status == 200) {
          this.crud.notify(res.message, CRUD.NOTIFICATION_TYPE.SUCCESS)
          this.crud.toQuery()
        } else {
          this.crud.notify(res.message, CRUD.NOTIFICATION_TYPE.ERROR)
        }
      })
    },
    toCallContainer(data) {
      if (data.point == null) {
        return this.crud.notify(data.code + '没有入场!', CRUD.NOTIFICATION_TYPE.ERROR)
      }
      this.$refs.callContainer.dialog = true
      this.$refs.callContainer.callContainerClick(data)
    },
    toReturnEntity(data) {
      this.$refs.returnContainer.dialog = true
      this.$refs.returnContainer.returnEntityClick(data)
    }
  }
}
</script>

<style scoped>

</style>
