<template>
  <div class="app-container">
    <div class="filter-container">
      <div style="width: 100%;text-align: center; height: 28px;font-size: 16px;margin-bottom: 15px">辅料领料单</div>
      <el-row :gutter="5">
        <el-col :span="4">
          <div>
            <span>部门:</span>
            <div style="display: inline-block;">
              <el-input style="width: 180px" size="mini" placeholder="选择部门" v-model="department"
                        class="input-with-select">
                <el-button @click="departmenClick" slot="append" icon="el-icon-more-outline"></el-button>
              </el-input>
            </div>
          </div>
        </el-col>
        <el-col :span="4">
          <div>
            <span>制单时间:</span>
            <div style="display: inline-block;">
              <el-date-picker
                style="width: 180px"
                size="mini"
                v-model="valueTime"
                type="datetime"
                placeholder="选择日期时间">
              </el-date-picker>
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div>
            <span>单据摘要:</span>
            <div style="display: inline-block;">
              <el-input disabled style="width: 320px" size="mini" v-model="billDocument"></el-input>
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div>
            <span>单据说明:</span>
            <div style="display: inline-block;">
              <el-input style="width: 280px" size="mini" v-model="billDescription"></el-input>
            </div>
          </div>
        </el-col>
      </el-row>
      <el-button @click="addBtn" plain style="margin-top: 7px" type="primary" size="mini" icon="el-icon-plus">增加
      </el-button>
      <el-button :disabled="disableBtn" @click="HandleUpdtadaBtn" plain style="margin-top: 7px" type="success" size="mini" icon="el-icon-top">
        提交
      </el-button>
    </div>
    <div class="table-con">
      <el-table
        size="mini"
        :data="tableData"
        v-loading="listLoading"
        highlight-current-row
        style="width: 100%;margin-bottom: 20px;"
        row-key="id"
        border
      >
        <el-table-column label="操作" fixed="left" align="center" width="70" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <template>
              <el-button @click="deleteThis(scope.$index)" type="primary" size="mini">
                删行
              </el-button>
            </template>
          </template>
        </el-table-column>
        <el-table-column
          label="#"
          align="center"
          type="index"
          :index="indexMethod">
        </el-table-column>
        <el-table-column
          width="80"
          label="物料编号"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.materialCode }}</span>
          </template>
        </el-table-column>
        <el-table-column
          width="130"
          show-overflow-tooltip
          label="物料名称"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.materialName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          width="90"
          label="物料规格"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.mtRule }}</span>
          </template>
        </el-table-column>
<!--        <el-table-column-->
<!--          label="施工单号"-->
<!--        >-->
<!--          <template slot-scope="scope">-->
<!--            <span>{{}}</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column
          label="领取数量"
          width="300px"
        >
          <template slot-scope="scope">
            <el-input
              size="mini"
              style="display: inline-block;width: 90px"
              oninput="value=Number(value.replace(/[^\d.]/g,''))"
              v-model.trim="scope.row.itemInputQty"
              @input="handleEdit(scope.$index, scope.row.itemInputQty)"></el-input>
<!--            <span style="width: 70px">{{ scope.row.num }}</span>-->
            <el-select
              style="display: inline-block;width: 120px;"
              size="mini"
              v-model="scope.row.unit"
              @change="selectUnit(scope.$index,scope.row.unit)"
            >
              <el-option
                v-for="item in scope.row.unitArray"
                :label="scope.row.seUnit+item.label"
                :value="item.value+','+scope.row.seUnit+','+item.label"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          width="150"
          label="机台名称"
        >
          <template slot-scope="scope">
            <el-select
              style="display: inline-block;width: 140px;"
              clearable
              size="mini"
              filterable
              v-model="scope.row.printMachineName"
              @change="selectMachine(scope.$index,scope.row.machineName)"
            >
              <el-option
                v-for="item in optionsMachine"
                :key="item.id"
                :label="item.machineName"
                :value="item.id+','+item.machineName+','+item.psSize+','+item.idMachineType+','+item.machineType.typeName"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          label="用途"
        >
          <template slot-scope="scope">
            <el-input
              size="mini"
              style="width: 200px"
              v-model.trim="scope.row.itemPurpose"
              @input="handleEdit(scope.$index, scope.row.itemPurpose)"></el-input>
          </template>
        </el-table-column>
        <el-table-column
          label="质量要求"
        >
          <template slot-scope="scope">
            <el-input
              size="mini"
              style="width: 200px"
              v-model.trim="scope.row.qualityRequirements"
              @input="handleEdit(scope.$index, scope.row.qualityRequirements)"></el-input>
          </template>
        </el-table-column>
        <!--        <el-table-column-->
        <!--          label="客户名称"-->
        <!--        >-->
        <!--          <template slot-scope="scope">-->
        <!--            <el-input-->
        <!--              size="mini"-->
        <!--              style="display: inline-block;width: 100px"-->
        <!--              v-model.trim="scope.row.num3"-->
        <!--              @input="handleEdit(scope.$index, scope.row.num3)"></el-input>-->
        <!--            <span style="width: 70px">{{ scope.row.num3 }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
      </el-table>
      <pagination v-show="listData.total>0" :total="listData.total" :page.sync="listData.page"
                  :limit.sync="listData.pageSize" @pagination="getTableInfo"/>
    </div>
    <el-dialog title="部门名称" :visible.sync="dialogTableVisible">
      <div style="height: 500px;overflow-y: auto">
        <el-table
          size="mini"
          :data="gridData"
          v-loading="listLoading"
          style="width: 100%;margin-bottom: 20px;"
          row-key="id"
          border>
          <el-table-column label="操作" align="center" width="80" class-name="small-padding fixed-width">
            <template slot-scope="{row}">
              <el-button @click="btnChoose(row)" type="primary" size="mini">
                选择
              </el-button>
            </template>
          </el-table-column>
          <el-table-column
            prop="deptName"
            label="部门名称"
            width="180">
          </el-table-column>
          <el-table-column
            label="负责人"
            prop="leader"
          ></el-table-column>
          <el-table-column
            label="联系电话"
            prop="phone"
          ></el-table-column>
          <el-table-column align="center" label="状态" class-name="status-col" width="100">
            <template slot-scope="{row}">
              <el-tag v-if="row.status==1" type="danger">
                停用
              </el-tag>
              <el-tag v-else="row.status==0" type="success">
                正常
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
    <el-dialog title="选择辅料档案" :visible.sync="dialogTableCheck">
      <div style="height: 600px;overflow-y: auto">
        <accessories-info @getAccessories="getAccessories" ref="accessories"></accessories-info>
      </div>

    </el-dialog>
  </div>
</template>

<script>
import {
  getInfo
} from '@/api/printbill/preOut/preOut.js'
import {getMenu} from '@/utils/getTable.js'
import {getDeptList} from "@/api/system/department";
import AccessoriesInfo from "@/views/select/accessoriesInfo";
import {getPrinterNameList} from "@/api/printbill/printbill";
import {mapGetters} from 'vuex';
import {getMachineOnWork, submitStockBill} from "@/api/feedBack/feedBack";
import {unLockWorkParts} from "@/api/printbill/editionList";

export default {
  name: "list",
  computed: {
    ...mapGetters([
      'user',
      'name',
      'loginName'
    ]),
  },
  components: {AccessoriesInfo},
  data() {
    return {
      disableBtn:false,
      deptId:"",
      machineId: "",
      printMachineName: "",
      optionsMachine: [],
      dialogTableCheck: false,
      gridData: [],
      dialogTableVisible: false,
      billDescription: "",
      billDocument: "",
      valueTime: "",
      department: "",
      listLoading: false,
      tableData: [],
      search: {
        keyWord: ''
      },
      listData: {
        total: 0,
        page: 1,
        pageSize: 10
      }
    }
  },
  mounted() {
    // this.getTableInfo();
    this.getNewDate();
    this.getHomeInfo();
    this.getPrintName();
    console.log("111111",this.user);
    this.deptId = this.user.deptId;
    this.department = this.user.deptName;
    this.getMachineOnWork();
  },
  methods: {
    HandleUpdtadaBtn() {
      const _that = this;
      if(_that.tableData.length<=0){
        _that.$message("请先选择辅料");
        return
      };
      var materialArray = [];
      for (let i = 0; i < _that.tableData.length; i++) {
        var datas = _that.tableData[i];
        if(datas.itemInputQty<=0 || !datas.itemInputQty){
          _that.$message("请先填写领取数量");
          return
        }
        if(i==0){
         var billTitle = _that.tableData[0].materialName
        }
        if(i==1){
          billTitle+= "等"
        }
        var dataItem = {
          id: 0,
          idMaterial: "",//物料id，
          materialName: "",//物料名称
          materialCode: "",//物料编号
          itemInputQty: "",//数量
          itemPurchaseQty: "",//数量
          itemQty: "",//数量
          itemUseQty: "",//数量
          itemInputUnit: 1,
          itemInputPriceUnit: 1,
          idMachineInfo: "",//机台id
          machineInfoName: "",//机台名称
          itemPurpose: "",//用途
          qualityRequirements: "",//质量要求
          materialFlag: 0
        }
        dataItem.idMaterial = datas.id;
        dataItem.materialName = datas.materialName;
        dataItem.materialCode = datas.materialCode;
        dataItem.itemInputQty = datas.itemInputQty;
        dataItem.itemPurchaseQty = datas.itemInputQty;
        dataItem.itemQty = datas.itemInputQty;
        dataItem.itemUseQty = datas.itemInputQty;
        dataItem.idMachineInfo = datas.machineId;
        dataItem.machineInfoName = datas.printMachineName;
        dataItem.itemPurpose = datas.itemPurpose;
        dataItem.qualityRequirements = datas.qualityRequirements;
        materialArray.push(dataItem)
      }
      _that.disableBtn = true;
      var params = {
        updateKind: 2,
        stockBill: {
          id: 0,
          idBillDefine: 10,
          idCurrentAction: 0,
          idDept: _that.deptId,//页面选择的部门id
          deptName: _that.department,//页面选择的部门名称
          billTitle: billTitle,//辅料领料[第一个明细的materialName]等（如果有超过一条记录，则加上“等”字，如只有一条记录，不加）
          billMemo: _that.billDescription,//单据说明（当前页面无此字段，可输入）
          itemMList: materialArray
        }
      }
      submitStockBill(params).then(response => {
        _that.disableBtn = false;
        if (response.httpCode == 200) {
          _that.tableData = [];
          _that.$message.success("提交成功");
          _that.$store.dispatch("tagsView/delView", _that.$route);
          _that.$router.push({ path: '/dashboard' })
        }
      })
    },
    deleteThis(index) {
      const _that = this;
      _that.tableData.splice(index, 1)
    },
    selectUnit(index, value) {
      const _that = this;
      _that.tableData[index].unit = value.split(',')[1] + value.split(',')[2];
    },
    selectMachine(index, value) {
      const _that = this;
      _that.tableData[index].printMachineName = value.split(',')[1];
      _that.tableData[index].machineId = value.split(',')[0];
    },
    handleEdit() {
    },
    addBtn() {
      const _that = this;
      _that.dialogTableCheck = true;
      _that.$nextTick(function () {
        _that.$refs.accessories.webType = false;
        _that.$refs.accessories.ERPChooseVisible = false;
      })
    },
    getAccessories(row) {
      const _that = this;
      //unit
      _that.dialogTableCheck = false;
      _that.$set(row, 'printMachineName', _that.printMachineName);
      _that.$set(row, 'machineId', _that.machineId);
      _that.$set(row, 'itemInputQty', "");
      _that.$set(row, 'itemPurpose', "");
      _that.$set(row, 'qualityRequirement', "");

      var arrayData = [
        {
          label: '(使用单位)',
          value: 'seUnit'
        },
        {
          label: '(采购单位)',
          value: 'byUnit'
        },
        {
          label: '(库存单位)',
          value: 'mtUnit'
        },
      ]
      _that.$set(row, 'unit', row.seUnit + arrayData[0].label);
      _that.$set(row, 'unitArray', arrayData);
      _that.tableData.push(row);
    },
    btnChoose(row) {
      const _that = this;
      _that.department = row.deptName;
      _that.dialogTableVisible = false;
    },
    departmenClick() {
      const _that = this
      _that.dialogTableVisible = true;
    },
    //获取表格数据
    getTableInfo() {
      const _that = this
      _that.listLoading = true
      var params = _that.search;
      var page = {
        pageIndex: _that.listData.page,
        pageSize: _that.listData.pageSize,
      }
      var data = {
        "params": JSON.stringify(params),
        "page": JSON.stringify(page),
      }
      // console.log(data);
      getInfo(data).then(response => {
        // console.log("tableData",response)
        const data = response.data
        // //  组合表单数据
        _that.tableData = data
        _that.listData.total = response.total
        // console.log(_that.tableData)
        _that.listLoading = false
      }).catch(err => {
        _that.listLoading = false
      })
    },
    getHomeInfo() {
      const _that = this;
      var data = {
        params: {
          status: 0
        }
      }
      getDeptList(data).then(response => {
        const data = response.data
        const menuData = getMenu(data)
        _that.gridData = menuData
        // console.log(_that.tableData)
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    getNewDate() {
      //获取当前时间
      var _this = this;
      let yy = new Date().getFullYear();
      let mm = new Date().getMonth() + 1;
      let dd = new Date().getDate();
      let hh = new Date().getHours();
      let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes();
      let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds();
      _this.valueTime = yy + '-' + mm + '-' + dd + ' ' + hh + ':' + mf + ':' + ss;
    },
    // 获取机台名称
    getPrintName() {
      var _that = this
      var data = {}
      getPrinterNameList(data).then(res => {
        // console.log('1', res.data)
        if (res.httpCode == 200) {
          _that.optionsMachine = res.data;
        } else {
          // _that.$message(res.msg)
        }
      }).catch(err => {
        // _that.$message(err);
      })
    },
    getMachineOnWork() {
      const _that = this;
      var data = {}
      getMachineOnWork(data).then(res => {
        // console.log("getMachineOnWork", res.data);
        // console.log(res.httpCode);
        if (res.httpCode == 200) {
          // console.log(res.data == "" || res.data == null);
          if (res.data == "" || res.data == null) {
          } else {
            _that.printMachineName = res.data.machineName;
            _that.machineId = res.data.id;
          }
        } else {

        }
      }).catch(err => {
      })

    },
    //搜索
    searchData() {
      this.listData.page = 1;
      this.getTableInfo()
    },
    //序号
    indexMethod(index) {
      return index + 1;
    }
  }
}
</script>

<style lang="scss" scoped>
.tb-edits .el-input {
  display: none
}

.tb-edits .current-row .el-input {
  display: block
}

.app-container {
  padding: 30px;
  min-height: calc(100vh - 84px);
}

.filter-container {
  margin-bottom: 15px;
}
</style>
