<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <!--     卡片头   -->
        <div style="width: 100%;height: 180px;position: relative;">
          <el-form ref="pickTicketFromRes" :model="pickTicketFromSave" :rules="rules" size="small" label-width="80px">
            <div style="width: 60%;height: 180px;float: left">
              <el-form-item label="出库库区" prop="area">
                <el-select v-model="pickTicketFromSave.area" prop="area" value-key="id" style="width: 100%"
                           placeholder="请选择出库库区" clearable filterable
                >
                  <el-option v-for="item in areaOptions" :key="item.id" :label="item.code" :value="item">
                    <span style="float: left;width: 110px" >{{ item.code }}</span>
                    <span style="width: 200px; color: #8492a6; font-size: 13px">{{ item.name }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
              <div style="width: 100%;position: relative;height: 45px;">
                <div style="width: 50%;float: left">
                  <el-form-item label="单据类型" prop="billType">
                    <el-select v-model="pickTicketFromSave.billType" value-key="id" style="width:100%"
                               placeholder="请选择单据类型" clearable :disabled="billTypeTF"
                    >
                      <el-option
                        v-for="item in billTypeOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item"
                      />
                    </el-select>
                  </el-form-item>
                </div>
                <div style="width: 50%;float: right">
                  <el-form-item label="订单日期" prop="orderDate">
                    <el-date-picker
                      style="width: 100%"
                      v-model="pickTicketFromSave.orderDate"
                      type="date"
                      value-format="yyyy-MM-dd"
                      placeholder="选择日期"
                    >
                    </el-date-picker>
                  </el-form-item>
                </div>
              </div>
              <div style="width: 100%;position: relative;height: 45px;">
                <div style="width: 50%;float: left">
                  <el-form-item label="单号" prop="code">
                    <el-input :disabled="true" v-model="pickTicketFromSave.code" style="width: 100%"/>
                  </el-form-item>
                </div>
                <div style="width: 50%;float: right">
                  <el-form-item label="订单数量">
                    <el-input :disabled="true" v-model="pickTicketFromSave.orderQuantity" style="width: 100%;"/>
                  </el-form-item>
                </div>
              </div>
              <div style="width: 100%;position: relative;">
                <div style="width: 50%;float: left">
                  <el-button type="primary" :disabled="pickTicketFromSave.code != null"
                             @click="submitFromPockTicket(pickTicketFromSave)"
                  >提交
                  </el-button>
                </div>
              </div>

            </div>
            <div style="width: 40%;height: 180px;float: right">
              <el-form-item label="备注:">

              </el-form-item>
              <el-input v-model="pickTicketFromSave.description" type="textarea" :autosize="{ minRows: 5, maxRows: 8}"
                        placeholder="请输入备注" style="width: 90%;height: 100%;float: right"
              />
            </div>
          </el-form>
        </div>
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" :tableKey="this.$options.name">
        <el-button
          slot="left"
          class="filter-item"
          type="primary"
          size="mini"
          @click="returnIndex"
        >
          返回
        </el-button>
        <el-upload
          class="upload-demo"
          ref="upload"
          slot='right'
          style="float: right;padding-left: 5px"
          :action="baseApi+'/api/importData/importPickDetail?ptId='+this.pickTicketId"
          :file-list="fileList"
          :on-success=handleSuccess
          :on-error="handleError"
          :headers="headers"
          :show-file-list="true">
          <el-button size="mini" type="success" icon="el-icon-upload">导入</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="400px"
      >
        <el-form ref="form" :rules="pickDetailRules" :model="form" size="small" label-width="80px"
                 style="height: 200px"
        >
          <el-form-item label="品番" prop="item" style="float: left">
            <el-select v-model="form.item" value-key="id" filterable placeholder="请选择品番" style="width: 200px;"
                       @change="getPointListByItem($event.code,pickTicket)"
                       clearable
            >
              <el-option
                v-for="item in itemOptions"
                :key="item.id"
                :label="item.code"
                :value="item"
              >
                <span style="float: left">{{ item.code }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.name }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="订单数量" prop="orderQty" style="float: left">
            <el-input v-model="form.orderQty" style="width: 200px;"/>
          </el-form-item>
          <el-form-item label="制造库位" prop="point" style="float: left" :rules="[{required:(pickTicket.area === undefined? false :pickTicket.area.bexb),message:'请输入库位',trigger:'blur'}]">
            <el-select v-model="form.point" value-key="id" filterable placeholder="请选择库位" clearable
                       style="width: 200px;"
            >
              <el-option
                v-for="item in pointOptions"
                :key="item.id"
                :label="item.code"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="remark" style="float: left">
            <el-input type="textarea" :rows="2" v-model="form.remark" style="width: 200px;"/>
          </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>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;"
                @selection-change="crud.selectionChangeHandler" :height="crud.tableHeight" border
      >
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="item.code" label="品番号" width="100px">
          <template slot-scope="scope">
            <div>{{ scope.row.item == null ? '' : scope.row.item.code }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="item.name " label="品番">
          <template slot-scope="scope">
            <div>{{ scope.row.item == null ? '' : scope.row.item.name }}</div>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" prop="item.unit" label="单位">
          <template slot-scope="scope">
            <div>{{ scope.row.item == null ? '' : scope.row.item.unit }}</div>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" prop="orderQty" label="订单数量">
          <template slot-scope="scope">
            <div>{{ scope.row == null ? '' : scope.row.orderQty }}</div>
          </template>
        </el-table-column>
        <!--出单数量 分配-->
        <el-table-column prop="allocatedQty" label="出单数量" width="100px"/>
        <!--备货数量 拣货-->
        <el-table-column prop="pickedQty" label="备货数量" width="100px"/>
        <el-table-column prop="shippedQty" label="发货数量"/>
        <el-table-column :show-overflow-tooltip="true" prop="point.code" label="制造库位">
          <template slot-scope="scope">
            <div>{{ scope.row.point == null ? '' : scope.row.point.code }}</div>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" prop="remark" label="备注">
          <template slot-scope="scope">
            <div>{{ scope.row.remark }}</div>
          </template>
        </el-table-column>
        <el-table-column v-if="checkPer(['admin','pickDetail:edit','pickDetail:del'])" label="操作" width="150px"
                         align="center"
        >
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <div style="float: right;">
        <pagination/>
      </div>
    </el-card>
  </div>
</template>

<script>
import crudPickTicket from '@/api/pickTicket'
import crudPickDetail from '@/api/pickDetail'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation.vue'
import crudOperation from '@crud/CRUD.operation.vue'
import udOperation from '@crud/UD.operation.vue'
import pagination from '@crud/Pagination.vue'
import { queryItemAll } from '@/api/item'
import { getOutPointAll, queryPointList } from '@/api/point'
import { getIdByPickTicket } from '@/api/pickTicket'
import { getAreas } from '@/api/area'
import { getBillType } from '@/api/billType'
import { getItemAll } from '@/api/itemKey'
import { queryBomAccountList } from '@/api/bomAccount'
import {mapGetters} from "vuex";
import {getToken} from "@/utils/auth";

const defaultForm = {
  id: null,
  pickId: null,
  item: null,
  lineNo: null,
  po: null,
  status: 'OPEN',
  orderQty: 0,
  allocatedQty: 0,
  pickedQty: 0,
  shippedQty: 0,
  weight: 0,
  volume: 0,
  remark: null,
  propC1: null,
  propC2: null,
  propC3: null,
  propC4: null,
  propC5: null,
  propC6: null,
  propD1: null,
  propD2: null,
  deptId: null,
  sourceName: null,
  sourceId: null,
  createBy: null,
  updateBy: null,
  createTime: null,
  updateTime: null,
  pickTicket: null,
  pickTicketId: null,
  point: null
}
const pickDetailQuery = {
  pickTicketId: 0
}
export default {
  name: 'viewPickDetail',
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({
      title: '出库管理',
      url: 'api/pickDetail',
      idField: 'id',
      sort: 'id,desc',
      crudMethod: { ...crudPickDetail },
      optShow: {
        add: true,
        edit: false,
        del: true,
        reset: false,
        download: false
      },
      query: { pickTicketId: 0 },
    })
  },
  created() {
    //判断是否有数据
    this.crud.query = pickDetailQuery
    let ids = this.$route.query.ids
    if (ids != null) {
      this.crud.query.pickTicketId = ids
      this.pickTicketId = ids
    } else {
      this.crud.query.pickTicketId = 0
      this.pickTicketId = 0
    }
    this.crud.refresh()
  },
  computed: {
    ...mapGetters([
      'baseApi'
    ])
  },
  data() {
    return {
      headers: { 'Authorization': getToken() },
      permission: {
        add: ['admin', 'pickDetail:add'],
        edit: ['admin', 'pickDetail:edit'],
        del: ['admin', 'pickDetail:del']
      },
      //主表的判断
      rules: {
        area: [
          { required: true, message: '出库库区不能为空', trigger: 'blur' }
        ],
        orderDate: [{
          required: true, message: '订单日期不能为空', trigger: 'blur'
        }],
        billType: [{
          required: true, message: '单据类型不能为空', trigger: 'blur'
        }]
      },
      //副表的判断
      pickDetailRules: {
        item: [
          { required: true, message: '物料不能为空', trigger: 'blur' }
        ],
        orderQty: [
          { required: true, message: '订单数量不能为空', trigger: 'blur' }
        ]
        // point: [
        //   { required: true, message: '库位不能为空', trigger: 'blur' }
        // ]
      },
      //下拉物料
      itemOptions: [],
      //下拉点位
      pointOptions: [],
      //下拉库区
      areaOptions: [],
      //下拉类型
      billTypeOptions: [],
      // 新增主表
      pickTicketFromSave: {
        area: null,
        status: 'OPEN',
        code: null,
        orderQuantity: 0,
        orderDate: null,
        billType: null,
        description: null,
        remarkOnOff: false,
        slQty: 0,
        tlQty: 0,
        allocatedQuantity: 0,
        pickedQuantity: 0,
        shippedQuantity: 0,
        xbQty: 0,
        ztQty: 0,
        xqQty: 0,
        bhQty: 0
      },
      //主表id
      pickTicketId: 0,
      pickTicket: {},
      billTypeTF: false
    }
  },
  beforeDestroy() {    //页面关闭时清除定时器
    clearInterval(this.clearTimeSet)
  },
  mounted() {
    //查询公用的下拉数据
    this.getOnceOptionAll()
    //判断是否是新增主表和是查看明细新政附表
    //  this.pickTicketTF()
    //  //定时查询 1000 为1s
    // this.setTime();
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      this.pickTicketTF()
      return true
    },
    // setTime() { //设置定时器
    //   this.clearTimeSet=setInterval(() => {
    //     this.pickTicketTF();
    //   }, 1000*20);
    // },
    //获取当前时间
    getNewDate() {
      const date = new Date()
      const year = date.getUTCFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      //存当前时间
      this.pickTicketFromSave.orderDate = `${year}-${month}-${day}`
    },
    //查询库位
    getPointList(data) {
      let selectDate = { areaName: null }
      selectDate.areaName = data
      if (selectDate.areaName === null) {
        this.$message.error('主表未绑定库区')
      }
      getOutPointAll(selectDate).then(res => {
        this.pointOptions = res.map(function(obj) {
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
        this.pointOptions = this.filterListObj(this.pointOptions)
      })
    },
    //查询公用的下拉数据
    getOnceOptionAll() {
      //物料数据
      getItemAll().then(res => {
        this.itemOptions = res
      }).catch(e => {
        this.$message({
          showClose: true,
          message: '物料加载失败',
          type: 'error'
        })
      })
      //获取库区数据
      getAreas().then(res => {
        this.areaOptions = res
      })
      //单据类型
      getBillType().then(res => {
        this.billTypeOptions = res
        for (const re of res) {
          if (re.code === 'CK') {
            this.pickTicketFromSave.billType = re
          }
        }
        let billTypeCode = this.$route.query.billTypeCode
        if (billTypeCode != null) {//判断是否传入单据类型  存值和禁止选着
          for (const bill of res) {
            if (bill.code === billTypeCode) {
              this.pickTicketFromSave.billType = bill
              this.billTypeTF = true
            }
          }
        }
      })
    },
    //判断是否是新增主表和是查看明细新政附表
    pickTicketTF() {
      if (this.pickTicketId != 0) {
        getIdByPickTicket(this.pickTicketId).then(res => {
          //存储主表的对象
          this.pickTicket = res
          defaultForm.pickTicket = res
          //将主表数据在新增哪里展示
          this.pickTicketFromSave = res
          pickDetailQuery.pickTicketId = res.id
          //查询点位数据
          this.getPointList(res.area.code)
        })
      } else {
        this.getNewDate()
      }
    },
    //新增主表数据
    submitFromPockTicket(data) {
      //校验
      this.$refs['pickTicketFromRes'].validate((valid) => {
        if (valid) {
          crudPickTicket.add(data).then(res => {
            //存主表id
            this.pickTicketId = res.id
            //加载数据
            this.pickTicketTF()
            this.$message.success('添加成功')
            // this.crud.toQuery()
            this.$router.push({ path: '/business-pick/viewPickTicket', query: { ids: res.id, billTypeCode: 'QTCK' } })
          })
        } else {
          return false
        }
      })
    },
    getPointListByItem(code, data) {
      if (data.area.bexb) {//判断是否为线边接收
        let selectDate = { rAreaCode: null, itemCode: null }
        selectDate.rAreaCode = data.area.code
        selectDate.itemCode = code
        queryBomAccountList(selectDate).then(res => {
          this.pointOptions = []
          if (res != null) {
            let data_ = []
            for (const re of res) {
              data_.push(re.zPoint)
            }
            this.pointOptions = this.filterListObj(data_)
          }
          if (!(this.pointOptions.length > 0)) {
            queryPointList({ code: 'ZZKW' }).then(re => {
              this.pointOptions = re
            })
          }
        })
      }
    },
    //过滤重复数据
    filterListObj(listObj) {
      let date = []
      let onOff = true
      listObj.filter((i) => {
        onOff = true
        date.filter((ii) => {
          if (i.id === ii.id) {
            onOff = false
          }
        })
        if (onOff) {
          date.push(i)
        }
      })
      return date
    },
    returnIndex(){//返回主页
      this.$router.push({ path: '/business-pick/pickTicket', query: {} })
    },
    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>
