<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input v-model="query.allocationNumber" clearable placeholder="指示单号" style="width: 185px;"
                  class="filter-item" @keyup.enter.native="crud.toQuery"
        />
        <el-input v-model="query.kitNumber" clearable placeholder="成套单号" style="width: 185px;"
                  class="filter-item" @keyup.enter.native="crud.toQuery"
        /> <el-input v-model="query.itemCode" clearable placeholder="品番" style="width: 185px;"
                  class="filter-item" @keyup.enter.native="crud.toQuery"
        /> <el-input v-model="query.itemName" clearable placeholder="品番名称" style="width: 185px;"
                  class="filter-item" @keyup.enter.native="crud.toQuery"
        />
        <el-select v-model="query.status" clearable placeholder="状态" value-key="id" class="filter-item"
                   @keyup.enter.native="crud.toQuery"
        >
          <el-option
            style="width: 180px"
            v-for="item in this.dict.pick_status"
            :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/importPickInstruction'"
            :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="success"
          size="mini"
          v-permission="permission.generatePrep"
          :disabled="crud.selections.length === 0"
          @click="generatePrepFlagM(crud.selections)"
        >
          生成备货操作
        </el-button>
      </crudOperation>
      <!--表单组件-->
      <el-dialog  v-loading="this.loading_add" element-loading-text="拼命加载中" element-loading-background="rgba(0, 0, 0, 0.1)"  append-to-body :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="50%">
          <el-form ref="form" :inline="true" :model="form" :rules="rules" size="small" label-width="80px">
              <el-form-item label="指示单号" prop="allocationNumber">
                <el-input v-model="form.allocationNumber" style="width: 200px;" />
              </el-form-item>
          <el-form-item label="指示纳所" prop="rkArea" :rules=" { required: true, message: '仓库不能为空', trigger: 'blur' }">
            <el-select v-model="form.rkArea" value-key="id" style="width:200px"
                       placeholder="指示纳所" clearable @change="getItems(form.rkArea.id)"
            >
              <el-option
                v-for="item in rkAreaOptions"
                :key="item.id"
                :label="item.name"
                :value="item"
              />
            </el-select>
          </el-form-item>
            <el-form-item label="品番" prop="itemCode"  :rules=" { required: true, message: '品番不能为空', trigger: 'blur' }">
              <el-select v-model="form.ba"  value-key="id" filterable placeholder="请选择"  @change="getBigItemName(form.ba)" style="width: 200px;"
              >
                <el-option
                  v-for="ba in itemOptions"
                  :key="ba.id"
                  :label="ba.item.code"
                  :value="ba">
                  <span style="float: left;width: 110px" >{{ ba.item.code }}</span>
                  <span style="width: 200px; color: #8492a6; font-size: 13px">{{ ba.item.name }}</span>
                  <span style="width: 100px; color: #008489; font-size: 13px">{{ ba.zPoint.code }}</span>
                </el-option>
              </el-select>
            </el-form-item>
              <el-form-item label="品名" prop="item.name">
                <el-input :disabled="true" v-model="form.itemName" style="width: 200px;" />
              </el-form-item>
              <el-form-item label="订单数量" prop="indicatedQty"
                            :rules=" { required: true, message: '订单数量不能为空', trigger: 'blur' }"
              >
                <el-input v-model="form.indicatedQty" style="width:200px"/></el-form-item>
            <el-form-item label="出库仓库" prop="item.name">
              <el-input :disabled="true" v-model="form.ckAreaCode" style="width: 200px;" />
            </el-form-item>
            <el-form-item label="制造库位" prop="item.name">
              <el-input :disabled="true" v-model="form.zzkwPointCode" style="width: 200px;" />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" :rows="3" type="textarea" 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" :height="crud.tableHeight" size="small"
                style="width: 100%;" border @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="id" label="序号"/>
        <el-table-column prop="allocationNumber" label="指示单号" width="120px"/>
        <el-table-column prop="allocationDate" label="指示日期">
          <template slot-scope="scope">
            {{getFormatDate(scope.row.allocationDate)}}
          </template>
        </el-table-column>
        <el-table-column prop="rkArea.code" label="指示纳所" width="150px"/>
        <el-table-column prop="item.code" label="品番" width="120px">
        </el-table-column>
        <el-table-column prop="item.name" label="品名" width="150px">
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            {{ dict.label.pick_status[scope.row.status] }}
          </template>
        </el-table-column>
        <el-table-column prop="indicatedQty" label="指示数量"/>
        <el-table-column prop="wcdNum" label="未出单数">
          <template slot-scope="scope">
            {{scope.row.indicatedQty - scope.row.allocatedQty}}
          </template>
        </el-table-column>
        <el-table-column prop="allocatedQty" label="出单数量"/>
        <el-table-column prop="bcAllocatedQty" label="本次出单"/>
        <el-table-column prop="pickedQty" label="备货数量"/>
        <el-table-column prop="ztQty" label="在途数量"/>
        <el-table-column prop="zzkwPoint.code" label="制造库位"/>
        <el-table-column prop="ckArea.code" label="出库库区" width="150px"/>
        <el-table-column prop="ac" label="A/C"/>
        <el-table-column prop="processContent" label="加工内容 "/>
        <el-table-column prop="outKType.name" label="出库类型"/>
        <el-table-column prop="remark" label="备注"/>
        <el-table-column prop="kitNumber" label="成套单号"/>
        <el-table-column v-if="checkPer(['admin','pickInstruction:edit','pickInstruction:del'])" label="操作" width="150px" align="center" fixed="right">
          <template slot-scope="scope" >
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <div style="float: right;">
        <pagination/>
      </div>
    </div>
  </div>
</template>

<script>
import crudPickInstruction, { generatePrepFlag } from '@/api/pickInstruction'
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 { getPoints } from '@/api/point'
import { queryAreaList } from '@/api/area'
import { getBillType } from '@/api/billType'
import { queryItemAll } from '@/api/item'
import { formatDate } from '@/utils/commonUtils'
import { queryItemByArea} from "@/api/bomAccount";
import DonMessage from "@/utils/message";
import {getToken} from "@/utils/auth";
import {mapGetters} from "vuex";

const defaultForm = {
  id: null,
  allocationNumber: null,
  allocationDate: null,
  rkArea: null,
  bomAccount: null,
  item:null,
  ac: null,
  processContent: null,
  taxCategory: null,
  outKType: null,
  status: "WCD",
  indicatedQty: 0,
  allocatedQty: 0,
  bcAllocatedQty: 0,
  pickedQty: 0,
  ztQty: 0,
  zzkwPoint:null,
  ckArea: null,
  kitNumber: null,
  remark: null,
  createBy: null,
  updateBy: null,
  createTime: null,
  updateTime: null,
  bomId:null
}
export default {
  name: 'PickInstruction',
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['pick_status'],
  cruds() {
    return CRUD({
      title: '手工指示',
      url: 'api/pickInstruction',
      idField: 'id',
      sort: 'id,desc',
      crudMethod: { ...crudPickInstruction }
    })
  },
  computed: {
    ...mapGetters([
      'baseApi'
    ])
  },
  data() {
    return {
      headers: { 'Authorization': getToken() },
      select_value: null,
      loading_add:false,
      bigItemName: null,
      permission: {
        add: ['admin', 'pickInstruction:add'],
        edit: ['admin', 'pickInstruction:edit'],
        del: ['admin', 'pickInstruction:del'],
        generatePrep: ['admin', 'pickInstruction:generatePrep'],
        import: ['admin', 'pickInstruction:import']
      },
      rules: {
        zzkwPoint: [
          { required: true, message: '制造库位不能为空', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'allocationNumber', display_name: '指示单号' }
      ],
      //制造库位
      zzkwPointOptions: [],
      //出库仓库
      ckAreaOptions: [],
      //指示纳所
      rkAreaOptions: [],
      //单据类型
      outKTypeOptions: [],
      //品番
      itemOptions: []
    }
  },
  mounted() {
    this.initData()
  },
  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
    },
    //初始化数据
    initData() {
      //制造库位
      getPoints(5).then(res => {
        this.zzkwPointOptions = res
      })
      //出库仓库
      queryAreaList({ besh: false }).then(res => {
        this.ckAreaOptions = res
      })
      //指示纳所
      queryAreaList({ besh: true }).then(res => {
        this.rkAreaOptions = res
      })

      //单据类型
      getBillType({}).then(res=>{
        for (const re of res) {
          if (re.code === 'SGDD'){
            this.outKTypeOptions.push(re)
          }
        }
      })
      //单据类型
      queryItemByArea(11).then(res=>{
        this.itemOptions = res
      })
    },
    generatePrepFlagM(data){
      //选着的数量
      let data_ = [];
      for (const datum of data) {
        data_.push(datum.id)
      }
      generatePrepFlag(data_).then(res=>{
        this.crud.toQuery()
        this.$message.success("生成备货操作成功")
      })
    },
    //日期格式化
    getFormatDate(data){
      return  formatDate(data);
    },
    getItems(dben) {
      this.itemOptions = null
      this.loading_add=true
      queryItemByArea(dben).then(res => {
      //  let obj = {}
      //  var newlist = res.reduce((cur, next) => {
        //   obj[next.item.code] ? '' : (obj[next.item.code] = true && cur.push(next))
       //   return cur
      //  }, [])
        this.itemOptions = res
       this.loading_add=false
      })
    },
    getBigItemName(dben) {

      //根据code 查询 在 itemOptions 中查询
      this.form.itemName=dben.item.name
      this.form.itemCode=dben.item.code
      this.form.zzkwPointCode=dben.zPoint.code
      this.form.zzkwPoint=dben.zPoint
      this.form.ckArea=dben.cArea;
      this.form.item=dben.item;
      this.form.ckAreaCode=dben.cArea.code;
      this.form.bomId=dben.id;
    },
    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>
