<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container"  v-loading="this.loading_add" element-loading-text="拼命加载中" element-loading-background="rgba(0, 0, 0, 0.1)">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <!--        <label class="el-form-item-label">指示单号</label>-->
        <el-input v-model="query.code" clearable placeholder="备货计划号" style="width: 185px;" class="filter-item"
                  @keyup.enter.native="crud.toQuery"
        />
        <el-input v-model="query.bigItemCode" clearable placeholder="机型" style="width: 185px;" class="filter-item"
                  @keyup.enter.native="crud.toQuery"
        />
        <el-input v-model="query.bigItemName" clearable placeholder="机型名称" style="width: 185px;" class="filter-item"
                  @keyup.enter.native="crud.toQuery"
        />
        <el-select v-model="query.gcCode" clearable placeholder="接收工厂" style="width: 185px;" class="filter-item"
                   @keyup.enter.native="crud.toQuery">
          <el-option
            v-for="baseStatus in dict.factory"
            :key="baseStatus.id"
            :label="baseStatus.label"
            :value="baseStatus.value"
          />
        </el-select>
        <el-select v-model="query.workingStation" placeholder="工位" value-key="id" class="filter-item" clearable @keyup.enter.native="crud.toQuery">
          <el-option
            v-for="item in this.dict.station_type"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
            <span style="float: left;width: 60px" >{{ item.value }}</span>
            <span style="width: 200px; color: #8492a6; font-size: 13px">{{ item.label }}</span>
          </el-option>
        </el-select>
        <rrOperation :crud="crud"/>
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" :tableKey="this.$options.name">
        <el-button size="mini" type="success" slot="right" class="filter-item"
                   icon="el-icon-plus" v-permission="permission.planPickSave"
                   @click="planPickSaveTF = true"
        >新增
        </el-button>
        <el-button size="mini" type="success" slot="right" class="filter-item"  v-permission="permission.scbhcz"
                   @click="scbhczM(crud.selections)" :disabled="generateStockOperationDisabled "
        >生成备货操作
        </el-button>
        <el-button size="mini" type="success" slot="right" class="filter-item"  v-permission="permission.cancelStockOperation"
                   @click="cancelStockOperationM(crud.selections)" :disabled="CancelStockOperationDisabled"
        >取消备货操作
        </el-button>
      </crudOperation>
      <!--  生成备货操作    -->
      <el-dialog
        title="生成备货操作"
        :visible.sync="generateStockOperationTF"
        width="30%"
        :close-on-click-modal="false"
      >
        <el-form ref="generateStockform" :rules="generateStockRules" :model="planPickButton"
                 size="small" label-width="90px"
        >
          <el-form-item label="份数" prop="quantity">
            <el-input v-model="planPickButton.quantity" placeholder="份数" clearable style="width: 220px;">
            </el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
    <el-button @click="generateStockOperationTF = false">取 消</el-button>
    <el-button type="primary" @click="generateStockOperationM(planPickButton)">确 定</el-button>
  </span>
      </el-dialog>
      <!--   新增   -->
      <el-dialog
        title="手工生成"
        :visible.sync="planPickSaveTF"
        width="40%"
        :close-on-click-modal="false"
      >
        <el-form ref="saveform" :rules="saveRules" :model="planPickButton.planPickSave"
                 size="small" label-width="90px"
        >
          <el-form-item label="计划" prop="code">
            <!--            <el-input v-model="planPickButton.planPickSave.code" placeholder="起始几号" clearable style="width: 300px;"-->
            <!--            ></el-input>-->
            <el-select filterable  v-model="planPickButton.planPickSave.code" value-key="id" placeholder="计划"
                       style="width: 300px;" clearable
            >
              <el-option
                v-for="item in codeOptions"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="计划单号" prop="code">
            <el-input v-model="planPickButton.planPickSave.code" placeholder="计划单号" clearable style="width: 300px;"
            ></el-input>
          </el-form-item>
          <el-form-item label="指示纳所" prop="zone">
            <el-select v-model="planPickButton.planPickSave.zone"  @change="getBigItem(planPickButton.planPickSave.zone)" value-key="id" placeholder="工位"
                       style="width: 300px;" clearable
            >
              <el-option
                v-for="item in areaOptions"
                :key="item.code"
                :label="item.name"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="BOM清单" prop="bigItem">
            <el-select v-model="planPickButton.planPickSave.bigItem" value-key="id" @change="getBigItemName(planPickButton.planPickSave.bigItem.name)"  filterable
                       placeholder="请选择" style="width: 370px;"
            >
              <el-option
                v-for="item in bigItems"
                :key="item.id"
                :label="item.code"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="数量" prop="orderQuantity">
            <el-input v-model.number="planPickButton.planPickSave.orderQuantity" placeholder="数量"
                      style="width: 300px;" clearable
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
    <el-button @click="planPickSaveTF = false">取 消</el-button>
    <el-button type="primary" @click="planPickSaveM('saveform')">确 定</el-button>
  </span>
      </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 @select="selectData" @select-all="selectAllData"
      >
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="id" label="序号" align="center"/>
        <el-table-column prop="code" label="备货计划号" width="120px" align="center"/>
        <el-table-column prop="zone.code" label="工位" width="120px" align="center"/>
        <el-table-column prop="zone.name" label="指示纳所" width="120px" align="center"/>
        <el-table-column prop="createTime" label="计划日期" width="100px" align="center">
          <template slot-scope="scope">
            {{getFormatDate(scope.row.createTime)}}
          </template>
        </el-table-column>
        <el-table-column prop="bigItem.code" label="机型" width="100px" align="center"/>
        <el-table-column prop="bigItem.name" label="机型名称" width="120px" align="center"/>
        <el-table-column prop="pick_status#status" label="状态" width="100px" align="center">
          <template slot-scope="scope">
            {{ dict.label.pick_status[scope.row.status] }}
          </template>
        </el-table-column>
        <el-table-column prop="orderQuantity" label="计划订单" width="80px" align="center"/>
        <el-table-column prop="allocatedQuantity" label="出单数量" width="80px" align="center"/>
        <el-table-column prop="startNo" label="起始机号" width="80px" align="center"/>
        <el-table-column prop="endNo" label="终止机号" width="80px" align="center"/>
        <el-table-column prop="bigItem.country" label="国别" width="80px" align="center"/>
        <el-table-column prop="remark" label="备注" width="150px" align="center"/>
        <el-table-column v-if="checkPer(['admin','planPickDetail:edit','planPickDetail:del'])" label="操作"
                         width="150px" align="center" fixed="right"
        >
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
              :show-edit="false"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <div style="float: right;">
        <pagination/>
      </div>
    </div>
  </div>
</template>

<script>
import crudPlanPickDetail, {
  cancelStockOperationApi,
  generateStockOperationApi,
  getAllCode,
  savePlanPickDetail
} from '@/api/planPickDetail'
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 { formatDate, getObjectClearData } from '@/utils/commonUtils'
import { queryItemAll } from '@/api/item'
import { queryAreaList } from '@/api/area'
import { getBillType } from '@/api/billType'
import { queryBigItemAll, queryBigItemAllInBomAccount } from '@/api/bigItem'
import ElTableOne from '@/components/Table/ElTableOne.vue'
import {queryBigItemByStationType} from "@/api/bomAccount";
import {mapGetters} from "vuex";


const defaultForm = {
  id: null,
  bigItem: null,
  item: null,
  zone: null,
  billType: null,
  orderQuantity: 0,
  allocatedQuantity: 0,
  pickedQuantity: 0,
  shippedQuantity: 0,
  allocateTime: null,
  shipTime: null,
  code: null,
  status: 'WCD',
  startNo: null,
  endNo: null,
  remark: null,
  createBy: null,
  updateBy: null,
  createTime: null,
  updateTime: null
}
export default {
  name: 'PlanPickDetail',
  components: { ElTableOne, pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['pick_status','station_type','factory'],
  cruds() {
    return CRUD({
      title: '备货计划明细',
      url: 'api/planPickDetail',
      idField: 'id',
      sort: 'id,desc',
      crudMethod: { ...crudPlanPickDetail },
      optShow: {
        add: false,
        edit: false,
        del: true,
        reset: true,
        download: true
      },
      queryOnPresenterCreated: true
    })
  },
  computed: {
    ...mapGetters([
      'baseApi'
    ])
  },
  data() {
    return {
      permission: {
        add: ['admin', 'planPickDetail:add'],
        edit: ['admin', 'planPickDetail:edit'],
        del: ['admin', 'planPickDetail:del'],
        scbhcz: ['admin', 'planPickDetail:scbhcz'],
        cancelStockOperation: ['admin', 'planPickDetail:cancelStockOperation'],
        planPickSave: ['admin', 'planPickDetail:planPickSave'],
      },
      rules: {},
      generateStockRules: {
        quantity: [{ required: true, message: '份数不能为空', trigger: 'blur' }]
      },
      saveRules: {
        zone: [{ required: true, message: '工位不能为空', trigger: 'blur' }],
        bigItem: [{ required: true, message: 'BOM清单不能为空', trigger: 'blur' }],
        orderQuantity: [{ required: true, message: '数量不能为空', trigger: 'blur' }]
      },
      queryTypeOptions: [
        { key: 'code', display_name: '指示单号' },
        { key: 'bigItemCode', display_name: '机型' },
        { key: 'bigItemName', display_name: '机型名称' },
        { key: 'workingStation', display_name: '工位' }
      ],
      loading_add:false,
      itemOptions: [],
      areaOptions: [],
      billTypeOptions: [],
      bigItemOptions: [],
      bigItems: [],
      codeOptions: [],
      planPickButton: {
        planPickSave: {
          code: null,
          zone: null,
          bigItem: null,
          orderQuantity: null
        },
        quantity: 0,
        planPickDetailList: []
      },
      //新增开关
      planPickSaveTF: false,
      // 表格的宽度
      tableHight: null,
      //生成备货操着的开关
      generateStockOperationTF: false,
      //按钮是否可以选着
      generateStockOperationDisabled: true,
      //取消备货操作
      CancelStockOperationDisabled:true,
    }
  },
  watch: {
    tableHight: {
      immediate: true,
      handler(val) {
        this.tableHight = val
      }
    }
  },
  mounted() {
    this.infoData()
    this.tableHightLoad()
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    // 页面高度
    tableHightLoad() {
      window.onresize = () => {
        return (() => {
          this.$nextTick(() => {
            // el-main-footer
            this.tableHight = document.documentElement.clientHeight - document.getElementById('tableId').getBoundingClientRect().top - 80
            // this.$refs.table.doLayout()
          })
        })()
      }
      // 当页面加载后执行
      setTimeout(() => {
        // 方法区
        this.tableHight = document.documentElement.clientHeight - document.getElementById('tableId').getBoundingClientRect().top - 80
        // this.$refs.table.doLayout()
      }, 100)
    },
    formatDateV(value) {
      return formatDate(value)
    },
    infoData() {
      queryItemAll({}).then(res => {
        this.itemOptions = res
      })
      //bexb = true
      queryAreaList({ bexb: true }).then(res => {
        this.areaOptions = res
      })
      getBillType({}).then(res => {
        this.billTypeOptions = res
      })
      getAllCode().then(res => {
        let data_ = []
        for (const re of res) {
          data_.push({ code: re, name: re })
        }
        this.codeOptions = data_
      })
    },
    planPickSaveM(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          savePlanPickDetail(this.planPickButton).then(res => {
            this.planPickSaveTF = false
            this.$message.success(res)
            this.crud.toQuery()
            this.planPickButton.planPickSave = getObjectClearData(this.planPickButton.planPickSave)

          })
        } else {
          return false
        }
      })
    },
    // 列宽改变
    headerDragend(newWidth, _, column) {
      this.colList.forEach((e) => {
        if (e.prop === column.property) {
          e.minWidth = Math.round(newWidth)
        }
      })
      this.dropCol = []
      this.$nextTick(() => {
        this.dropCol = this.columnDrop(this.dropCol)
      })
    },
    handleCurrentChange(val) {
      this.currentRow = val
    },
    generateStockOperationM(data) {
      this.$refs['generateStockform'].validate((valid) => {
        if (valid) {
          console.log(data)
          generateStockOperationApi(data).then(res => {
            this.generateStockOperationTF = false
            this.$message.success(res)
            this.crud.toQuery()
            this.planPickButton.quantity = 0
          }).catch(err => {
            this.$message.error(err)
          })
        } else {
          return false
        }
      })
    },
    generateStockOperationTFM(data){
      this.planPickButton.planPickDetailList = data;
      this.generateStockOperationTF=true;
    },
    //勾选
    selectData(selection, row) {
      this.generateStockOperationDisabled = false
      this.CancelStockOperationDisabled = false
      if (selection.length === 0) {
        this.generateStockOperationDisabled = true
        this.CancelStockOperationDisabled = true
      }
      selection.forEach((item) => {
        if (item.status != 'WCD') {
          this.generateStockOperationDisabled = true
        }else {
          this.CancelStockOperationDisabled = true
        }
      })
    },
    //全选
    selectAllData(selection) {
      this.generateStockOperationDisabled = false
      this.CancelStockOperationDisabled = false
      if (selection.length === 0) {
        this.generateStockOperationDisabled = true
        this.CancelStockOperationDisabled = true
      }
      selection.forEach((item) => {
        if (item.status != 'WCD') {
          this.generateStockOperationDisabled = true
        }else {
          this.CancelStockOperationDisabled = true
        }
      })
    },
    //取消备货
    cancelStockOperationM(data){
      this.loading_add=true;
      let data_ = this.planPickButton;
      data_.planPickDetailList = data;
      cancelStockOperationApi(data_).then(res=>{
        this.$message.success(res);
        this.loading_add=false;
        this.crud.toQuery()
      },e=>{
        this.loading_add=false;
      })
    },
    //日期格式化
    getFormatDate(data){
      return  formatDate(data);
    },
    //生成备货操作不需要数据数量
    scbhczM(data){
      this.loading_add=true;
      //generateStockOperationTFM(crud.selections)
      this.planPickButton.planPickDetailList = data;
      generateStockOperationApi(this.planPickButton).then(res => {
        this.$message.success(res)
        this.loading_add=false;
        this.crud.toQuery()
        this.planPickButton.quantity = 0
      },e=>{
        this.loading_add=false;
      }).catch(err => {
        this.$message.error(err)
      })
    },
    getBigItem(dben) {
      console.log(dben)
      this.bigItems = null
      queryBigItemByStationType(dben.workingStation).then(res => {
        this.bigItems = res
      })
    },
    getBigItemName(dben) {
      this.bigItemName = dben
    },
    doXiuGai(dben) {
      this.getBigItem(dben.zone)
      this.getBigItemName(dben.bigItem.name)
      this.crud.toEdit(dben)
    }
  }
}
</script>

<style scoped>

</style>
