<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">
        <!-- 搜索 -->
        <el-input v-model="query.bigItemModels" clearable placeholder="请选择机型" style="width: 150px;" class="filter-item" @keyup.enter.native="crud.toQuery"/>
        <el-date-picker
          style="width: 150px;" class="filter-item"
          v-model="query.downlineDate"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetime"
          placeholder="下线日期"
        >
        </el-date-picker>
        <el-input v-model="query.idno" clearable placeholder="IDNO" style="width: 150px;" class="filter-item"
                  @keyup.enter.native="crud.toQuery"
        />
        <el-select v-model="query.rkCode"  value-key="id" filterable placeholder="库区" style="width: 185px;" class="filter-item"  @keyup.enter.native="crud.toQuery" clearable>
          <el-option
            v-for="item in rAreaList"
            :key="item.id"
            :label="item.code"
            :value="item.code">
            <span style="float: left;width: 60px" >{{ item.code }}</span>
            <span style="width: 200px; color: #8492a6; font-size: 13px">{{ item.name }}</span>
            </el-option>
        </el-select>
        <el-select v-model="query.statue" clearable placeholder="耗用状态" style="width: 120px;" class="filter-item"
                   @keyup.enter.native="crud.toQuery"
        >
          <el-option
            v-for="baseStatus in dict.hy_status"
            :key="baseStatus.id"
            :label="baseStatus.label"
            :value="baseStatus.value"
          />
        </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/importProductionPlan'"
          :file-list="fileList"
          :on-success=handleSuccess
          :on-error="handleError"
          :headers="headers"
          v-permission="permission.import"
          :show-file-list="true">
          <el-button size="mini" type="success" icon="el-icon-upload">导入</el-button>
        </el-upload>
        <!--        dict.label.hy_status[scope.row.statue]-->
       <!-- <el-button size="mini" type="success" slot="right" class="upload-demo" style="float: right;"
                   :disabled="sgscDisabled"  v-permission="permission.sgscM"
                   @click="sgscM(crud.selections[0])"
        >手工生成
        </el-button>-->

        <el-button size="mini" type="success" slot="right" class="upload-demo" style="float: right;"
                   :disabled="crud.selections.length !== 1"
                   @click="haoYongM(crud.selections[0])"  v-permission="permission.haoYong"
        >批量耗用
        </el-button>
      </crudOperation>
      <!--      手工生成   -->
      <el-dialog
        title="手工生成"
        :visible.sync="sgscOnOff"
        width="30%"
        :close-on-click-modal="false">
        <el-form ref="sgscform" :rules="sgscRules" :model="productionPlanButton.manualGeneration"
                 size="small" label-width="80px"
        >
          <el-form-item label="起始机号" prop="startMachineNo">
            <el-input v-model="productionPlanButton.manualGeneration.startMachineNo" placeholder="起始几号" clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="工位" prop="workingStation">
            <el-input v-model="productionPlanButton.manualGeneration.workingStation" placeholder="工位" clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="数量" prop="quantity">
            <el-input v-model.number="productionPlanButton.manualGeneration.quantity" placeholder="数量" clearable
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="sgscOnOff = false">取 消</el-button>
          <el-button type="primary" @click="sgscSend('sgscform')" :loading="loadingTF">确 定</el-button>
         </span>
      </el-dialog>

      <!--      批量耗用   -->
      <el-dialog
        title="批量耗用"
        :visible.sync="haoYongOnOff"
        width="30%"
        :close-on-click-modal="false">
        <el-form ref="haoYongform" :rules="haoYongform" :model="productionPlanVo"  size="small" label-width="80px">
          <el-form-item label="id" prop="id" style="display: none">
            <el-input v-model="productionPlanVo.id" placeholder="起始机号" disabled >
            </el-input>
          </el-form-item>
          <el-form-item label="起始机号" prop="id">
            <el-input v-model="productionPlanVo.machineNo" placeholder="工件" disabled>
            </el-input>
          </el-form-item>
        <!--  <el-form-item label="工位名" prop="name">
            <el-input v-model="productionPlanVo.workingStation"  disabled>
            </el-input>
          </el-form-item>-->
          <el-form-item label="数量" prop="number">
            <el-input v-model.number="productionPlanVo.number" placeholder="数量" clearable>
            </el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="haoYongOnOff = false">取 消</el-button>
          <el-button type="primary" @click="submitHaoYongForm" >确 定</el-button>
         </span>
      </el-dialog>
      <!--表单组件-->
      <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="bigItem">
            <!--            <el-input v-model="form.bigItem" style="width: 370px;" />-->
            <el-select v-model="form.bigItem" placeholder="请选择机型" style="width: 370px;">
              <el-option
                v-for="item in bigItemListoOptions"
                :key="item.code"
                :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="workingStation">
            <el-select v-model="form.workingStation" filterable placeholder="请选择">
              <el-option
                v-for="item in dict.station_type"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="No" prop="no">
            <el-input v-model="form.no" style="width: 370px;"/>
          </el-form-item>
          <el-form-item label="下线日期" prop="downlineDate">
            <el-date-picker v-model="form.downlineDate" type="datetime" style="width: 370px;"/>
          </el-form-item>
          <el-form-item label="机号" prop="machineNo">
            <el-input v-model="form.machineNo" style="width: 370px;"/>
          </el-form-item>
          <el-form-item label="描述">
            <el-input type="textarea" v-model="form.description" style="width: 370px;"/>
          </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%;" border
                :height="crud.tableHeight" @selection-change="crud.selectionChangeHandler" @select="selectTableM" @select-all="selectAllTableM"
      >
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="id" label="ID" width="100"/>
        <el-table-column prop="no" label="序号" width="60"/>
        <el-table-column prop="makeLine" label="制造线" width="65"/>
        <el-table-column prop="rkArea.code" label="库区" width="80"/>
        <el-table-column prop="rkArea.name" label="库区名" width="100"/>
        <el-table-column :show-overflow-tooltip="true" prop="downlineDate" label="下线日期" width="100"/>
        <el-table-column prop="idno" label="ID NO./刻印号" width="120"/>
        <el-table-column prop="bigItem.code" label="机型" width="120px"/>
        <el-table-column  prop="bigItem.name" label="机型名称" width="150px"/>
        <el-table-column prop="machineNo" label="工件" width="120"/>
        <el-table-column prop="hy_status#statue" label="耗用状态" width="70px">
          <template slot-scope="scope">
            {{ dict.label.hy_status[scope.row.statue] }}
          </template>
        </el-table-column>
        <el-table-column prop="orderNo" label="序号" width="50"/>
        <el-table-column :show-overflow-tooltip="true" prop="takeUpTime" label="耗用时间"/>
        <el-table-column :show-overflow-tooltip="true" prop="description" label="描述"/>
        <el-table-column prop="createBy" label="创建人" width="60"/>
        <el-table-column prop="updateBy" label="更新人" width="60"/>
        <el-table-column :show-overflow-tooltip="true" prop="createTime" label="创建时间"/>
        <el-table-column :show-overflow-tooltip="true" prop="updateTime" label="修改日期"/>
        <el-table-column v-if="checkPer(['admin','productionPlan:edit','productionPlan:del'])" fixed="right"
                         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>
    </div>
  </div>
</template>

<script>
import crudProductionPlan, {haoYong, manualGeneration, readHaoYongData} from '@/api/productionPlan'
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 crudArea, {queryAreaList} from '@/api/area'
import { getBigItem } from '@/api/bigItem'
import { getToken } from '@/utils/auth'
import DonMessage from '@/utils/message'
import { formatDate } from '@/utils/commonUtils'
import {mapGetters} from "vuex";

const defaultForm = {
  id: null,
  dept: null,
  enabled: false,
  bigItem: null,
  workingStation: null,
  no: null,
  importDate: null,
  plannedDate: null,
  downlineDate: null,
  takeUpTime: null,
  idno: null,
  monthlyNo: null,
  projectNo: null,
  makeLine: null,
  orderNo: null,
  bomList: null,
  shArea: null,
  rkArea: null,
  pickPlan: null,
  type: null,
  partVariety: null,
  statue: null,
  autoProduction: null,
  description: null,
  createBy: null,
  updateBy: null,
  createTime: null,
  updateTime: null,
  offLinePart: null,
  machineNo: null,
  bigItemModels: null
}
export default {
  name: 'ProductionPlan',
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['station_type', 'base_staus', 'hy_status','pick_status'],
  cruds() {
    return CRUD({
      title: '生产顺序计划',
      url: 'api/productionPlan',
      idField: 'id',
      sort: 'id,desc',
      crudMethod: { ...crudProductionPlan }
    })
  },
  computed: {
    ...mapGetters([
      'baseApi'
    ])
  },
  data() {
    return {
      productionPlanVo: {},
      rAreaList: [],
      permission: {
        add: ['admin', 'productionPlan:add'],
        edit: ['admin', 'productionPlan:edit'],
        del: ['admin', 'productionPlan:del'],
        sgscM: ['admin', 'productionPlan:sgscM'],
        import: ['admin', 'productionPlan:import'],
        haoYong: ['admin', 'productionPlan:haoYong']
      },
      rules: {
        bigItem: [
          { required: true, message: '机型不能为空', trigger: 'blur' }
        ],
        workingStation: [
          { required: true, message: '工位不能为空', trigger: 'blur' }
        ],
        no: [
          { required: true, message: 'No不能为空', trigger: 'blur' }
        ],
        downlineDate: [
          { required: true, message: '下线日期不能为空', trigger: 'blur' }
        ],
        machineNo: [
          { required: true, message: '机号不能为空', trigger: 'blur' }
        ]

      },
      sgscRules: {
        startMachineNo: [
          { required: true, message: '机号不能为空', trigger: 'blur' }
        ],
        workingStation: [
          { required: true, message: '工位不能为空', trigger: 'blur' }
        ],
        quantity: [
          { required: true, message: '数量不能为空', trigger: 'blur' }
        ]
      },
      haoYongform: {
        number: [
          { required: true, message: '数量不能为空', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'enabled', display_name: '状态' },
        { key: 'bigItemModels', display_name: '机型' },
        { key: 'downlineDate', display_name: '下线日期' },
        { key: 'idno', display_name: 'IDNO' },
        { key: 'workingStation', display_name: '工位' },
        { key: 'statue', display_name: '耗用状态' },
        { key: 'projectNo', display_name: '计划单号' },
      ],
      bigItemListoOptions: [],
      tableKey: '/api/productionPlan',
      headers: { 'Authorization': getToken() },
      onOff: [{ label: '启用', value: true }, { label: '关闭', value: false }],
      sgscOnOff: false,
      haoYongOnOff: false,
      productionPlanButton: {
        manualGeneration: {
          productionPlan:{},
          rkAreaId:null,
          bigItem: null,
          startMachineNo: null,
          workingStation: null,
          quantity: 0
        }
      },
      loadingTF: false,
      sgscDisabled: true,
      loading_add:false,

    }
  },
  mounted() {
    this.bigItemXL();
    this.getRAreaList();
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    handleErr(err, file, fileList) {

      let myError = err.toString()//转字符串
      myError = myError.replace('Error: ', '') // 去掉前面的" Error: "
      myError = JSON.parse(myError)//转对象
      DonMessage.error('' + myError['message'])
    },
    getRAreaList() {
      queryAreaList({bexb:true,enabled:true}).then(res=>{
        this.rAreaList = res
      })
    },
    //修改状态
    updataBooleanButton(data, val) {
      this.$confirm(val ? '启用' : '关闭', '提示', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        crudProductionPlan.edit(data).then(res => {
          this.crud.notify((val ? '启用' : '关闭') + '成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        }).catch(() => {
          this.crud.toQuery
        })
      }).catch(() => {
        this.crud.toQuery
      })
    },
    bigItemXL() {
      getBigItem(1).then(res => {
        this.bigItemListoOptions = res
      }).catch(e => {

      })
    },
    sgscM(data) {
      //起始单号
      this.productionPlanButton.manualGeneration.startMachineNo = data.machineNo
      //工位
      this.productionPlanButton.manualGeneration.workingStation = data.workingStation
      //物料
      this.productionPlanButton.manualGeneration.bigItem = data.bigItem
      //入库库区
      this.productionPlanButton.manualGeneration.productionPlan = data;
      this.productionPlanButton.manualGeneration.rkAreaId = data.rkArea
      this.sgscOnOff = true
    },
    haoYongM(data) {
      console.log("------------------")
      console.log(this.dict.label.hy_status)
      //id
      this.productionPlanVo.id = data.id
      //起始单号
      this.productionPlanVo.machineNo = data.machineNo
      //工位名
      //this.productionPlanVo.workingStation = data.rkArea.name
     // this.productionPlanVo.areaId = data.rkArea.id
      this.haoYongOnOff = true
    },
    submitHaoYongForm() {
      this.loading_add=true;
      this.$refs['haoYongform'].validate(valid => {
        if (!valid) {
          this.loading_add=false;
          return
        }
        haoYong(this.productionPlanVo).then(res =>{
          if(res.status==200){
            this.crud.notify('批量耗用成功！', CRUD.NOTIFICATION_TYPE.SUCCESS);
            this.haoYongOnOff = false
            this.crud.refresh()
            this.loading_add=false;
          }
        },e=>{
          this.loading_add=false;
        })

      });
    },
    sgscSend(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loadingTF = true
          //验证成功
          manualGeneration(this.productionPlanButton).then(res => {
            this.loadingTF = false
            this.productionPlanButton.manualGeneration = {
              rkAreaId:null,
              bigItem: null,
              startMachineNo: null,
              workingStation: null,
              quantity: 0
            }
            this.sgscOnOff = false
            this.crud.toQuery();
            this.$message.success(res)
          }).catch(err => {
            this.loadingTF = false
          })
        } else {
          //验证失败
          return false
        }
      })
    },
    selectTableM(selection, row){
     if (selection.length === 1 && selection[0].statue === "UN_CONSUME"){
       this.sgscDisabled = false;
     }else {
       this.sgscDisabled = true;
     }
    },
    selectAllTableM(selection){

    },
    //日期格式化
    getFormatDate(data){
      return  formatDate(data);
    },
    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>
