<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="search.keyWord" placeholder="关键字" style="width: 200px;" class="filter-item" />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="searchData">

      </el-button>
      <el-button
        v-if="webType && isChoose == false"
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-plus"
        @click="handleCreateAdd">
        增加机台档案
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="green"
        @click="printInfo">
        打印机台信息
      </el-button>
    </div>
    <el-table
      :data="tableData"
      v-loading="listLoading"
      style="width: 100%;margin-bottom: 20px;"
      row-key="id"
      border
      ref="machineTable"
      @row-click="handleClickTableRow"
      @selection-change="handleSelectionChange"
      default-expand-all>
      <el-table-column
        type="selection"
        fixed="left"
        width="55">
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <template v-if="webType">
            <template v-if="!isChoose">
          <el-button @click="handleUpdate(row)" type="primary" size="mini">
            编辑
          </el-button>
          <el-button @click="editStatus(row.id,'1')" type="danger" v-if="row.voidFlag==0" size="mini">
            禁用
          </el-button>
          <el-button @click="editStatus(row.id,'0')" v-else="row.voidFlag==1" size="mini">
            启用
          </el-button>
            </template>
            <template v-else>
              <el-button @click="sourceType == 1? chooseThisTo(row):chooseThis(row)" type="primary" size="mini">
                选择
              </el-button>
            </template>
          </template>
          <template v-else>
            <el-button @click="ERPChoose(row)" type="primary" size="mini">
              选择
            </el-button>
          </template>
        </template>
      </el-table-column>
      <el-table-column
        prop="machineName"
        label="机台名称">
      </el-table-column>
     <el-table-column
        label="分厂名称"
        prop="companyName"
      >
      </el-table-column>
      <el-table-column
        label="ps版规格"
        prop="psSize"
      >
      </el-table-column>
      <el-table-column align="center" label="状态" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-tag v-if="row.voidFlag==0" type="success">
            启用
          </el-tag>
          <el-tag v-else="row.voidFlag==1" type="danger">
            禁用
          </el-tag>
        </template>
      </el-table-column>

    </el-table>
    <pagination v-show="listData.total>0" :total="listData.total" :page.sync="listData.page" :limit.sync="listData.pageSize" @pagination="getInfo" />

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form label-width="130px" label-position="right">
        <el-form-item label="机台名称">
          <el-input v-model="form.machineName"></el-input>
        </el-form-item>
        <el-form-item label="对应机型">
          <el-select v-model="form.idMachineType" filterable placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.typeName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择分厂">
          <el-select v-model="form.idCompany" filterable placeholder="选择分厂" style="width: 160px;margin-top: -20px">
            <el-option
              v-for="item in typeOptions"
              :key="item.id"
              :label="item.companyName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="参与机台负荷统计">
          <el-switch v-model="form.calcBurdenFlag"></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogStatus==='1'?addBtn():editBtn()">确 定</el-button>
      </div>
    </el-dialog>
<!--    <servicedialog @tableRefresh="tableRefresh" ref="menuDialog" :dialogStatus="dialogStatus" :menuId="menuId" :titleDialog="titleDialog" :dialogVisible="dialogVisible"/>-->
    <cancledialog @tableRefresh="tableRefresh" ref="confirmDialog"></cancledialog>
  </div>
</template>

<script>
import { addMachineInfo, getMachineInfoList, getMachineInfoByID, updateMachineInfo, getPrinterNameList } from '@/api/baseInfo/machineInfo.js'
import Cancledialog from '@/components/Dialog/Cancledialog.vue'
import Pagination from '@/components/Pagination'
import {getAllCompanyInfoList} from "@/api/printbill/printbill";
import {doLocalPrint} from "@/utils";

export default {
  components: {
    Cancledialog, Pagination
  },
  props: {
    isChoose: {
      type: Boolean,
      default: false
    },
    /**
     * 调用来源
     * 0 普通调用
     * 1 查询统计调用
     */
    sourceType: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      typeOptions:[],
      webType: true,
      dialogStatus: 1, // 1增加，2修改
      dialogTitle: '',
      dialogVisible: false,
      search: {
        keyWord: ''
      },
      form: {
        calcBurdenFlag:false
      },
      listData: {
        total: 0,
        page: 1,
        pageSize: 10
      },
      options: [],
      confirmdialog: false,
      listLoading: false,
      tableData: [],
      chooseMachineList: [],
    }
  },
  mounted() {
    this.getInfo()
    this.getCompanyInfoList();
    // this.getPrintName();
    if (this.$route.query.type === undefined) {
      this.webType = true
    } else {
      this.webType = false
    }
  },
  methods: {
    // 获取列表
    getInfo() {
      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)
      }

      getMachineInfoList(data).then(response => {
        // console.log('getMachineInfoList', response)
        const data = response.data
        // //  组合表单数据
        _that.tableData = data
        // console.log(_that.tableData)
        _that.listData.total = response.total
        _that.listLoading = false
      }).catch(err => {
        _that.$message.error(err)
        _that.listLoading = false
      })
    },
    // 增加机台档案
    handleCreateAdd() {
      // 增加系统目录
      const _that = this
      _that.getPrintName()
      _that.form.calcBurdenFlag = false;
      _that.form = {}
      _that.dialogTitle = '增加机台档案'
      _that.dialogStatus = '1'
      _that.dialogVisible = true
    },
    // 刷新变革
    tableRefresh() {
      // 刷新变革
      this.getInfo()
    },
    // 增加机台档案
    addBtn() {
      const _that = this
      // console.log("_that.form",_that.form);
      // var machineInfo =JSON.stringify(_that.form)
      if(!_that.form.machineName){
        _that.$message("请填写机台档案名称")
        return
      }
      if(!_that.form.idMachineType){
        _that.$message("请选择机型")
        return
      }
      if(!_that.form.idCompany){
        _that.$message("请选择分厂信息")
        return
      }
      if(_that.form.calcBurdenFlag){
        var calcBurdenFlag = 1
      }else {
        var calcBurdenFlag = 0
      }
      var machineInfo = {
        // idMachineType: _that.form.typeName.split(',')[1],
        idMachineType: _that.form.idMachineType,
        machineName: _that.form.machineName,
        // idCompany: _that.form.companyName.split(',')[1],
        // companyName: _that.form.companyName.split(',')[0]

        idCompany: _that.form.idCompany,
        companyName: _that.typeOptions.find(x=> x.id === _that.form.idCompany).companyName,
        calcBurdenFlag:calcBurdenFlag
      }
      var data = {
        'machineInfo': JSON.stringify(machineInfo)
      }

      addMachineInfo(data).then(res => {
        // console.log(res);
        if (res.httpCode == 200) {
          _that.dialogVisible = false
          _that.$message({
            message: '增加成功',
            type: 'success'
          })
          _that.tableRefresh()
        } else {
          _that.$message.error(res.msg)
        }
      }).catch(err => {
        _that.$message.error(err)
        _that.dialogVisible = true
      })
    },

    // 唤起修改
    handleUpdate(row) {
      const _that = this
      _that.getPrintName()
      _that.form = {}

      _that.dialogTitle = '修改机台档案信息'
      _that.dialogVisible = true
      _that.dialogStatus = '2'

      var idPrint = row.id
      var data = {
        idMachineInfo: idPrint
      }

      getMachineInfoByID(data).then(res => {
        // console.log('getMachineInfoByID', res)
        const data = res.data;
        if(data.calcBurdenFlag==1){
          var calcBurdenFlag = true;
        }else {
          var calcBurdenFlag = false
        }

        _that.form = {
          id: data.id,
          machineName: data.machineName,
          idMachineType: data.idMachineType,
          idCompany: data.idCompany,
          calcBurdenFlag:calcBurdenFlag
        }
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    // 修改机台档案
    editBtn() {
      const _that = this
      // if (_that.form.typeName.split(',').length > 1) {
      //   var idMachineType = _that.form.typeName.split(',')[1]
      // } else {
      //   var idMachineType = _that.form.idMachineType
      // }
      if(_that.form.calcBurdenFlag){
        var calcBurdenFlag = 1
      }else {
        var calcBurdenFlag = 0
      }
      var machineInfo = {
        id: _that.form.id,
        idMachineType: _that.form.idMachineType,
        machineName: _that.form.machineName,
        // idCompany: _that.form.companyName.split(',')[1],
        // companyName: _that.form.companyName.split(',')[0]

        idCompany: _that.form.idCompany,
        companyName: _that.typeOptions.find(x=> x.id === _that.form.idCompany).companyName,
        calcBurdenFlag:calcBurdenFlag
      }
      // console.log(machineInfo);

      var data = {
        'machineInfo': JSON.stringify(machineInfo)
      }

      updateMachineInfo(data).then(res => {
        // console.log(res);
        if (res.httpCode == 200) {
          _that.dialogVisible = false
          _that.$message({
            message: '修改成功',
            type: 'success'
          })
          _that.tableRefresh()
        } else {
          _that.$message.error(res.msg)
        }
      }).catch(err => {
        _that.$message.error(err)
        _that.dialogVisible = true
      })
    },

    // 启用禁用
    editStatus(id, status) {
      var _that = this;
      var machineInfo = {
        id: id,
        voidFlag: status
      }
      var params = {
        'machineInfo': JSON.stringify(machineInfo)
      }

      var url = '/doc/voidMachineInfo'
      _that.$refs.confirmDialog.updataClick(params, url)
    },

    // 获取机型名称
    getPrintName() {
      var _that = this
      var data = {}
      getPrinterNameList(data).then(res => {
        // console.log('getPrinterNameList', res)
        if (res.httpCode == 200) {
          _that.options = res.data
        } else {
          _that.$message.error(res.msg)
        }
      }).catch(err => {
        _that.$message.error(err)
        _that.dialogVisible = true
      })
    },

    // 搜索
    searchData() {
      this.listData.page = 1
      this.getInfo()
    },
    handleSelectionChange(val) {
      console.log(val);
      this.chooseMachineList = val
    },

    // 点击行内任何地方选中
    handleClickTableRow(row, event, column) {
      this.$refs.machineTable.toggleRowSelection(row)
    },
    printInfo() {
      const _that = this
      var rootData = []
      _that.chooseMachineList.forEach(item =>{
        rootData.push({
          id: item.id.toString(),
          machineName: item.machineName
        })
      })
      var PrintData = {
        '_rootData': rootData
      }
      var data = {
        PrintTemplate: 'machinePrint.fr3',
        NeedPreview: 1,
        PrintData: JSON.stringify(PrintData)
      }
      console.log(data);
      // 以后打印调这个通用接口
      doLocalPrint(data)
    },
    // 弹窗内选择操作
    chooseThis(row) {
      // console.log('点击选择');
      this.$emit('chooseMachine', row)
    },
    // 查询统计选择
    chooseThisTo(row) {
      var data = {
        id: row.id,
        name: row.machineName
      }
      this.$emit('chooseRow', data)
    },
    ERPChoose(row) {
      // this.$message.error(row)
      dyERP.sendJson(JSON.stringify(row))
    },
    getCompanyInfoList(){
      const _that = this;
      getAllCompanyInfoList().then(response => {
        // _that.BreedInfoList = data;
        // console.log("_that.list",response.data);

        // console.log("typeOptions",response.data);
        _that.typeOptions = response.data;


      }).catch(err => {
        console.log(err);
      })
    },
  }
}
</script>

<style lang="scss" scoped>
  .filter-container {
    margin-bottom: 15px;
  }
</style>
