<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;"
                  @keyup.enter.native="crud.toQuery"
        />
        <AreaSelect  v-model="query.areaCode" :return-type="'value'" :return-value-key="'code'" :bexb="false"
                     class="filter-item" placeholder="库区" style="width: 155px;"
        />
        <el-input v-model="query.itemCode" clearable placeholder="品番" style="width: 150px;"
                  @keyup.enter.native="crud.toQuery"
        />
        <el-input v-model="query.bqlx" clearable placeholder="标签类型" style="width: 120px;"
                  @keyup.enter.native="crud.toQuery"
        />
        <el-select v-model="query.type" clearable placeholder="存储类型" value-key="id"
                   @keyup.enter.native="crud.toQuery"
        >
          <el-option
            style="width: 150px"
            v-for="item in this.dict.point_type"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <rrOperation :crud="crud"/>
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" :tableKey="this.$options.name">
        <el-upload
          class="upload-demo"
          ref="upload"
          slot='right'
          style="float: right;padding-left: 5px"
          :action="baseApi+'/api/importData/importPoint'"
          :file-list="fileList"
          :on-success=handleSuccess
          :on-error="handleError"
          :headers="headers"
          :show-file-list="true">
          <el-button size="mini" type="success"   v-permission="permission.import" icon="el-icon-upload">导入</el-button>
        </el-upload>
        <el-upload
          class="upload-demo"
          ref="upload"
          slot='right'
          style="float: right;padding-left: 5px"
          :action="baseApi+'/api/importData/importPointUpdate'"
          :file-list="fileList"
          :on-success=handleSuccess
          :on-error="handleError"
          :headers="headers"
          :show-file-list="true">
          <el-button size="mini" type="success"   v-permission="permission.import" icon="el-icon-upload">更新导入</el-button>
        </el-upload>
        <el-button
          slot="right"
          class="filter-item"
          type="primary"
          size="mini"
          @click="savePointPrintList()"
          v-permission="permission.showReport"
          icon="el-icon-document-add"
        >
          自由标签
        </el-button>
      </crudOperation>
      <!--   呼叫空车  -->
      <el-dialog title="地标点绑定" :visible.sync="callEmptyCarStatus" width="400px">
        <el-form ref="from1" :model="from1" :rules="rules" size="small" label-width="80px">
          <el-form-item label="地标点" prop="pointCode">
            <el-input v-model="from1.pointCode" style="width: 180px;"/>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="callEmptyCarStatus = false">取 消</el-button>
          <el-button type="primary" @click="callEmpty()">确 定</el-button>
        </div>
      </el-dialog>
      <!--   空车入库  -->
      <el-dialog title="空车入库" :visible.sync="EmptyCarBackStatus" width="400px">
        <el-form ref="fromBack" :model="fromBack" :rules="rules" size="small" label-width="80px">
          <el-form-item label="地标点" prop="pointCode">
            <el-input v-model="fromBack.pointCode" style="width: 180px;"/>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="EmptyCarBackStatus = false">取 消</el-button>
          <el-button type="primary" @click="callStockBackIn()">确 定</el-button>
        </div>
      </el-dialog>
      <viewFullStockIn ref="fullStockIn"/>
      <viewFullStockOut ref="fullStockOut"/>
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0"
                 :title="crud.status.title" width="500px"
      >
        <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: 370px;"/>
          </el-form-item>
          <!--<el-form-item label="名称">
            <el-input v-model="form.name" style="width: 370px;"/>
          </el-form-item>-->
          <el-form-item label="品番">
            <el-input v-model="form.itemCode" style="width: 370px;"/>
          </el-form-item>
          <el-form-item label="纳所">
            <el-input v-model="form.beatCode" style="width: 370px;"/>
          </el-form-item>
          <el-form-item label="存储类型" prop="type">
            <el-select v-model="form.type" filterable placeholder="请选择" style="width: 370px;"
                       :default-first-option="true"
            >
              <el-option
                v-for="item in dict.point_type"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
<!--                    <el-form-item label="暂存库位">-->
<!--                      <el-input v-model="form.point.code" style="width: 370px;"/>-->
<!--                    </el-form-item>-->
          <el-form-item label="库区" prop="area">
            <el-select v-model="form.area" value-key="id" filterable placeholder="请选择" style="width: 370px;">
              <el-option
                v-for="item in areas"
                :key="item.id"
                :label="item.name"
                :value="item"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="库存下限">
            <el-input v-model="form.invMin" style="width: 370px;"/>
          </el-form-item>

          <el-form-item label="标签类型">
            <el-input v-model="form.bqlx" style="width: 370px;"/>
          </el-form-item>
          <el-form-item label="总分类型">
            <el-input v-model="form.zflx" style="width: 370px;"/>
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" height="66vh" v-loading="crud.loading" :data="crud.data" size="mini" style="width: 100%;"
                @selection-change="crud.selectionChangeHandler" border
      >
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="id" label="序号"/>
        <el-table-column prop="area.name" label="库区"/>
        <el-table-column prop="code" label="库位号"/>
       <!-- <el-table-column prop="name" label="名称"/>-->
        <el-table-column prop="itemCode" label="品番"/>
        <el-table-column prop="beatCode" label="纳所"/>
        <el-table-column prop="invMin" label="库存下限"/>
        <el-table-column prop="point_type#type" label="存储类型">
          <template slot-scope="scope">
            {{ dict.label.point_type[scope.row.type] }}
          </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 prop="bqlx" label="标签类型"/>
        <el-table-column prop="zflx" label="总分类型"/>

        <el-table-column v-if="checkPer(['admin','item:edit'])" label="操作" width="60px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
              :show-dle="false"
              :showPointIn="true"
              style="float: left"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <div style="float: right;">
        <pagination/>
      </div>
    </div>
  </div>
</template>

<script>
import crudPoint, { pointCallStock,queryPointPrintList,pointPrintBiaoQianList } from '@/api/point'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import rrOperation from '@crud/RR.operation'
import pagination from '@crud/Pagination'
import { getAres, getAresXl, queryAreaList } from '@/api/area'
import Treeselect from '@riophae/vue-treeselect'
import { getToken } from '@/utils/auth'
import DonMessage from '@/utils/message'
import { callTrolley } from '@/api/box'
import viewFullStockIn from '@/views/base-data/point/fullStockIn.vue'
import viewFullStockOut from '@/views/base-data/point/fullStockOut.vue'
import crudStock from '@/api/stock'
import pointUrl from '@/api/point'
import {mapGetters} from "vuex";
import {queryBomPrintListX} from "@/api/bomAccount";
import AreaSelect from "@/views/generic-component/AreaSelect.vue";

const defaultForm = {
  id: null,
  status: 'FREE',
  enabled: 1,
  code: null,
  name: null,
  description: null,
  area: null,
  point: null,
  invMin:999,
  zflx:null
}
export default {
  name: 'Point',
  components: {
    AreaSelect, Treeselect, pagination, crudOperation, udOperation, rrOperation, viewFullStockIn, viewFullStockOut },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['base_staus', 'use_status', 'point_type', 'agv_on_off'],
  cruds() {
    return CRUD({
      title: '库位',
      url: 'api/point',
      idField: 'id',
      sort: 'id,desc',
      query: { typeNotData: ['FHZC', 'SHZC'] },
      crudMethod: { ...crudPoint },
      optShow: {
        add: true,
        edit: false,
        del: true,
        reset: true,
        download: true
      },
      queryOnPresenterCreated: true
    })
  },
  computed: {
    ...mapGetters([
      'baseApi'
    ])
  },
  data() {
    return {
      //暂存库位下拉框
      pointList: [],
      from1: [],
      fromBack: [],
      fileList:[],
      pointListData: [],
      headers: { 'Authorization': getToken() },
      queryTypeOptions: [
        { key: 'code', display_name: '代码' },
        { key: 'name', display_name: '名称' },
        { key: 'beatCode', display_name: '区域编码' },
        { key: 'areaCode', display_name: '仓库' },
        { key: 'enabled', display_name: '启用' }
      ],
      callStock: {
        pointCode: '',
        agvScene: 'ZC'
      },
      callStockBack: {
        pointCode: '',
        agvScene: 'ZC'
      },
      areas: [],
      permission: {
        add: ['admin', 'point:add'],
        edit: ['admin', 'point:edit'],
        del: ['admin', 'point:del'],
        import:['admin', 'point:import']
      },
      tableKey: 'api/point',
      rules: {
        code: [
          { required: true, message: '代码不能为空', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '类型不能为空', trigger: 'blur' }
        ],
        area: [
          { required: true, message: '库区不能为空', trigger: 'blur' }
        ]
      },
      //呼叫空车的弹出按钮
      callEmptyCarStatus: false,
      EmptyCarBackStatus: false
      //表单数据
    }
  },
  mounted() {
    this.getArea()
    //获取点位表的数据
    this.getPointListData()
  },
  methods: {
    handleErr(err, file, fileList) {

      let myError = err.toString()//转字符串
      myError = myError.replace('Error: ', '') // 去掉前面的" Error: "
      myError = JSON.parse(myError)//转对象
      DonMessage.error('' + myError['message'])
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    // 改变状态
    changeEnabled(data, val) {
      this.$confirm('此操作将 "' + this.dict.label.base_staus[val] + ', 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        crudPoint.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
      })
    },
    getArea() {
      queryAreaList({ enabled: true }).then(res => {
        this.areas = res
        //   this.areas = res.content.map(function (obj) {
        //     if (obj.hasChildren) {
        //       obj.children = null
        //     }
        //     return obj
        //   })
        // })

        // getAres({size: 50}).then(res => {
        //   this.areas = res.content.map(function (obj) {
        //     if (obj.hasChildren) {
        //       obj.children = null
        //     }
        //     return obj
        //   })
      })
    },
    savePointPrintList() {
      console.log("打印自由货位标签")
      queryPointPrintList(this.crud.getQueryParams2()).then(res => {
        this.showEwmReportZy();
      })
    },

    showEwmReportZy(){
      this.$router.push({path:'/base-data/base-ware/point_print_zy',query:{tableID: '打印自由库位标签'}})
    },
    //呼叫空车
    callEmpty() {
      this.callStock.pointCode = this.from1.pointCode
      this.callStock.agvScene = 'ZC'
      pointUrl.pointCallStock(this.callStock).then(res => {
        this.callEmptyCarStatus = false
        DonMessage.success('呼叫成功')
      }).catch(e => {
        DonMessage.error('呼叫失败')
      })
    },
    //空车入库
    callStockBackIn() {
      this.callStockBack.pointCode = this.fromBack.pointCode
      this.callStockBack.agvScene = 'ZC'
      pointUrl.pointStockBack(this.callStockBack).then(res => {
        this.EmptyCarBackStatus = false
        DonMessage.success('呼叫成功')
      }).catch(e => {
        DonMessage.error('呼叫失败')
      })
    },
    //获取点位表的数据
    getPointListData() {
      crudPoint.queryPointList({}).then(res => {
        for (const re of res) {
          if (re.status === 'USED' && re.area.name === '轴承座空车区') {
            this.pointListData.push(re)
          }
        }
      }).catch(e => {
        DonMessage.error('点位表数据获取失败')
      })
    },
    //满车入库
    showFullStockIn(parent) {
      this.$refs.fullStockIn.dialogVisible = true
      this.$refs.fullStockIn.stockInClick(parent)
    },
    //呼叫满车出库
    showFullStockOut(parent) {
      this.$refs.fullStockOut.dialogVisible = true
      this.$refs.fullStockOut.stockOutClick(parent)
    },
    //呼叫空车的弹出框的触发
    callEmptyCarStatusOffOn(obj) {
      this.callEmptyCarStatus = true
      this.from1.pointCode = obj.code
    },
    //空车入库
    emptyCarBack(obj) {
      this.EmptyCarBackStatus = true
      this.fromBack.pointCode = obj.code
    },
    handleSuccess(response, file, fileList) {
      this.crud.notify('上传成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
      this.$refs.upload.clearFiles()
      this.crud.status.add = CRUD.STATUS.NORMAL
      this.crud.resetForm()
      this.crud.toQuery()
    },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
      this.loading = false
    }
  }
}
</script>

<style scoped>

</style>
